title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to check if a given character is a number/letter in Java?
|
The Character class is a subclass of Object class and it wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char. We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.
public class CharacterIsNumberOrDigitTest {
public static void main(String[] args) {
String str = "Tutorials123";
for(int i=0; i < str.length(); i++) {
Boolean flag = Character.isDigit(str.charAt(i));
if(flag) {
System.out.println("'"+ str.charAt(i)+"' is a number");
}
else {
System.out.println("'"+ str.charAt(i)+"' is a letter");
}
}
}
}
'T' is a letter
'u' is a letter
't' is a letter
'o' is a letter
'r' is a letter
'i' is a letter
'a' is a letter
'l' is a letter
's' is a letter
'1' is a number
'2' is a number
'3' is a number
|
[
{
"code": null,
"e": 1458,
"s": 1062,
"text": "The Character class is a subclass of Object class and it wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char. We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit."
},
{
"code": null,
"e": 1892,
"s": 1458,
"text": "public class CharacterIsNumberOrDigitTest {\n public static void main(String[] args) {\n String str = \"Tutorials123\";\n for(int i=0; i < str.length(); i++) {\n Boolean flag = Character.isDigit(str.charAt(i));\n if(flag) {\n System.out.println(\"'\"+ str.charAt(i)+\"' is a number\");\n }\n else {\n System.out.println(\"'\"+ str.charAt(i)+\"' is a letter\");\n }\n }\n }\n}"
},
{
"code": null,
"e": 2084,
"s": 1892,
"text": "'T' is a letter\n'u' is a letter\n't' is a letter\n'o' is a letter\n'r' is a letter\n'i' is a letter\n'a' is a letter\n'l' is a letter\n's' is a letter\n'1' is a number\n'2' is a number\n'3' is a number"
}
] |
JqueryUI - Effect
|
This chapter will discuss the effect() method, which is one of the methods used to manage jQueryUI visual effects. effect() method applies an animation effect to the elements without having to show or hide it.
The effect() method has the following syntax −
.effect( effect [, options ] [, duration ] [, complete ] )
effect
This is a String indicating which effect to use for the transition.
options
This is of type Object and indicates effect-specific settings and easing. Additionally, each effect has its own set of options that can be specified common across multiple effects described in the table jQueryUI Effects.
duration
This is of type Number or String, and indicates the number of milliseconds of the effect. Its default value is 400.
complete
This is a callback method called for each element when the effect is complete for this element.
The following table describes the various effects that can be used with the effects() method −
blind
Shows or hides the element in the manner of a window blind: by moving the bottom edge down or up, or the right edge to the right or left, depending upon the specified direction and mode.
bounce
Causes the element to appear to bounce in the vertical or horizontal direction, optionally showing or hiding the element.
clip
Shows or hides the element by moving opposite borders of the element together until they meet in the middle, or vice versa.
drop
Shows or hides the element by making it appear to drop onto, or drop off of, the page.
explode
Shows or hides the element by splitting it into multiple pieces that move in radial directions as if imploding into, or exploding from, the page.
fade
Shows or hides the element by adjusting its opacity. This is the same as the core fade effects, but without options.
fold
Shows or hides the element by adjusting opposite borders in or out, and then doing the same for the other set of borders.
highlight
Calls attention to the element by momentarily changing its background color while showing or hiding the element.
puff
Expands or contracts the element in place while adjusting its opacity.
pulsate
Adjusts the opacity of the element on and off before ensuring that the element is shown or hidden as specified.
scale
Expands or contracts the element by a specified percentage.
shake
Shakes the element back and forth, either vertically or horizontally.
size
Resizes the element to a specified width and height. Similar to scale except for how the target size is specified.
slide
Moves the element such that it appears to slide onto or off of the page.
transfer
Animates a transient outline element that makes the element appear to transfer to another element. The appearance of the outline element must be defined via CSS rules for the ui-effects-transfer class, or the class specified as an option.
The following examples demonstrates the use of effect() method with different effect listed in the above table.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI effect Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style>
#box-1 {
height: 100px;
width: 100px;
background: #b9cd6d;
}
</style>
<script>
$(document).ready(function() {
$('#box-1').click(function() {
$( "#box-1" ).effect( "shake", {
times: 10,
distance: 100
}, 3000, function() {
$( this ).css( "background", "#cccccc" );
});
});
});
</script>
</head>
<body>
<div id = "box-1">Click On Me</div>
</body>
</html>
Let us save the above code in an HTML file effectexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI effect Example</title>
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style>
#box-2 {
height: 100px;
width: 100px;
background: #b9cd6d;
}
</style>
<script>
$(document).ready(function() {
$('#box-2').click(function() {
$( "#box-2" ).effect({
effect: "explode",
easing: "easeInExpo",
pieces: 4,
duration: 5000
});
});
});
</script>
</head>
<body>
<div id="box-2"></div>
</body>
</html>
Let us save the above code in an HTML file effectexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2474,
"s": 2264,
"text": "This chapter will discuss the effect() method, which is one of the methods used to manage jQueryUI visual effects. effect() method applies an animation effect to the elements without having to show or hide it."
},
{
"code": null,
"e": 2521,
"s": 2474,
"text": "The effect() method has the following syntax −"
},
{
"code": null,
"e": 2580,
"s": 2521,
"text": ".effect( effect [, options ] [, duration ] [, complete ] )"
},
{
"code": null,
"e": 2587,
"s": 2580,
"text": "effect"
},
{
"code": null,
"e": 2655,
"s": 2587,
"text": "This is a String indicating which effect to use for the transition."
},
{
"code": null,
"e": 2663,
"s": 2655,
"text": "options"
},
{
"code": null,
"e": 2884,
"s": 2663,
"text": "This is of type Object and indicates effect-specific settings and easing. Additionally, each effect has its own set of options that can be specified common across multiple effects described in the table jQueryUI Effects."
},
{
"code": null,
"e": 2893,
"s": 2884,
"text": "duration"
},
{
"code": null,
"e": 3009,
"s": 2893,
"text": "This is of type Number or String, and indicates the number of milliseconds of the effect. Its default value is 400."
},
{
"code": null,
"e": 3018,
"s": 3009,
"text": "complete"
},
{
"code": null,
"e": 3114,
"s": 3018,
"text": "This is a callback method called for each element when the effect is complete for this element."
},
{
"code": null,
"e": 3209,
"s": 3114,
"text": "The following table describes the various effects that can be used with the effects() method −"
},
{
"code": null,
"e": 3215,
"s": 3209,
"text": "blind"
},
{
"code": null,
"e": 3402,
"s": 3215,
"text": "Shows or hides the element in the manner of a window blind: by moving the bottom edge down or up, or the right edge to the right or left, depending upon the specified direction and mode."
},
{
"code": null,
"e": 3409,
"s": 3402,
"text": "bounce"
},
{
"code": null,
"e": 3531,
"s": 3409,
"text": "Causes the element to appear to bounce in the vertical or horizontal direction, optionally showing or hiding the element."
},
{
"code": null,
"e": 3536,
"s": 3531,
"text": "clip"
},
{
"code": null,
"e": 3660,
"s": 3536,
"text": "Shows or hides the element by moving opposite borders of the element together until they meet in the middle, or vice versa."
},
{
"code": null,
"e": 3665,
"s": 3660,
"text": "drop"
},
{
"code": null,
"e": 3752,
"s": 3665,
"text": "Shows or hides the element by making it appear to drop onto, or drop off of, the page."
},
{
"code": null,
"e": 3760,
"s": 3752,
"text": "explode"
},
{
"code": null,
"e": 3906,
"s": 3760,
"text": "Shows or hides the element by splitting it into multiple pieces that move in radial directions as if imploding into, or exploding from, the page."
},
{
"code": null,
"e": 3911,
"s": 3906,
"text": "fade"
},
{
"code": null,
"e": 4028,
"s": 3911,
"text": "Shows or hides the element by adjusting its opacity. This is the same as the core fade effects, but without options."
},
{
"code": null,
"e": 4033,
"s": 4028,
"text": "fold"
},
{
"code": null,
"e": 4155,
"s": 4033,
"text": "Shows or hides the element by adjusting opposite borders in or out, and then doing the same for the other set of borders."
},
{
"code": null,
"e": 4165,
"s": 4155,
"text": "highlight"
},
{
"code": null,
"e": 4278,
"s": 4165,
"text": "Calls attention to the element by momentarily changing its background color while showing or hiding the element."
},
{
"code": null,
"e": 4283,
"s": 4278,
"text": "puff"
},
{
"code": null,
"e": 4354,
"s": 4283,
"text": "Expands or contracts the element in place while adjusting its opacity."
},
{
"code": null,
"e": 4362,
"s": 4354,
"text": "pulsate"
},
{
"code": null,
"e": 4474,
"s": 4362,
"text": "Adjusts the opacity of the element on and off before ensuring that the element is shown or hidden as specified."
},
{
"code": null,
"e": 4480,
"s": 4474,
"text": "scale"
},
{
"code": null,
"e": 4540,
"s": 4480,
"text": "Expands or contracts the element by a specified percentage."
},
{
"code": null,
"e": 4546,
"s": 4540,
"text": "shake"
},
{
"code": null,
"e": 4616,
"s": 4546,
"text": "Shakes the element back and forth, either vertically or horizontally."
},
{
"code": null,
"e": 4621,
"s": 4616,
"text": "size"
},
{
"code": null,
"e": 4736,
"s": 4621,
"text": "Resizes the element to a specified width and height. Similar to scale except for how the target size is specified."
},
{
"code": null,
"e": 4742,
"s": 4736,
"text": "slide"
},
{
"code": null,
"e": 4815,
"s": 4742,
"text": "Moves the element such that it appears to slide onto or off of the page."
},
{
"code": null,
"e": 4824,
"s": 4815,
"text": "transfer"
},
{
"code": null,
"e": 5063,
"s": 4824,
"text": "Animates a transient outline element that makes the element appear to transfer to another element. The appearance of the outline element must be defined via CSS rules for the ui-effects-transfer class, or the class specified as an option."
},
{
"code": null,
"e": 5175,
"s": 5063,
"text": "The following examples demonstrates the use of effect() method with different effect listed in the above table."
},
{
"code": null,
"e": 6198,
"s": 5175,
"text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI effect Example</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n #box-1 {\n height: 100px;\n width: 100px;\n background: #b9cd6d;\n }\n </style>\n \n <script>\n $(document).ready(function() {\n $('#box-1').click(function() {\n $( \"#box-1\" ).effect( \"shake\", {\n times: 10,\n distance: 100\n }, 3000, function() {\n $( this ).css( \"background\", \"#cccccc\" );\n });\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"box-1\">Click On Me</div>\n </body>\n</html>"
},
{
"code": null,
"e": 6393,
"s": 6198,
"text": "Let us save the above code in an HTML file effectexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 7362,
"s": 6393,
"text": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>jQuery UI effect Example</title>\n <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel=\"stylesheet\">\n <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n #box-2 {\n height: 100px;\n width: 100px;\n background: #b9cd6d;\n }\n </style>\n \n <script>\n $(document).ready(function() {\n $('#box-2').click(function() {\n $( \"#box-2\" ).effect({\n effect: \"explode\",\n easing: \"easeInExpo\",\n pieces: 4,\n duration: 5000\n });\n });\n });\n </script>\n </head>\n \n <body>\n <div id=\"box-2\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 7560,
"s": 7362,
"text": "Let us save the above code in an HTML file effectexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 7567,
"s": 7560,
"text": " Print"
},
{
"code": null,
"e": 7578,
"s": 7567,
"text": " Add Notes"
}
] |
Time-series Analysis with VAR & VECM: Statistical approach | by Sarit Maitra | Towards Data Science
| ERROR: type should be string, got "https://sarit-maitra.medium.com/membership\nVECTOR auto-regressive (VAR) integrated model comprises multiple time series and is quite a useful tool for forecasting. It can be considered an extension of the auto-regressive (AR part of ARIMA) model. VAR model involves multiple independent variables and therefore has more than one equations. Each equation uses as its explanatory variables lags of all the variables and likely a deterministic trend. Time series models for VAR are usually based on applying VAR to stationary series with first differences to original series and because of that, there is always a possibility of loss of information about the relationship among integrated series.\nTherefore, differencing the series to make them stationary is one solution, but at the cost of ignoring possibly important (“long run”) relationships between the levels. A better solution is to test whether the levels regressions are trustworthy (“cointegration”.) The usual approach is to use Johansen’s method for testing whether or not cointegration exists. If the answer is “yes” then a vector error correction model (VECM), which combines levels and differences, can be estimated instead of a VAR in levels. So, we shall check if VECM is been able to outperform VAR for the series we have.\nThis an extension of my previously published article.\nAfter necessary cleaning & pre-processing (filling the missing values with previous ones), we finally have the three time series for necessary analysis.\nA quick test is to check if the data is random. Random data will not exhibit a structure in the lag plot.\nThe time series plot clearly indicates some kind of relationships among the series. The linear shape of the lag plot suggests that an AR model is a better choice. We also don’t see any outlier in the data. Data here showing linear pattern, indicating the presence of positive auto-correlation.\n“Time series for economic data is generally stochastic or has a trend that is not stationary, meaning that the data has a root unit”\n# plots the autocorrelation plots at 75 lagsfor i in dataset: plot_acf(dataset[i], lags = 50) plt.title(‘ACF for %s’ % i) plt.show()\ndef augmented_dickey_fuller_statistics(time_series): result = adfuller(time_series.values) print('ADF Statistic: %f' % result[0]) print('p-value: %f' % result[1]) print('Critical Values:')for key, value in result[4].items(): print('\\t%s: %.3f' % (key, value))\nThrough the above function, we can run Augmented Dickey Fuller (ADF) test on all columns, which clearly shows the original series are non-stationary and contain unit root.\nprint('Augmented Dickey-Fuller Test: Gold Price Time Series')augmented_dickey_fuller_statistics(X_train['Gold'])print('Augmented Dickey-Fuller Test: Silver Price Time Series')augmented_dickey_fuller_statistics(X_train['Silver'])print('Augmented Dickey-Fuller Test: Oil Price Time Series')augmented_dickey_fuller_statistics(X_train['Oil'])\nVAR models can also be used for analyzing the relation between the variables involved using Granger Causality tests. Granger causality specifies that a variable y1t is causal for a variable y2t if the information in y1t is helpful for improving the forecasts of y2t.\nGranger Causality tests try to determine if one variable(x1) can be used as a predictor of another variable(x2) where the past values of that another variable may or may not help. This means that x1 explains beyond the past values of x2. Two important assumptions here are -\nboth x1 and x2 are stationary\nthere exists a linear relation between their current and past values.\nThis means that if x1 and x2 are non-stationary, we have to make them stationary before testing for Granger Causality.\nWe will fit the VAR model on X_train to forecast the next 10 observations. These forecasts will be compared against the actuals present in test data (X_test). We shall use multiple forecast accuracy metrics.\nA difference transform is a simple way for removing a systematic structure from the time series. We will remove trend by subtracting the previous value from each value in the series which is the first order differencing. To keep it simple, we will do first order differencing or seasonal differencing.\nIf we have an integrated order to n time series and if we take first order to difference and time, we will be left with series integrated order of zero.\nX_train_log = np.log(X_train)X_train_log_diff =(X_train_log).diff().dropna()X_train_log_diff.describe()\nlooking at the plot, we could figure out that data set looks like normalized\nBelow function plots the auto-correlation plots for the difference in each stock’s price from the price the previous trading day at 75 lags.\nfig, ax = plt.subplots(1,2, figsize=(10,5)) ax[0] = plot_acf(X_train_log_diff['Gold'], ax=ax[0])ax[1] = plot_pacf(X_train_log_diff['Gold'], ax=ax[1])\nWe have shown ACF & PACF of transformed Gold series; likewise, other series can be plotted.\nprint('Augmented Dickey-Fuller Test: Gold Price Time Series')augmented_dickey_fuller_statistics(X_train_log_diff['Gold'])print('Augmented Dickey-Fuller Test: Silver Price Time Series')augmented_dickey_fuller_statistics(X_train_log_diff['Silver'])print('Augmented Dickey-Fuller Test: Oil Price Time Series')augmented_dickey_fuller_statistics(X_train_log_diff['Oil'])Augmented Dickey-Fuller Test on \"Oil\" \nThe Granger causality test is conducted to determine whether one time series is useful in forecasting another. A time series X is said to Granger-cause Y if it can be shown, usually through a series of t-tests and F-tests on lagged values of X (and with lagged values of Y also included), that those X values provide statistically significant information about future values of Y.\nHere, for multivariate Granger causality analysis performed by fitting a VAR to the time series. Considering below is a d-dimensional multivariate time series —\nGranger causality is performed by fitting a VAR model with L time lags as follows:\nwhere ε ( t ) is a white Gaussian random vector, and A τ is a matrix for every τ. A time series X i is called a Granger cause of another time series X j, if at least one of the elements A τ ( j , i ) for τ = 1 , ... , L is significantly larger than zero.\nprint(grangercausalitytests(X_train_log_diff[['Gold','Silver']], maxlag=15, addconst=True, verbose=True))print(grangercausalitytests(X_train_log_diff[['Gold','Oil']], maxlag=15, addconst=True, verbose=True))print(grangercausalitytests(X_train_log_diff[['Oil','Silver']], maxlag=15, addconst=True, verbose=True))\nBelow output shown for Gold & Oil which differs the test hypothesis till lag 4.\nA VAR(p) process in its basic form is:\nHere yt represents a set of variables collected in a vector, c denotes a vector of constants, a is a matrix of autoregressive coefficients and et is white noise. Since the parameters of a are unknown, we have to estimate these parameters. Each variable in the model has one equation. The current (time t) observation of each variable depends on its own lagged values as well as on the lagged values of each other variable in the VAR.\nI have implemented Akaike’s Information Criteria (AIC) through the VAR (p) to determine the lag order value. In the fit function, I have passed a maximum number of lags and the order criterion to use for order selection.\n#Initiate VAR modelmodel = VAR(endog=X_train_log_diff)res = model.select_order(15)res.summary()\n#Fit to a VAR modelmodel_fit = model.fit(maxlags=3)#Print a summary of the model resultsmodel_fit.summary()\nThe forecasts are generated on the training data used by the model.\n# Get the lag orderlag_order = model_fit.k_arprint(lag_order)# Input data for forecastinginput_data = X_train_log_diff.values[-lag_order:]print(input_data)# forecastingpred = model_fit.forecast(y=input_data, steps=nobs)pred = (pd.DataFrame(pred, index=X_test.index, columns=X_test.columns + '_pred'))print(pred)\nSo, to bring it back up to its original scale, we need to de-difference to the original input data. Our data is 1st logarithm transformed and then differenced. So, to inverse, we have to first use cumulative sum to de-differentiate and then use exponential. Natural logarithm is the inverse of the exp().\n# inverting transformationdef invert_transformation(X_train, pred_df): forecast = pred.copy() columns = X_train.columnsfor col in columns: forecast[str(col)+'_pred'] = X_train[col].iloc[-1] + forecast[str(col) +'_pred'].cumsum() return forecastoutput = invert_transformation(X_train, pred)print(output)output_original = np.exp(output)print(output_original)\n#Calculate forecast biasforecast_errors = [X_test['Oil'][i]- output_original['Oil_pred'][i] for i in range(len(X_test['Oil']))]bias = sum(forecast_errors) * 1.0/len(X_test['Oil'])print('Bias: %f' % bias)#Calculate mean absolute errormae = mean_absolute_error(X_test['Oil'],output_original['Oil_pred'])print('MAE: %f' % mae)#Calculate mean squared error and root mean squared errormse = mean_squared_error(X_test['Oil'], output_original['Oil_pred'])print('MSE: %f' % mse)rmse = sqrt(mse)print('RMSE: %f' % rmse)\n“Least squares parameter estimation of dynamic regression models is known to exhibit substantial bias in small samples when the data is fairly persistent”\nVECM imposes additional restriction due to the existence of non-stationary but co-integrated data forms. It utilizes the co-integration restriction information into its specifications. After the cointegration is known then the next test process is done by using error correction method. Through VECM we can interpret long term and short term equations. We need to determine the number of co-integrating relationships. The advantage of VECM over VAR is that the resulting VAR from VECM representation has more efficient coefficient estimates.\nIn order to fit a VECM model, we need to determine the number of co-integrating relationships using a VEC rank test.\nvec_rank1 = vecm.select_coint_rank(X_train, det_order = 1, k_ar_diff = 1, method = 'trace', signif=0.01)print(vec_rank.summary())\nWe find the λtrace statistics in the third column, together with the corresponding critical values. The test statistic of 38.25 is lower than the critical value (41.08) and so the null of at most one co-integrating vector cannot be rejected.\nLet us employ an alternative statistic, the maximum-eigenvalue statistic (λmax).\nvec_rank2 = vecm.select_coint_rank(X_train, det_order = 1, k_ar_diff = 1, method = 'maxeig', signif=0.01)print(vec_rank2.summary())\nThe test output reports the results for the λmax statistics which does not differ much from trace statistic; the critical value (29.28) is still higher than test statistic.\nWe will still go ahead and estimate VECM, since it can still valuable for short-run dynamics in absence of co-integration. Let’s estimates the VECM on the prices with 9 lags, 1 co-integrating relationship, and a constant within the co-integration relationship. I have used ‘cili’ a combination of “ci” — constant within the co-integration relation and “li” — linear trend within the co-integration relation\nvecm = VECM(endog = X_train, k_ar_diff = 9, coint_rank = 3, deterministic = ‘ci’)vecm_fit = vecm.fit()vecm_fit.predict(steps=10)\nforecast, lower, upper = vecm_fit.predict(10, 0.05)print(“lower bounds of confidence intervals:”)print(lower.round(3))print(“\\npoint forecasts:”)print(forecast.round(3))print(“\\nupper bounds of confidence intervals:”)print(upper.round(3))\nThough we had an indication that, VAR would be best for our data set for price prediction; however, we have shown VECM for experimentation and illustration purpose. This is a simple procedure to explain VAR. However, there are other procedures like impulse response analysis and variance decomposition also can be introduced to experiment if we are able to see how a shock to one variable affects other variable in subsequent periods.\nTime series for economic data is generally stochastic or has a trend that is not stationary, meaning that the data has a root unit. To be able to estimate a model using the data-\nSteps for VAR-\nTest stationarity of data and degree of integrationDetermination of lag lengthTest the granger causalityEstimation of VARVariance decomposition\nTest stationarity of data and degree of integration\nDetermination of lag length\nTest the granger causality\nEstimation of VAR\nVariance decomposition\nForecasting Steps for VECM-\nDetermination of lag lengthTest the granger causalityCointegration degree testEstimation of VECMVariance decomposition\nDetermination of lag length\nTest the granger causality\nCointegration degree test\nEstimation of VECM\nVariance decomposition\nI can be reached here.\nNotice: The programs described here are experimental and should be used with caution. All such use at your own risk.\nReferences:\n(1) Rao, B. (2007). Cointegration: for the Applied Economist, Springer.\n(2) Ashley, R. A., & Verbrugge, R. J. (2009). To difference or not to difference: a Monte Carlo investigation of inference in vector autoregression models. International Journal of Data Analysis Techniques and Strategies, 1(3), 242–274.\n(3) Lütkepohl, H. (2011). Vector autoregressive models. In International Encyclopedia of Statistical Science (pp. 1645–1647). Springer Berlin Heidelberg.\n(4) Kuo, C. Y. (2016). Does the vector error correction model perform better than others in forecasting stock price? An application of residual income svaluation theory. Economic Modelling, 52, 772–789." |
[
{
"code": null,
"e": 215,
"s": 172,
"text": "https://sarit-maitra.medium.com/membership"
},
{
"code": null,
"e": 866,
"s": 215,
"text": "VECTOR auto-regressive (VAR) integrated model comprises multiple time series and is quite a useful tool for forecasting. It can be considered an extension of the auto-regressive (AR part of ARIMA) model. VAR model involves multiple independent variables and therefore has more than one equations. Each equation uses as its explanatory variables lags of all the variables and likely a deterministic trend. Time series models for VAR are usually based on applying VAR to stationary series with first differences to original series and because of that, there is always a possibility of loss of information about the relationship among integrated series."
},
{
"code": null,
"e": 1461,
"s": 866,
"text": "Therefore, differencing the series to make them stationary is one solution, but at the cost of ignoring possibly important (“long run”) relationships between the levels. A better solution is to test whether the levels regressions are trustworthy (“cointegration”.) The usual approach is to use Johansen’s method for testing whether or not cointegration exists. If the answer is “yes” then a vector error correction model (VECM), which combines levels and differences, can be estimated instead of a VAR in levels. So, we shall check if VECM is been able to outperform VAR for the series we have."
},
{
"code": null,
"e": 1515,
"s": 1461,
"text": "This an extension of my previously published article."
},
{
"code": null,
"e": 1668,
"s": 1515,
"text": "After necessary cleaning & pre-processing (filling the missing values with previous ones), we finally have the three time series for necessary analysis."
},
{
"code": null,
"e": 1774,
"s": 1668,
"text": "A quick test is to check if the data is random. Random data will not exhibit a structure in the lag plot."
},
{
"code": null,
"e": 2068,
"s": 1774,
"text": "The time series plot clearly indicates some kind of relationships among the series. The linear shape of the lag plot suggests that an AR model is a better choice. We also don’t see any outlier in the data. Data here showing linear pattern, indicating the presence of positive auto-correlation."
},
{
"code": null,
"e": 2201,
"s": 2068,
"text": "“Time series for economic data is generally stochastic or has a trend that is not stationary, meaning that the data has a root unit”"
},
{
"code": null,
"e": 2335,
"s": 2201,
"text": "# plots the autocorrelation plots at 75 lagsfor i in dataset: plot_acf(dataset[i], lags = 50) plt.title(‘ACF for %s’ % i) plt.show()"
},
{
"code": null,
"e": 2600,
"s": 2335,
"text": "def augmented_dickey_fuller_statistics(time_series): result = adfuller(time_series.values) print('ADF Statistic: %f' % result[0]) print('p-value: %f' % result[1]) print('Critical Values:')for key, value in result[4].items(): print('\\t%s: %.3f' % (key, value))"
},
{
"code": null,
"e": 2772,
"s": 2600,
"text": "Through the above function, we can run Augmented Dickey Fuller (ADF) test on all columns, which clearly shows the original series are non-stationary and contain unit root."
},
{
"code": null,
"e": 3111,
"s": 2772,
"text": "print('Augmented Dickey-Fuller Test: Gold Price Time Series')augmented_dickey_fuller_statistics(X_train['Gold'])print('Augmented Dickey-Fuller Test: Silver Price Time Series')augmented_dickey_fuller_statistics(X_train['Silver'])print('Augmented Dickey-Fuller Test: Oil Price Time Series')augmented_dickey_fuller_statistics(X_train['Oil'])"
},
{
"code": null,
"e": 3378,
"s": 3111,
"text": "VAR models can also be used for analyzing the relation between the variables involved using Granger Causality tests. Granger causality specifies that a variable y1t is causal for a variable y2t if the information in y1t is helpful for improving the forecasts of y2t."
},
{
"code": null,
"e": 3653,
"s": 3378,
"text": "Granger Causality tests try to determine if one variable(x1) can be used as a predictor of another variable(x2) where the past values of that another variable may or may not help. This means that x1 explains beyond the past values of x2. Two important assumptions here are -"
},
{
"code": null,
"e": 3683,
"s": 3653,
"text": "both x1 and x2 are stationary"
},
{
"code": null,
"e": 3753,
"s": 3683,
"text": "there exists a linear relation between their current and past values."
},
{
"code": null,
"e": 3872,
"s": 3753,
"text": "This means that if x1 and x2 are non-stationary, we have to make them stationary before testing for Granger Causality."
},
{
"code": null,
"e": 4080,
"s": 3872,
"text": "We will fit the VAR model on X_train to forecast the next 10 observations. These forecasts will be compared against the actuals present in test data (X_test). We shall use multiple forecast accuracy metrics."
},
{
"code": null,
"e": 4382,
"s": 4080,
"text": "A difference transform is a simple way for removing a systematic structure from the time series. We will remove trend by subtracting the previous value from each value in the series which is the first order differencing. To keep it simple, we will do first order differencing or seasonal differencing."
},
{
"code": null,
"e": 4535,
"s": 4382,
"text": "If we have an integrated order to n time series and if we take first order to difference and time, we will be left with series integrated order of zero."
},
{
"code": null,
"e": 4639,
"s": 4535,
"text": "X_train_log = np.log(X_train)X_train_log_diff =(X_train_log).diff().dropna()X_train_log_diff.describe()"
},
{
"code": null,
"e": 4716,
"s": 4639,
"text": "looking at the plot, we could figure out that data set looks like normalized"
},
{
"code": null,
"e": 4857,
"s": 4716,
"text": "Below function plots the auto-correlation plots for the difference in each stock’s price from the price the previous trading day at 75 lags."
},
{
"code": null,
"e": 5007,
"s": 4857,
"text": "fig, ax = plt.subplots(1,2, figsize=(10,5)) ax[0] = plot_acf(X_train_log_diff['Gold'], ax=ax[0])ax[1] = plot_pacf(X_train_log_diff['Gold'], ax=ax[1])"
},
{
"code": null,
"e": 5099,
"s": 5007,
"text": "We have shown ACF & PACF of transformed Gold series; likewise, other series can be plotted."
},
{
"code": null,
"e": 5506,
"s": 5099,
"text": "print('Augmented Dickey-Fuller Test: Gold Price Time Series')augmented_dickey_fuller_statistics(X_train_log_diff['Gold'])print('Augmented Dickey-Fuller Test: Silver Price Time Series')augmented_dickey_fuller_statistics(X_train_log_diff['Silver'])print('Augmented Dickey-Fuller Test: Oil Price Time Series')augmented_dickey_fuller_statistics(X_train_log_diff['Oil'])Augmented Dickey-Fuller Test on \"Oil\" "
},
{
"code": null,
"e": 5887,
"s": 5506,
"text": "The Granger causality test is conducted to determine whether one time series is useful in forecasting another. A time series X is said to Granger-cause Y if it can be shown, usually through a series of t-tests and F-tests on lagged values of X (and with lagged values of Y also included), that those X values provide statistically significant information about future values of Y."
},
{
"code": null,
"e": 6048,
"s": 5887,
"text": "Here, for multivariate Granger causality analysis performed by fitting a VAR to the time series. Considering below is a d-dimensional multivariate time series —"
},
{
"code": null,
"e": 6131,
"s": 6048,
"text": "Granger causality is performed by fitting a VAR model with L time lags as follows:"
},
{
"code": null,
"e": 6386,
"s": 6131,
"text": "where ε ( t ) is a white Gaussian random vector, and A τ is a matrix for every τ. A time series X i is called a Granger cause of another time series X j, if at least one of the elements A τ ( j , i ) for τ = 1 , ... , L is significantly larger than zero."
},
{
"code": null,
"e": 6698,
"s": 6386,
"text": "print(grangercausalitytests(X_train_log_diff[['Gold','Silver']], maxlag=15, addconst=True, verbose=True))print(grangercausalitytests(X_train_log_diff[['Gold','Oil']], maxlag=15, addconst=True, verbose=True))print(grangercausalitytests(X_train_log_diff[['Oil','Silver']], maxlag=15, addconst=True, verbose=True))"
},
{
"code": null,
"e": 6778,
"s": 6698,
"text": "Below output shown for Gold & Oil which differs the test hypothesis till lag 4."
},
{
"code": null,
"e": 6817,
"s": 6778,
"text": "A VAR(p) process in its basic form is:"
},
{
"code": null,
"e": 7258,
"s": 6817,
"text": "Here yt represents a set of variables collected in a vector, c denotes a vector of constants, a is a matrix of autoregressive coefficients and et is white noise. Since the parameters of a are unknown, we have to estimate these parameters. Each variable in the model has one equation. The current (time t) observation of each variable depends on its own lagged values as well as on the lagged values of each other variable in the VAR."
},
{
"code": null,
"e": 7479,
"s": 7258,
"text": "I have implemented Akaike’s Information Criteria (AIC) through the VAR (p) to determine the lag order value. In the fit function, I have passed a maximum number of lags and the order criterion to use for order selection."
},
{
"code": null,
"e": 7575,
"s": 7479,
"text": "#Initiate VAR modelmodel = VAR(endog=X_train_log_diff)res = model.select_order(15)res.summary()"
},
{
"code": null,
"e": 7683,
"s": 7575,
"text": "#Fit to a VAR modelmodel_fit = model.fit(maxlags=3)#Print a summary of the model resultsmodel_fit.summary()"
},
{
"code": null,
"e": 7751,
"s": 7683,
"text": "The forecasts are generated on the training data used by the model."
},
{
"code": null,
"e": 8063,
"s": 7751,
"text": "# Get the lag orderlag_order = model_fit.k_arprint(lag_order)# Input data for forecastinginput_data = X_train_log_diff.values[-lag_order:]print(input_data)# forecastingpred = model_fit.forecast(y=input_data, steps=nobs)pred = (pd.DataFrame(pred, index=X_test.index, columns=X_test.columns + '_pred'))print(pred)"
},
{
"code": null,
"e": 8368,
"s": 8063,
"text": "So, to bring it back up to its original scale, we need to de-difference to the original input data. Our data is 1st logarithm transformed and then differenced. So, to inverse, we have to first use cumulative sum to de-differentiate and then use exponential. Natural logarithm is the inverse of the exp()."
},
{
"code": null,
"e": 8729,
"s": 8368,
"text": "# inverting transformationdef invert_transformation(X_train, pred_df): forecast = pred.copy() columns = X_train.columnsfor col in columns: forecast[str(col)+'_pred'] = X_train[col].iloc[-1] + forecast[str(col) +'_pred'].cumsum() return forecastoutput = invert_transformation(X_train, pred)print(output)output_original = np.exp(output)print(output_original)"
},
{
"code": null,
"e": 9240,
"s": 8729,
"text": "#Calculate forecast biasforecast_errors = [X_test['Oil'][i]- output_original['Oil_pred'][i] for i in range(len(X_test['Oil']))]bias = sum(forecast_errors) * 1.0/len(X_test['Oil'])print('Bias: %f' % bias)#Calculate mean absolute errormae = mean_absolute_error(X_test['Oil'],output_original['Oil_pred'])print('MAE: %f' % mae)#Calculate mean squared error and root mean squared errormse = mean_squared_error(X_test['Oil'], output_original['Oil_pred'])print('MSE: %f' % mse)rmse = sqrt(mse)print('RMSE: %f' % rmse)"
},
{
"code": null,
"e": 9395,
"s": 9240,
"text": "“Least squares parameter estimation of dynamic regression models is known to exhibit substantial bias in small samples when the data is fairly persistent”"
},
{
"code": null,
"e": 9937,
"s": 9395,
"text": "VECM imposes additional restriction due to the existence of non-stationary but co-integrated data forms. It utilizes the co-integration restriction information into its specifications. After the cointegration is known then the next test process is done by using error correction method. Through VECM we can interpret long term and short term equations. We need to determine the number of co-integrating relationships. The advantage of VECM over VAR is that the resulting VAR from VECM representation has more efficient coefficient estimates."
},
{
"code": null,
"e": 10054,
"s": 9937,
"text": "In order to fit a VECM model, we need to determine the number of co-integrating relationships using a VEC rank test."
},
{
"code": null,
"e": 10184,
"s": 10054,
"text": "vec_rank1 = vecm.select_coint_rank(X_train, det_order = 1, k_ar_diff = 1, method = 'trace', signif=0.01)print(vec_rank.summary())"
},
{
"code": null,
"e": 10426,
"s": 10184,
"text": "We find the λtrace statistics in the third column, together with the corresponding critical values. The test statistic of 38.25 is lower than the critical value (41.08) and so the null of at most one co-integrating vector cannot be rejected."
},
{
"code": null,
"e": 10507,
"s": 10426,
"text": "Let us employ an alternative statistic, the maximum-eigenvalue statistic (λmax)."
},
{
"code": null,
"e": 10639,
"s": 10507,
"text": "vec_rank2 = vecm.select_coint_rank(X_train, det_order = 1, k_ar_diff = 1, method = 'maxeig', signif=0.01)print(vec_rank2.summary())"
},
{
"code": null,
"e": 10812,
"s": 10639,
"text": "The test output reports the results for the λmax statistics which does not differ much from trace statistic; the critical value (29.28) is still higher than test statistic."
},
{
"code": null,
"e": 11219,
"s": 10812,
"text": "We will still go ahead and estimate VECM, since it can still valuable for short-run dynamics in absence of co-integration. Let’s estimates the VECM on the prices with 9 lags, 1 co-integrating relationship, and a constant within the co-integration relationship. I have used ‘cili’ a combination of “ci” — constant within the co-integration relation and “li” — linear trend within the co-integration relation"
},
{
"code": null,
"e": 11348,
"s": 11219,
"text": "vecm = VECM(endog = X_train, k_ar_diff = 9, coint_rank = 3, deterministic = ‘ci’)vecm_fit = vecm.fit()vecm_fit.predict(steps=10)"
},
{
"code": null,
"e": 11587,
"s": 11348,
"text": "forecast, lower, upper = vecm_fit.predict(10, 0.05)print(“lower bounds of confidence intervals:”)print(lower.round(3))print(“\\npoint forecasts:”)print(forecast.round(3))print(“\\nupper bounds of confidence intervals:”)print(upper.round(3))"
},
{
"code": null,
"e": 12022,
"s": 11587,
"text": "Though we had an indication that, VAR would be best for our data set for price prediction; however, we have shown VECM for experimentation and illustration purpose. This is a simple procedure to explain VAR. However, there are other procedures like impulse response analysis and variance decomposition also can be introduced to experiment if we are able to see how a shock to one variable affects other variable in subsequent periods."
},
{
"code": null,
"e": 12201,
"s": 12022,
"text": "Time series for economic data is generally stochastic or has a trend that is not stationary, meaning that the data has a root unit. To be able to estimate a model using the data-"
},
{
"code": null,
"e": 12216,
"s": 12201,
"text": "Steps for VAR-"
},
{
"code": null,
"e": 12360,
"s": 12216,
"text": "Test stationarity of data and degree of integrationDetermination of lag lengthTest the granger causalityEstimation of VARVariance decomposition"
},
{
"code": null,
"e": 12412,
"s": 12360,
"text": "Test stationarity of data and degree of integration"
},
{
"code": null,
"e": 12440,
"s": 12412,
"text": "Determination of lag length"
},
{
"code": null,
"e": 12467,
"s": 12440,
"text": "Test the granger causality"
},
{
"code": null,
"e": 12485,
"s": 12467,
"text": "Estimation of VAR"
},
{
"code": null,
"e": 12508,
"s": 12485,
"text": "Variance decomposition"
},
{
"code": null,
"e": 12536,
"s": 12508,
"text": "Forecasting Steps for VECM-"
},
{
"code": null,
"e": 12655,
"s": 12536,
"text": "Determination of lag lengthTest the granger causalityCointegration degree testEstimation of VECMVariance decomposition"
},
{
"code": null,
"e": 12683,
"s": 12655,
"text": "Determination of lag length"
},
{
"code": null,
"e": 12710,
"s": 12683,
"text": "Test the granger causality"
},
{
"code": null,
"e": 12736,
"s": 12710,
"text": "Cointegration degree test"
},
{
"code": null,
"e": 12755,
"s": 12736,
"text": "Estimation of VECM"
},
{
"code": null,
"e": 12778,
"s": 12755,
"text": "Variance decomposition"
},
{
"code": null,
"e": 12801,
"s": 12778,
"text": "I can be reached here."
},
{
"code": null,
"e": 12918,
"s": 12801,
"text": "Notice: The programs described here are experimental and should be used with caution. All such use at your own risk."
},
{
"code": null,
"e": 12930,
"s": 12918,
"text": "References:"
},
{
"code": null,
"e": 13002,
"s": 12930,
"text": "(1) Rao, B. (2007). Cointegration: for the Applied Economist, Springer."
},
{
"code": null,
"e": 13239,
"s": 13002,
"text": "(2) Ashley, R. A., & Verbrugge, R. J. (2009). To difference or not to difference: a Monte Carlo investigation of inference in vector autoregression models. International Journal of Data Analysis Techniques and Strategies, 1(3), 242–274."
},
{
"code": null,
"e": 13394,
"s": 13239,
"text": "(3) Lütkepohl, H. (2011). Vector autoregressive models. In International Encyclopedia of Statistical Science (pp. 1645–1647). Springer Berlin Heidelberg."
}
] |
C++ Program to Swap Two Numbers
|
There are two ways to create a program to swap two numbers. One involves using a temp variable and the second way does not use a third variable. These are explained in detail as follows −
The program to swap two numbers using a temp variable is as follows.
Live Demo
#include <iostream >
using namespace std;
int main() {
int a = 10, b = 5, temp;
temp = a;
a = b;
b = temp;
cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;
return 0;
}
Value of a is 5
Value of b is 10
In the above program, there are two variables a and b that store the two numbers. First, the value of a is stored in temp. Then, the value of b is stored in a. Lastly, the value of temp is stored in b. After this, the values in a and b are swapped.
temp = a;
a = b;
b = temp;
Then the values of a and b are displayed.
cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;
The program to swap two numbers without using a third variable is as follows −
Live Demo
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5;
a = a+b;
b = a-b;
a = a-b;
cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;
return 0;
}
Value of a is 5
Value of b is 10
In the above program, first the sum of a and b is stored in a. Then, the difference of a and b is stored in b. Finally, the difference of a and b is stored in b. At the end of this, the values in a and b are swapped.
a = a+b;
b = a-b;
a = a-b;
Then the values of a and b are displayed.
cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;
|
[
{
"code": null,
"e": 1250,
"s": 1062,
"text": "There are two ways to create a program to swap two numbers. One involves using a temp variable and the second way does not use a third variable. These are explained in detail as follows −"
},
{
"code": null,
"e": 1319,
"s": 1250,
"text": "The program to swap two numbers using a temp variable is as follows."
},
{
"code": null,
"e": 1330,
"s": 1319,
"text": " Live Demo"
},
{
"code": null,
"e": 1530,
"s": 1330,
"text": "#include <iostream >\nusing namespace std;\nint main() {\n int a = 10, b = 5, temp;\n temp = a;\n a = b;\n b = temp;\n cout<<\"Value of a is \"<<a<<endl;\n cout<<\"Value of b is \"<<b;\n return 0;\n}"
},
{
"code": null,
"e": 1563,
"s": 1530,
"text": "Value of a is 5\nValue of b is 10"
},
{
"code": null,
"e": 1812,
"s": 1563,
"text": "In the above program, there are two variables a and b that store the two numbers. First, the value of a is stored in temp. Then, the value of b is stored in a. Lastly, the value of temp is stored in b. After this, the values in a and b are swapped."
},
{
"code": null,
"e": 1839,
"s": 1812,
"text": "temp = a;\na = b;\nb = temp;"
},
{
"code": null,
"e": 1881,
"s": 1839,
"text": "Then the values of a and b are displayed."
},
{
"code": null,
"e": 1941,
"s": 1881,
"text": "cout<<\"Value of a is \"<<a<<endl;\ncout<<\"Value of b is \"<<b;"
},
{
"code": null,
"e": 2020,
"s": 1941,
"text": "The program to swap two numbers without using a third variable is as follows −"
},
{
"code": null,
"e": 2031,
"s": 2020,
"text": " Live Demo"
},
{
"code": null,
"e": 2224,
"s": 2031,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int a = 10, b = 5;\n a = a+b;\n b = a-b;\n a = a-b;\n cout<<\"Value of a is \"<<a<<endl;\n cout<<\"Value of b is \"<<b;\n return 0;\n}"
},
{
"code": null,
"e": 2257,
"s": 2224,
"text": "Value of a is 5\nValue of b is 10"
},
{
"code": null,
"e": 2474,
"s": 2257,
"text": "In the above program, first the sum of a and b is stored in a. Then, the difference of a and b is stored in b. Finally, the difference of a and b is stored in b. At the end of this, the values in a and b are swapped."
},
{
"code": null,
"e": 2501,
"s": 2474,
"text": "a = a+b;\nb = a-b;\na = a-b;"
},
{
"code": null,
"e": 2543,
"s": 2501,
"text": "Then the values of a and b are displayed."
},
{
"code": null,
"e": 2603,
"s": 2543,
"text": "cout<<\"Value of a is \"<<a<<endl;\ncout<<\"Value of b is \"<<b;"
}
] |
R - Pie Charts
|
R Programming language has numerous libraries to create charts and graphs. A pie-chart is a representation of values as slices of a circle with different colors. The slices are labeled and the numbers corresponding to each slice is also represented in the chart.
In R the pie chart is created using the pie() function which takes positive numbers as a vector input. The additional parameters are used to control labels, color, title etc.
The basic syntax for creating a pie-chart using the R is −
pie(x, labels, radius, main, col, clockwise)
Following is the description of the parameters used −
x is a vector containing the numeric values used in the pie chart.
x is a vector containing the numeric values used in the pie chart.
labels is used to give description to the slices.
labels is used to give description to the slices.
radius indicates the radius of the circle of the pie chart.(value between −1 and +1).
radius indicates the radius of the circle of the pie chart.(value between −1 and +1).
main indicates the title of the chart.
main indicates the title of the chart.
col indicates the color palette.
col indicates the color palette.
clockwise is a logical value indicating if the slices are drawn clockwise or anti clockwise.
clockwise is a logical value indicating if the slices are drawn clockwise or anti clockwise.
A very simple pie-chart is created using just the input vector and labels. The below script will create and save the pie chart in the current R working directory.
# Create data for the graph.
x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")
# Give the chart file a name.
png(file = "city.png")
# Plot the chart.
pie(x,labels)
# Save the file.
dev.off()
When we execute the above code, it produces the following result −
We can expand the features of the chart by adding more parameters to the function. We will use parameter main to add a title to the chart and another parameter is col which will make use of rainbow colour pallet while drawing the chart. The length of the pallet should be same as the number of values we have for the chart. Hence we use length(x).
The below script will create and save the pie chart in the current R working directory.
# Create data for the graph.
x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")
# Give the chart file a name.
png(file = "city_title_colours.jpg")
# Plot the chart with title and rainbow color pallet.
pie(x, labels, main = "City pie chart", col = rainbow(length(x)))
# Save the file.
dev.off()
When we execute the above code, it produces the following result −
We can add slice percentage and a chart legend by creating additional chart variables.
# Create data for the graph.
x <- c(21, 62, 10,53)
labels <- c("London","New York","Singapore","Mumbai")
piepercent<- round(100*x/sum(x), 1)
# Give the chart file a name.
png(file = "city_percentage_legends.jpg")
# Plot the chart.
pie(x, labels = piepercent, main = "City pie chart",col = rainbow(length(x)))
legend("topright", c("London","New York","Singapore","Mumbai"), cex = 0.8,
fill = rainbow(length(x)))
# Save the file.
dev.off()
When we execute the above code, it produces the following result −
A pie chart with 3 dimensions can be drawn using additional packages. The package plotrix has a function called pie3D() that is used for this.
# Get the library.
library(plotrix)
# Create data for the graph.
x <- c(21, 62, 10,53)
lbl <- c("London","New York","Singapore","Mumbai")
# Give the chart file a name.
png(file = "3d_pie_chart.jpg")
# Plot the chart.
pie3D(x,labels = lbl,explode = 0.1, main = "Pie Chart of Countries ")
# Save the file.
dev.off()
When we execute the above code, it produces the following result −
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2665,
"s": 2402,
"text": "R Programming language has numerous libraries to create charts and graphs. A pie-chart is a representation of values as slices of a circle with different colors. The slices are labeled and the numbers corresponding to each slice is also represented in the chart."
},
{
"code": null,
"e": 2840,
"s": 2665,
"text": "In R the pie chart is created using the pie() function which takes positive numbers as a vector input. The additional parameters are used to control labels, color, title etc."
},
{
"code": null,
"e": 2899,
"s": 2840,
"text": "The basic syntax for creating a pie-chart using the R is −"
},
{
"code": null,
"e": 2945,
"s": 2899,
"text": "pie(x, labels, radius, main, col, clockwise)\n"
},
{
"code": null,
"e": 2999,
"s": 2945,
"text": "Following is the description of the parameters used −"
},
{
"code": null,
"e": 3066,
"s": 2999,
"text": "x is a vector containing the numeric values used in the pie chart."
},
{
"code": null,
"e": 3133,
"s": 3066,
"text": "x is a vector containing the numeric values used in the pie chart."
},
{
"code": null,
"e": 3183,
"s": 3133,
"text": "labels is used to give description to the slices."
},
{
"code": null,
"e": 3233,
"s": 3183,
"text": "labels is used to give description to the slices."
},
{
"code": null,
"e": 3319,
"s": 3233,
"text": "radius indicates the radius of the circle of the pie chart.(value between −1 and +1)."
},
{
"code": null,
"e": 3405,
"s": 3319,
"text": "radius indicates the radius of the circle of the pie chart.(value between −1 and +1)."
},
{
"code": null,
"e": 3444,
"s": 3405,
"text": "main indicates the title of the chart."
},
{
"code": null,
"e": 3483,
"s": 3444,
"text": "main indicates the title of the chart."
},
{
"code": null,
"e": 3516,
"s": 3483,
"text": "col indicates the color palette."
},
{
"code": null,
"e": 3549,
"s": 3516,
"text": "col indicates the color palette."
},
{
"code": null,
"e": 3642,
"s": 3549,
"text": "clockwise is a logical value indicating if the slices are drawn clockwise or anti clockwise."
},
{
"code": null,
"e": 3735,
"s": 3642,
"text": "clockwise is a logical value indicating if the slices are drawn clockwise or anti clockwise."
},
{
"code": null,
"e": 3898,
"s": 3735,
"text": "A very simple pie-chart is created using just the input vector and labels. The below script will create and save the pie chart in the current R working directory."
},
{
"code": null,
"e": 4122,
"s": 3898,
"text": "# Create data for the graph.\nx <- c(21, 62, 10, 53)\nlabels <- c(\"London\", \"New York\", \"Singapore\", \"Mumbai\")\n\n# Give the chart file a name.\npng(file = \"city.png\")\n\n# Plot the chart.\npie(x,labels)\n\n# Save the file.\ndev.off()"
},
{
"code": null,
"e": 4189,
"s": 4122,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 4537,
"s": 4189,
"text": "We can expand the features of the chart by adding more parameters to the function. We will use parameter main to add a title to the chart and another parameter is col which will make use of rainbow colour pallet while drawing the chart. The length of the pallet should be same as the number of values we have for the chart. Hence we use length(x)."
},
{
"code": null,
"e": 4625,
"s": 4537,
"text": "The below script will create and save the pie chart in the current R working directory."
},
{
"code": null,
"e": 4951,
"s": 4625,
"text": "# Create data for the graph.\nx <- c(21, 62, 10, 53)\nlabels <- c(\"London\", \"New York\", \"Singapore\", \"Mumbai\")\n\n# Give the chart file a name.\npng(file = \"city_title_colours.jpg\")\n\n# Plot the chart with title and rainbow color pallet.\npie(x, labels, main = \"City pie chart\", col = rainbow(length(x)))\n\n# Save the file.\ndev.off()"
},
{
"code": null,
"e": 5018,
"s": 4951,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 5105,
"s": 5018,
"text": "We can add slice percentage and a chart legend by creating additional chart variables."
},
{
"code": null,
"e": 5552,
"s": 5105,
"text": "# Create data for the graph.\nx <- c(21, 62, 10,53)\nlabels <- c(\"London\",\"New York\",\"Singapore\",\"Mumbai\")\n\npiepercent<- round(100*x/sum(x), 1)\n\n# Give the chart file a name.\npng(file = \"city_percentage_legends.jpg\")\n\n# Plot the chart.\npie(x, labels = piepercent, main = \"City pie chart\",col = rainbow(length(x)))\nlegend(\"topright\", c(\"London\",\"New York\",\"Singapore\",\"Mumbai\"), cex = 0.8,\n fill = rainbow(length(x)))\n\n# Save the file.\ndev.off()"
},
{
"code": null,
"e": 5619,
"s": 5552,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 5762,
"s": 5619,
"text": "A pie chart with 3 dimensions can be drawn using additional packages. The package plotrix has a function called pie3D() that is used for this."
},
{
"code": null,
"e": 6082,
"s": 5762,
"text": "# Get the library.\nlibrary(plotrix)\n\n# Create data for the graph.\nx <- c(21, 62, 10,53)\nlbl <- c(\"London\",\"New York\",\"Singapore\",\"Mumbai\")\n\n# Give the chart file a name.\npng(file = \"3d_pie_chart.jpg\")\n\n# Plot the chart.\npie3D(x,labels = lbl,explode = 0.1, main = \"Pie Chart of Countries \")\n\n# Save the file.\ndev.off()"
},
{
"code": null,
"e": 6149,
"s": 6082,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 6182,
"s": 6149,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6197,
"s": 6182,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6232,
"s": 6197,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6247,
"s": 6232,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6282,
"s": 6247,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6297,
"s": 6282,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6330,
"s": 6297,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6344,
"s": 6330,
"text": " Asif Hussain"
},
{
"code": null,
"e": 6379,
"s": 6344,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6394,
"s": 6379,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6429,
"s": 6394,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6443,
"s": 6429,
"text": " Asif Hussain"
},
{
"code": null,
"e": 6450,
"s": 6443,
"text": " Print"
},
{
"code": null,
"e": 6461,
"s": 6450,
"text": " Add Notes"
}
] |
Introduction to Javascript Engines - GeeksforGeeks
|
21 Sep, 2021
JavaScript is not understandable by computer but the only browser understands JavaScript. So, we need a program to convert our JavaScript program into computer-understandable language. A JavaScript engine is a computer program that executes JavaScript code and converts it into computer understandable language.
List of JavaScript Engines:
Let’s understand each of them.
1. V8: V8 is a JavaScript engine developed by the Chromium Project for Google Chrome and Chromium web browsers. It is a JavaScript engine that can run standalone, or be embedded into any C++ application. Using its own parser, it generates an abstract syntax tree. Then, Ignition generates bytecode from this syntax tree using the internal V8 bytecode format. Bytecode is compiled into machine code by TurboFan. It also handles memory allocation for objects, and garbage collects objects it no longer needs. Optimization techniques such as elision of expensive runtime properties, and inline caching. The garbage collector is a generational incremental collector.
V8 provides an edge as it allows JavaScript to run much faster, which improves users’ experience of the web, paves the way for the development of web applications, and spurs rapid growth of server-side JavaScript through projects like Node.js.
2. Chakra: Chakra is a JScript engine developed by Microsoft. It is proprietary software. It is used in the Internet Explorer web browser. A distinctive feature of the engine is that it JIT compiles scripts on a separate CPU core, parallel to the web browser.
3. Spider Monkey: SpiderMonkey is the first JavaScript engine, written by Brendan Eich at Netscape Communications, later released as open-source and currently maintained by the Mozilla Foundation. It is still used in the Firefox web browser.
4. Webkit: WebKit is developed by Apple and used in its Safari web browser, as well as all iOS web browsers. It is used by the BlackBerry Browser, PlayStation consoles beginning from the PS3, the Tizen mobile operating systems, and a browser included with the Amazon Kindle e-book reader. WebKit’s C++ application programming interface (API) provides a set of classes to display Web content in windows and implements browser features such as following links when clicked by the user, managing a back-forward list, and managing a history of pages recently visited.
Example 1: Executing JavaScript code by using console: For Nashorn engine, Java 8 introduced one new command-line tool i.e.jjl. We have to follow the below steps to execute JavaScript code through the console:
Create a file named with geeksforgeeks.js.
Open geeks.js and write following code into the file and save it.
Javascript
<script> var gfg= function(){ print("Welcome to Geeksforgeeks!!!");};gfg(); </script>
Output:
Welcome to Geeksforgeeks!!!
Example 2: Executing JavaScript file by embedding JavaScript file into Java code with the help of ScriptEngine class: By the help of the ScriptEngine class, we can create a JavaScript engine and with the JavaScript engine, we can execute the javaScript file.
// Program to show usecase of Javascript // prog in Java Progimport javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { // Generating Nashorn JavaScript Engine ScriptEngine ee = new ScriptEngineManager() .getEngineByName("Nashorn"); // Directly use JS Code inside Java Code ee.eval("print('Welcome to Geeksforgeeks!!!')"); }}
Output:
You might get a Runtime Error like
Warning: Nashorn engine is planned to be removed from a future JDK release
This is because Nashorn is going to be replaced by GraalVM.
GraalVM: It is a high-performance runtime that ameliorates application performance and efficiency. It is designed for applications written in various programming languages like Java, JavaScript, LLVM-based languages such as C and C++, and other dynamic languages. It removes the isolation between programming languages and enables interoperability in a shared runtime
Blogathon-2021
JavaScript-Questions
Blogathon
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
SQL Query to Create Table With a Primary Key
SQL Query to Convert Datetime to Date
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": 24838,
"s": 24810,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 25150,
"s": 24838,
"text": "JavaScript is not understandable by computer but the only browser understands JavaScript. So, we need a program to convert our JavaScript program into computer-understandable language. A JavaScript engine is a computer program that executes JavaScript code and converts it into computer understandable language."
},
{
"code": null,
"e": 25178,
"s": 25150,
"text": "List of JavaScript Engines:"
},
{
"code": null,
"e": 25209,
"s": 25178,
"text": "Let’s understand each of them."
},
{
"code": null,
"e": 25872,
"s": 25209,
"text": "1. V8: V8 is a JavaScript engine developed by the Chromium Project for Google Chrome and Chromium web browsers. It is a JavaScript engine that can run standalone, or be embedded into any C++ application. Using its own parser, it generates an abstract syntax tree. Then, Ignition generates bytecode from this syntax tree using the internal V8 bytecode format. Bytecode is compiled into machine code by TurboFan. It also handles memory allocation for objects, and garbage collects objects it no longer needs. Optimization techniques such as elision of expensive runtime properties, and inline caching. The garbage collector is a generational incremental collector."
},
{
"code": null,
"e": 26116,
"s": 25872,
"text": "V8 provides an edge as it allows JavaScript to run much faster, which improves users’ experience of the web, paves the way for the development of web applications, and spurs rapid growth of server-side JavaScript through projects like Node.js."
},
{
"code": null,
"e": 26376,
"s": 26116,
"text": "2. Chakra: Chakra is a JScript engine developed by Microsoft. It is proprietary software. It is used in the Internet Explorer web browser. A distinctive feature of the engine is that it JIT compiles scripts on a separate CPU core, parallel to the web browser."
},
{
"code": null,
"e": 26618,
"s": 26376,
"text": "3. Spider Monkey: SpiderMonkey is the first JavaScript engine, written by Brendan Eich at Netscape Communications, later released as open-source and currently maintained by the Mozilla Foundation. It is still used in the Firefox web browser."
},
{
"code": null,
"e": 27184,
"s": 26618,
"text": "4. Webkit: WebKit is developed by Apple and used in its Safari web browser, as well as all iOS web browsers. It is used by the BlackBerry Browser, PlayStation consoles beginning from the PS3, the Tizen mobile operating systems, and a browser included with the Amazon Kindle e-book reader. WebKit’s C++ application programming interface (API) provides a set of classes to display Web content in windows and implements browser features such as following links when clicked by the user, managing a back-forward list, and managing a history of pages recently visited."
},
{
"code": null,
"e": 27394,
"s": 27184,
"text": "Example 1: Executing JavaScript code by using console: For Nashorn engine, Java 8 introduced one new command-line tool i.e.jjl. We have to follow the below steps to execute JavaScript code through the console:"
},
{
"code": null,
"e": 27437,
"s": 27394,
"text": "Create a file named with geeksforgeeks.js."
},
{
"code": null,
"e": 27503,
"s": 27437,
"text": "Open geeks.js and write following code into the file and save it."
},
{
"code": null,
"e": 27516,
"s": 27505,
"text": "Javascript"
},
{
"code": "<script> var gfg= function(){ print(\"Welcome to Geeksforgeeks!!!\");};gfg(); </script>",
"e": 27607,
"s": 27516,
"text": null
},
{
"code": null,
"e": 27615,
"s": 27607,
"text": "Output:"
},
{
"code": null,
"e": 27643,
"s": 27615,
"text": "Welcome to Geeksforgeeks!!!"
},
{
"code": null,
"e": 27903,
"s": 27643,
"text": "Example 2: Executing JavaScript file by embedding JavaScript file into Java code with the help of ScriptEngine class: By the help of the ScriptEngine class, we can create a JavaScript engine and with the JavaScript engine, we can execute the javaScript file."
},
{
"code": "// Program to show usecase of Javascript // prog in Java Progimport javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { // Generating Nashorn JavaScript Engine ScriptEngine ee = new ScriptEngineManager() .getEngineByName(\"Nashorn\"); // Directly use JS Code inside Java Code ee.eval(\"print('Welcome to Geeksforgeeks!!!')\"); }}",
"e": 28374,
"s": 27903,
"text": null
},
{
"code": null,
"e": 28383,
"s": 28374,
"text": "Output: "
},
{
"code": null,
"e": 28418,
"s": 28383,
"text": "You might get a Runtime Error like"
},
{
"code": null,
"e": 28493,
"s": 28418,
"text": "Warning: Nashorn engine is planned to be removed from a future JDK release"
},
{
"code": null,
"e": 28553,
"s": 28493,
"text": "This is because Nashorn is going to be replaced by GraalVM."
},
{
"code": null,
"e": 28923,
"s": 28553,
"text": " GraalVM: It is a high-performance runtime that ameliorates application performance and efficiency. It is designed for applications written in various programming languages like Java, JavaScript, LLVM-based languages such as C and C++, and other dynamic languages. It removes the isolation between programming languages and enables interoperability in a shared runtime"
},
{
"code": null,
"e": 28938,
"s": 28923,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 28959,
"s": 28938,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28969,
"s": 28959,
"text": "Blogathon"
},
{
"code": null,
"e": 28980,
"s": 28969,
"text": "JavaScript"
},
{
"code": null,
"e": 28997,
"s": 28980,
"text": "Web Technologies"
},
{
"code": null,
"e": 29095,
"s": 28997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29136,
"s": 29095,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 29193,
"s": 29136,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 29228,
"s": 29193,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 29273,
"s": 29228,
"text": "SQL Query to Create Table With a Primary Key"
},
{
"code": null,
"e": 29311,
"s": 29273,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 29356,
"s": 29311,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29417,
"s": 29356,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29486,
"s": 29417,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 29558,
"s": 29486,
"text": "Differences between Functional Components and Class Components in React"
}
] |
PyTorch: Switching to the GPU. How and Why to train models on the GPU... | by Dario Radečić | Towards Data Science
|
Unlike TensorFlow, PyTorch doesn’t have a dedicated library for GPU users, and as a developer, you’ll need to do some manual work here. But in the end, it will save you a lot of time.
Just if you are wondering, installing CUDA on your machine or switching to GPU runtime on Colab isn’t enough. Don’t get me wrong, it is still a necessary first step, but doing only this won’t leverage the power of the GPU.
In this article you’ll find out how to switch from CPU to GPU for the following scenarios:
Train/Test split approachData Loader approach
Train/Test split approach
Data Loader approach
The first one is most commonly used for tabular data, whilst you’ll use the second one pretty much every time you’re dealing with image data (at least according to my experience).
There are quite some differences between these two approaches, so each one will be explained in depth. I should also mention that I will be using Google Colab for this article. You can read my opinion and more about it here if you haven’t already:
towardsdatascience.com
The article is structured as follows:
Why Should I Switch to the GPU?Train/Test Split ApproachDataLoader ApproachConclusion
Why Should I Switch to the GPU?
Train/Test Split Approach
DataLoader Approach
Conclusion
So without much ado, let’s get started!
In cases where you are using really deep neural networks — e.g. transfer learning with ResNet152 — training on the CPU will last for a long time. If you are a sane person you won’t try to do that.
The linear algebra operations are done in parallel on the GPU and therefore you can achieve around 100x decrease in training time. Needless to mention, but it is also an option to perform training on multiple GPUs, which would once again decrease training time.
You don’t need to take my words for it. I’ve decided to make a Cat vs Dog classifier based on this dataset. The model is based on the ResNet50 architecture — trained on the CPU first and then on the GPU.
Here are the training times:
Judge for yourself, but I’ll stick to the GPU runtime. It’s free on Colab, so there’s no reason why not. Okay, we now know that GPUs should be used for model training, let’s now see how to make a switch.
If you’ve done some machine learning with Python in Scikit-Learn, you are most certainly familiar with the train/test split. In a nutshell, the idea is to train the model on a portion of the dataset (let’s say 80%) and evaluate the model on the remaining portion (let’s say 20%).
Train/Test split is still a valid approach in deep learning — particularly with tabular data. The first thing to do is to declare a variable which will hold the device we’re training on (CPU or GPU):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')device>>> device(type='cuda')
Now I will declare some dummy data which will act as X_train tensor:
X_train = torch.FloatTensor([0., 1., 2.])X_train>>> tensor([0., 1., 2.])
Cool! We can now check if the tensor is stored on the GPU:
X_train.is_cuda>>> False
As expected — by default data won’t be stored on GPU, but it’s fairly easy to move it there:
X_train = X_train.to(device)X_train>>> tensor([0., 1., 2.], device='cuda:0')
Neat. The same sanity check can be performed again, and this time we know that the tensor was moved to the GPU:
X_train.is_cuda>>> True
Great, but what about model declaration?
I’m glad you’ve asked. Once again, it’s a pretty straightforward thing to do:
model = MyAwesomeNeuralNetwork()model.to(device)
And that’s it, you can begin the training process now. Just to recap, here’s a summary of how your code should be structured:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)X_train, X_test = X_train.to(device), X_test.to(device)y_train, y_test = y_train.to(device), y_test.to(device)class MyAwesomeNeuralNetwork(nn.Module): # your model heremodel = MyAwesomeNeuralNetwork()model.to(device)# training code here
Let’s proceed with the DataLoader approach.
DataLoader approach is more common for CNNs and in this section, we’ll see how to put data (images) on the GPU. The first step remains the same, ergo you must declare a variable which will hold the device we’re training on (CPU or GPU):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')device>>> device(type='cuda')
Now we will declare our model and place it on the GPU:
model = MyAwesomeNeuralNetwork()model.to(device)
You’ve probably noticed that we haven’t placed data on the GPU yet. It’s not possible to transfer Data Loaders directly, so we’ll have to be a bit smarter here. We’ll transfer the images during the training process, like this:
for epoch in range(epochs): for inputs, labels in train_loader: inputs, labels = inputs.to(device), labels.to(device)
So the overall structure of your code should look something like this:
class MyAwesomeNeuralNetwork(nn.Module): # your model heremodel = MyAwesomeNeuralNetwork()model.to(device)epochs = 10for epoch in range(epochs): for inputs, labels in train_loader: inputs, labels = inputs.to(device), labels.to(device) # backpropagation code here # evaluation with torch.no_grad(): for inputs, labels in test_loader: inputs, labels = inputs.to(device), labels.to(device) # ...
And that’s all you have to do — both data and model are placed on GPU.
And there you have it — two steps to drastically reduce the training time. At first, it might seem like a lot of additional steps you need to perform, but it’s straightforward once you get the gist of it.
Training on the CPU is something I would never advise you to do, and thanks to Google Colab you don’t have to — as you can use GPU runtime for free.
Thanks for reading.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
|
[
{
"code": null,
"e": 355,
"s": 171,
"text": "Unlike TensorFlow, PyTorch doesn’t have a dedicated library for GPU users, and as a developer, you’ll need to do some manual work here. But in the end, it will save you a lot of time."
},
{
"code": null,
"e": 578,
"s": 355,
"text": "Just if you are wondering, installing CUDA on your machine or switching to GPU runtime on Colab isn’t enough. Don’t get me wrong, it is still a necessary first step, but doing only this won’t leverage the power of the GPU."
},
{
"code": null,
"e": 669,
"s": 578,
"text": "In this article you’ll find out how to switch from CPU to GPU for the following scenarios:"
},
{
"code": null,
"e": 715,
"s": 669,
"text": "Train/Test split approachData Loader approach"
},
{
"code": null,
"e": 741,
"s": 715,
"text": "Train/Test split approach"
},
{
"code": null,
"e": 762,
"s": 741,
"text": "Data Loader approach"
},
{
"code": null,
"e": 942,
"s": 762,
"text": "The first one is most commonly used for tabular data, whilst you’ll use the second one pretty much every time you’re dealing with image data (at least according to my experience)."
},
{
"code": null,
"e": 1190,
"s": 942,
"text": "There are quite some differences between these two approaches, so each one will be explained in depth. I should also mention that I will be using Google Colab for this article. You can read my opinion and more about it here if you haven’t already:"
},
{
"code": null,
"e": 1213,
"s": 1190,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1251,
"s": 1213,
"text": "The article is structured as follows:"
},
{
"code": null,
"e": 1337,
"s": 1251,
"text": "Why Should I Switch to the GPU?Train/Test Split ApproachDataLoader ApproachConclusion"
},
{
"code": null,
"e": 1369,
"s": 1337,
"text": "Why Should I Switch to the GPU?"
},
{
"code": null,
"e": 1395,
"s": 1369,
"text": "Train/Test Split Approach"
},
{
"code": null,
"e": 1415,
"s": 1395,
"text": "DataLoader Approach"
},
{
"code": null,
"e": 1426,
"s": 1415,
"text": "Conclusion"
},
{
"code": null,
"e": 1466,
"s": 1426,
"text": "So without much ado, let’s get started!"
},
{
"code": null,
"e": 1663,
"s": 1466,
"text": "In cases where you are using really deep neural networks — e.g. transfer learning with ResNet152 — training on the CPU will last for a long time. If you are a sane person you won’t try to do that."
},
{
"code": null,
"e": 1925,
"s": 1663,
"text": "The linear algebra operations are done in parallel on the GPU and therefore you can achieve around 100x decrease in training time. Needless to mention, but it is also an option to perform training on multiple GPUs, which would once again decrease training time."
},
{
"code": null,
"e": 2129,
"s": 1925,
"text": "You don’t need to take my words for it. I’ve decided to make a Cat vs Dog classifier based on this dataset. The model is based on the ResNet50 architecture — trained on the CPU first and then on the GPU."
},
{
"code": null,
"e": 2158,
"s": 2129,
"text": "Here are the training times:"
},
{
"code": null,
"e": 2362,
"s": 2158,
"text": "Judge for yourself, but I’ll stick to the GPU runtime. It’s free on Colab, so there’s no reason why not. Okay, we now know that GPUs should be used for model training, let’s now see how to make a switch."
},
{
"code": null,
"e": 2642,
"s": 2362,
"text": "If you’ve done some machine learning with Python in Scikit-Learn, you are most certainly familiar with the train/test split. In a nutshell, the idea is to train the model on a portion of the dataset (let’s say 80%) and evaluate the model on the remaining portion (let’s say 20%)."
},
{
"code": null,
"e": 2842,
"s": 2642,
"text": "Train/Test split is still a valid approach in deep learning — particularly with tabular data. The first thing to do is to declare a variable which will hold the device we’re training on (CPU or GPU):"
},
{
"code": null,
"e": 2941,
"s": 2842,
"text": "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')device>>> device(type='cuda')"
},
{
"code": null,
"e": 3010,
"s": 2941,
"text": "Now I will declare some dummy data which will act as X_train tensor:"
},
{
"code": null,
"e": 3083,
"s": 3010,
"text": "X_train = torch.FloatTensor([0., 1., 2.])X_train>>> tensor([0., 1., 2.])"
},
{
"code": null,
"e": 3142,
"s": 3083,
"text": "Cool! We can now check if the tensor is stored on the GPU:"
},
{
"code": null,
"e": 3167,
"s": 3142,
"text": "X_train.is_cuda>>> False"
},
{
"code": null,
"e": 3260,
"s": 3167,
"text": "As expected — by default data won’t be stored on GPU, but it’s fairly easy to move it there:"
},
{
"code": null,
"e": 3337,
"s": 3260,
"text": "X_train = X_train.to(device)X_train>>> tensor([0., 1., 2.], device='cuda:0')"
},
{
"code": null,
"e": 3449,
"s": 3337,
"text": "Neat. The same sanity check can be performed again, and this time we know that the tensor was moved to the GPU:"
},
{
"code": null,
"e": 3473,
"s": 3449,
"text": "X_train.is_cuda>>> True"
},
{
"code": null,
"e": 3514,
"s": 3473,
"text": "Great, but what about model declaration?"
},
{
"code": null,
"e": 3592,
"s": 3514,
"text": "I’m glad you’ve asked. Once again, it’s a pretty straightforward thing to do:"
},
{
"code": null,
"e": 3641,
"s": 3592,
"text": "model = MyAwesomeNeuralNetwork()model.to(device)"
},
{
"code": null,
"e": 3767,
"s": 3641,
"text": "And that’s it, you can begin the training process now. Just to recap, here’s a summary of how your code should be structured:"
},
{
"code": null,
"e": 4079,
"s": 3767,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)X_train, X_test = X_train.to(device), X_test.to(device)y_train, y_test = y_train.to(device), y_test.to(device)class MyAwesomeNeuralNetwork(nn.Module): # your model heremodel = MyAwesomeNeuralNetwork()model.to(device)# training code here"
},
{
"code": null,
"e": 4123,
"s": 4079,
"text": "Let’s proceed with the DataLoader approach."
},
{
"code": null,
"e": 4360,
"s": 4123,
"text": "DataLoader approach is more common for CNNs and in this section, we’ll see how to put data (images) on the GPU. The first step remains the same, ergo you must declare a variable which will hold the device we’re training on (CPU or GPU):"
},
{
"code": null,
"e": 4459,
"s": 4360,
"text": "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')device>>> device(type='cuda')"
},
{
"code": null,
"e": 4514,
"s": 4459,
"text": "Now we will declare our model and place it on the GPU:"
},
{
"code": null,
"e": 4563,
"s": 4514,
"text": "model = MyAwesomeNeuralNetwork()model.to(device)"
},
{
"code": null,
"e": 4790,
"s": 4563,
"text": "You’ve probably noticed that we haven’t placed data on the GPU yet. It’s not possible to transfer Data Loaders directly, so we’ll have to be a bit smarter here. We’ll transfer the images during the training process, like this:"
},
{
"code": null,
"e": 4918,
"s": 4790,
"text": "for epoch in range(epochs): for inputs, labels in train_loader: inputs, labels = inputs.to(device), labels.to(device)"
},
{
"code": null,
"e": 4989,
"s": 4918,
"text": "So the overall structure of your code should look something like this:"
},
{
"code": null,
"e": 5449,
"s": 4989,
"text": "class MyAwesomeNeuralNetwork(nn.Module): # your model heremodel = MyAwesomeNeuralNetwork()model.to(device)epochs = 10for epoch in range(epochs): for inputs, labels in train_loader: inputs, labels = inputs.to(device), labels.to(device) # backpropagation code here # evaluation with torch.no_grad(): for inputs, labels in test_loader: inputs, labels = inputs.to(device), labels.to(device) # ..."
},
{
"code": null,
"e": 5520,
"s": 5449,
"text": "And that’s all you have to do — both data and model are placed on GPU."
},
{
"code": null,
"e": 5725,
"s": 5520,
"text": "And there you have it — two steps to drastically reduce the training time. At first, it might seem like a lot of additional steps you need to perform, but it’s straightforward once you get the gist of it."
},
{
"code": null,
"e": 5874,
"s": 5725,
"text": "Training on the CPU is something I would never advise you to do, and thanks to Google Colab you don’t have to — as you can use GPU runtime for free."
},
{
"code": null,
"e": 5894,
"s": 5874,
"text": "Thanks for reading."
}
] |
PLSQL | CONVERT Function - GeeksforGeeks
|
19 Sep, 2019
The string in PL/SQL is actually a sequence of characters with an optional size specification.The characters could be numeric, letters, blank, special characters or a combination of all.The CONVERT function in PLSQL is used to convert a string from one character set to another.Generally, the destination character set contains a representation of all the characters defined in the source character set.If in any case, a character does not exist in the destination character set, a replacement character appears. These replacement characters can be defined as part of a character set definition.
Syntax:
CONVERT( string1, char_set_to [, char_set_from] )
Parameters Used –
string1 –It is used to specify the string to be converted. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.char_set_to –It is used to specify the character set to which the string needs to be converted.char_set_from –It is an optional parameter which is used to specify the character set from which the string needs to be converted.
string1 –It is used to specify the string to be converted. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
char_set_to –It is used to specify the character set to which the string needs to be converted.
char_set_from –It is an optional parameter which is used to specify the character set from which the string needs to be converted.
Note – Both the destination and source character set arguments can be either literals or columns containing the name of the character set.
Available Character Sets:
US7ASCII : US 7-bit ASCII character set
WE8DEC : West European 8-bit character set
WE8HP : HP West European Laserjet 8-bit character set
F7DEC : DEC French 7-bit character set
WE8EBCDIC500 : IBM West European EBCDIC Code Page 500
WE8PC850 : IBM PC Code Page 850
WE8ISO8859P1 : ISO 8859-1 West European 8-bit character set
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example:
DECLARE
Test_String string(10) := 'A B C D';
Test_String2 string(20) := 'E Ä Ê Í';
BEGIN
dbms_output.put_line(CONVERT(Test_String, 'US7ASCII', 'WE8ISO8859P1'));
dbms_output.put_line(CONVERT(Test_String2, 'US7ASCII'));
END;
Output:
A B C D
E A E I
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
SQL | Views
CTE in SQL
Difference between DELETE, DROP and TRUNCATE
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DDL and DML in DBMS
SQL Interview Questions
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Difference between Where and Having Clause in SQL
|
[
{
"code": null,
"e": 23589,
"s": 23561,
"text": "\n19 Sep, 2019"
},
{
"code": null,
"e": 24185,
"s": 23589,
"text": "The string in PL/SQL is actually a sequence of characters with an optional size specification.The characters could be numeric, letters, blank, special characters or a combination of all.The CONVERT function in PLSQL is used to convert a string from one character set to another.Generally, the destination character set contains a representation of all the characters defined in the source character set.If in any case, a character does not exist in the destination character set, a replacement character appears. These replacement characters can be defined as part of a character set definition."
},
{
"code": null,
"e": 24193,
"s": 24185,
"text": "Syntax:"
},
{
"code": null,
"e": 24243,
"s": 24193,
"text": "CONVERT( string1, char_set_to [, char_set_from] )"
},
{
"code": null,
"e": 24261,
"s": 24243,
"text": "Parameters Used –"
},
{
"code": null,
"e": 24626,
"s": 24261,
"text": "string1 –It is used to specify the string to be converted. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.char_set_to –It is used to specify the character set to which the string needs to be converted.char_set_from –It is an optional parameter which is used to specify the character set from which the string needs to be converted."
},
{
"code": null,
"e": 24766,
"s": 24626,
"text": "string1 –It is used to specify the string to be converted. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB."
},
{
"code": null,
"e": 24862,
"s": 24766,
"text": "char_set_to –It is used to specify the character set to which the string needs to be converted."
},
{
"code": null,
"e": 24993,
"s": 24862,
"text": "char_set_from –It is an optional parameter which is used to specify the character set from which the string needs to be converted."
},
{
"code": null,
"e": 25132,
"s": 24993,
"text": "Note – Both the destination and source character set arguments can be either literals or columns containing the name of the character set."
},
{
"code": null,
"e": 25158,
"s": 25132,
"text": "Available Character Sets:"
},
{
"code": null,
"e": 25198,
"s": 25158,
"text": "US7ASCII : US 7-bit ASCII character set"
},
{
"code": null,
"e": 25241,
"s": 25198,
"text": "WE8DEC : West European 8-bit character set"
},
{
"code": null,
"e": 25295,
"s": 25241,
"text": "WE8HP : HP West European Laserjet 8-bit character set"
},
{
"code": null,
"e": 25334,
"s": 25295,
"text": "F7DEC : DEC French 7-bit character set"
},
{
"code": null,
"e": 25388,
"s": 25334,
"text": "WE8EBCDIC500 : IBM West European EBCDIC Code Page 500"
},
{
"code": null,
"e": 25420,
"s": 25388,
"text": "WE8PC850 : IBM PC Code Page 850"
},
{
"code": null,
"e": 25480,
"s": 25420,
"text": "WE8ISO8859P1 : ISO 8859-1 West European 8-bit character set"
},
{
"code": null,
"e": 25516,
"s": 25480,
"text": "Supported Versions of Oracle/PLSQL:"
},
{
"code": null,
"e": 25565,
"s": 25516,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 25576,
"s": 25565,
"text": "Oracle 12c"
},
{
"code": null,
"e": 25587,
"s": 25576,
"text": "Oracle 11g"
},
{
"code": null,
"e": 25598,
"s": 25587,
"text": "Oracle 10g"
},
{
"code": null,
"e": 25608,
"s": 25598,
"text": "Oracle 9i"
},
{
"code": null,
"e": 25618,
"s": 25608,
"text": "Oracle 8i"
},
{
"code": null,
"e": 25627,
"s": 25618,
"text": "Example:"
},
{
"code": null,
"e": 25879,
"s": 25627,
"text": "DECLARE \n Test_String string(10) := 'A B C D';\n Test_String2 string(20) := 'E Ä Ê Í';\n \nBEGIN \n dbms_output.put_line(CONVERT(Test_String, 'US7ASCII', 'WE8ISO8859P1')); \n dbms_output.put_line(CONVERT(Test_String2, 'US7ASCII')); \n \nEND; "
},
{
"code": null,
"e": 25887,
"s": 25879,
"text": "Output:"
},
{
"code": null,
"e": 25903,
"s": 25887,
"text": "A B C D\nE A E I"
},
{
"code": null,
"e": 25914,
"s": 25903,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 25918,
"s": 25914,
"text": "SQL"
},
{
"code": null,
"e": 25922,
"s": 25918,
"text": "SQL"
},
{
"code": null,
"e": 26020,
"s": 25922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26029,
"s": 26020,
"text": "Comments"
},
{
"code": null,
"e": 26042,
"s": 26029,
"text": "Old Comments"
},
{
"code": null,
"e": 26073,
"s": 26042,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 26085,
"s": 26073,
"text": "SQL | Views"
},
{
"code": null,
"e": 26096,
"s": 26085,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26141,
"s": 26096,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 26207,
"s": 26141,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26246,
"s": 26207,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 26270,
"s": 26246,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26302,
"s": 26270,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26380,
"s": 26302,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
}
] |
Bokeh - ColumnDataSource
|
Most of the plotting methods in Bokeh API are able to receive data source parameters through ColumnDatasource object. It makes sharing data between plots and ‘DataTables’.
A ColumnDatasource can be considered as a mapping between column name and list of data. A Python dict object with one or more string keys and lists or numpy arrays as values is passed to ColumnDataSource constructor.
Below is the example
from bokeh.models import ColumnDataSource
data = {'x':[1, 4, 3, 2, 5],
'y':[6, 5, 2, 4, 7]}
cds = ColumnDataSource(data = data)
This object is then used as value of source property in a glyph method. Following code generates a scatter plot using ColumnDataSource.
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource
data = {'x':[1, 4, 3, 2, 5],
'y':[6, 5, 2, 4, 7]}
cds = ColumnDataSource(data = data)
fig = figure()
fig.scatter(x = 'x', y = 'y',source = cds, marker = "circle", size = 20, fill_color = "grey")
show(fig)
Instead of assigning a Python dictionary to ColumnDataSource, we can use a Pandas DataFrame for it.
Let us use ‘test.csv’ (used earlier in this section) to obtain a DataFrame and use it for getting ColumnDataSource and rendering line plot.
from bokeh.plotting import figure, output_file, show
import pandas as pd
from bokeh.models import ColumnDataSource
df = pd.read_csv('test.csv')
cds = ColumnDataSource(df)
fig = figure(y_axis_type = 'log')
fig.line(x = 'x', y = 'pow',source = cds, line_color = "grey")
show(fig)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2442,
"s": 2270,
"text": "Most of the plotting methods in Bokeh API are able to receive data source parameters through ColumnDatasource object. It makes sharing data between plots and ‘DataTables’."
},
{
"code": null,
"e": 2659,
"s": 2442,
"text": "A ColumnDatasource can be considered as a mapping between column name and list of data. A Python dict object with one or more string keys and lists or numpy arrays as values is passed to ColumnDataSource constructor."
},
{
"code": null,
"e": 2680,
"s": 2659,
"text": "Below is the example"
},
{
"code": null,
"e": 2811,
"s": 2680,
"text": "from bokeh.models import ColumnDataSource\ndata = {'x':[1, 4, 3, 2, 5],\n 'y':[6, 5, 2, 4, 7]}\ncds = ColumnDataSource(data = data)"
},
{
"code": null,
"e": 2947,
"s": 2811,
"text": "This object is then used as value of source property in a glyph method. Following code generates a scatter plot using ColumnDataSource."
},
{
"code": null,
"e": 3250,
"s": 2947,
"text": "from bokeh.plotting import figure, output_file, show\nfrom bokeh.models import ColumnDataSource\ndata = {'x':[1, 4, 3, 2, 5],\n 'y':[6, 5, 2, 4, 7]}\ncds = ColumnDataSource(data = data)\nfig = figure()\nfig.scatter(x = 'x', y = 'y',source = cds, marker = \"circle\", size = 20, fill_color = \"grey\")\nshow(fig)"
},
{
"code": null,
"e": 3350,
"s": 3250,
"text": "Instead of assigning a Python dictionary to ColumnDataSource, we can use a Pandas DataFrame for it."
},
{
"code": null,
"e": 3490,
"s": 3350,
"text": "Let us use ‘test.csv’ (used earlier in this section) to obtain a DataFrame and use it for getting ColumnDataSource and rendering line plot."
},
{
"code": null,
"e": 3768,
"s": 3490,
"text": "from bokeh.plotting import figure, output_file, show\nimport pandas as pd\nfrom bokeh.models import ColumnDataSource\ndf = pd.read_csv('test.csv')\ncds = ColumnDataSource(df)\nfig = figure(y_axis_type = 'log')\nfig.line(x = 'x', y = 'pow',source = cds, line_color = \"grey\")\nshow(fig)"
},
{
"code": null,
"e": 3775,
"s": 3768,
"text": " Print"
},
{
"code": null,
"e": 3786,
"s": 3775,
"text": " Add Notes"
}
] |
Divide binary array into three equal parts with same value - GeeksforGeeks
|
13 Nov, 2018
Given an array A of length n such that it contains only ‘0s’ and ‘1s’. The task is to divide the array into THREE different non-empty parts such that all of these parts represent the same binary value(in decimals).If it is possible, return any [i, j] with i+1 < j, such that:1. A[0], A[1], ..., A[i] is the first part.2. A[i+1], A[i+2], ..., A[j-1] is the second part.3. A[j], A[j+1], ..., A[n- 1] is the third part.Note: All three parts should have equal binary value. However, If it is not possible, return [-1, -1].
Examples:
Input : A = [1, 1, 1, 1, 1, 1]
Output : [1, 4]
All three parts are,
A[0] to A[1] first part,
A[2] to A[3] second part,
A[4] to A[5] third part.
Input : A = [1, 0, 0, 1, 0, 1]
Output : [0, 4]
Approach:Lets say total number of ones in A be S. Since every part has the same number of ones, thus all parts should have K = S / 3 ones.
If S isn’t divisible by 3 i:e S % 3 != 0, then the task is impossible.
Now we will find the position of the 1st, K-th, K+1-th, 2K-th, 2K+1-th, and 3K-th one. The positions of these ones will form 3 intervals: [i1, j1], [i2, j2], [i3, j3]. (If there are only 3 ones, then the intervals are each length 1.)
Between the intervals, there may be some number of zeros. The zeros after third interval j3 must be included in each part: say there are z of them (z = length of (S) – j3).
So the first part, [i1, j1], is now [i1, j1+z]. Similarly, the second part, [i2, j2], is now [i2, j2+z].
If all this is actually possible, then the final answer is [j1+z, j2+z+1].
Below is the implementation of above approach.
C++
Java
Python3
C#
PHP
// C++ implementation of the // above approach#include <bits/stdc++.h>using namespace std; // Function to return required // interval answer.vector<int> ThreeEqualParts(vector<int> A){ int imp[] = {-1, -1}; vector<int> IMP(imp, imp + 2); // Finding total number of ones int Sum = accumulate(A.begin(), A.end(), 0); if (Sum % 3) { return IMP; } int K = Sum / 3; // Array contains all zeros. if (K == 0) { return {0, (int)A.size() - 1}; } vector<int> interval; int S = 0; for (int i = 0 ;i < A.size(); i++) { int x = A[i]; if (x) { S += x; if (S == 1 or S == K + 1 or S == 2 * K + 1) { interval.push_back(i); } if (S == K or S == 2 * K or S == 3 * K) { interval.push_back(i); } } } int i1 = interval[0], j1 = interval[1], i2 = interval[2], j2 = interval[3], i3 = interval[4], j3 = interval[5]; vector<int> a(A.begin() + i1, A.begin() + j1 + 1); vector<int> b(A.begin() + i2, A.begin() + j2 + 1); vector<int> c(A.begin() + i3, A.begin() + j3 + 1); // The array is in the form // W [i1, j1] X [i2, j2] Y [i3, j3] Z // where [i1, j1] is a block of 1s, and so on. if (!((a == b) and (b == c))) { return {-1, -1}; } // x, y, z: the number of zeros // after part 1, 2, 3 int x = i2 - j1 - 1; int y = i3 - j2 - 1; int z = A.size() - j3 - 1; if (x < z or y < z) { return IMP; } // appending extra zeros at end of // first and second interval j1 += z; j2 += z; return {j1, j2 + 1}; } // Driver Codeint main(){ vector<int> A = {1, 1, 1, 1, 1, 1}; // Output required result vector<int> res = ThreeEqualParts(A); for(auto it :res) cout << it << " "; return 0;} // This code is contributed // by Harshit Saini
// Java implementation of the // above approachimport java.util.*; class GFG{ // Function to return required // interval answer.public static int[] ThreeEqualParts(int[] A){ int IMP[] = new int[]{-1, -1}; // Finding total number of ones int Sum = Arrays.stream(A).sum(); if ((Sum % 3) != 0) { return IMP; } int K = Sum / 3; // Array contains all zeros. if (K == 0) { return new int[]{0, A.length - 1}; } ArrayList<Integer> interval = new ArrayList<Integer>(); int S = 0; for (int i = 0 ;i < A.length; i++) { int x = A[i]; if (x != 0) { S += x; if ((S == 1) || (S == K + 1) || (S == 2 * K + 1)) { interval.add(i); } if ((S == K) || (S == 2 * K) || (S == 3 * K)) { interval.add(i); } } } int i1 = interval.get(0), j1 = interval.get(1), i2 = interval.get(2), j2 = interval.get(3), i3 = interval.get(4), j3 = interval.get(5); int [] a = Arrays.copyOfRange(A, i1, j1 + 1); int [] b = Arrays.copyOfRange(A, i2, j2 + 1); int [] c = Arrays.copyOfRange(A, i3, j3 + 1); // The array is in the form // W [i1, j1] X [i2, j2] Y [i3, j3] Z // where [i1, j1] is a block of 1s, and so on. if (!(Arrays.equals(a, b) && Arrays.equals(b, c))) { return new int[]{-1, -1}; } // x, y, z: // the number of zeros after part 1, 2, 3 int x = i2 - j1 - 1; int y = i3 - j2 - 1; int z = A.length - j3 - 1; if (x < z || y < z) { return IMP; } // appending extra zeros at end // of first and second interval j1 += z; j2 += z; return new int[]{j1, j2 + 1}; } // Driver Codepublic static void main(String []args){ int[] A = new int[]{1, 1, 1, 1, 1, 1}; // Output required result int[] res = ThreeEqualParts(A); System.out.println(Arrays.toString(res));}} // This code is contributed // by Harshit Saini
# Python implementation of the above approach # Function to return required interval answer.def ThreeEqualParts(A): IMP = [-1, -1] # Finding total number of ones Sum = sum(A) if Sum % 3: return IMP K = Sum / 3 # Array contains all zeros. if K == 0: return [0, len(A) - 1] interval = [] S = 0 for i, x in enumerate(A): if x: S += x if S in {1, K + 1, 2 * K + 1}: interval.append(i) if S in {K, 2 * K, 3 * K}: interval.append(i) i1, j1, i2, j2, i3, j3 = interval # The array is in the form W [i1, j1] X [i2, j2] Y [i3, j3] Z # where [i1, j1] is a block of 1s, and so on. if not(A[i1:j1 + 1] == A[i2:j2 + 1] == A[i3:j3 + 1]): return [-1, -1] # x, y, z: the number of zeros after part 1, 2, 3 x = i2 - j1 - 1 y = i3 - j2 - 1 z = len(A) - j3 - 1 if x < z or y < z: return IMP # appending extra zeros at end of first and second interval j1 += z j2 += z return [j1, j2 + 1] # Driver ProgramA = [1, 1, 1, 1, 1, 1] # Output required resultprint(ThreeEqualParts(A)) # This code is written by# Sanjit_Prasad
// C# implementation of the // above approachusing System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to return required// interval answer.static int[] ThreeEqualParts(int[] A){ int []IMP = new int[]{-1, -1}; // Finding total number of ones int Sum = A.Sum(); if ((Sum % 3) != 0) { return IMP; } int K = Sum / 3; // Array contains all zeros. if (K == 0) { return new int[]{0, A.Length - 1}; } List<int> interval = new List<int>(); int S = 0; for (int i = 0 ;i < A.Length; i++) { int x = A[i]; if (x != 0) { S += x; if ((S == 1) || (S == K + 1) || (S == 2 * K + 1)) { interval.Add(i); } if ((S == K) || (S == 2 * K) || (S == 3 * K)) { interval.Add(i); } } } int i1 = interval[0], j1 = interval[1], i2 = interval[2], j2 = interval[3], i3 = interval[4], j3 = interval[5]; var a = A.Skip(i1).Take(j1 - i1 + 1).ToArray(); var b = A.Skip(i2).Take(j2 - i2 + 1).ToArray(); var c = A.Skip(i3).Take(j3 - i3 + 1).ToArray(); // The array is in the form // W [i1, j1] X [i2, j2] Y [i3, j3] Z // where [i1, j1] is a block of 1s, // and so on. if (!(Enumerable.SequenceEqual(a,b) && Enumerable.SequenceEqual(b,c))) { return new int[]{-1, -1}; } // x, y, z: the number of zeros // after part 1, 2, 3 int X = i2 - j1 - 1; int y = i3 - j2 - 1; int z = A.Length - j3 - 1; if (X < z || y < z) { return IMP; } // appending extra zeros at end // of first and second interval j1 += z; j2 += z; return new int[]{j1, j2 + 1}; } // Driver Codepublic static void Main(){ int[] A = new int[]{1, 1, 1, 1, 1, 1}; // Output required result int[] res = ThreeEqualParts(A); Console.WriteLine(string.Join(" ", res));}} // This code is contributed // by Harshit Saini
<?php// PHP implementation of the// above approach // Function to return required // interval answer.function ThreeEqualParts($A){ $IMP = array(-1, -1); // Finding total number of ones $Sum = array_sum($A); if ($Sum % 3) { return $IMP; } $K = $Sum / 3; // Array contains all zeros. if ($K == 0) { return array(0, count(A, COUNT_NORMAL) - 1); } $interval = array(); $S = 0; for ($i = 0; $i < count($A, COUNT_NORMAL); $i++) { $x = $A[$i]; if ($x) { $S += $x; if ($S == 1 or $S == $K + 1 or $S == 2 * $K + 1) { array_push($interval,$i); } if ($S == $K or $S == 2 * $K or $S == 3 * $K) { array_push($interval, $i); } } } $i1 = $interval[0]; $j1 = $interval[1]; $i2 = $interval[2]; $j2 = $interval[3]; $i3 = $interval[4]; $j3 = $interval[5]; $a = array_slice($A, $i1, $j1 - $i1 + 1); $b = array_slice($A, $i1, $j2 - $i2 + 1); $c = array_slice($A, $i1, $j3 - $i3 + 1); // The array is in the form // W [i1, j1] X [i2, j2] Y [i3, j3] Z // where [i1, j1] is a block of 1s, // and so on. if (!($a == $b and $b == $c)) { return array(-1, -1); } // x, y, z: the number of zeros // after part 1, 2, 3 $x = $i2 - $j1 - 1; $y = $i3 - $j2 - 1; $z = count($A) - $j3 - 1; if ($x < $z or $y < $z) { return $IMP; } // appending extra zeros at end // of first and second interval $j1 += $z; $j2 += $z; return array($j1, $j2 + 1); } // Driver Code$A = array(1, 1, 1, 1, 1, 1); // Output required result$res = ThreeEqualParts($A); foreach ($res as $key => $value) { echo $value." ";} // This code is contributed // by Harshit Saini ?>
1 4
Time Complexity: O(N), where N is the length of S.Space Complexity: O(N)
Harshit Saini
binary-string
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Python | Using 2D arrays/lists the right way
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Queue | Set 1 (Introduction and Array Implementation)
|
[
{
"code": null,
"e": 25060,
"s": 25032,
"text": "\n13 Nov, 2018"
},
{
"code": null,
"e": 25579,
"s": 25060,
"text": "Given an array A of length n such that it contains only ‘0s’ and ‘1s’. The task is to divide the array into THREE different non-empty parts such that all of these parts represent the same binary value(in decimals).If it is possible, return any [i, j] with i+1 < j, such that:1. A[0], A[1], ..., A[i] is the first part.2. A[i+1], A[i+2], ..., A[j-1] is the second part.3. A[j], A[j+1], ..., A[n- 1] is the third part.Note: All three parts should have equal binary value. However, If it is not possible, return [-1, -1]."
},
{
"code": null,
"e": 25589,
"s": 25579,
"text": "Examples:"
},
{
"code": null,
"e": 25782,
"s": 25589,
"text": "Input : A = [1, 1, 1, 1, 1, 1]\nOutput : [1, 4]\nAll three parts are,\nA[0] to A[1] first part,\nA[2] to A[3] second part,\nA[4] to A[5] third part.\n\nInput : A = [1, 0, 0, 1, 0, 1]\nOutput : [0, 4]\n"
},
{
"code": null,
"e": 25921,
"s": 25782,
"text": "Approach:Lets say total number of ones in A be S. Since every part has the same number of ones, thus all parts should have K = S / 3 ones."
},
{
"code": null,
"e": 25992,
"s": 25921,
"text": "If S isn’t divisible by 3 i:e S % 3 != 0, then the task is impossible."
},
{
"code": null,
"e": 26226,
"s": 25992,
"text": "Now we will find the position of the 1st, K-th, K+1-th, 2K-th, 2K+1-th, and 3K-th one. The positions of these ones will form 3 intervals: [i1, j1], [i2, j2], [i3, j3]. (If there are only 3 ones, then the intervals are each length 1.)"
},
{
"code": null,
"e": 26399,
"s": 26226,
"text": "Between the intervals, there may be some number of zeros. The zeros after third interval j3 must be included in each part: say there are z of them (z = length of (S) – j3)."
},
{
"code": null,
"e": 26504,
"s": 26399,
"text": "So the first part, [i1, j1], is now [i1, j1+z]. Similarly, the second part, [i2, j2], is now [i2, j2+z]."
},
{
"code": null,
"e": 26579,
"s": 26504,
"text": "If all this is actually possible, then the final answer is [j1+z, j2+z+1]."
},
{
"code": null,
"e": 26626,
"s": 26579,
"text": "Below is the implementation of above approach."
},
{
"code": null,
"e": 26630,
"s": 26626,
"text": "C++"
},
{
"code": null,
"e": 26635,
"s": 26630,
"text": "Java"
},
{
"code": null,
"e": 26643,
"s": 26635,
"text": "Python3"
},
{
"code": null,
"e": 26646,
"s": 26643,
"text": "C#"
},
{
"code": null,
"e": 26650,
"s": 26646,
"text": "PHP"
},
{
"code": "// C++ implementation of the // above approach#include <bits/stdc++.h>using namespace std; // Function to return required // interval answer.vector<int> ThreeEqualParts(vector<int> A){ int imp[] = {-1, -1}; vector<int> IMP(imp, imp + 2); // Finding total number of ones int Sum = accumulate(A.begin(), A.end(), 0); if (Sum % 3) { return IMP; } int K = Sum / 3; // Array contains all zeros. if (K == 0) { return {0, (int)A.size() - 1}; } vector<int> interval; int S = 0; for (int i = 0 ;i < A.size(); i++) { int x = A[i]; if (x) { S += x; if (S == 1 or S == K + 1 or S == 2 * K + 1) { interval.push_back(i); } if (S == K or S == 2 * K or S == 3 * K) { interval.push_back(i); } } } int i1 = interval[0], j1 = interval[1], i2 = interval[2], j2 = interval[3], i3 = interval[4], j3 = interval[5]; vector<int> a(A.begin() + i1, A.begin() + j1 + 1); vector<int> b(A.begin() + i2, A.begin() + j2 + 1); vector<int> c(A.begin() + i3, A.begin() + j3 + 1); // The array is in the form // W [i1, j1] X [i2, j2] Y [i3, j3] Z // where [i1, j1] is a block of 1s, and so on. if (!((a == b) and (b == c))) { return {-1, -1}; } // x, y, z: the number of zeros // after part 1, 2, 3 int x = i2 - j1 - 1; int y = i3 - j2 - 1; int z = A.size() - j3 - 1; if (x < z or y < z) { return IMP; } // appending extra zeros at end of // first and second interval j1 += z; j2 += z; return {j1, j2 + 1}; } // Driver Codeint main(){ vector<int> A = {1, 1, 1, 1, 1, 1}; // Output required result vector<int> res = ThreeEqualParts(A); for(auto it :res) cout << it << \" \"; return 0;} // This code is contributed // by Harshit Saini ",
"e": 28627,
"s": 26650,
"text": null
},
{
"code": "// Java implementation of the // above approachimport java.util.*; class GFG{ // Function to return required // interval answer.public static int[] ThreeEqualParts(int[] A){ int IMP[] = new int[]{-1, -1}; // Finding total number of ones int Sum = Arrays.stream(A).sum(); if ((Sum % 3) != 0) { return IMP; } int K = Sum / 3; // Array contains all zeros. if (K == 0) { return new int[]{0, A.length - 1}; } ArrayList<Integer> interval = new ArrayList<Integer>(); int S = 0; for (int i = 0 ;i < A.length; i++) { int x = A[i]; if (x != 0) { S += x; if ((S == 1) || (S == K + 1) || (S == 2 * K + 1)) { interval.add(i); } if ((S == K) || (S == 2 * K) || (S == 3 * K)) { interval.add(i); } } } int i1 = interval.get(0), j1 = interval.get(1), i2 = interval.get(2), j2 = interval.get(3), i3 = interval.get(4), j3 = interval.get(5); int [] a = Arrays.copyOfRange(A, i1, j1 + 1); int [] b = Arrays.copyOfRange(A, i2, j2 + 1); int [] c = Arrays.copyOfRange(A, i3, j3 + 1); // The array is in the form // W [i1, j1] X [i2, j2] Y [i3, j3] Z // where [i1, j1] is a block of 1s, and so on. if (!(Arrays.equals(a, b) && Arrays.equals(b, c))) { return new int[]{-1, -1}; } // x, y, z: // the number of zeros after part 1, 2, 3 int x = i2 - j1 - 1; int y = i3 - j2 - 1; int z = A.length - j3 - 1; if (x < z || y < z) { return IMP; } // appending extra zeros at end // of first and second interval j1 += z; j2 += z; return new int[]{j1, j2 + 1}; } // Driver Codepublic static void main(String []args){ int[] A = new int[]{1, 1, 1, 1, 1, 1}; // Output required result int[] res = ThreeEqualParts(A); System.out.println(Arrays.toString(res));}} // This code is contributed // by Harshit Saini ",
"e": 30705,
"s": 28627,
"text": null
},
{
"code": "# Python implementation of the above approach # Function to return required interval answer.def ThreeEqualParts(A): IMP = [-1, -1] # Finding total number of ones Sum = sum(A) if Sum % 3: return IMP K = Sum / 3 # Array contains all zeros. if K == 0: return [0, len(A) - 1] interval = [] S = 0 for i, x in enumerate(A): if x: S += x if S in {1, K + 1, 2 * K + 1}: interval.append(i) if S in {K, 2 * K, 3 * K}: interval.append(i) i1, j1, i2, j2, i3, j3 = interval # The array is in the form W [i1, j1] X [i2, j2] Y [i3, j3] Z # where [i1, j1] is a block of 1s, and so on. if not(A[i1:j1 + 1] == A[i2:j2 + 1] == A[i3:j3 + 1]): return [-1, -1] # x, y, z: the number of zeros after part 1, 2, 3 x = i2 - j1 - 1 y = i3 - j2 - 1 z = len(A) - j3 - 1 if x < z or y < z: return IMP # appending extra zeros at end of first and second interval j1 += z j2 += z return [j1, j2 + 1] # Driver ProgramA = [1, 1, 1, 1, 1, 1] # Output required resultprint(ThreeEqualParts(A)) # This code is written by# Sanjit_Prasad",
"e": 31897,
"s": 30705,
"text": null
},
{
"code": "// C# implementation of the // above approachusing System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to return required// interval answer.static int[] ThreeEqualParts(int[] A){ int []IMP = new int[]{-1, -1}; // Finding total number of ones int Sum = A.Sum(); if ((Sum % 3) != 0) { return IMP; } int K = Sum / 3; // Array contains all zeros. if (K == 0) { return new int[]{0, A.Length - 1}; } List<int> interval = new List<int>(); int S = 0; for (int i = 0 ;i < A.Length; i++) { int x = A[i]; if (x != 0) { S += x; if ((S == 1) || (S == K + 1) || (S == 2 * K + 1)) { interval.Add(i); } if ((S == K) || (S == 2 * K) || (S == 3 * K)) { interval.Add(i); } } } int i1 = interval[0], j1 = interval[1], i2 = interval[2], j2 = interval[3], i3 = interval[4], j3 = interval[5]; var a = A.Skip(i1).Take(j1 - i1 + 1).ToArray(); var b = A.Skip(i2).Take(j2 - i2 + 1).ToArray(); var c = A.Skip(i3).Take(j3 - i3 + 1).ToArray(); // The array is in the form // W [i1, j1] X [i2, j2] Y [i3, j3] Z // where [i1, j1] is a block of 1s, // and so on. if (!(Enumerable.SequenceEqual(a,b) && Enumerable.SequenceEqual(b,c))) { return new int[]{-1, -1}; } // x, y, z: the number of zeros // after part 1, 2, 3 int X = i2 - j1 - 1; int y = i3 - j2 - 1; int z = A.Length - j3 - 1; if (X < z || y < z) { return IMP; } // appending extra zeros at end // of first and second interval j1 += z; j2 += z; return new int[]{j1, j2 + 1}; } // Driver Codepublic static void Main(){ int[] A = new int[]{1, 1, 1, 1, 1, 1}; // Output required result int[] res = ThreeEqualParts(A); Console.WriteLine(string.Join(\" \", res));}} // This code is contributed // by Harshit Saini ",
"e": 33959,
"s": 31897,
"text": null
},
{
"code": "<?php// PHP implementation of the// above approach // Function to return required // interval answer.function ThreeEqualParts($A){ $IMP = array(-1, -1); // Finding total number of ones $Sum = array_sum($A); if ($Sum % 3) { return $IMP; } $K = $Sum / 3; // Array contains all zeros. if ($K == 0) { return array(0, count(A, COUNT_NORMAL) - 1); } $interval = array(); $S = 0; for ($i = 0; $i < count($A, COUNT_NORMAL); $i++) { $x = $A[$i]; if ($x) { $S += $x; if ($S == 1 or $S == $K + 1 or $S == 2 * $K + 1) { array_push($interval,$i); } if ($S == $K or $S == 2 * $K or $S == 3 * $K) { array_push($interval, $i); } } } $i1 = $interval[0]; $j1 = $interval[1]; $i2 = $interval[2]; $j2 = $interval[3]; $i3 = $interval[4]; $j3 = $interval[5]; $a = array_slice($A, $i1, $j1 - $i1 + 1); $b = array_slice($A, $i1, $j2 - $i2 + 1); $c = array_slice($A, $i1, $j3 - $i3 + 1); // The array is in the form // W [i1, j1] X [i2, j2] Y [i3, j3] Z // where [i1, j1] is a block of 1s, // and so on. if (!($a == $b and $b == $c)) { return array(-1, -1); } // x, y, z: the number of zeros // after part 1, 2, 3 $x = $i2 - $j1 - 1; $y = $i3 - $j2 - 1; $z = count($A) - $j3 - 1; if ($x < $z or $y < $z) { return $IMP; } // appending extra zeros at end // of first and second interval $j1 += $z; $j2 += $z; return array($j1, $j2 + 1); } // Driver Code$A = array(1, 1, 1, 1, 1, 1); // Output required result$res = ThreeEqualParts($A); foreach ($res as $key => $value) { echo $value.\" \";} // This code is contributed // by Harshit Saini ?>",
"e": 35858,
"s": 33959,
"text": null
},
{
"code": null,
"e": 35863,
"s": 35858,
"text": "1 4 "
},
{
"code": null,
"e": 35936,
"s": 35863,
"text": "Time Complexity: O(N), where N is the length of S.Space Complexity: O(N)"
},
{
"code": null,
"e": 35950,
"s": 35936,
"text": "Harshit Saini"
},
{
"code": null,
"e": 35964,
"s": 35950,
"text": "binary-string"
},
{
"code": null,
"e": 35971,
"s": 35964,
"text": "Arrays"
},
{
"code": null,
"e": 35978,
"s": 35971,
"text": "Arrays"
},
{
"code": null,
"e": 36076,
"s": 35978,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36144,
"s": 36076,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36192,
"s": 36144,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36236,
"s": 36192,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36268,
"s": 36236,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36291,
"s": 36268,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36305,
"s": 36291,
"text": "Linear Search"
},
{
"code": null,
"e": 36350,
"s": 36305,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 36371,
"s": 36350,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 36456,
"s": 36371,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
}
] |
User-Defined Exceptions in Python
|
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions."
},
{
"code": null,
"e": 1376,
"s": 1174,
"text": "Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught."
},
{
"code": null,
"e": 1535,
"s": 1376,
"text": "In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror."
},
{
"code": null,
"e": 1619,
"s": 1535,
"text": "class Networkerror(RuntimeError):\n def __init__(self, arg):\n self.args = arg"
},
{
"code": null,
"e": 1693,
"s": 1619,
"text": "So once you defined above class, you can raise the exception as follows −"
},
{
"code": null,
"e": 1775,
"s": 1693,
"text": "try:\n raise Networkerror(\"Bad hostname\")\nexcept Networkerror,e:\n print e.args"
}
] |
SQL Certificate Mock Exams
|
1. What will be the outcome of the following query?
SELECT ROUND(144.23,-1) FROM dual;
140
144
150
100
140
144
150
100
2.In which of the following cases, parenthesis should be specified?
When INTERSECT is used with other set operators
When UNION is used with UNION ALL
When MINUS is used for the queries
None of the above
When INTERSECT is used with other set operators
When UNION is used with UNION ALL
When MINUS is used for the queries
None of the above
3. Which of the following are DML commands in Oracle Database?
SELECT
GROUP BY
INTERSECT
INSERT
SELECT
GROUP BY
INTERSECT
INSERT
4. Write a query to display employee details (Name, Department, Salary and Job) from EMP table.
SELECT ename, deptno, sal, job FROM emp;
SELECT * FROM emp;
SELECT DISTINCT ename, deptno, sal, job FROM emp;
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal, job FROM emp;
SELECT ename, deptno, sal, job FROM emp;
SELECT * FROM emp;
SELECT * FROM emp;
SELECT DISTINCT ename, deptno, sal, job FROM emp;
SELECT DISTINCT ename, deptno, sal, job FROM emp;
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal FROM emp;
5.What among the following are different types of Views?
Simple views
Complex views
Both A and B
None of the above
Simple views
Complex views
Both A and B
None of the above
6.What is true about the SET operators?
The SELECT clause should have the same number of columns, data types can be different
The SET operators can be used only for combining two queries
The data type of each column in the 2nd query must match the data type of its corresponding column in the first query.
None of the above
The SELECT clause should have the same number of columns, data types can be different
The SET operators can be used only for combining two queries
The data type of each column in the 2nd query must match the data type of its corresponding column in the first query.
None of the above
7.Which of the following multi-row operators can be used with a sub-query?
IN
ANY
ALL
All of the above
IN
ANY
ALL
All of the above
8. When a table can be created?
When the database is not being used by any user
When the database is newly created
It can be created any time, even when a user is using the database
None of the above
When the database is not being used by any user
When the database is newly created
It can be created any time, even when a user is using the database
None of the above
9. Which among the following is a common technique for inserting rows into a table? (Choose the most sensible and appropriate answer)
Using SELECT clause
Manually typing each value into the INSERT clause
Using SET operators
None of the above
Using SELECT clause
Manually typing each value into the INSERT clause
Using SET operators
None of the above
10. What among the following is true about a View?
Sub-queries can be embedded in a CREATE VIEW statement
A sub-query used in the CREATE VIEW statement has to have a simple SELECT syntax
You cannot use a WHERE clause in a sub-query when it is used in the CREATE VIEW statement
None of the above
Sub-queries can be embedded in a CREATE VIEW statement
A sub-query used in the CREATE VIEW statement has to have a simple SELECT syntax
You cannot use a WHERE clause in a sub-query when it is used in the CREATE VIEW statement
None of the above
11. Predict the output when below statement is executed in SQL* Plus?
DESC emp
Raises error "SP2-0042: unknown command "desc emp" - rest of line ignored."
Lists the columns of EMP table
Lists the EMP table columns, their data type and nullity
Lists the columns of EMP table along with their data types
Raises error "SP2-0042: unknown command "desc emp" - rest of line ignored."
Lists the columns of EMP table
Lists the EMP table columns, their data type and nullity
Lists the columns of EMP table along with their data types
12. What will be the outcome of the query given below?
SELECT 100+NULL+999 FROM dual;
100
999
NULL
1099
100
999
NULL
1099
13. With respect to the given query, if the JOIN used is replaced with NATURAL JOIN, it throws an error. What is the reason for this error?
When the NATURAL JOIN is used, a WHERE clause is mandatory, omitting which gives an error
The ON clause should be replaced with the USING clause
The words NATURAL, JOIN and USING are mutually exclusively in the context of the same join clause
A query can't combine the NATURAL JOIN and ON (or USING) clauses while joining.
When the NATURAL JOIN is used, a WHERE clause is mandatory, omitting which gives an error
The ON clause should be replaced with the USING clause
The words NATURAL, JOIN and USING are mutually exclusively in the context of the same join clause
A query can't combine the NATURAL JOIN and ON (or USING) clauses while joining.
14.Which of the following syntax models is used in extensively in the software systems worldwide?
ANSI SQL: 1999
Both traditional Oracle syntax and the ANSI SQL: 1999 syntax
Traditional Oracle syntax
All of the options
ANSI SQL: 1999
Both traditional Oracle syntax and the ANSI SQL: 1999 syntax
Traditional Oracle syntax
All of the options
15.What is true about co-related sub-queries?
The tables used in the main query are also used in a co-related sub-query
The sub-queries which reference a column used in the main query are called co-related sub-queries
The sub-queries which are written without parenthesis are called co-related sub-queries
The sub-queries which mandatorily use different tables than those used in the main query are called co-related sub-queries
The tables used in the main query are also used in a co-related sub-query
The sub-queries which reference a column used in the main query are called co-related sub-queries
The sub-queries which are written without parenthesis are called co-related sub-queries
The sub-queries which mandatorily use different tables than those used in the main query are called co-related sub-queries
16. You issue an UPDATE statement as follows:
UPDATE employees
SET employee_id = NULL;
WHERE job_id = 'CLERK';
What will be the outcome of the above statement? (Here the column EMPLOYEE_ID is marked as mandatory by putting a constraint)
The first column of the data set will get updated to NULL
The 3rd column of the first row will get updated to NULL
The 3rd column of all the rows will get updated to NULL
And ORA error will be thrown
The first column of the data set will get updated to NULL
The 3rd column of the first row will get updated to NULL
The 3rd column of all the rows will get updated to NULL
And ORA error will be thrown
17.What is true with respect to the query given above?
It gives an ORA error as the mandatory WHERE clause is not present
The JOIN..ON clause can't contain more than one condition
The query ignores the last condition and executes without an ORA error
The JOIN..ON clause can be written in the form given above for putting more conditions.
It gives an ORA error as the mandatory WHERE clause is not present
The JOIN..ON clause can't contain more than one condition
The query ignores the last condition and executes without an ORA error
The JOIN..ON clause can be written in the form given above for putting more conditions.
18. Consider the following query.
SELECT e.job_id , e.first_name, d.department_id
FROM departments D JOIN employees e JOIN BONUS b
USING (job_id );
This query results in an error. What is the reason of the error?
A JOINOUSING can happen only between two tables at a time
USING clause in the query doesn't have any column from the department
There is no WHERE clause in the query
None of the above
A JOINOUSING can happen only between two tables at a time
USING clause in the query doesn't have any column from the department
There is no WHERE clause in the query
None of the above
19. Predict the output of the below query
SELECT 50 || 0001
FROM dual
500001
51
501
5001
500001
51
501
5001
20. You create a table and name it as COUNT. What will be the outcome of CREATE TABLE script?
The table will not be created
The table will be created and an underscore will be added automatically to the name COUNT_
An ORA error will be thrown
The table COUNT will be created without any errors
The table will not be created
The table will be created and an underscore will be added automatically to the name COUNT_
An ORA error will be thrown
The table COUNT will be created without any errors
21. What will be the outcome of the following query?
SELECT *
FROM employees
WHERE salary BETWEEN (SELECT max(salary)
FROM employees
WHERE department_id = 100)
AND (SELECT min(salary) FROM employees where department_id = 100);
This query returns an error. What is the reason for the error?
A GROUP BY clause should be used as the function MAX is used
Both the sub-queries cannot use the same department ID in the same outer query
BETWEEN operator cannot be used with a sub-query
SELECT clause should have columns mentioned and not a asterix (*)
A GROUP BY clause should be used as the function MAX is used
Both the sub-queries cannot use the same department ID in the same outer query
BETWEEN operator cannot be used with a sub-query
SELECT clause should have columns mentioned and not a asterix (*)
22. Which of the following is not a property of functions?
Perform calculations on data
Convert column data types
Modify individual data items
None of the above
Perform calculations on data
Convert column data types
Modify individual data items
None of the above
23.What is true with respect to INNER JOINS and OUTER JOINS in Oracle DB?
INNER JOIN returns only the rows that are matched
OUTER JOIN returns only the rows that are not matched
OUTER JOIN returns the rows that are matched as well as those which do not match
None of the above
INNER JOIN returns only the rows that are matched
OUTER JOIN returns only the rows that are not matched
OUTER JOIN returns the rows that are matched as well as those which do not match
None of the above
24. Which of the following can create a view even if the base table(s) does not exist?
NOFORCE
FORCE
OR REPLACE
CREATE VIEW
NOFORCE
FORCE
OR REPLACE
CREATE VIEW
25. Which of the following ANSI SQL: 1999 join syntax joins are supported by Oracle?
Cartesian products
Natural joins
Full OUTER join
Equijoins
Cartesian products
Natural joins
Full OUTER join
Equijoins
26. What among the following are the pre-requisites for creating a table?
CREATE TABLE privilege
Storage space
Data in the table
None of the above
CREATE TABLE privilege
Storage space
Data in the table
None of the above
27. What is the syntax for creating a table?
CREATE TABLE [schema.] table (column datatype [DEFAULT expr] [,..] );
CREATE TABLE INTO [schema.] table (column datatype [DEFAULT expr] [,..] );
CREATE TABLE VALUES [schema.] table (column datatype [DEFAULT expr] [,..] );
None of the above
CREATE TABLE [schema.] table (column datatype [DEFAULT expr] [,..] );
CREATE TABLE INTO [schema.] table (column datatype [DEFAULT expr] [,..] );
CREATE TABLE VALUES [schema.] table (column datatype [DEFAULT expr] [,..] );
None of the above
28.You need to display all the non-matching rows from the EMPLOYEES table and the non-matching rows from the DEPARTMENT table without giving a Cartesian product of rows between them. Which of the following queries will give the desired output?
SELECT *
FROM employees e, department d
WHERE e.department_id = d.department_id ;
SELECT *
FROM employees e NATURAL JOIN department d;
SELECT *
FROM employees e FULL OUTER JOIN department d
ON e.department_id = d.department_id ;
SELECT *
FROM employees e JOIN department d
ON ( e.department_id > d.department_id ) ;
SELECT *
FROM employees e, department d
WHERE e.department_id = d.department_id ;
SELECT *
FROM employees e, department d
WHERE e.department_id = d.department_id ;
SELECT *
FROM employees e NATURAL JOIN department d;
SELECT *
FROM employees e NATURAL JOIN department d;
SELECT *
FROM employees e FULL OUTER JOIN department d
ON e.department_id = d.department_id ;
SELECT *
FROM employees e FULL OUTER JOIN department d
ON e.department_id = d.department_id ;
SELECT *
FROM employees e JOIN department d
ON ( e.department_id > d.department_id ) ;
SELECT *
FROM employees e JOIN department d
ON ( e.department_id > d.department_id ) ;
29. Which of the below alphanumeric characters are used to signify concatenation operator in SQL?
+
||
-
::
+
||
-
::
30.What is the best way to change the precedence of SET operators given the fact that they have equal precedence?
The order of usage of the SET operators can be changed to change the precedence
The equal precedence cannot be changed
Parenthesis can be used to change the precedence
None of the above
The order of usage of the SET operators can be changed to change the precedence
The equal precedence cannot be changed
Parenthesis can be used to change the precedence
None of the above
31.What will be displayed in the result of this query?
It will display distinct department id(s) contained jointly in EMPLOYEES and DEPARTMENTS table
It will throw ORA error
No rows selected
None of the above
It will display distinct department id(s) contained jointly in EMPLOYEES and DEPARTMENTS table
It will throw ORA error
No rows selected
None of the above
32. Which of the following commands ensures that no DML operations can be performed on a view?
NOFORCE
FORCE
WITH READ ONLY
OR REPLACE
NOFORCE
FORCE
WITH READ ONLY
OR REPLACE
33. What is true about the NOFORCE option in CREATE VIEW statement?
It creates a view even if the base table(s) does not exist.
It creates a view only if the base table(s) exists.
It is the default while creating a view.
None of the above
It creates a view even if the base table(s) does not exist.
It creates a view only if the base table(s) exists.
It is the default while creating a view.
None of the above
34. What is true about the OR REPLACE keyword?
Object privileges are lost when a view is created using this keyword
There is no need of re granting the object privileges previously granted on it
Neither of A nor B
None of the above
Object privileges are lost when a view is created using this keyword
There is no need of re granting the object privileges previously granted on it
Neither of A nor B
None of the above
35. What among the following is a type of Oracle SQL functions?
Multiple-row functions
Single column functions
Single value functions
Multiple columns functions
Multiple-row functions
Single column functions
Single value functions
Multiple columns functions
36. What among the following is a type of single-row function?
VARCHAR2
Character
LONG
NULLIF
VARCHAR2
Character
LONG
NULLIF
37. What is the most appropriate about Multiple Row Functions?
They return multiple values per each row.
They return one result per group of rows and can manipulate groups of rows.
They return one result per row and can manipulate groups of rows.
They return multiple values per a group of row.
They return multiple values per each row.
They return one result per group of rows and can manipulate groups of rows.
They return one result per row and can manipulate groups of rows.
They return multiple values per a group of row.
38. Which of the following are also called Group functions?
Single row functions
Multi group functions
Multiple row functions
Single group functions.
Single row functions
Multi group functions
Multiple row functions
Single group functions.
39. A table T_COUNT has 12 number values as 1, 2, 3, 32, 1, 1, null, 24, 12, null, 32, null. Predict the output of the below query.
SELECT COUNT (*) FROM t_count;
12
6
9
Throws exception because COUNT function doesn't works with NULL values
12
6
9
Throws exception because COUNT function doesn't works with NULL values
40. Pick the element which you must specify while creating a table.
Column name
Column Data type
Column size
All of the above
Column name
Column Data type
Column size
All of the above
41. What can be said about the statement given above?
Alternative names have been given for the view
Giving alternative names is mandatory if any column is derived from a function or an expression
Both A and B
None of the above
Alternative names have been given for the view
Giving alternative names is mandatory if any column is derived from a function or an expression
Both A and B
None of the above
42. A table T_COUNT has 12 number values as 1, 2, 3, 32, 1, 1, null, 24, 12, null, 32, null. Predict the output of the below query.
SELECT COUNT (num) FROM t_count;
12
6
9
Throws exception because COUNT function doesn't works with NULL values
12
6
9
Throws exception because COUNT function doesn't works with NULL values
43. You need to find the results obtained by the above query only for the departments 100 and 101. Which of the following clauses should be added / modified to the above query?
ON (e.department_id = d.department_id ) should be added
USING (e.department_id ) should be added
WHERE e.department_id in (100,101) should be added
None of the above
ON (e.department_id = d.department_id ) should be added
USING (e.department_id ) should be added
WHERE e.department_id in (100,101) should be added
None of the above
44. Which of the following is NOT a GROUP BY extensions in SQL?
GROUP BY
GROUPING SETS
CUBE
ROLLUP
GROUP BY
GROUPING SETS
CUBE
ROLLUP
45. What will happen if the above statement is modified as below?
CREATE OR REPLACE VIEW dept_sum_vu(name, maxsal, minsal, avgsal)
AS
SELECT d.dept_name, MIN(e.salary), MAX(e.salary), AVG (e.salary)
FROM employees e JOIN departments d
ON (e.department_id= d.dept_id)
GROUP BY d.dept_name;
It will be no different than the original statement
It will execute successfully giving the same results but change in alias names.
It will throw an ORA error
None of the above
It will be no different than the original statement
It will execute successfully giving the same results but change in alias names.
It will throw an ORA error
None of the above
46. What among the following is true about the DELETE statement?
The DELETE statement has to be accompanied by the WHERE clause
It is not mandatory to write a WHERE clause with the DELETE statement
DELETE can remove data from multiple tables at a time
None of the above
The DELETE statement has to be accompanied by the WHERE clause
It is not mandatory to write a WHERE clause with the DELETE statement
DELETE can remove data from multiple tables at a time
None of the above
47. Assuming the last names of the employees are in a proper case in the table employees, what will be the outcome of the following query?
SELECT employee_id, last_name, department_id FROM employees WHERE last_name = 'smith';
It will display the details of the employee with the last name as Smith
It will give no result.
It will give the details for the employee having the last name as 'Smith' in all Lower case.
It will give the details for the employee having the last name as 'Smith' in all INITCAP case.
It will display the details of the employee with the last name as Smith
It will give no result.
It will give the details for the employee having the last name as 'Smith' in all Lower case.
It will give the details for the employee having the last name as 'Smith' in all INITCAP case.
48.What among the following happens when we issue a DELETE statement on a table? (Choose the most appropriate answer)
A prompt pops up asking the user whether he/she is sure of deleting the rows requested
The rows obeying the condition given in the DELETE statement are removed immediately
The requested rows are removed immediately without any prompt.
None of the above
A prompt pops up asking the user whether he/she is sure of deleting the rows requested
The rows obeying the condition given in the DELETE statement are removed immediately
The requested rows are removed immediately without any prompt.
None of the above
49.What is true about the query given above?
This query returns an ORA error
It executes successfully but gives no results
Queries from different tables cannot be used with the SET operators
The query executes successfully and gives the results as expected
This query returns an ORA error
It executes successfully but gives no results
Queries from different tables cannot be used with the SET operators
The query executes successfully and gives the results as expected
50.What will happen if a value is provided to the &N variable in the above query (option C in question 76) does not match with any row? (Choose the best answer)
The statement would throw an ORA error
The statement would return all the rows in the table
The statement would return NULL as the output result.
The statement would return no rows in the result.
The statement would throw an ORA error
The statement would return all the rows in the table
The statement would return NULL as the output result.
The statement would return no rows in the result.
51.What is the default sorting order of the results when UNION ALL operator is used?
Descending
Ascending
Either A or B
All of the above
Descending
Ascending
Either A or B
All of the above
52. A table T_COUNT has 12 number values as 1, 2, 3, 32, 1, 1, null, 24, 12, null, 32, null. Predict the output of the below query.
SELECT COUNT (ALL num) FROM t_count;
12
6
9
Throws exception because COUNT function doesn't works with NULL values
12
6
9
Throws exception because COUNT function doesn't works with NULL values
53.What is the maximum level up to which Sub-queries can be nested?
255
100
2
16
255
100
2
16
54. A table T_COUNT has 12 number values as 1, 2, 3, 32, 1, 1, null, 24, 12, null, 32, null. Predict the output of the below query.
SELECT COUNT (DISTINCT num) FROM t_count;
12
6
9
Throws exception because COUNT function doesn't works with NULL values
12
6
9
Throws exception because COUNT function doesn't works with NULL values
55. Here are few statements about VARIANCE function in SQL.
i. The function accepts multiple numeric inputs and returns variance of all the values
ii. The function accepts a number column and returns variance of all column values including NULLs
iii. The function accepts a number column and returns variance of all column values excluding NULLs
Chose the correct combination from the below options.
i and iii
i and ii
ii
iii
i and iii
i and ii
ii
iii
56. Which clause is used to filter the query output based on aggregated results using a group by function?
WHERE
LIMIT
GROUP WHERE
HAVING
WHERE
LIMIT
GROUP WHERE
HAVING
57. A user named "Kevin" wants to access a table which is owned by another user named "Jonathan". Which of the following will work for Kevin?
Select * from Kevin.employees;
Select * from jonathan.employees;
Either of A or B
None of the above
Select * from Kevin.employees;
Select * from jonathan.employees;
Either of A or B
None of the above
58.What is true about the ALL operator used for sub-queries? (Choose the most appropriate answer.)
Returns rows that match all the values in a list/sub-query
Returns rows that match only some values in a list/sub-query
Returns rows only if all the values match in a list/sub-query
All of the above
Returns rows that match all the values in a list/sub-query
Returns rows that match only some values in a list/sub-query
Returns rows only if all the values match in a list/sub-query
All of the above
59. Suppose you select DISTINCT departments and employee salaries in the view query used in above question. What will be the outcome if you try to remove rows from the view dept_sum_vu?
The rows will get removed without any error
Only the first 10 rows will get removed
The rows cannot be deleted.
None of the above
The rows will get removed without any error
Only the first 10 rows will get removed
The rows cannot be deleted.
None of the above
60.What will happen if the SELECT list of the compound queries returns both a VARCHAR2 and a NUMBER data type result?
Oracle will convert them implicitly and return a VARCHAR2 data type result
Oracle will convert them implicitly and return a NUMBER data type result
An ORA error is thrown
None of the above
Oracle will convert them implicitly and return a VARCHAR2 data type result
Oracle will convert them implicitly and return a NUMBER data type result
An ORA error is thrown
None of the above
61. What is true about a schema?
A schema is owned by a database user and has the same name as that user
Each user owns a single schema
Schema objects include database links
All of the above
A schema is owned by a database user and has the same name as that user
Each user owns a single schema
Schema objects include database links
All of the above
62. In which order the values will get inserted with respect to the above INSERT statement?
Location_id , manager_id, department_name , department_id
department_id , department_name , manager_id, location_id
department_id , manager_id, department_name , location_id
department_id , department_name , location_id , manager_id
Location_id , manager_id, department_name , department_id
department_id , department_name , manager_id, location_id
department_id , manager_id, department_name , location_id
department_id , department_name , location_id , manager_id
63. What among the following is true about tables?
A default value is given to a table
A default value can be given to a column of a table during an INSERT statement
Either of A or B
None of the above
A default value is given to a table
A default value can be given to a column of a table during an INSERT statement
Either of A or B
None of the above
65. Which of the below SQL query will display employee names, department, and annual salary?
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal + comm FROM emp;
SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;
Annual salary cannot be queried since the column doesn't exists in the table
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal FROM emp;
SELECT ename, deptno, sal + comm FROM emp;
SELECT ename, deptno, sal + comm FROM emp;
SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;
SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;
Annual salary cannot be queried since the column doesn't exists in the table
66. What is true about the SUBSTR function in Oracle DB?
It extracts a string of determined length
It shows the length of a string as a numeric value
It finds the numeric position of a named character
It trims characters from one (or both) sides from a character string
It extracts a string of determined length
It shows the length of a string as a numeric value
It finds the numeric position of a named character
It trims characters from one (or both) sides from a character string
67. Which of the following SELECT statements lists the highest retail price of all books in the Family category?
SELECT MAX(retail) FROM books WHERE category = 'FAMILY';
SELECT MAX(retail) FROM books HAVING category = 'FAMILY';
SELECT retail FROM books WHERE category = 'FAMILY' HAVING MAX(retail);
None of the above
SELECT MAX(retail) FROM books WHERE category = 'FAMILY';
SELECT MAX(retail) FROM books WHERE category = 'FAMILY';
SELECT MAX(retail) FROM books HAVING category = 'FAMILY';
SELECT MAX(retail) FROM books HAVING category = 'FAMILY';
SELECT retail FROM books WHERE category = 'FAMILY' HAVING MAX(retail);
SELECT retail FROM books WHERE category = 'FAMILY' HAVING MAX(retail);
None of the above
68. Which of the following functions can be used to include NULL values in calculations?
SUM
NVL
MAX
MIN
SUM
NVL
MAX
MIN
69.Which statements best describes the inference drawn from the questions 34 and 35?
There are duplicate values for job codes
The query executes but results produced are unexpected
There are no duplicate values for departments
None of the above
There are duplicate values for job codes
The query executes but results produced are unexpected
There are no duplicate values for departments
None of the above
70. What will be the outcome of the following query?
SELECT length('hi') FROM dual;
2
3
1
hi
2
3
1
hi
Answer(1): A. The ROUND function will round off the value 144.23 according to the specified precision -1 and returns 140.
Examine the structure of the EMPLOYEES table as given and answer the questions 2 and 3 that follow.
SQL> DESC employees
Name Null? Type
----------------------- -------- ----------------
EMPLOYEE_ID NOT NULL NUMBER(6)
FIRST_NAME VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(25)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER VARCHAR2(20)
HIRE_DATE NOT NULL DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(2,2)
MANAGER_ID NUMBER(6)
DEPARTMENT_ID NUMBER(4)
Answer(2): A. Using parenthesis will explicitly change the order of evaluation when INTERSECT is used with other operators.
Answer(3): A, D. On strict grounds, SELECT is a DML command as it is one of the mandatory clauses for manipulation of data present in tables.
Answer(4): A.Select the required from the tables each separated by a
comma.
Answer(5): C. Simple and Complex views are two types of views.
Simple views are based on a subquery that references only one table and doesn't include group
functions, expressions, or GROUP BY clauses. Complex views are based on a subquery that
retrieves or derives data from one or more tables and can contain functions or grouped data.
Answer(6): C. All the combined should have the same no. of columns
when using SET operators. The corresponding columns in the queries that make up a compound
query must be of the same data type group.
Answer:(7) D. Multiple-row subqueries return more than one row of results.Operators that
can be used with multiple-row subqueries include IN, ALL, ANY, and EXISTS.
Answer(8): C. An index can be created to speed up the query process.
DML operations are always slower when indexes exist. Oracle 11g creates an index for PRIMARY
KEY and UNIQUE constraints automatically. An explicit index is created with the CREATE INDEX
command. An index can be used by Oracle 11g automatically if a query criterion or sort
operation is based on a column or an expression used to create the index.
Answer(9): A. Using the SELECT clause is the most common technique
for inserting rows into tables. It reduces the effort of manually keying in values for each
column.
Answer(10): A. View definition can make use of sub-queries.
Answer(11): C. DESCRIBE is used to show the table structure along
with table columns, their data type and nullity
Answer(12): C. Any arithmetic operation with NULL results in a NULL.
Answer()13: C, D.
Answer(14): C. The ANSI SQL: 1999 syntax though not used as much as
the traditional Oracle syntax, it still is one of the syntaxes that may be used in Oracle SQL
Answer(15): B. Correlated subquery references a column in the outer query and executes the subquery once for every row in the outer query while Uncorrelated subquery executes the subquery first and passes the value to the outer query.
Answer(16): D. The constraints on the column must be obeyed while updating its value. In the given UPDATE statement, error will be thrown because the
EMPLOYEE_ID column is a primary key in the EMPLOYEES table which means it cannot be NULL.
Answer(17): D. The WHERE clause can be omitted and the relevant conditions can be accommodated in the JOIN..ON clause itself as shown in the given query
Answer(18): A. Table1 JOIN table2 JOIN table3 is not allowed without the ON clauses for between each JOIN
Answer(19): C. The leading zeroes in the right operand of expression are ignored by Oracle.
Answer(20): A, C. You cannot create a table with the name same as an Oracle Server reserved word.
Answer(21): C. The BETWEEN operator can be used within a sub-query but not with a sub-query.
Answer(22): D. Functions can perform calculations, perform case conversions and type conversions.
Answer(23): A, C. A join can be an inner join,in which the only records returned have a matching record in all tables,or an outer join, in which records can be returned regardless of whether there's a matching record in the join.An outer join is created when records need to be included in the results without having corresponding records in the join tables. These records are matched with NULL records so that they're included in the output.
Answer(24): B. Ff you include the FORCE keyword in the CREATE clause, Oracle 11g creates the view in spite of the absence of any referenced tables. NOFORCE is the default mode for the CREATE VIEW command, which means all tables and columns must be valid, or the view isn't created.
Answer(25): D.
Answer(26): A, B. A user must possess the CREATE TABLE privilege and must have sufficient space to allocate the initial extent to the table segment.
Answer(27): A.
Answer(28): C. The FULL OUTER JOIN returns the non-matched rows from both the tables. A full outer join includes all records from both tables, even if no corresponding record in the other table is found.
Answer(29): B.In SQL, concatenation operator is represented by two vertical bars (||).
Answer(30): C. Parenthesis can be used to group the specific queries in order to change the precedence explicitly. Parentheses are preferred over other SET operators during execution.
Answer(31): A. UNION Returns the combined rows from two queries, sorting them and removing duplicates.
Answer(32): C. The WITH READ ONLY option prevents performing any DML operations on the view. This option is used often when it's important that users can only query data, not make any changes to it.
Answer(33): B, C. NOFORCE is the default mode for the CREATE VIEW command, which means all tables and columns must be valid, or the view isn't created.
Answer(34): B. The OR REPLACE option notifies Oracle 11g that a view with the same name might already exist; if it does, the view's previous version should be replaced with the one defined in the new command.
Answer(35): A. There are basically two types of functions - Single row and Multiple row functions.
Answer(36): B. Character, Date, Conversion, General, Number are the types of Single row functions.
Answer(37): B. Multiple Row functions always work on a group of rows and return one value per group of rows.
Answer(38): C. Group functions are same as Multi row functions and aggregate functions.
Answer(39): A. The COUNT(*) counts the number of rows including duplicates and NULLs. Use DISTINCT and ALL keyword to restrict duplicate and
NULL values.
Answer(40): D. A table must have atleasr one column, its data type specification, and precision (if required).
Answer(41): C. Specifying alias name is good practice to improve the readability of the code and the view queries.
Answer(42): C. COUNT (column) ignores the NULL values but counts the duplicates.
Answer(43): C. The NATURAL JOIN clause implicitly matches all the identical named columns. To add additional conditions the WHERE clause can be used.
Answer(44): A. GROUPING SETS operations can be used to perform multiple GROUP BY aggregations with a single query.
Answer(45): B. The sequence of the column alias not matters much as they don't carry any behavioral attribute.
Answer(46): B. The WHERE clause predicate is optional in DELETE statement. If the WHERE clause is omitted, all the rows of the table will be deleted.
Answer(47): B. Provided the last names in the employees table are in a proper case, the condition WHERE last_name = 'smith' will not be satistified and hence no results will be displayed.
Answer(48): C. As a part of the active or a new transaction, the rows in the table will be deleted.
Answer(49): D. A compound query is one query made up of several queries using different tables.
Answer(50): D.
Answer(51): B. A compound query will by default return rows sorted across all the columns,from left to right in ascending order.The only exception is UNION ALL, where the rows will not be sorted. The only place where an ORDER BY clause is permitted is at the end of the compound query.
Answer(52): C. COUNT(ALL column) ignores the NULL values but counts the duplicates.
Answer(53): A.
Answer(54): B. COUNT (DISTINCT column) counts the distinct not null values.
Answer(55): C. The VARIANCE function accepts single numeric argument as the column name and returns variance of all the column values considering
NULLs.
Answer(56): D. HAVING Clause is used for restricting group results. You use the HAVING clause to specify the groups that are to be displayed, thus further restricting the groups on the basis of aggregate information. The HAVING clause can precede the GROUP BY clause, but it is recommended that you place the GROUP BY clause first because it is more logical. Groups are formed and group functions are calculated before the HAVING clause is applied to the groups in the SELECT list.
Answer(57): B.
Answer(58): C. '> ALL' More than the highest value returned by the subquery. '< ALL' Less than the lowest value returned by the subquery. '< ANY' Less than the highest value returned by the subquery. '> ANY' More than the lowest value returned by the subquery. '= ANY' Equal to any value returned by the subquery (same as IN). '[NOT] EXISTS' Row must match a value in the subquery.
Answer(59): C. The view DEPT_SUM_VU is still a complex view as it uses DISTINCT keyword. Hence, DML operations are not possible on it.
Answer(60): C. Oracle does not convert data types implicitly.
Answer(61): D. The user space in a database is known as schema. A schema contains the objects which are owned or accessed by the user. Each user can have single schema of its own.
Answer(62): B. If the columns are mentioned in the INSERT clause, the VALUES keyword should contain values in the same order
Answer(63): B. A default value can be specified for a column during the definition using the keyword DEFAULT.
Answer(65): C. Use numeric expressions in SELECT statement to perform basic arithmetic calculations.
Answer(66): A. The SUBSTR(string, x, y) function accepts three parameters and returns a string consisting of the number of characters extracted from the source string, beginning at the specified start position (x). When position is positive, then the function counts from the beginning of string to find the first character. When position is negative, then the function counts backward from the end of string.
Answer(67): A. Since the category FAMILY has to be restricted before grouping, table rows must be filtered using WHERE clause and not HAVING clause.
Answer(68): B. NVL is a general function to provide alternate values to the NULL values. It can really make a difference in arithmetic calculations using AVG, STDDEV and VARIANCE group functions.
Answer(69): C. As the combination of the job codes and departments is unique, there are no duplicates obtained.
Answer(70): A. the LENGTH function simply gives the length of the string.
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2515,
"s": 2463,
"text": "1. What will be the outcome of the following query?"
},
{
"code": null,
"e": 2550,
"s": 2515,
"text": "SELECT ROUND(144.23,-1) FROM dual;"
},
{
"code": null,
"e": 2568,
"s": 2550,
"text": "\n140\n144\n150\n100\n"
},
{
"code": null,
"e": 2572,
"s": 2568,
"text": "140"
},
{
"code": null,
"e": 2576,
"s": 2572,
"text": "144"
},
{
"code": null,
"e": 2580,
"s": 2576,
"text": "150"
},
{
"code": null,
"e": 2584,
"s": 2580,
"text": "100"
},
{
"code": null,
"e": 2652,
"s": 2584,
"text": "2.In which of the following cases, parenthesis should be specified?"
},
{
"code": null,
"e": 2789,
"s": 2652,
"text": "\nWhen INTERSECT is used with other set operators\nWhen UNION is used with UNION ALL\nWhen MINUS is used for the queries\nNone of the above\n"
},
{
"code": null,
"e": 2837,
"s": 2789,
"text": "When INTERSECT is used with other set operators"
},
{
"code": null,
"e": 2871,
"s": 2837,
"text": "When UNION is used with UNION ALL"
},
{
"code": null,
"e": 2906,
"s": 2871,
"text": "When MINUS is used for the queries"
},
{
"code": null,
"e": 2924,
"s": 2906,
"text": "None of the above"
},
{
"code": null,
"e": 2987,
"s": 2924,
"text": "3. Which of the following are DML commands in Oracle Database?"
},
{
"code": null,
"e": 3022,
"s": 2987,
"text": "\nSELECT\nGROUP BY\nINTERSECT\nINSERT\n"
},
{
"code": null,
"e": 3029,
"s": 3022,
"text": "SELECT"
},
{
"code": null,
"e": 3038,
"s": 3029,
"text": "GROUP BY"
},
{
"code": null,
"e": 3048,
"s": 3038,
"text": "INTERSECT"
},
{
"code": null,
"e": 3055,
"s": 3048,
"text": "INSERT"
},
{
"code": null,
"e": 3151,
"s": 3055,
"text": "4. Write a query to display employee details (Name, Department, Salary and Job) from EMP table."
},
{
"code": null,
"e": 3299,
"s": 3151,
"text": "\nSELECT ename, deptno, sal, job FROM emp;\nSELECT * FROM emp;\nSELECT DISTINCT ename, deptno, sal, job FROM emp;\nSELECT ename, deptno, sal FROM emp;\n"
},
{
"code": null,
"e": 3340,
"s": 3299,
"text": "SELECT ename, deptno, sal, job FROM emp;"
},
{
"code": null,
"e": 3381,
"s": 3340,
"text": "SELECT ename, deptno, sal, job FROM emp;"
},
{
"code": null,
"e": 3400,
"s": 3381,
"text": "SELECT * FROM emp;"
},
{
"code": null,
"e": 3419,
"s": 3400,
"text": "SELECT * FROM emp;"
},
{
"code": null,
"e": 3469,
"s": 3419,
"text": "SELECT DISTINCT ename, deptno, sal, job FROM emp;"
},
{
"code": null,
"e": 3519,
"s": 3469,
"text": "SELECT DISTINCT ename, deptno, sal, job FROM emp;"
},
{
"code": null,
"e": 3555,
"s": 3519,
"text": "SELECT ename, deptno, sal FROM emp;"
},
{
"code": null,
"e": 3591,
"s": 3555,
"text": "SELECT ename, deptno, sal FROM emp;"
},
{
"code": null,
"e": 3648,
"s": 3591,
"text": "5.What among the following are different types of Views?"
},
{
"code": null,
"e": 3708,
"s": 3648,
"text": "\nSimple views\nComplex views\nBoth A and B\nNone of the above\n"
},
{
"code": null,
"e": 3721,
"s": 3708,
"text": "Simple views"
},
{
"code": null,
"e": 3735,
"s": 3721,
"text": "Complex views"
},
{
"code": null,
"e": 3748,
"s": 3735,
"text": "Both A and B"
},
{
"code": null,
"e": 3766,
"s": 3748,
"text": "None of the above"
},
{
"code": null,
"e": 3806,
"s": 3766,
"text": "6.What is true about the SET operators?"
},
{
"code": null,
"e": 4092,
"s": 3806,
"text": "\nThe SELECT clause should have the same number of columns, data types can be different\nThe SET operators can be used only for combining two queries\nThe data type of each column in the 2nd query must match the data type of its corresponding column in the first query.\nNone of the above\n"
},
{
"code": null,
"e": 4178,
"s": 4092,
"text": "The SELECT clause should have the same number of columns, data types can be different"
},
{
"code": null,
"e": 4239,
"s": 4178,
"text": "The SET operators can be used only for combining two queries"
},
{
"code": null,
"e": 4358,
"s": 4239,
"text": "The data type of each column in the 2nd query must match the data type of its corresponding column in the first query."
},
{
"code": null,
"e": 4376,
"s": 4358,
"text": "None of the above"
},
{
"code": null,
"e": 4451,
"s": 4376,
"text": "7.Which of the following multi-row operators can be used with a sub-query?"
},
{
"code": null,
"e": 4481,
"s": 4451,
"text": "\nIN\nANY\nALL\nAll of the above\n"
},
{
"code": null,
"e": 4484,
"s": 4481,
"text": "IN"
},
{
"code": null,
"e": 4488,
"s": 4484,
"text": "ANY"
},
{
"code": null,
"e": 4492,
"s": 4488,
"text": "ALL"
},
{
"code": null,
"e": 4509,
"s": 4492,
"text": "All of the above"
},
{
"code": null,
"e": 4541,
"s": 4509,
"text": "8.\tWhen a table can be created?"
},
{
"code": null,
"e": 4711,
"s": 4541,
"text": "\nWhen the database is not being used by any user\nWhen the database is newly created\nIt can be created any time, even when a user is using the database\nNone of the above\n"
},
{
"code": null,
"e": 4759,
"s": 4711,
"text": "When the database is not being used by any user"
},
{
"code": null,
"e": 4794,
"s": 4759,
"text": "When the database is newly created"
},
{
"code": null,
"e": 4861,
"s": 4794,
"text": "It can be created any time, even when a user is using the database"
},
{
"code": null,
"e": 4879,
"s": 4861,
"text": "None of the above"
},
{
"code": null,
"e": 5013,
"s": 4879,
"text": "9. Which among the following is a common technique for inserting rows into a table? (Choose the most sensible and appropriate answer)"
},
{
"code": null,
"e": 5123,
"s": 5013,
"text": "\nUsing SELECT clause\nManually typing each value into the INSERT clause\nUsing SET operators\nNone of the above\n"
},
{
"code": null,
"e": 5143,
"s": 5123,
"text": "Using SELECT clause"
},
{
"code": null,
"e": 5193,
"s": 5143,
"text": "Manually typing each value into the INSERT clause"
},
{
"code": null,
"e": 5213,
"s": 5193,
"text": "Using SET operators"
},
{
"code": null,
"e": 5231,
"s": 5213,
"text": "None of the above"
},
{
"code": null,
"e": 5282,
"s": 5231,
"text": "10.\tWhat among the following is true about a View?"
},
{
"code": null,
"e": 5528,
"s": 5282,
"text": "\nSub-queries can be embedded in a CREATE VIEW statement\nA sub-query used in the CREATE VIEW statement has to have a simple SELECT syntax\nYou cannot use a WHERE clause in a sub-query when it is used in the CREATE VIEW statement\nNone of the above\n"
},
{
"code": null,
"e": 5583,
"s": 5528,
"text": "Sub-queries can be embedded in a CREATE VIEW statement"
},
{
"code": null,
"e": 5664,
"s": 5583,
"text": "A sub-query used in the CREATE VIEW statement has to have a simple SELECT syntax"
},
{
"code": null,
"e": 5754,
"s": 5664,
"text": "You cannot use a WHERE clause in a sub-query when it is used in the CREATE VIEW statement"
},
{
"code": null,
"e": 5772,
"s": 5754,
"text": "None of the above"
},
{
"code": null,
"e": 5842,
"s": 5772,
"text": "11. Predict the output when below statement is executed in SQL* Plus?"
},
{
"code": null,
"e": 5851,
"s": 5842,
"text": "DESC emp"
},
{
"code": null,
"e": 6076,
"s": 5851,
"text": "\nRaises error \"SP2-0042: unknown command \"desc emp\" - rest of line ignored.\"\nLists the columns of EMP table\nLists the EMP table columns, their data type and nullity\nLists the columns of EMP table along with their data types\n"
},
{
"code": null,
"e": 6152,
"s": 6076,
"text": "Raises error \"SP2-0042: unknown command \"desc emp\" - rest of line ignored.\""
},
{
"code": null,
"e": 6183,
"s": 6152,
"text": "Lists the columns of EMP table"
},
{
"code": null,
"e": 6240,
"s": 6183,
"text": "Lists the EMP table columns, their data type and nullity"
},
{
"code": null,
"e": 6299,
"s": 6240,
"text": "Lists the columns of EMP table along with their data types"
},
{
"code": null,
"e": 6354,
"s": 6299,
"text": "12. What will be the outcome of the query given below?"
},
{
"code": null,
"e": 6385,
"s": 6354,
"text": "SELECT 100+NULL+999 FROM dual;"
},
{
"code": null,
"e": 6405,
"s": 6385,
"text": "\n100\n999\nNULL\n1099\n"
},
{
"code": null,
"e": 6409,
"s": 6405,
"text": "100"
},
{
"code": null,
"e": 6413,
"s": 6409,
"text": "999"
},
{
"code": null,
"e": 6418,
"s": 6413,
"text": "NULL"
},
{
"code": null,
"e": 6423,
"s": 6418,
"text": "1099"
},
{
"code": null,
"e": 6563,
"s": 6423,
"text": "13.\tWith respect to the given query, if the JOIN used is replaced with NATURAL JOIN, it throws an error. What is the reason for this error?"
},
{
"code": null,
"e": 6892,
"s": 6563,
"text": "\nWhen the NATURAL JOIN is used, a WHERE clause is mandatory, omitting which gives an error\n\nThe ON clause should be replaced with the USING clause\n\nThe words NATURAL, JOIN and USING are mutually exclusively in the context of the same join clause\n\nA query can't combine the NATURAL JOIN and ON (or USING) clauses while joining.\n\n"
},
{
"code": null,
"e": 6983,
"s": 6892,
"text": "When the NATURAL JOIN is used, a WHERE clause is mandatory, omitting which gives an error\n"
},
{
"code": null,
"e": 7039,
"s": 6983,
"text": "The ON clause should be replaced with the USING clause\n"
},
{
"code": null,
"e": 7138,
"s": 7039,
"text": "The words NATURAL, JOIN and USING are mutually exclusively in the context of the same join clause\n"
},
{
"code": null,
"e": 7219,
"s": 7138,
"text": "A query can't combine the NATURAL JOIN and ON (or USING) clauses while joining.\n"
},
{
"code": null,
"e": 7317,
"s": 7219,
"text": "14.Which of the following syntax models is used in extensively in the software systems worldwide?"
},
{
"code": null,
"e": 7440,
"s": 7317,
"text": "\nANSI SQL: 1999\nBoth traditional Oracle syntax and the ANSI SQL: 1999 syntax\nTraditional Oracle syntax\nAll of the options\n"
},
{
"code": null,
"e": 7455,
"s": 7440,
"text": "ANSI SQL: 1999"
},
{
"code": null,
"e": 7516,
"s": 7455,
"text": "Both traditional Oracle syntax and the ANSI SQL: 1999 syntax"
},
{
"code": null,
"e": 7542,
"s": 7516,
"text": "Traditional Oracle syntax"
},
{
"code": null,
"e": 7561,
"s": 7542,
"text": "All of the options"
},
{
"code": null,
"e": 7608,
"s": 7561,
"text": " 15.What is true about co-related sub-queries?"
},
{
"code": null,
"e": 7993,
"s": 7608,
"text": "\nThe tables used in the main query are also used in a co-related sub-query\nThe sub-queries which reference a column used in the main query are called co-related sub-queries\nThe sub-queries which are written without parenthesis are called co-related sub-queries\nThe sub-queries which mandatorily use different tables than those used in the main query are called co-related sub-queries\n"
},
{
"code": null,
"e": 8067,
"s": 7993,
"text": "The tables used in the main query are also used in a co-related sub-query"
},
{
"code": null,
"e": 8165,
"s": 8067,
"text": "The sub-queries which reference a column used in the main query are called co-related sub-queries"
},
{
"code": null,
"e": 8253,
"s": 8165,
"text": "The sub-queries which are written without parenthesis are called co-related sub-queries"
},
{
"code": null,
"e": 8376,
"s": 8253,
"text": "The sub-queries which mandatorily use different tables than those used in the main query are called co-related sub-queries"
},
{
"code": null,
"e": 8424,
"s": 8376,
"text": " 16. You issue an UPDATE statement as follows:"
},
{
"code": null,
"e": 8493,
"s": 8424,
"text": "UPDATE employees \nSET employee_id = NULL;\nWHERE job_id = 'CLERK';"
},
{
"code": null,
"e": 8621,
"s": 8493,
"text": "What will be the outcome of the above statement? (Here the column EMPLOYEE_ID is marked as mandatory by putting a constraint)"
},
{
"code": null,
"e": 8823,
"s": 8621,
"text": "\nThe first column of the data set will get updated to NULL\nThe 3rd column of the first row will get updated to NULL\nThe 3rd column of all the rows will get updated to NULL\nAnd ORA error will be thrown\n"
},
{
"code": null,
"e": 8881,
"s": 8823,
"text": "The first column of the data set will get updated to NULL"
},
{
"code": null,
"e": 8938,
"s": 8881,
"text": "The 3rd column of the first row will get updated to NULL"
},
{
"code": null,
"e": 8994,
"s": 8938,
"text": "The 3rd column of all the rows will get updated to NULL"
},
{
"code": null,
"e": 9023,
"s": 8994,
"text": "And ORA error will be thrown"
},
{
"code": null,
"e": 9078,
"s": 9023,
"text": "17.What is true with respect to the query given above?"
},
{
"code": null,
"e": 9364,
"s": 9078,
"text": "\nIt gives an ORA error as the mandatory WHERE clause is not present\nThe JOIN..ON clause can't contain more than one condition\nThe query ignores the last condition and executes without an ORA error\nThe JOIN..ON clause can be written in the form given above for putting more conditions.\n"
},
{
"code": null,
"e": 9431,
"s": 9364,
"text": "It gives an ORA error as the mandatory WHERE clause is not present"
},
{
"code": null,
"e": 9489,
"s": 9431,
"text": "The JOIN..ON clause can't contain more than one condition"
},
{
"code": null,
"e": 9560,
"s": 9489,
"text": "The query ignores the last condition and executes without an ORA error"
},
{
"code": null,
"e": 9648,
"s": 9560,
"text": "The JOIN..ON clause can be written in the form given above for putting more conditions."
},
{
"code": null,
"e": 9682,
"s": 9648,
"text": "18.\tConsider the following query."
},
{
"code": null,
"e": 9797,
"s": 9682,
"text": "SELECT e.job_id , e.first_name, d.department_id \nFROM departments D JOIN employees e JOIN BONUS b\nUSING (job_id );"
},
{
"code": null,
"e": 9862,
"s": 9797,
"text": "This query results in an error. What is the reason of the error?"
},
{
"code": null,
"e": 10053,
"s": 9862,
"text": "\nA JOINOUSING can happen only between two tables at a time\n\nUSING clause in the query doesn't have any column from the department \n\nThere is no WHERE clause in the query\n\nNone of the above\n\n"
},
{
"code": null,
"e": 10112,
"s": 10053,
"text": "A JOINOUSING can happen only between two tables at a time\n"
},
{
"code": null,
"e": 10184,
"s": 10112,
"text": "USING clause in the query doesn't have any column from the department \n"
},
{
"code": null,
"e": 10223,
"s": 10184,
"text": "There is no WHERE clause in the query\n"
},
{
"code": null,
"e": 10242,
"s": 10223,
"text": "None of the above\n"
},
{
"code": null,
"e": 10284,
"s": 10242,
"text": "19. Predict the output of the below query"
},
{
"code": null,
"e": 10312,
"s": 10284,
"text": "SELECT 50 || 0001\nFROM dual"
},
{
"code": null,
"e": 10333,
"s": 10312,
"text": "\n500001\n51\n501\n5001\n"
},
{
"code": null,
"e": 10340,
"s": 10333,
"text": "500001"
},
{
"code": null,
"e": 10343,
"s": 10340,
"text": "51"
},
{
"code": null,
"e": 10347,
"s": 10343,
"text": "501"
},
{
"code": null,
"e": 10352,
"s": 10347,
"text": "5001"
},
{
"code": null,
"e": 10446,
"s": 10352,
"text": "20.\tYou create a table and name it as COUNT. What will be the outcome of CREATE TABLE script?"
},
{
"code": null,
"e": 10648,
"s": 10446,
"text": "\nThe table will not be created\nThe table will be created and an underscore will be added automatically to the name COUNT_\nAn ORA error will be thrown\nThe table COUNT will be created without any errors\n"
},
{
"code": null,
"e": 10678,
"s": 10648,
"text": "The table will not be created"
},
{
"code": null,
"e": 10769,
"s": 10678,
"text": "The table will be created and an underscore will be added automatically to the name COUNT_"
},
{
"code": null,
"e": 10797,
"s": 10769,
"text": "An ORA error will be thrown"
},
{
"code": null,
"e": 10848,
"s": 10797,
"text": "The table COUNT will be created without any errors"
},
{
"code": null,
"e": 10902,
"s": 10848,
"text": " 21.\tWhat will be the outcome of the following query?"
},
{
"code": null,
"e": 11086,
"s": 10902,
"text": "SELECT *\nFROM employees\nWHERE salary BETWEEN (SELECT max(salary)\n\t\t\tFROM employees\n\t\t\tWHERE department_id = 100) \nAND (SELECT min(salary) FROM employees where department_id = 100); "
},
{
"code": null,
"e": 11149,
"s": 11086,
"text": "This query returns an error. What is the reason for the error?"
},
{
"code": null,
"e": 11406,
"s": 11149,
"text": "\nA GROUP BY clause should be used as the function MAX is used\nBoth the sub-queries cannot use the same department ID in the same outer query\nBETWEEN operator cannot be used with a sub-query\nSELECT clause should have columns mentioned and not a asterix (*)\n"
},
{
"code": null,
"e": 11467,
"s": 11406,
"text": "A GROUP BY clause should be used as the function MAX is used"
},
{
"code": null,
"e": 11546,
"s": 11467,
"text": "Both the sub-queries cannot use the same department ID in the same outer query"
},
{
"code": null,
"e": 11595,
"s": 11546,
"text": "BETWEEN operator cannot be used with a sub-query"
},
{
"code": null,
"e": 11661,
"s": 11595,
"text": "SELECT clause should have columns mentioned and not a asterix (*)"
},
{
"code": null,
"e": 11720,
"s": 11661,
"text": "22. Which of the following is not a property of functions?"
},
{
"code": null,
"e": 11824,
"s": 11720,
"text": "\nPerform calculations on data\nConvert column data types\nModify individual data items\nNone of the above\n"
},
{
"code": null,
"e": 11853,
"s": 11824,
"text": "Perform calculations on data"
},
{
"code": null,
"e": 11879,
"s": 11853,
"text": "Convert column data types"
},
{
"code": null,
"e": 11908,
"s": 11879,
"text": "Modify individual data items"
},
{
"code": null,
"e": 11926,
"s": 11908,
"text": "None of the above"
},
{
"code": null,
"e": 12000,
"s": 11926,
"text": "23.What is true with respect to INNER JOINS and OUTER JOINS in Oracle DB?"
},
{
"code": null,
"e": 12205,
"s": 12000,
"text": "\nINNER JOIN returns only the rows that are matched\nOUTER JOIN returns only the rows that are not matched\nOUTER JOIN returns the rows that are matched as well as those which do not match\nNone of the above\n"
},
{
"code": null,
"e": 12255,
"s": 12205,
"text": "INNER JOIN returns only the rows that are matched"
},
{
"code": null,
"e": 12309,
"s": 12255,
"text": "OUTER JOIN returns only the rows that are not matched"
},
{
"code": null,
"e": 12390,
"s": 12309,
"text": "OUTER JOIN returns the rows that are matched as well as those which do not match"
},
{
"code": null,
"e": 12408,
"s": 12390,
"text": "None of the above"
},
{
"code": null,
"e": 12495,
"s": 12408,
"text": "24.\tWhich of the following can create a view even if the base table(s) does not exist?"
},
{
"code": null,
"e": 12538,
"s": 12495,
"text": "\nNOFORCE\n\nFORCE\n\nOR REPLACE\n\nCREATE VIEW\n\n"
},
{
"code": null,
"e": 12547,
"s": 12538,
"text": "NOFORCE\n"
},
{
"code": null,
"e": 12554,
"s": 12547,
"text": "FORCE\n"
},
{
"code": null,
"e": 12566,
"s": 12554,
"text": "OR REPLACE\n"
},
{
"code": null,
"e": 12579,
"s": 12566,
"text": "CREATE VIEW\n"
},
{
"code": null,
"e": 12664,
"s": 12579,
"text": "25.\tWhich of the following ANSI SQL: 1999 join syntax joins are supported by Oracle?"
},
{
"code": null,
"e": 12726,
"s": 12664,
"text": "\nCartesian products\nNatural joins \nFull OUTER join\nEquijoins\n"
},
{
"code": null,
"e": 12745,
"s": 12726,
"text": "Cartesian products"
},
{
"code": null,
"e": 12760,
"s": 12745,
"text": "Natural joins "
},
{
"code": null,
"e": 12776,
"s": 12760,
"text": "Full OUTER join"
},
{
"code": null,
"e": 12786,
"s": 12776,
"text": "Equijoins"
},
{
"code": null,
"e": 12860,
"s": 12786,
"text": "26.\tWhat among the following are the pre-requisites for creating a table?"
},
{
"code": null,
"e": 12939,
"s": 12860,
"text": "\nCREATE TABLE privilege\n\nStorage space\n\nData in the table\n\nNone of the above\n\n"
},
{
"code": null,
"e": 12963,
"s": 12939,
"text": "CREATE TABLE privilege\n"
},
{
"code": null,
"e": 12978,
"s": 12963,
"text": "Storage space\n"
},
{
"code": null,
"e": 12997,
"s": 12978,
"text": "Data in the table\n"
},
{
"code": null,
"e": 13016,
"s": 12997,
"text": "None of the above\n"
},
{
"code": null,
"e": 13061,
"s": 13016,
"text": "27.\tWhat is the syntax for creating a table?"
},
{
"code": null,
"e": 13311,
"s": 13061,
"text": "\nCREATE TABLE [schema.] table (column datatype [DEFAULT expr] [,..] ); \n\nCREATE TABLE INTO [schema.] table (column datatype [DEFAULT expr] [,..] ); \n\nCREATE TABLE VALUES [schema.] table (column datatype [DEFAULT expr] [,..] ); \n\nNone of the above\n\n"
},
{
"code": null,
"e": 13383,
"s": 13311,
"text": "CREATE TABLE [schema.] table (column datatype [DEFAULT expr] [,..] ); \n"
},
{
"code": null,
"e": 13460,
"s": 13383,
"text": "CREATE TABLE INTO [schema.] table (column datatype [DEFAULT expr] [,..] ); \n"
},
{
"code": null,
"e": 13540,
"s": 13460,
"text": "CREATE TABLE VALUES [schema.] table (column datatype [DEFAULT expr] [,..] ); \n"
},
{
"code": null,
"e": 13559,
"s": 13540,
"text": "None of the above\n"
},
{
"code": null,
"e": 13803,
"s": 13559,
"text": "28.You need to display all the non-matching rows from the EMPLOYEES table and the non-matching rows from the DEPARTMENT table without giving a Cartesian product of rows between them. Which of the following queries will give the desired output?"
},
{
"code": null,
"e": 14130,
"s": 13803,
"text": "\nSELECT *\nFROM employees e, department d\nWHERE e.department_id = d.department_id ; \nSELECT *\nFROM employees e NATURAL JOIN department d; \nSELECT *\nFROM employees e FULL OUTER JOIN department d\nON e.department_id = d.department_id ; \nSELECT *\nFROM employees e JOIN department d\nON ( e.department_id > d.department_id ) ; \n"
},
{
"code": null,
"e": 14214,
"s": 14130,
"text": "SELECT *\nFROM employees e, department d\nWHERE e.department_id = d.department_id ; "
},
{
"code": null,
"e": 14298,
"s": 14214,
"text": "SELECT *\nFROM employees e, department d\nWHERE e.department_id = d.department_id ; "
},
{
"code": null,
"e": 14352,
"s": 14298,
"text": "SELECT *\nFROM employees e NATURAL JOIN department d; "
},
{
"code": null,
"e": 14406,
"s": 14352,
"text": "SELECT *\nFROM employees e NATURAL JOIN department d; "
},
{
"code": null,
"e": 14503,
"s": 14406,
"text": "SELECT *\nFROM employees e FULL OUTER JOIN department d\nON e.department_id = d.department_id ; "
},
{
"code": null,
"e": 14600,
"s": 14503,
"text": "SELECT *\nFROM employees e FULL OUTER JOIN department d\nON e.department_id = d.department_id ; "
},
{
"code": null,
"e": 14690,
"s": 14600,
"text": "SELECT *\nFROM employees e JOIN department d\nON ( e.department_id > d.department_id ) ; "
},
{
"code": null,
"e": 14780,
"s": 14690,
"text": "SELECT *\nFROM employees e JOIN department d\nON ( e.department_id > d.department_id ) ; "
},
{
"code": null,
"e": 14878,
"s": 14780,
"text": "29. Which of the below alphanumeric characters are used to signify concatenation operator in SQL?"
},
{
"code": null,
"e": 14890,
"s": 14878,
"text": "\n+\n||\n-\n::\n"
},
{
"code": null,
"e": 14892,
"s": 14890,
"text": "+"
},
{
"code": null,
"e": 14895,
"s": 14892,
"text": "||"
},
{
"code": null,
"e": 14897,
"s": 14895,
"text": "-"
},
{
"code": null,
"e": 14900,
"s": 14897,
"text": "::"
},
{
"code": null,
"e": 15014,
"s": 14900,
"text": "30.What is the best way to change the precedence of SET operators given the fact that they have equal precedence?"
},
{
"code": null,
"e": 15206,
"s": 15014,
"text": "\nThe order of usage of the SET operators can be changed to change the precedence \nThe equal precedence cannot be changed \nParenthesis can be used to change the precedence \nNone of the above \n"
},
{
"code": null,
"e": 15287,
"s": 15206,
"text": "The order of usage of the SET operators can be changed to change the precedence "
},
{
"code": null,
"e": 15327,
"s": 15287,
"text": "The equal precedence cannot be changed "
},
{
"code": null,
"e": 15377,
"s": 15327,
"text": "Parenthesis can be used to change the precedence "
},
{
"code": null,
"e": 15396,
"s": 15377,
"text": "None of the above "
},
{
"code": null,
"e": 15451,
"s": 15396,
"text": "31.What will be displayed in the result of this query?"
},
{
"code": null,
"e": 15611,
"s": 15451,
"text": "\nIt will display distinct department id(s) contained jointly in EMPLOYEES and DEPARTMENTS table \nIt will throw ORA error \nNo rows selected \nNone of the above \n"
},
{
"code": null,
"e": 15707,
"s": 15611,
"text": "It will display distinct department id(s) contained jointly in EMPLOYEES and DEPARTMENTS table "
},
{
"code": null,
"e": 15732,
"s": 15707,
"text": "It will throw ORA error "
},
{
"code": null,
"e": 15750,
"s": 15732,
"text": "No rows selected "
},
{
"code": null,
"e": 15769,
"s": 15750,
"text": "None of the above "
},
{
"code": null,
"e": 15864,
"s": 15769,
"text": "32.\tWhich of the following commands ensures that no DML operations can be performed on a view?"
},
{
"code": null,
"e": 15906,
"s": 15864,
"text": "\nNOFORCE\nFORCE\nWITH READ ONLY\nOR REPLACE\n"
},
{
"code": null,
"e": 15914,
"s": 15906,
"text": "NOFORCE"
},
{
"code": null,
"e": 15920,
"s": 15914,
"text": "FORCE"
},
{
"code": null,
"e": 15935,
"s": 15920,
"text": "WITH READ ONLY"
},
{
"code": null,
"e": 15946,
"s": 15935,
"text": "OR REPLACE"
},
{
"code": null,
"e": 16014,
"s": 15946,
"text": "33.\tWhat is true about the NOFORCE option in CREATE VIEW statement?"
},
{
"code": null,
"e": 16187,
"s": 16014,
"text": "\nIt creates a view even if the base table(s) does not exist.\nIt creates a view only if the base table(s) exists.\nIt is the default while creating a view.\nNone of the above\n"
},
{
"code": null,
"e": 16247,
"s": 16187,
"text": "It creates a view even if the base table(s) does not exist."
},
{
"code": null,
"e": 16299,
"s": 16247,
"text": "It creates a view only if the base table(s) exists."
},
{
"code": null,
"e": 16340,
"s": 16299,
"text": "It is the default while creating a view."
},
{
"code": null,
"e": 16358,
"s": 16340,
"text": "None of the above"
},
{
"code": null,
"e": 16405,
"s": 16358,
"text": "34.\tWhat is true about the OR REPLACE keyword?"
},
{
"code": null,
"e": 16596,
"s": 16405,
"text": "\nObject privileges are lost when a view is created using this keyword\n\nThere is no need of re granting the object privileges previously granted on it\n\nNeither of A nor B\n\nNone of the above\n\n"
},
{
"code": null,
"e": 16666,
"s": 16596,
"text": "Object privileges are lost when a view is created using this keyword\n"
},
{
"code": null,
"e": 16746,
"s": 16666,
"text": "There is no need of re granting the object privileges previously granted on it\n"
},
{
"code": null,
"e": 16766,
"s": 16746,
"text": "Neither of A nor B\n"
},
{
"code": null,
"e": 16785,
"s": 16766,
"text": "None of the above\n"
},
{
"code": null,
"e": 16849,
"s": 16785,
"text": "35. What among the following is a type of Oracle SQL functions?"
},
{
"code": null,
"e": 16948,
"s": 16849,
"text": "\nMultiple-row functions\nSingle column functions\nSingle value functions\nMultiple columns functions\n"
},
{
"code": null,
"e": 16971,
"s": 16948,
"text": "Multiple-row functions"
},
{
"code": null,
"e": 16995,
"s": 16971,
"text": "Single column functions"
},
{
"code": null,
"e": 17018,
"s": 16995,
"text": "Single value functions"
},
{
"code": null,
"e": 17045,
"s": 17018,
"text": "Multiple columns functions"
},
{
"code": null,
"e": 17108,
"s": 17045,
"text": "36. What among the following is a type of single-row function?"
},
{
"code": null,
"e": 17141,
"s": 17108,
"text": "\nVARCHAR2\nCharacter\nLONG\nNULLIF\n"
},
{
"code": null,
"e": 17150,
"s": 17141,
"text": "VARCHAR2"
},
{
"code": null,
"e": 17160,
"s": 17150,
"text": "Character"
},
{
"code": null,
"e": 17165,
"s": 17160,
"text": "LONG"
},
{
"code": null,
"e": 17172,
"s": 17165,
"text": "NULLIF"
},
{
"code": null,
"e": 17235,
"s": 17172,
"text": "37. What is the most appropriate about Multiple Row Functions?"
},
{
"code": null,
"e": 17472,
"s": 17235,
"text": "\nThey return multiple values per each row. \nThey return one result per group of rows and can manipulate groups of rows. \nThey return one result per row and can manipulate groups of rows. \nThey return multiple values per a group of row.\n"
},
{
"code": null,
"e": 17515,
"s": 17472,
"text": "They return multiple values per each row. "
},
{
"code": null,
"e": 17592,
"s": 17515,
"text": "They return one result per group of rows and can manipulate groups of rows. "
},
{
"code": null,
"e": 17659,
"s": 17592,
"text": "They return one result per row and can manipulate groups of rows. "
},
{
"code": null,
"e": 17707,
"s": 17659,
"text": "They return multiple values per a group of row."
},
{
"code": null,
"e": 17767,
"s": 17707,
"text": "38. Which of the following are also called Group functions?"
},
{
"code": null,
"e": 17859,
"s": 17767,
"text": "\nSingle row functions\nMulti group functions\nMultiple row functions\nSingle group functions.\n"
},
{
"code": null,
"e": 17880,
"s": 17859,
"text": "Single row functions"
},
{
"code": null,
"e": 17902,
"s": 17880,
"text": "Multi group functions"
},
{
"code": null,
"e": 17925,
"s": 17902,
"text": "Multiple row functions"
},
{
"code": null,
"e": 17949,
"s": 17925,
"text": "Single group functions."
},
{
"code": null,
"e": 18081,
"s": 17949,
"text": "39. A table T_COUNT has 12 number values as 1, 2, 3, 32, 1, 1, null, 24, 12, null, 32, null. Predict the output of the below query."
},
{
"code": null,
"e": 18112,
"s": 18081,
"text": "SELECT COUNT (*) FROM t_count;"
},
{
"code": null,
"e": 18192,
"s": 18112,
"text": "\n12\n6\n9\nThrows exception because COUNT function doesn't works with NULL values\n"
},
{
"code": null,
"e": 18195,
"s": 18192,
"text": "12"
},
{
"code": null,
"e": 18197,
"s": 18195,
"text": "6"
},
{
"code": null,
"e": 18199,
"s": 18197,
"text": "9"
},
{
"code": null,
"e": 18270,
"s": 18199,
"text": "Throws exception because COUNT function doesn't works with NULL values"
},
{
"code": null,
"e": 18338,
"s": 18270,
"text": "40.\tPick the element which you must specify while creating a table."
},
{
"code": null,
"e": 18398,
"s": 18338,
"text": "\nColumn name\nColumn Data type\nColumn size\nAll of the above\n"
},
{
"code": null,
"e": 18410,
"s": 18398,
"text": "Column name"
},
{
"code": null,
"e": 18427,
"s": 18410,
"text": "Column Data type"
},
{
"code": null,
"e": 18439,
"s": 18427,
"text": "Column size"
},
{
"code": null,
"e": 18456,
"s": 18439,
"text": "All of the above"
},
{
"code": null,
"e": 18510,
"s": 18456,
"text": "41.\tWhat can be said about the statement given above?"
},
{
"code": null,
"e": 18690,
"s": 18510,
"text": "\nAlternative names have been given for the view\n\nGiving alternative names is mandatory if any column is derived from a function or an expression\n\nBoth A and B\n\nNone of the above\n\n"
},
{
"code": null,
"e": 18738,
"s": 18690,
"text": "Alternative names have been given for the view\n"
},
{
"code": null,
"e": 18835,
"s": 18738,
"text": "Giving alternative names is mandatory if any column is derived from a function or an expression\n"
},
{
"code": null,
"e": 18849,
"s": 18835,
"text": "Both A and B\n"
},
{
"code": null,
"e": 18868,
"s": 18849,
"text": "None of the above\n"
},
{
"code": null,
"e": 19000,
"s": 18868,
"text": "42. A table T_COUNT has 12 number values as 1, 2, 3, 32, 1, 1, null, 24, 12, null, 32, null. Predict the output of the below query."
},
{
"code": null,
"e": 19033,
"s": 19000,
"text": "SELECT COUNT (num) FROM t_count;"
},
{
"code": null,
"e": 19113,
"s": 19033,
"text": "\n12\n6\n9\nThrows exception because COUNT function doesn't works with NULL values\n"
},
{
"code": null,
"e": 19116,
"s": 19113,
"text": "12"
},
{
"code": null,
"e": 19118,
"s": 19116,
"text": "6"
},
{
"code": null,
"e": 19120,
"s": 19118,
"text": "9"
},
{
"code": null,
"e": 19191,
"s": 19120,
"text": "Throws exception because COUNT function doesn't works with NULL values"
},
{
"code": null,
"e": 19368,
"s": 19191,
"text": "43.\tYou need to find the results obtained by the above query only for the departments 100 and 101. Which of the following clauses should be added / modified to the above query?"
},
{
"code": null,
"e": 19542,
"s": 19368,
"text": "\nON (e.department_id = d.department_id ) should be added\n\nUSING (e.department_id ) should be added\n\nWHERE e.department_id in (100,101) should be added\n\nNone of the above\n\n"
},
{
"code": null,
"e": 19600,
"s": 19542,
"text": "ON (e.department_id = d.department_id ) should be added\n"
},
{
"code": null,
"e": 19642,
"s": 19600,
"text": "USING (e.department_id ) should be added\n"
},
{
"code": null,
"e": 19695,
"s": 19642,
"text": "WHERE e.department_id in (100,101) should be added\n"
},
{
"code": null,
"e": 19714,
"s": 19695,
"text": "None of the above\n"
},
{
"code": null,
"e": 19778,
"s": 19714,
"text": "44. Which of the following is NOT a GROUP BY extensions in SQL?"
},
{
"code": null,
"e": 19815,
"s": 19778,
"text": "\nGROUP BY\nGROUPING SETS\nCUBE\nROLLUP\n"
},
{
"code": null,
"e": 19824,
"s": 19815,
"text": "GROUP BY"
},
{
"code": null,
"e": 19838,
"s": 19824,
"text": "GROUPING SETS"
},
{
"code": null,
"e": 19843,
"s": 19838,
"text": "CUBE"
},
{
"code": null,
"e": 19850,
"s": 19843,
"text": "ROLLUP"
},
{
"code": null,
"e": 19916,
"s": 19850,
"text": "45.\tWhat will happen if the above statement is modified as below?"
},
{
"code": null,
"e": 20142,
"s": 19916,
"text": "CREATE OR REPLACE VIEW dept_sum_vu(name, maxsal, minsal, avgsal)\nAS \nSELECT d.dept_name, MIN(e.salary), MAX(e.salary), AVG (e.salary)\nFROM employees e JOIN departments d \nON (e.department_id= d.dept_id)\nGROUP BY d.dept_name; "
},
{
"code": null,
"e": 20325,
"s": 20142,
"text": "\nIt will be no different than the original statement\n\nIt will execute successfully giving the same results but change in alias names.\n\nIt will throw an ORA error\n\nNone of the above\n\n"
},
{
"code": null,
"e": 20378,
"s": 20325,
"text": "It will be no different than the original statement\n"
},
{
"code": null,
"e": 20459,
"s": 20378,
"text": "It will execute successfully giving the same results but change in alias names.\n"
},
{
"code": null,
"e": 20487,
"s": 20459,
"text": "It will throw an ORA error\n"
},
{
"code": null,
"e": 20506,
"s": 20487,
"text": "None of the above\n"
},
{
"code": null,
"e": 20571,
"s": 20506,
"text": "46. What among the following is true about the DELETE statement?"
},
{
"code": null,
"e": 20778,
"s": 20571,
"text": "\nThe DELETE statement has to be accompanied by the WHERE clause\nIt is not mandatory to write a WHERE clause with the DELETE statement\nDELETE can remove data from multiple tables at a time\nNone of the above\n"
},
{
"code": null,
"e": 20841,
"s": 20778,
"text": "The DELETE statement has to be accompanied by the WHERE clause"
},
{
"code": null,
"e": 20911,
"s": 20841,
"text": "It is not mandatory to write a WHERE clause with the DELETE statement"
},
{
"code": null,
"e": 20965,
"s": 20911,
"text": "DELETE can remove data from multiple tables at a time"
},
{
"code": null,
"e": 20983,
"s": 20965,
"text": "None of the above"
},
{
"code": null,
"e": 21122,
"s": 20983,
"text": "47. Assuming the last names of the employees are in a proper case in the table employees, what will be the outcome of the following query?"
},
{
"code": null,
"e": 21210,
"s": 21122,
"text": "SELECT employee_id, last_name, department_id FROM employees WHERE last_name = 'smith';"
},
{
"code": null,
"e": 21496,
"s": 21210,
"text": "\nIt will display the details of the employee with the last name as Smith\nIt will give no result.\nIt will give the details for the employee having the last name as 'Smith' in all Lower case.\nIt will give the details for the employee having the last name as 'Smith' in all INITCAP case.\n"
},
{
"code": null,
"e": 21568,
"s": 21496,
"text": "It will display the details of the employee with the last name as Smith"
},
{
"code": null,
"e": 21592,
"s": 21568,
"text": "It will give no result."
},
{
"code": null,
"e": 21685,
"s": 21592,
"text": "It will give the details for the employee having the last name as 'Smith' in all Lower case."
},
{
"code": null,
"e": 21780,
"s": 21685,
"text": "It will give the details for the employee having the last name as 'Smith' in all INITCAP case."
},
{
"code": null,
"e": 21899,
"s": 21780,
"text": "48.What among the following happens when we issue a DELETE statement on a table? (Choose the most appropriate answer)\n"
},
{
"code": null,
"e": 22154,
"s": 21899,
"text": "\nA prompt pops up asking the user whether he/she is sure of deleting the rows requested\nThe rows obeying the condition given in the DELETE statement are removed immediately\nThe requested rows are removed immediately without any prompt.\nNone of the above\n"
},
{
"code": null,
"e": 22241,
"s": 22154,
"text": "A prompt pops up asking the user whether he/she is sure of deleting the rows requested"
},
{
"code": null,
"e": 22326,
"s": 22241,
"text": "The rows obeying the condition given in the DELETE statement are removed immediately"
},
{
"code": null,
"e": 22389,
"s": 22326,
"text": "The requested rows are removed immediately without any prompt."
},
{
"code": null,
"e": 22407,
"s": 22389,
"text": "None of the above"
},
{
"code": null,
"e": 22452,
"s": 22407,
"text": "49.What is true about the query given above?"
},
{
"code": null,
"e": 22670,
"s": 22452,
"text": "\nThis query returns an ORA error \nIt executes successfully but gives no results \nQueries from different tables cannot be used with the SET operators \nThe query executes successfully and gives the results as expected \n"
},
{
"code": null,
"e": 22703,
"s": 22670,
"text": "This query returns an ORA error "
},
{
"code": null,
"e": 22750,
"s": 22703,
"text": "It executes successfully but gives no results "
},
{
"code": null,
"e": 22819,
"s": 22750,
"text": "Queries from different tables cannot be used with the SET operators "
},
{
"code": null,
"e": 22886,
"s": 22819,
"text": "The query executes successfully and gives the results as expected "
},
{
"code": null,
"e": 23047,
"s": 22886,
"text": "50.What will happen if a value is provided to the &N variable in the above query (option C in question 76) does not match with any row? (Choose the best answer)"
},
{
"code": null,
"e": 23246,
"s": 23047,
"text": "\nThe statement would throw an ORA error\nThe statement would return all the rows in the table\nThe statement would return NULL as the output result.\nThe statement would return no rows in the result. \n"
},
{
"code": null,
"e": 23285,
"s": 23246,
"text": "The statement would throw an ORA error"
},
{
"code": null,
"e": 23338,
"s": 23285,
"text": "The statement would return all the rows in the table"
},
{
"code": null,
"e": 23392,
"s": 23338,
"text": "The statement would return NULL as the output result."
},
{
"code": null,
"e": 23443,
"s": 23392,
"text": "The statement would return no rows in the result. "
},
{
"code": null,
"e": 23528,
"s": 23443,
"text": "51.What is the default sorting order of the results when UNION ALL operator is used?"
},
{
"code": null,
"e": 23586,
"s": 23528,
"text": "\nDescending \nAscending \nEither A or B \nAll of the above \n"
},
{
"code": null,
"e": 23598,
"s": 23586,
"text": "Descending "
},
{
"code": null,
"e": 23609,
"s": 23598,
"text": "Ascending "
},
{
"code": null,
"e": 23624,
"s": 23609,
"text": "Either A or B "
},
{
"code": null,
"e": 23642,
"s": 23624,
"text": "All of the above "
},
{
"code": null,
"e": 23774,
"s": 23642,
"text": "52. A table T_COUNT has 12 number values as 1, 2, 3, 32, 1, 1, null, 24, 12, null, 32, null. Predict the output of the below query."
},
{
"code": null,
"e": 23811,
"s": 23774,
"text": "SELECT COUNT (ALL num) FROM t_count;"
},
{
"code": null,
"e": 23891,
"s": 23811,
"text": "\n12\n6\n9\nThrows exception because COUNT function doesn't works with NULL values\n"
},
{
"code": null,
"e": 23894,
"s": 23891,
"text": "12"
},
{
"code": null,
"e": 23896,
"s": 23894,
"text": "6"
},
{
"code": null,
"e": 23898,
"s": 23896,
"text": "9"
},
{
"code": null,
"e": 23969,
"s": 23898,
"text": "Throws exception because COUNT function doesn't works with NULL values"
},
{
"code": null,
"e": 24037,
"s": 23969,
"text": "53.What is the maximum level up to which Sub-queries can be nested?"
},
{
"code": null,
"e": 24052,
"s": 24037,
"text": "\n255\n100\n2\n16\n"
},
{
"code": null,
"e": 24056,
"s": 24052,
"text": "255"
},
{
"code": null,
"e": 24060,
"s": 24056,
"text": "100"
},
{
"code": null,
"e": 24062,
"s": 24060,
"text": "2"
},
{
"code": null,
"e": 24065,
"s": 24062,
"text": "16"
},
{
"code": null,
"e": 24197,
"s": 24065,
"text": "54. A table T_COUNT has 12 number values as 1, 2, 3, 32, 1, 1, null, 24, 12, null, 32, null. Predict the output of the below query."
},
{
"code": null,
"e": 24239,
"s": 24197,
"text": "SELECT COUNT (DISTINCT num) FROM t_count;"
},
{
"code": null,
"e": 24319,
"s": 24239,
"text": "\n12\n6\n9\nThrows exception because COUNT function doesn't works with NULL values\n"
},
{
"code": null,
"e": 24322,
"s": 24319,
"text": "12"
},
{
"code": null,
"e": 24324,
"s": 24322,
"text": "6"
},
{
"code": null,
"e": 24326,
"s": 24324,
"text": "9"
},
{
"code": null,
"e": 24397,
"s": 24326,
"text": "Throws exception because COUNT function doesn't works with NULL values"
},
{
"code": null,
"e": 24457,
"s": 24397,
"text": "55. Here are few statements about VARIANCE function in SQL."
},
{
"code": null,
"e": 24546,
"s": 24457,
"text": " i. The function accepts multiple numeric inputs and returns variance of all the values"
},
{
"code": null,
"e": 24646,
"s": 24546,
"text": " ii. The function accepts a number column and returns variance of all column values including NULLs"
},
{
"code": null,
"e": 24746,
"s": 24646,
"text": "iii. The function accepts a number column and returns variance of all column values excluding NULLs"
},
{
"code": null,
"e": 24800,
"s": 24746,
"text": "Chose the correct combination from the below options."
},
{
"code": null,
"e": 24828,
"s": 24800,
"text": "\ni and iii\ni and ii\nii\niii\n"
},
{
"code": null,
"e": 24838,
"s": 24828,
"text": "i and iii"
},
{
"code": null,
"e": 24847,
"s": 24838,
"text": "i and ii"
},
{
"code": null,
"e": 24850,
"s": 24847,
"text": "ii"
},
{
"code": null,
"e": 24854,
"s": 24850,
"text": "iii"
},
{
"code": null,
"e": 24961,
"s": 24854,
"text": "56. Which clause is used to filter the query output based on aggregated results using a group by function?"
},
{
"code": null,
"e": 24994,
"s": 24961,
"text": "\nWHERE\nLIMIT\nGROUP WHERE\nHAVING\n"
},
{
"code": null,
"e": 25000,
"s": 24994,
"text": "WHERE"
},
{
"code": null,
"e": 25006,
"s": 25000,
"text": "LIMIT"
},
{
"code": null,
"e": 25018,
"s": 25006,
"text": "GROUP WHERE"
},
{
"code": null,
"e": 25025,
"s": 25018,
"text": "HAVING"
},
{
"code": null,
"e": 25167,
"s": 25025,
"text": "57.\tA user named \"Kevin\" wants to access a table which is owned by another user named \"Jonathan\". Which of the following will work for Kevin?"
},
{
"code": null,
"e": 25270,
"s": 25167,
"text": "\nSelect * from Kevin.employees; \nSelect * from jonathan.employees;\nEither of A or B\nNone of the above\n"
},
{
"code": null,
"e": 25302,
"s": 25270,
"text": "Select * from Kevin.employees; "
},
{
"code": null,
"e": 25336,
"s": 25302,
"text": "Select * from jonathan.employees;"
},
{
"code": null,
"e": 25353,
"s": 25336,
"text": "Either of A or B"
},
{
"code": null,
"e": 25371,
"s": 25353,
"text": "None of the above"
},
{
"code": null,
"e": 25470,
"s": 25371,
"text": "58.What is true about the ALL operator used for sub-queries? (Choose the most appropriate answer.)"
},
{
"code": null,
"e": 25671,
"s": 25470,
"text": "\nReturns rows that match all the values in a list/sub-query\nReturns rows that match only some values in a list/sub-query\nReturns rows only if all the values match in a list/sub-query\nAll of the above\n"
},
{
"code": null,
"e": 25730,
"s": 25671,
"text": "Returns rows that match all the values in a list/sub-query"
},
{
"code": null,
"e": 25791,
"s": 25730,
"text": "Returns rows that match only some values in a list/sub-query"
},
{
"code": null,
"e": 25853,
"s": 25791,
"text": "Returns rows only if all the values match in a list/sub-query"
},
{
"code": null,
"e": 25870,
"s": 25853,
"text": "All of the above"
},
{
"code": null,
"e": 26056,
"s": 25870,
"text": "59.\tSuppose you select DISTINCT departments and employee salaries in the view query used in above question. What will be the outcome if you try to remove rows from the view dept_sum_vu?"
},
{
"code": null,
"e": 26192,
"s": 26056,
"text": "\nThe rows will get removed without any error\n\nOnly the first 10 rows will get removed\n\nThe rows cannot be deleted.\n\nNone of the above\n\n"
},
{
"code": null,
"e": 26237,
"s": 26192,
"text": "The rows will get removed without any error\n"
},
{
"code": null,
"e": 26278,
"s": 26237,
"text": "Only the first 10 rows will get removed\n"
},
{
"code": null,
"e": 26307,
"s": 26278,
"text": "The rows cannot be deleted.\n"
},
{
"code": null,
"e": 26326,
"s": 26307,
"text": "None of the above\n"
},
{
"code": null,
"e": 26444,
"s": 26326,
"text": "60.What will happen if the SELECT list of the compound queries returns both a VARCHAR2 and a NUMBER data type result?"
},
{
"code": null,
"e": 26639,
"s": 26444,
"text": "\nOracle will convert them implicitly and return a VARCHAR2 data type result \nOracle will convert them implicitly and return a NUMBER data type result \nAn ORA error is thrown \nNone of the above \n"
},
{
"code": null,
"e": 26715,
"s": 26639,
"text": "Oracle will convert them implicitly and return a VARCHAR2 data type result "
},
{
"code": null,
"e": 26789,
"s": 26715,
"text": "Oracle will convert them implicitly and return a NUMBER data type result "
},
{
"code": null,
"e": 26813,
"s": 26789,
"text": "An ORA error is thrown "
},
{
"code": null,
"e": 26832,
"s": 26813,
"text": "None of the above "
},
{
"code": null,
"e": 26865,
"s": 26832,
"text": "61.\tWhat is true about a schema?"
},
{
"code": null,
"e": 27025,
"s": 26865,
"text": "\nA schema is owned by a database user and has the same name as that user\nEach user owns a single schema\nSchema objects include database links\nAll of the above\n"
},
{
"code": null,
"e": 27097,
"s": 27025,
"text": "A schema is owned by a database user and has the same name as that user"
},
{
"code": null,
"e": 27128,
"s": 27097,
"text": "Each user owns a single schema"
},
{
"code": null,
"e": 27166,
"s": 27128,
"text": "Schema objects include database links"
},
{
"code": null,
"e": 27183,
"s": 27166,
"text": "All of the above"
},
{
"code": null,
"e": 27275,
"s": 27183,
"text": "62.\tIn which order the values will get inserted with respect to the above INSERT statement?"
},
{
"code": null,
"e": 27513,
"s": 27275,
"text": "\nLocation_id , manager_id, department_name , department_id \ndepartment_id , department_name , manager_id, location_id \ndepartment_id , manager_id, department_name , location_id \ndepartment_id , department_name , location_id , manager_id\n"
},
{
"code": null,
"e": 27572,
"s": 27513,
"text": "Location_id , manager_id, department_name , department_id "
},
{
"code": null,
"e": 27631,
"s": 27572,
"text": "department_id , department_name , manager_id, location_id "
},
{
"code": null,
"e": 27690,
"s": 27631,
"text": "department_id , manager_id, department_name , location_id "
},
{
"code": null,
"e": 27749,
"s": 27690,
"text": "department_id , department_name , location_id , manager_id"
},
{
"code": null,
"e": 27800,
"s": 27749,
"text": "63.\tWhat among the following is true about tables?"
},
{
"code": null,
"e": 27952,
"s": 27800,
"text": "\nA default value is given to a table\nA default value can be given to a column of a table during an INSERT statement\nEither of A or B\nNone of the above\n"
},
{
"code": null,
"e": 27988,
"s": 27952,
"text": "A default value is given to a table"
},
{
"code": null,
"e": 28067,
"s": 27988,
"text": "A default value can be given to a column of a table during an INSERT statement"
},
{
"code": null,
"e": 28084,
"s": 28067,
"text": "Either of A or B"
},
{
"code": null,
"e": 28102,
"s": 28084,
"text": "None of the above"
},
{
"code": null,
"e": 28195,
"s": 28102,
"text": "65. Which of the below SQL query will display employee names, department, and annual salary?"
},
{
"code": null,
"e": 28407,
"s": 28195,
"text": "\nSELECT ename, deptno, sal FROM emp;\nSELECT ename, deptno, sal + comm FROM emp;\nSELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;\nAnnual salary cannot be queried since the column doesn't exists in the table\n"
},
{
"code": null,
"e": 28443,
"s": 28407,
"text": "SELECT ename, deptno, sal FROM emp;"
},
{
"code": null,
"e": 28479,
"s": 28443,
"text": "SELECT ename, deptno, sal FROM emp;"
},
{
"code": null,
"e": 28522,
"s": 28479,
"text": "SELECT ename, deptno, sal + comm FROM emp;"
},
{
"code": null,
"e": 28565,
"s": 28522,
"text": "SELECT ename, deptno, sal + comm FROM emp;"
},
{
"code": null,
"e": 28619,
"s": 28565,
"text": "SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;"
},
{
"code": null,
"e": 28673,
"s": 28619,
"text": "SELECT ename, deptno, (sal * 12) Annual_Sal FROM emp;"
},
{
"code": null,
"e": 28750,
"s": 28673,
"text": "Annual salary cannot be queried since the column doesn't exists in the table"
},
{
"code": null,
"e": 28807,
"s": 28750,
"text": "66. What is true about the SUBSTR function in Oracle DB?"
},
{
"code": null,
"e": 29022,
"s": 28807,
"text": "\nIt extracts a string of determined length\nIt shows the length of a string as a numeric value\nIt finds the numeric position of a named character\nIt trims characters from one (or both) sides from a character string\n"
},
{
"code": null,
"e": 29064,
"s": 29022,
"text": "It extracts a string of determined length"
},
{
"code": null,
"e": 29115,
"s": 29064,
"text": "It shows the length of a string as a numeric value"
},
{
"code": null,
"e": 29166,
"s": 29115,
"text": "It finds the numeric position of a named character"
},
{
"code": null,
"e": 29235,
"s": 29166,
"text": "It trims characters from one (or both) sides from a character string"
},
{
"code": null,
"e": 29349,
"s": 29235,
"text": " 67. Which of the following SELECT statements lists the highest retail price of all books in the Family category?"
},
{
"code": null,
"e": 29555,
"s": 29349,
"text": "\nSELECT MAX(retail) FROM books WHERE category = 'FAMILY';\nSELECT MAX(retail) FROM books HAVING category = 'FAMILY';\nSELECT retail FROM books WHERE category = 'FAMILY' HAVING MAX(retail);\nNone of the above\n"
},
{
"code": null,
"e": 29612,
"s": 29555,
"text": "SELECT MAX(retail) FROM books WHERE category = 'FAMILY';"
},
{
"code": null,
"e": 29669,
"s": 29612,
"text": "SELECT MAX(retail) FROM books WHERE category = 'FAMILY';"
},
{
"code": null,
"e": 29727,
"s": 29669,
"text": "SELECT MAX(retail) FROM books HAVING category = 'FAMILY';"
},
{
"code": null,
"e": 29785,
"s": 29727,
"text": "SELECT MAX(retail) FROM books HAVING category = 'FAMILY';"
},
{
"code": null,
"e": 29856,
"s": 29785,
"text": "SELECT retail FROM books WHERE category = 'FAMILY' HAVING MAX(retail);"
},
{
"code": null,
"e": 29927,
"s": 29856,
"text": "SELECT retail FROM books WHERE category = 'FAMILY' HAVING MAX(retail);"
},
{
"code": null,
"e": 29945,
"s": 29927,
"text": "None of the above"
},
{
"code": null,
"e": 30034,
"s": 29945,
"text": "68. Which of the following functions can be used to include NULL values in calculations?"
},
{
"code": null,
"e": 30052,
"s": 30034,
"text": "\nSUM\nNVL\nMAX\nMIN\n"
},
{
"code": null,
"e": 30056,
"s": 30052,
"text": "SUM"
},
{
"code": null,
"e": 30060,
"s": 30056,
"text": "NVL"
},
{
"code": null,
"e": 30064,
"s": 30060,
"text": "MAX"
},
{
"code": null,
"e": 30068,
"s": 30064,
"text": "MIN"
},
{
"code": null,
"e": 30153,
"s": 30068,
"text": "69.Which statements best describes the inference drawn from the questions 34 and 35?"
},
{
"code": null,
"e": 30319,
"s": 30153,
"text": "\nThere are duplicate values for job codes \nThe query executes but results produced are unexpected \nThere are no duplicate values for departments \nNone of the above \n"
},
{
"code": null,
"e": 30361,
"s": 30319,
"text": "There are duplicate values for job codes "
},
{
"code": null,
"e": 30417,
"s": 30361,
"text": "The query executes but results produced are unexpected "
},
{
"code": null,
"e": 30464,
"s": 30417,
"text": "There are no duplicate values for departments "
},
{
"code": null,
"e": 30483,
"s": 30464,
"text": "None of the above "
},
{
"code": null,
"e": 30536,
"s": 30483,
"text": "70. What will be the outcome of the following query?"
},
{
"code": null,
"e": 30567,
"s": 30536,
"text": "SELECT length('hi') FROM dual;"
},
{
"code": null,
"e": 30578,
"s": 30567,
"text": "\n2\n3\n1\nhi\n"
},
{
"code": null,
"e": 30580,
"s": 30578,
"text": "2"
},
{
"code": null,
"e": 30582,
"s": 30580,
"text": "3"
},
{
"code": null,
"e": 30584,
"s": 30582,
"text": "1"
},
{
"code": null,
"e": 30587,
"s": 30584,
"text": "hi"
},
{
"code": null,
"e": 30709,
"s": 30587,
"text": "Answer(1): A. The ROUND function will round off the value 144.23 according to the specified precision -1 and returns 140."
},
{
"code": null,
"e": 30809,
"s": 30709,
"text": "Examine the structure of the EMPLOYEES table as given and answer the questions 2 and 3 that follow."
},
{
"code": null,
"e": 31235,
"s": 30809,
"text": "SQL> DESC employees\n Name\t\t\t Null?\t Type\n ----------------------- -------- ----------------\n EMPLOYEE_ID\t\t NOT NULL NUMBER(6)\n FIRST_NAME\t\t\t VARCHAR2(20)\n LAST_NAME\t\t NOT NULL VARCHAR2(25)\n EMAIL\t\t\t NOT NULL VARCHAR2(25)\n PHONE_NUMBER\t\t\t VARCHAR2(20)\n HIRE_DATE\t\t NOT NULL DATE\n JOB_ID \t\t NOT NULL VARCHAR2(10)\n SALARY \t\t\t NUMBER(8,2)\n COMMISSION_PCT \t\t NUMBER(2,2)\n MANAGER_ID\t\t\t NUMBER(6)\n DEPARTMENT_ID\t\t\t NUMBER(4)"
},
{
"code": null,
"e": 31359,
"s": 31235,
"text": "Answer(2): A. Using parenthesis will explicitly change the order of evaluation when INTERSECT is used with other operators."
},
{
"code": null,
"e": 31502,
"s": 31359,
"text": "Answer(3): A, D. On strict grounds, SELECT is a DML command as it is one of the mandatory clauses for manipulation of data present in tables."
},
{
"code": null,
"e": 31579,
"s": 31502,
"text": "Answer(4): A.Select the required from the tables each separated by a \ncomma."
},
{
"code": null,
"e": 31920,
"s": 31579,
"text": "Answer(5): C. Simple and Complex views are two types of views. \nSimple views are based on a subquery that references only one table and doesn't include group \nfunctions, expressions, or GROUP BY clauses. Complex views are based on a subquery that \nretrieves or derives data from one or more tables and can contain functions or grouped data."
},
{
"code": null,
"e": 32123,
"s": 31920,
"text": "Answer(6): C. All the combined should have the same no. of columns \nwhen using SET operators. The corresponding columns in the queries that make up a compound \nquery must be of the same data type group."
},
{
"code": null,
"e": 32288,
"s": 32123,
"text": "Answer:(7) D. Multiple-row subqueries return more than one row of results.Operators that \ncan be used with multiple-row subqueries include IN, ALL, ANY, and EXISTS."
},
{
"code": null,
"e": 32708,
"s": 32288,
"text": "Answer(8): C. An index can be created to speed up the query process. \nDML operations are always slower when indexes exist. Oracle 11g creates an index for PRIMARY \nKEY and UNIQUE constraints automatically. An explicit index is created with the CREATE INDEX \ncommand. An index can be used by Oracle 11g automatically if a query criterion or sort \noperation is based on a column or an expression used to create the index."
},
{
"code": null,
"e": 32878,
"s": 32708,
"text": "Answer(9): A. Using the SELECT clause is the most common technique \nfor inserting rows into tables. It reduces the effort of manually keying in values for each \ncolumn."
},
{
"code": null,
"e": 32938,
"s": 32878,
"text": "Answer(10): A. View definition can make use of sub-queries."
},
{
"code": null,
"e": 33054,
"s": 32938,
"text": "Answer(11): C. DESCRIBE is used to show the table structure along \nwith table columns, their data type and nullity "
},
{
"code": null,
"e": 33123,
"s": 33054,
"text": "Answer(12): C. Any arithmetic operation with NULL results in a NULL."
},
{
"code": null,
"e": 33142,
"s": 33123,
"text": "Answer()13: C, D. "
},
{
"code": null,
"e": 33305,
"s": 33142,
"text": "Answer(14): C. The ANSI SQL: 1999 syntax though not used as much as \nthe traditional Oracle syntax, it still is one of the syntaxes that may be used in Oracle SQL"
},
{
"code": null,
"e": 33540,
"s": 33305,
"text": "Answer(15): B. Correlated subquery references a column in the outer query and executes the subquery once for every row in the outer query while Uncorrelated subquery executes the subquery first and passes the value to the outer query."
},
{
"code": null,
"e": 33785,
"s": 33540,
"text": "Answer(16): D. The constraints on the column must be obeyed while updating its value. In the given UPDATE statement, error will be thrown because the \nEMPLOYEE_ID column is a primary key in the EMPLOYEES table which means it cannot be NULL."
},
{
"code": null,
"e": 33938,
"s": 33785,
"text": "Answer(17): D. The WHERE clause can be omitted and the relevant conditions can be accommodated in the JOIN..ON clause itself as shown in the given query"
},
{
"code": null,
"e": 34044,
"s": 33938,
"text": "Answer(18): A. Table1 JOIN table2 JOIN table3 is not allowed without the ON clauses for between each JOIN"
},
{
"code": null,
"e": 34137,
"s": 34044,
"text": "Answer(19): C. The leading zeroes in the right operand of expression are ignored by Oracle. "
},
{
"code": null,
"e": 34235,
"s": 34137,
"text": "Answer(20): A, C. You cannot create a table with the name same as an Oracle Server reserved word."
},
{
"code": null,
"e": 34328,
"s": 34235,
"text": "Answer(21): C. The BETWEEN operator can be used within a sub-query but not with a sub-query."
},
{
"code": null,
"e": 34426,
"s": 34328,
"text": "Answer(22): D. Functions can perform calculations, perform case conversions and type conversions."
},
{
"code": null,
"e": 34869,
"s": 34426,
"text": "Answer(23): A, C. A join can be an inner join,in which the only records returned have a matching record in all tables,or an outer join, in which records can be returned regardless of whether there's a matching record in the join.An outer join is created when records need to be included in the results without having corresponding records in the join tables. These records are matched with NULL records so that they're included in the output."
},
{
"code": null,
"e": 35151,
"s": 34869,
"text": "Answer(24): B. Ff you include the FORCE keyword in the CREATE clause, Oracle 11g creates the view in spite of the absence of any referenced tables. NOFORCE is the default mode for the CREATE VIEW command, which means all tables and columns must be valid, or the view isn't created."
},
{
"code": null,
"e": 35167,
"s": 35151,
"text": "Answer(25): D. "
},
{
"code": null,
"e": 35316,
"s": 35167,
"text": "Answer(26): A, B. A user must possess the CREATE TABLE privilege and must have sufficient space to allocate the initial extent to the table segment."
},
{
"code": null,
"e": 35332,
"s": 35316,
"text": "Answer(27): A. "
},
{
"code": null,
"e": 35536,
"s": 35332,
"text": "Answer(28): C. The FULL OUTER JOIN returns the non-matched rows from both the tables. A full outer join includes all records from both tables, even if no corresponding record in the other table is found."
},
{
"code": null,
"e": 35623,
"s": 35536,
"text": "Answer(29): B.In SQL, concatenation operator is represented by two vertical bars (||)."
},
{
"code": null,
"e": 35807,
"s": 35623,
"text": "Answer(30): C. Parenthesis can be used to group the specific queries in order to change the precedence explicitly. Parentheses are preferred over other SET operators during execution."
},
{
"code": null,
"e": 35910,
"s": 35807,
"text": "Answer(31): A. UNION Returns the combined rows from two queries, sorting them and removing duplicates."
},
{
"code": null,
"e": 36109,
"s": 35910,
"text": "Answer(32): C. The WITH READ ONLY option prevents performing any DML operations on the view. This option is used often when it's important that users can only query data, not make any changes to it."
},
{
"code": null,
"e": 36261,
"s": 36109,
"text": "Answer(33): B, C. NOFORCE is the default mode for the CREATE VIEW command, which means all tables and columns must be valid, or the view isn't created."
},
{
"code": null,
"e": 36470,
"s": 36261,
"text": "Answer(34): B. The OR REPLACE option notifies Oracle 11g that a view with the same name might already exist; if it does, the view's previous version should be replaced with the one defined in the new command."
},
{
"code": null,
"e": 36570,
"s": 36470,
"text": "Answer(35): A. There are basically two types of functions - Single row and Multiple row functions."
},
{
"code": null,
"e": 36670,
"s": 36570,
"text": "Answer(36): B. Character, Date, Conversion, General, Number are the types of Single row functions."
},
{
"code": null,
"e": 36780,
"s": 36670,
"text": "Answer(37): B. Multiple Row functions always work on a group of rows and return one value per group of rows."
},
{
"code": null,
"e": 36868,
"s": 36780,
"text": "Answer(38): C. Group functions are same as Multi row functions and aggregate functions."
},
{
"code": null,
"e": 37024,
"s": 36868,
"text": "Answer(39): A. The COUNT(*) counts the number of rows including duplicates and NULLs. Use DISTINCT and ALL keyword to restrict duplicate and \nNULL values."
},
{
"code": null,
"e": 37135,
"s": 37024,
"text": "Answer(40): D. A table must have atleasr one column, its data type specification, and precision (if required)."
},
{
"code": null,
"e": 37250,
"s": 37135,
"text": "Answer(41): C. Specifying alias name is good practice to improve the readability of the code and the view queries."
},
{
"code": null,
"e": 37332,
"s": 37250,
"text": "Answer(42): C. COUNT (column) ignores the NULL values but counts the duplicates. "
},
{
"code": null,
"e": 37482,
"s": 37332,
"text": "Answer(43): C. The NATURAL JOIN clause implicitly matches all the identical named columns. To add additional conditions the WHERE clause can be used."
},
{
"code": null,
"e": 37597,
"s": 37482,
"text": "Answer(44): A. GROUPING SETS operations can be used to perform multiple GROUP BY aggregations with a single query."
},
{
"code": null,
"e": 37709,
"s": 37597,
"text": "Answer(45): B. The sequence of the column alias not matters much as they don't carry any behavioral attribute."
},
{
"code": null,
"e": 37860,
"s": 37709,
"text": "Answer(46): B. The WHERE clause predicate is optional in DELETE statement. If the WHERE clause is omitted, all the rows of the table will be deleted."
},
{
"code": null,
"e": 38049,
"s": 37860,
"text": "Answer(47): B. Provided the last names in the employees table are in a proper case, the condition WHERE last_name = 'smith' will not be satistified and hence no results will be displayed."
},
{
"code": null,
"e": 38150,
"s": 38049,
"text": "Answer(48): C. As a part of the active or a new transaction, the rows in the table will be deleted."
},
{
"code": null,
"e": 38246,
"s": 38150,
"text": "Answer(49): D. A compound query is one query made up of several queries using different tables."
},
{
"code": null,
"e": 38262,
"s": 38246,
"text": "Answer(50): D. "
},
{
"code": null,
"e": 38548,
"s": 38262,
"text": "Answer(51): B. A compound query will by default return rows sorted across all the columns,from left to right in ascending order.The only exception is UNION ALL, where the rows will not be sorted. The only place where an ORDER BY clause is permitted is at the end of the compound query."
},
{
"code": null,
"e": 38633,
"s": 38548,
"text": "Answer(52): C. COUNT(ALL column) ignores the NULL values but counts the duplicates. "
},
{
"code": null,
"e": 38649,
"s": 38633,
"text": "Answer(53): A. "
},
{
"code": null,
"e": 38726,
"s": 38649,
"text": "Answer(54): B. COUNT (DISTINCT column) counts the distinct not null values. "
},
{
"code": null,
"e": 38881,
"s": 38726,
"text": "Answer(55): C. The VARIANCE function accepts single numeric argument as the column name and returns variance of all the column values considering \nNULLs."
},
{
"code": null,
"e": 39363,
"s": 38881,
"text": "Answer(56): D. HAVING Clause is used for restricting group results. You use the HAVING clause to specify the groups that are to be displayed, thus further restricting the groups on the basis of aggregate information. The HAVING clause can precede the GROUP BY clause, but it is recommended that you place the GROUP BY clause first because it is more logical. Groups are formed and group functions are calculated before the HAVING clause is applied to the groups in the SELECT list."
},
{
"code": null,
"e": 39379,
"s": 39363,
"text": "Answer(57): B. "
},
{
"code": null,
"e": 39761,
"s": 39379,
"text": "Answer(58): C. '> ALL' More than the highest value returned by the subquery. '< ALL' Less than the lowest value returned by the subquery. '< ANY' Less than the highest value returned by the subquery. '> ANY' More than the lowest value returned by the subquery. '= ANY' Equal to any value returned by the subquery (same as IN). '[NOT] EXISTS' Row must match a value in the subquery."
},
{
"code": null,
"e": 39896,
"s": 39761,
"text": "Answer(59): C. The view DEPT_SUM_VU is still a complex view as it uses DISTINCT keyword. Hence, DML operations are not possible on it."
},
{
"code": null,
"e": 39958,
"s": 39896,
"text": "Answer(60): C. Oracle does not convert data types implicitly."
},
{
"code": null,
"e": 40138,
"s": 39958,
"text": "Answer(61): D. The user space in a database is known as schema. A schema contains the objects which are owned or accessed by the user. Each user can have single schema of its own."
},
{
"code": null,
"e": 40263,
"s": 40138,
"text": "Answer(62): B. If the columns are mentioned in the INSERT clause, the VALUES keyword should contain values in the same order"
},
{
"code": null,
"e": 40373,
"s": 40263,
"text": "Answer(63): B. A default value can be specified for a column during the definition using the keyword DEFAULT."
},
{
"code": null,
"e": 40475,
"s": 40373,
"text": "Answer(65): C. Use numeric expressions in SELECT statement to perform basic arithmetic calculations. "
},
{
"code": null,
"e": 40885,
"s": 40475,
"text": "Answer(66): A. The SUBSTR(string, x, y) function accepts three parameters and returns a string consisting of the number of characters extracted from the source string, beginning at the specified start position (x). When position is positive, then the function counts from the beginning of string to find the first character. When position is negative, then the function counts backward from the end of string."
},
{
"code": null,
"e": 41035,
"s": 40885,
"text": "Answer(67): A. Since the category FAMILY has to be restricted before grouping, table rows must be filtered using WHERE clause and not HAVING clause. "
},
{
"code": null,
"e": 41232,
"s": 41035,
"text": "Answer(68): B. NVL is a general function to provide alternate values to the NULL values. It can really make a difference in arithmetic calculations using AVG, STDDEV and VARIANCE group functions. "
},
{
"code": null,
"e": 41344,
"s": 41232,
"text": "Answer(69): C. As the combination of the job codes and departments is unique, there are no duplicates obtained."
},
{
"code": null,
"e": 41419,
"s": 41344,
"text": "Answer(70): A. the LENGTH function simply gives the length of the string."
},
{
"code": null,
"e": 41452,
"s": 41419,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 41466,
"s": 41452,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 41499,
"s": 41466,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 41513,
"s": 41499,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 41548,
"s": 41513,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 41562,
"s": 41548,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 41595,
"s": 41562,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 41617,
"s": 41595,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 41652,
"s": 41617,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 41706,
"s": 41652,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 41739,
"s": 41706,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 41767,
"s": 41739,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 41774,
"s": 41767,
"text": " Print"
},
{
"code": null,
"e": 41785,
"s": 41774,
"text": " Add Notes"
}
] |
Check if a File is hidden in C#
|
To retrieve the attributes of a file, use the FileAttributes Eumeration. It has various members like compressed, directory, hidden, etc.
To check if a file is hidden, use the hidden member name.
If the FileAttributes.hidden is set that would mean the file is hidden. Firstly, get the path to find the attributes.
FileAttributes attributes = File.GetAttributes(path);
If the following is set, that would mean the file is now hidden using the hidden member name.
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
Console.WriteLine("The {0} file is hidden.", path);
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "To retrieve the attributes of a file, use the FileAttributes Eumeration. It has various members like compressed, directory, hidden, etc."
},
{
"code": null,
"e": 1257,
"s": 1199,
"text": "To check if a file is hidden, use the hidden member name."
},
{
"code": null,
"e": 1375,
"s": 1257,
"text": "If the FileAttributes.hidden is set that would mean the file is hidden. Firstly, get the path to find the attributes."
},
{
"code": null,
"e": 1430,
"s": 1375,
"text": "FileAttributes attributes = File.GetAttributes(path);\n"
},
{
"code": null,
"e": 1524,
"s": 1430,
"text": "If the following is set, that would mean the file is now hidden using the hidden member name."
},
{
"code": null,
"e": 1654,
"s": 1524,
"text": " File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);\nConsole.WriteLine(\"The {0} file is hidden.\", path);\n"
}
] |
How to generate 2-D Gaussian array using NumPy? - GeeksforGeeks
|
20 Apr, 2022
In this article, Let’s discuss how to generate a 2-D Gaussian array using NumPy. To create a 2 D Gaussian array using Numpy python module
numpy.meshgrid()– It is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing.
Syntax:
numpy.meshgrid(*xi, copy=True, sparse=False, indexing=’xy’)
numpy.linspace()– returns number spaces evenly w.r.t interval.
Syntax:
numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None)
numpy.exp()– this mathematical function helps the user to calculate the exponential of all the elements in the input array.
Syntax:
numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None)
Example 1:
Python3
# Importing Numpy packageimport numpy as np # Initializing value of x-axis and y-axis# in the range -1 to 1x, y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))dst = np.sqrt(x*x+y*y) # Initializing sigma and muusigma = 1muu = 0.000 # Calculating Gaussian arraygauss = np.exp(-( (dst-muu)**2 / ( 2.0 * sigma**2 ) ) ) print("2D Gaussian array :\n")print(gauss)
Output:
2D Gaussian array:[[0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.602798180.57375342 0.51979489 0.44822088 0.36787944][0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.734443670.69905581 0.63331324 0.54610814 0.44822088][0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.851723080.81068432 0.73444367 0.63331324 0.51979489][0.57375342 0.69905581 0.81068432 0.89483932 0.9401382 0.94013820.89483932 0.81068432 0.69905581 0.57375342][0.60279818 0.73444367 0.85172308 0.9401382 0.98773022 0.987730220.9401382 0.85172308 0.73444367 0.60279818][0.60279818 0.73444367 0.85172308 0.9401382 0.98773022 0.987730220.9401382 0.85172308 0.73444367 0.60279818][0.57375342 0.69905581 0.81068432 0.89483932 0.9401382 0.94013820.89483932 0.81068432 0.69905581 0.57375342][0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.851723080.81068432 0.73444367 0.63331324 0.51979489][0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.734443670.69905581 0.63331324 0.54610814 0.44822088][0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.602798180.57375342 0.51979489 0.44822088 0.36787944]]
Example 2:
Python3
# Importing Numpy packageimport numpy as np # Initializing value of x-axis and y-axis# in the range -2 to +2x, y = np.meshgrid(np.linspace(-2,2,15), np.linspace(-2,2,15))dst = np.sqrt(x*x+y*y) # Initializing sigma and muusigma = 1muu = 0.000 # Calculating Gaussian arraygauss = np.exp(-( (dst-muu)**2 / ( 2.0 * sigma**2 ) ) ) print("2D Gaussian array :\n")print(gauss)
Output:
2D Gaussian array:[[0.01831564 0.03113609 0.0487813 0.07043526 0.09372907 0.11494916 0.12992261 0.13533528 0.12992261 0.11494916 0.09372907 0.07043526 0.0487813 0.03113609 0.01831564][0.03113609 0.0529305 0.08292689 0.11973803 0.15933686 0.19541045 0.2208649 0.2300663 0.2208649 0.19541045 0.15933686 0.11973803 0.08292689 0.0529305 0.03113609][0.0487813 0.08292689 0.12992261 0.1875951 0.24963508 0.30615203 0.34603184 0.36044779 0.34603184 0.30615203 0.24963508 0.1875951 0.12992261 0.08292689 0.0487813 ][0.07043526 0.11973803 0.1875951 0.27086833 0.36044779 0.44205254 0.49963495 0.52045012 0.49963495 0.44205254 0.36044779 0.27086833 0.1875951 0.11973803 0.07043526][0.09372907 0.15933686 0.24963508 0.36044779 0.47965227 0.58824471 0.66487032 0.69256932 0.66487032 0.58824471 0.47965227 0.36044779 0.24963508 0.15933686 0.09372907][0.11494916 0.19541045 0.30615203 0.44205254 0.58824471 0.72142229 0.81539581 0.84936582 0.81539581 0.72142229 0.58824471 0.44205254 0.30615203 0.19541045 0.11494916][0.12992261 0.2208649 0.34603184 0.49963495 0.66487032 0.81539581 0.92161045 0.96000544 0.92161045 0.81539581 0.66487032 0.49963495 0.34603184 0.2208649 0.12992261][0.13533528 0.2300663 0.36044779 0.52045012 0.69256932 0.84936582 0.96000544 1. 0.96000544 0.84936582 0.69256932 0.52045012 0.36044779 0.2300663 0.13533528][0.12992261 0.2208649 0.34603184 0.49963495 0.66487032 0.81539581 0.92161045 0.96000544 0.92161045 0.81539581 0.66487032 0.49963495 0.34603184 0.2208649 0.12992261][0.11494916 0.19541045 0.30615203 0.44205254 0.58824471 0.72142229 0.81539581 0.84936582 0.81539581 0.72142229 0.58824471 0.44205254 0.30615203 0.19541045 0.11494916][0.09372907 0.15933686 0.24963508 0.36044779 0.47965227 0.58824471 0.66487032 0.69256932 0.66487032 0.58824471 0.47965227 0.36044779 0.24963508 0.15933686 0.09372907][0.07043526 0.11973803 0.1875951 0.27086833 0.36044779 0.44205254 0.49963495 0.52045012 0.49963495 0.44205254 0.36044779 0.27086833 0.1875951 0.11973803 0.07043526][0.0487813 0.08292689 0.12992261 0.1875951 0.24963508 0.30615203 0.34603184 0.36044779 0.34603184 0.30615203 0.24963508 0.1875951 0.12992261 0.08292689 0.0487813 ][0.03113609 0.0529305 0.08292689 0.11973803 0.15933686 0.19541045 0.2208649 0.2300663 0.2208649 0.19541045 0.15933686 0.11973803 0.08292689 0.0529305 0.03113609][0.01831564 0.03113609 0.0487813 0.07043526 0.09372907 0.11494916 0.12992261 0.13533528 0.12992261 0.11494916 0.09372907 0.07043526 0.0487813 0.03113609 0.01831564]]
arorakashish0911
Pyhton numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
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": 23901,
"s": 23873,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 24039,
"s": 23901,
"text": "In this article, Let’s discuss how to generate a 2-D Gaussian array using NumPy. To create a 2 D Gaussian array using Numpy python module"
},
{
"code": null,
"e": 24194,
"s": 24039,
"text": "numpy.meshgrid()– It is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing. "
},
{
"code": null,
"e": 24202,
"s": 24194,
"text": "Syntax:"
},
{
"code": null,
"e": 24263,
"s": 24202,
"text": "numpy.meshgrid(*xi, copy=True, sparse=False, indexing=’xy’) "
},
{
"code": null,
"e": 24326,
"s": 24263,
"text": "numpy.linspace()– returns number spaces evenly w.r.t interval."
},
{
"code": null,
"e": 24334,
"s": 24326,
"text": "Syntax:"
},
{
"code": null,
"e": 24422,
"s": 24334,
"text": "numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None) "
},
{
"code": null,
"e": 24546,
"s": 24422,
"text": "numpy.exp()– this mathematical function helps the user to calculate the exponential of all the elements in the input array."
},
{
"code": null,
"e": 24554,
"s": 24546,
"text": "Syntax:"
},
{
"code": null,
"e": 24648,
"s": 24554,
"text": "numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) "
},
{
"code": null,
"e": 24659,
"s": 24648,
"text": "Example 1:"
},
{
"code": null,
"e": 24667,
"s": 24659,
"text": "Python3"
},
{
"code": "# Importing Numpy packageimport numpy as np # Initializing value of x-axis and y-axis# in the range -1 to 1x, y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))dst = np.sqrt(x*x+y*y) # Initializing sigma and muusigma = 1muu = 0.000 # Calculating Gaussian arraygauss = np.exp(-( (dst-muu)**2 / ( 2.0 * sigma**2 ) ) ) print(\"2D Gaussian array :\\n\")print(gauss)",
"e": 25035,
"s": 24667,
"text": null
},
{
"code": null,
"e": 25043,
"s": 25035,
"text": "Output:"
},
{
"code": null,
"e": 26163,
"s": 25043,
"text": "2D Gaussian array:[[0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.602798180.57375342 0.51979489 0.44822088 0.36787944][0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.734443670.69905581 0.63331324 0.54610814 0.44822088][0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.851723080.81068432 0.73444367 0.63331324 0.51979489][0.57375342 0.69905581 0.81068432 0.89483932 0.9401382 0.94013820.89483932 0.81068432 0.69905581 0.57375342][0.60279818 0.73444367 0.85172308 0.9401382 0.98773022 0.987730220.9401382 0.85172308 0.73444367 0.60279818][0.60279818 0.73444367 0.85172308 0.9401382 0.98773022 0.987730220.9401382 0.85172308 0.73444367 0.60279818][0.57375342 0.69905581 0.81068432 0.89483932 0.9401382 0.94013820.89483932 0.81068432 0.69905581 0.57375342][0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.851723080.81068432 0.73444367 0.63331324 0.51979489][0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.734443670.69905581 0.63331324 0.54610814 0.44822088][0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.602798180.57375342 0.51979489 0.44822088 0.36787944]] "
},
{
"code": null,
"e": 26174,
"s": 26163,
"text": "Example 2:"
},
{
"code": null,
"e": 26182,
"s": 26174,
"text": "Python3"
},
{
"code": "# Importing Numpy packageimport numpy as np # Initializing value of x-axis and y-axis# in the range -2 to +2x, y = np.meshgrid(np.linspace(-2,2,15), np.linspace(-2,2,15))dst = np.sqrt(x*x+y*y) # Initializing sigma and muusigma = 1muu = 0.000 # Calculating Gaussian arraygauss = np.exp(-( (dst-muu)**2 / ( 2.0 * sigma**2 ) ) ) print(\"2D Gaussian array :\\n\")print(gauss)",
"e": 26551,
"s": 26182,
"text": null
},
{
"code": null,
"e": 26559,
"s": 26551,
"text": "Output:"
},
{
"code": null,
"e": 29068,
"s": 26559,
"text": "2D Gaussian array:[[0.01831564 0.03113609 0.0487813 0.07043526 0.09372907 0.11494916 0.12992261 0.13533528 0.12992261 0.11494916 0.09372907 0.07043526 0.0487813 0.03113609 0.01831564][0.03113609 0.0529305 0.08292689 0.11973803 0.15933686 0.19541045 0.2208649 0.2300663 0.2208649 0.19541045 0.15933686 0.11973803 0.08292689 0.0529305 0.03113609][0.0487813 0.08292689 0.12992261 0.1875951 0.24963508 0.30615203 0.34603184 0.36044779 0.34603184 0.30615203 0.24963508 0.1875951 0.12992261 0.08292689 0.0487813 ][0.07043526 0.11973803 0.1875951 0.27086833 0.36044779 0.44205254 0.49963495 0.52045012 0.49963495 0.44205254 0.36044779 0.27086833 0.1875951 0.11973803 0.07043526][0.09372907 0.15933686 0.24963508 0.36044779 0.47965227 0.58824471 0.66487032 0.69256932 0.66487032 0.58824471 0.47965227 0.36044779 0.24963508 0.15933686 0.09372907][0.11494916 0.19541045 0.30615203 0.44205254 0.58824471 0.72142229 0.81539581 0.84936582 0.81539581 0.72142229 0.58824471 0.44205254 0.30615203 0.19541045 0.11494916][0.12992261 0.2208649 0.34603184 0.49963495 0.66487032 0.81539581 0.92161045 0.96000544 0.92161045 0.81539581 0.66487032 0.49963495 0.34603184 0.2208649 0.12992261][0.13533528 0.2300663 0.36044779 0.52045012 0.69256932 0.84936582 0.96000544 1. 0.96000544 0.84936582 0.69256932 0.52045012 0.36044779 0.2300663 0.13533528][0.12992261 0.2208649 0.34603184 0.49963495 0.66487032 0.81539581 0.92161045 0.96000544 0.92161045 0.81539581 0.66487032 0.49963495 0.34603184 0.2208649 0.12992261][0.11494916 0.19541045 0.30615203 0.44205254 0.58824471 0.72142229 0.81539581 0.84936582 0.81539581 0.72142229 0.58824471 0.44205254 0.30615203 0.19541045 0.11494916][0.09372907 0.15933686 0.24963508 0.36044779 0.47965227 0.58824471 0.66487032 0.69256932 0.66487032 0.58824471 0.47965227 0.36044779 0.24963508 0.15933686 0.09372907][0.07043526 0.11973803 0.1875951 0.27086833 0.36044779 0.44205254 0.49963495 0.52045012 0.49963495 0.44205254 0.36044779 0.27086833 0.1875951 0.11973803 0.07043526][0.0487813 0.08292689 0.12992261 0.1875951 0.24963508 0.30615203 0.34603184 0.36044779 0.34603184 0.30615203 0.24963508 0.1875951 0.12992261 0.08292689 0.0487813 ][0.03113609 0.0529305 0.08292689 0.11973803 0.15933686 0.19541045 0.2208649 0.2300663 0.2208649 0.19541045 0.15933686 0.11973803 0.08292689 0.0529305 0.03113609][0.01831564 0.03113609 0.0487813 0.07043526 0.09372907 0.11494916 0.12992261 0.13533528 0.12992261 0.11494916 0.09372907 0.07043526 0.0487813 0.03113609 0.01831564]]"
},
{
"code": null,
"e": 29087,
"s": 29070,
"text": "arorakashish0911"
},
{
"code": null,
"e": 29114,
"s": 29087,
"text": "Pyhton numpy-arrayCreation"
},
{
"code": null,
"e": 29127,
"s": 29114,
"text": "Python-numpy"
},
{
"code": null,
"e": 29134,
"s": 29127,
"text": "Python"
},
{
"code": null,
"e": 29232,
"s": 29134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29241,
"s": 29232,
"text": "Comments"
},
{
"code": null,
"e": 29254,
"s": 29241,
"text": "Old Comments"
},
{
"code": null,
"e": 29286,
"s": 29254,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29342,
"s": 29286,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29384,
"s": 29342,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29426,
"s": 29384,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29462,
"s": 29426,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29501,
"s": 29462,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29523,
"s": 29501,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29554,
"s": 29523,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29581,
"s": 29554,
"text": "Python Classes and Objects"
}
] |
How to get the information from a meta tag using JavaScript?
|
28 Jan, 2020
To display meta tag information in HTML with JavaScript, we will use a method called getElementByTagName() function.
Method 1: Using getElementsByTagName() method.
Syntax:
document.getElementsByTagName("meta");
With this, we can get all the meta elements from an HTML file. As we click on the button, all the meta tag names and content will be displayed on the web page.
Example 1:
<!DOCTYPE html><html> <head> <meta name="description" content="GeeksforGeeks Article"> <meta name="keywords" content="GeeksforGeeks,GfG,Article"> <meta name="author" content="Aakash Pawar"> <title>GfG</title> <style> body { font-size: 20px; margin: 20px; } button { font-size: 18px; } </style></head> <body> <button onclick="GfGFunction()"> Click Here! </button> <br> <div id="demo"> <h2>Content of Meta Tag<h2></div> <script> function GfGFunction() { var meta = document.getElementsByTagName("meta"); for (var i = 0; i < 3; i++) { document.getElementById("demo").innerHTML += "name: <b>"+meta[i].name+"</b> and content: <b>" +meta[i].content+"</b><br>"; } } </script></body></html>
Output:
Method 2: Using getElementsByTagName() method with index specification.
Syntax:
var meta = document.getElementsByTagName("meta")[0];
Here, the index number ‘0’ represents the first meta element. You can consider all the meta element in an HTML file as an array and can access them by specifying the index of the meta tag. This way, we can get specific meta elements from an HTML file.
Example 2:
<!DOCTYPE html><html> <head> <meta id="author" name="description" content="GeeksforGeeks Article"> <meta id="author" name="keywords" content="GeeksforGeeks,GfG,Article"> <meta id="author" name="author" content="Aakash Pawar"> <title>Meta Tag</title> <style> body { font-size: 20px; margin: 20px; } button { font-size: 18px; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <button onclick="GfGFunction()">Click Here!</button> <br> <div id="demo"> <h2>Content of Meta Tag<h2></div> <script> function GfGFunction() { var meta = document.getElementsByTagName("meta")[0]; document.getElementById("demo").innerHTML += "name: <b>"+meta.name+"</b> and content: <b>" +meta.content+"</b><br>"; } </script></body></html>
Output:
HTML-DOM
HTML5
JavaScript-Misc
Picked
Technical Scripter 2019
HTML
JavaScript
Technical Scripter
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
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2020"
},
{
"code": null,
"e": 145,
"s": 28,
"text": "To display meta tag information in HTML with JavaScript, we will use a method called getElementByTagName() function."
},
{
"code": null,
"e": 192,
"s": 145,
"text": "Method 1: Using getElementsByTagName() method."
},
{
"code": null,
"e": 200,
"s": 192,
"text": "Syntax:"
},
{
"code": null,
"e": 239,
"s": 200,
"text": "document.getElementsByTagName(\"meta\");"
},
{
"code": null,
"e": 399,
"s": 239,
"text": "With this, we can get all the meta elements from an HTML file. As we click on the button, all the meta tag names and content will be displayed on the web page."
},
{
"code": null,
"e": 410,
"s": 399,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"description\" content=\"GeeksforGeeks Article\"> <meta name=\"keywords\" content=\"GeeksforGeeks,GfG,Article\"> <meta name=\"author\" content=\"Aakash Pawar\"> <title>GfG</title> <style> body { font-size: 20px; margin: 20px; } button { font-size: 18px; } </style></head> <body> <button onclick=\"GfGFunction()\"> Click Here! </button> <br> <div id=\"demo\"> <h2>Content of Meta Tag<h2></div> <script> function GfGFunction() { var meta = document.getElementsByTagName(\"meta\"); for (var i = 0; i < 3; i++) { document.getElementById(\"demo\").innerHTML += \"name: <b>\"+meta[i].name+\"</b> and content: <b>\" +meta[i].content+\"</b><br>\"; } } </script></body></html>",
"e": 1316,
"s": 410,
"text": null
},
{
"code": null,
"e": 1324,
"s": 1316,
"text": "Output:"
},
{
"code": null,
"e": 1396,
"s": 1324,
"text": "Method 2: Using getElementsByTagName() method with index specification."
},
{
"code": null,
"e": 1404,
"s": 1396,
"text": "Syntax:"
},
{
"code": null,
"e": 1457,
"s": 1404,
"text": "var meta = document.getElementsByTagName(\"meta\")[0];"
},
{
"code": null,
"e": 1709,
"s": 1457,
"text": "Here, the index number ‘0’ represents the first meta element. You can consider all the meta element in an HTML file as an array and can access them by specifying the index of the meta tag. This way, we can get specific meta elements from an HTML file."
},
{
"code": null,
"e": 1720,
"s": 1709,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta id=\"author\" name=\"description\" content=\"GeeksforGeeks Article\"> <meta id=\"author\" name=\"keywords\" content=\"GeeksforGeeks,GfG,Article\"> <meta id=\"author\" name=\"author\" content=\"Aakash Pawar\"> <title>Meta Tag</title> <style> body { font-size: 20px; margin: 20px; } button { font-size: 18px; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <button onclick=\"GfGFunction()\">Click Here!</button> <br> <div id=\"demo\"> <h2>Content of Meta Tag<h2></div> <script> function GfGFunction() { var meta = document.getElementsByTagName(\"meta\")[0]; document.getElementById(\"demo\").innerHTML += \"name: <b>\"+meta.name+\"</b> and content: <b>\" +meta.content+\"</b><br>\"; } </script></body></html>",
"e": 2716,
"s": 1720,
"text": null
},
{
"code": null,
"e": 2724,
"s": 2716,
"text": "Output:"
},
{
"code": null,
"e": 2733,
"s": 2724,
"text": "HTML-DOM"
},
{
"code": null,
"e": 2739,
"s": 2733,
"text": "HTML5"
},
{
"code": null,
"e": 2755,
"s": 2739,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2762,
"s": 2755,
"text": "Picked"
},
{
"code": null,
"e": 2786,
"s": 2762,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 2791,
"s": 2786,
"text": "HTML"
},
{
"code": null,
"e": 2802,
"s": 2791,
"text": "JavaScript"
},
{
"code": null,
"e": 2821,
"s": 2802,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2826,
"s": 2821,
"text": "HTML"
},
{
"code": null,
"e": 2924,
"s": 2826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2972,
"s": 2924,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3034,
"s": 2972,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3084,
"s": 3034,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3108,
"s": 3084,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3161,
"s": 3108,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3222,
"s": 3161,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3294,
"s": 3222,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3334,
"s": 3294,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3387,
"s": 3334,
"text": "Hide or show elements in HTML using display property"
}
] |
Countplot using seaborn in Python
|
12 Jun, 2021
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas.
seaborn.countplot() method is used to Show the counts of observations in each categorical bin using bars.
Syntax : seaborn.countplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, dodge=True, ax=None, **kwargs)Parameters : This method is accepting the following parameters that are described below:
x, y: This parameter take names of variables in data or vector data, optional, Inputs for plotting long-form data.
hue : (optional) This parameter take column name for colour encoding.
data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form.
order, hue_order : (optional) This parameter take lists of strings. Order to plot the categorical levels in, otherwise the levels are inferred from the data objects.
orient : (optional)This parameter take “v” | “h”, Orientation of the plot (vertical or horizontal). This is usually inferred from the dtype of the input variables but can be used to specify when the “categorical” variable is a numeric or when plotting wide-form data.
color : (optional) This parameter take matplotlib color, Color for all of the elements, or seed for a gradient palette.
palette : (optional) This parameter take palette name, list, or dict, Colors to use for the different levels of the hue variable. Should be something that can be interpreted by color_palette(), or a dictionary mapping hue levels to matplotlib colors.
saturation : (optional) This parameter take float value, Proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color spec.
dodge : (optional) This parameter take bool value, When hue nesting is used, whether elements should be shifted along the categorical axis.
ax : (optional) This parameter take matplotlib Axes, Axes object to draw the plot onto, otherwise uses the current Axes.
kwargs : This parameter take key, value mappings, Other keyword arguments are passed through to matplotlib.axes.Axes.bar().
Returns: Returns the Axes object with the plot drawn onto it.
The below examples illustrate the countplot() method of the seaborn library.
Example 1: Show value counts for a single categorical variable.
If we use only one data variable instead of two data variables then it means that the axis denotes each of these data variables as an axis.
X denotes an x-axis and y denote a y-axis.
Syntax:
seaborn.countplot(x)
Python3
# importing the required library import seaborn as snsimport matplotlib.pyplot as plt # read a tips.csv file from seaborn librarydf = sns.load_dataset('tips') # count plot on single categorical variablesns.countplot(x ='sex', data = df) # Show the plotplt.show()
Output :
Example 2 : Show value counts for two categorical variables and using hue parameter:
While the points are plotted in two dimensions, another dimension can be added to the plot by coloring the points according to a third variable.
Syntax:
seaborn.countplot(x, y, hue, data);
Python3
# importing the required library import seaborn as snsimport matplotlib.pyplot as plt # read a tips.csv file from seaborn librarydf = sns.load_dataset('tips') # count plot on two categorical variablesns.countplot(x ='sex', hue = "smoker", data = df) # Show the plotplt.show()
Output :
Example 3 : Plot the bars horizontally.
In the above example, we see how to plot a single horizontal countplot and here can perform multiple horizontal count plots with the exchange of the data variable with another axis.
Python3
# importing the required library import seaborn as snsimport matplotlib.pyplot as plt # read a tips.csv file from seaborn librarydf = sns.load_dataset('tips') # count plot along y axissns.countplot(y ='sex', hue = "smoker", data = df) # Show the plotplt.show()
Output :
Example 4 : Use different color palette attributes.
Using the palette we can generate the point with different colors. In this below example we can see the palette can be responsible for a generate the countplot with different colormap values.
Syntax:
seaborn.countplot(x, y, data, hue, palette)
Python3
# importing the required library import seaborn as snsimport matplotlib.pyplot as plt # read a tips.csv file from seaborn librarydf = sns.load_dataset('tips') # use a different colour palette in count plotsns.countplot(x ='sex', data = df, palette = "Set2") # Show the plotplt.show()
Output :
Possible values of palette are:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r,
GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r,
Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r,
Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1,
Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr,
YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r,
cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth,
gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern,
Example 5: using a color parameter in the plot.
Using color attributes we are Color for all the elements.
Syntax:
seaborn.countplot(x, y, data, color)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.countplot(x = 'class', y = 'fare', hue = 'sex', data = df,color="salmon") # Show the plotplt.show()
Output:
Example 6: Using a saturation parameter in the plot.
Proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color spec.
Syntax:
seaborn.colorplot(x, y, data, saturation)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplotsns.countplot(x ='sex', data = df, color="salmon", saturation = 0.1)# Show the plotplt.show()
Output:
Example 7: Use matplotlib.axes.Axes.bar() parameters to control the style.
We can set Width of the gray lines that frame the plot elements using linewidth. Whenever we increase linewidth than the point also will increase automatically.
Syntax:
seaborn.countplot(x, y, data, linewidth, edgecolor)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplotsns.countplot(x ='sex', data = df,color="salmon", facecolor=(0, 0, 0, 0), linewidth=5, edgecolor=sns.color_palette("BrBG", 2))# Show the plotplt.show()
Output:
Colormap Possible values are:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r,
CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r,
OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r,
Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd,
PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r,
RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral,
kumar_satyam
simmytarika5
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jun, 2021"
},
{
"code": null,
"e": 350,
"s": 52,
"text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas. "
},
{
"code": null,
"e": 457,
"s": 350,
"text": "seaborn.countplot() method is used to Show the counts of observations in each categorical bin using bars. "
},
{
"code": null,
"e": 726,
"s": 457,
"text": "Syntax : seaborn.countplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, dodge=True, ax=None, **kwargs)Parameters : This method is accepting the following parameters that are described below: "
},
{
"code": null,
"e": 841,
"s": 726,
"text": "x, y: This parameter take names of variables in data or vector data, optional, Inputs for plotting long-form data."
},
{
"code": null,
"e": 911,
"s": 841,
"text": "hue : (optional) This parameter take column name for colour encoding."
},
{
"code": null,
"e": 1107,
"s": 911,
"text": "data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form."
},
{
"code": null,
"e": 1273,
"s": 1107,
"text": "order, hue_order : (optional) This parameter take lists of strings. Order to plot the categorical levels in, otherwise the levels are inferred from the data objects."
},
{
"code": null,
"e": 1541,
"s": 1273,
"text": "orient : (optional)This parameter take “v” | “h”, Orientation of the plot (vertical or horizontal). This is usually inferred from the dtype of the input variables but can be used to specify when the “categorical” variable is a numeric or when plotting wide-form data."
},
{
"code": null,
"e": 1661,
"s": 1541,
"text": "color : (optional) This parameter take matplotlib color, Color for all of the elements, or seed for a gradient palette."
},
{
"code": null,
"e": 1912,
"s": 1661,
"text": "palette : (optional) This parameter take palette name, list, or dict, Colors to use for the different levels of the hue variable. Should be something that can be interpreted by color_palette(), or a dictionary mapping hue levels to matplotlib colors."
},
{
"code": null,
"e": 2179,
"s": 1912,
"text": "saturation : (optional) This parameter take float value, Proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color spec."
},
{
"code": null,
"e": 2319,
"s": 2179,
"text": "dodge : (optional) This parameter take bool value, When hue nesting is used, whether elements should be shifted along the categorical axis."
},
{
"code": null,
"e": 2440,
"s": 2319,
"text": "ax : (optional) This parameter take matplotlib Axes, Axes object to draw the plot onto, otherwise uses the current Axes."
},
{
"code": null,
"e": 2564,
"s": 2440,
"text": "kwargs : This parameter take key, value mappings, Other keyword arguments are passed through to matplotlib.axes.Axes.bar()."
},
{
"code": null,
"e": 2627,
"s": 2564,
"text": "Returns: Returns the Axes object with the plot drawn onto it. "
},
{
"code": null,
"e": 2704,
"s": 2627,
"text": "The below examples illustrate the countplot() method of the seaborn library."
},
{
"code": null,
"e": 2769,
"s": 2704,
"text": "Example 1: Show value counts for a single categorical variable. "
},
{
"code": null,
"e": 2909,
"s": 2769,
"text": "If we use only one data variable instead of two data variables then it means that the axis denotes each of these data variables as an axis."
},
{
"code": null,
"e": 2952,
"s": 2909,
"text": "X denotes an x-axis and y denote a y-axis."
},
{
"code": null,
"e": 2961,
"s": 2952,
"text": "Syntax: "
},
{
"code": null,
"e": 2982,
"s": 2961,
"text": "seaborn.countplot(x)"
},
{
"code": null,
"e": 2990,
"s": 2982,
"text": "Python3"
},
{
"code": "# importing the required library import seaborn as snsimport matplotlib.pyplot as plt # read a tips.csv file from seaborn librarydf = sns.load_dataset('tips') # count plot on single categorical variablesns.countplot(x ='sex', data = df) # Show the plotplt.show()",
"e": 3253,
"s": 2990,
"text": null
},
{
"code": null,
"e": 3264,
"s": 3253,
"text": "Output : "
},
{
"code": null,
"e": 3349,
"s": 3264,
"text": "Example 2 : Show value counts for two categorical variables and using hue parameter:"
},
{
"code": null,
"e": 3494,
"s": 3349,
"text": "While the points are plotted in two dimensions, another dimension can be added to the plot by coloring the points according to a third variable."
},
{
"code": null,
"e": 3502,
"s": 3494,
"text": "Syntax:"
},
{
"code": null,
"e": 3538,
"s": 3502,
"text": "seaborn.countplot(x, y, hue, data);"
},
{
"code": null,
"e": 3546,
"s": 3538,
"text": "Python3"
},
{
"code": "# importing the required library import seaborn as snsimport matplotlib.pyplot as plt # read a tips.csv file from seaborn librarydf = sns.load_dataset('tips') # count plot on two categorical variablesns.countplot(x ='sex', hue = \"smoker\", data = df) # Show the plotplt.show()",
"e": 3822,
"s": 3546,
"text": null
},
{
"code": null,
"e": 3833,
"s": 3822,
"text": "Output : "
},
{
"code": null,
"e": 3874,
"s": 3833,
"text": "Example 3 : Plot the bars horizontally. "
},
{
"code": null,
"e": 4057,
"s": 3874,
"text": "In the above example, we see how to plot a single horizontal countplot and here can perform multiple horizontal count plots with the exchange of the data variable with another axis. "
},
{
"code": null,
"e": 4065,
"s": 4057,
"text": "Python3"
},
{
"code": "# importing the required library import seaborn as snsimport matplotlib.pyplot as plt # read a tips.csv file from seaborn librarydf = sns.load_dataset('tips') # count plot along y axissns.countplot(y ='sex', hue = \"smoker\", data = df) # Show the plotplt.show()",
"e": 4326,
"s": 4065,
"text": null
},
{
"code": null,
"e": 4337,
"s": 4326,
"text": "Output : "
},
{
"code": null,
"e": 4390,
"s": 4337,
"text": "Example 4 : Use different color palette attributes. "
},
{
"code": null,
"e": 4582,
"s": 4390,
"text": "Using the palette we can generate the point with different colors. In this below example we can see the palette can be responsible for a generate the countplot with different colormap values."
},
{
"code": null,
"e": 4590,
"s": 4582,
"text": "Syntax:"
},
{
"code": null,
"e": 4635,
"s": 4590,
"text": "seaborn.countplot(x, y, data, hue, palette) "
},
{
"code": null,
"e": 4643,
"s": 4635,
"text": "Python3"
},
{
"code": "# importing the required library import seaborn as snsimport matplotlib.pyplot as plt # read a tips.csv file from seaborn librarydf = sns.load_dataset('tips') # use a different colour palette in count plotsns.countplot(x ='sex', data = df, palette = \"Set2\") # Show the plotplt.show()",
"e": 4927,
"s": 4643,
"text": null
},
{
"code": null,
"e": 4938,
"s": 4927,
"text": "Output : "
},
{
"code": null,
"e": 4970,
"s": 4938,
"text": "Possible values of palette are:"
},
{
"code": null,
"e": 5080,
"s": 4970,
"text": "Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r,"
},
{
"code": null,
"e": 5194,
"s": 5080,
"text": "GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r,"
},
{
"code": null,
"e": 5308,
"s": 5194,
"text": "Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r,"
},
{
"code": null,
"e": 5426,
"s": 5308,
"text": "Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1,"
},
{
"code": null,
"e": 5542,
"s": 5426,
"text": "Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr,"
},
{
"code": null,
"e": 5662,
"s": 5542,
"text": "YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r,"
},
{
"code": null,
"e": 5786,
"s": 5662,
"text": "cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth,"
},
{
"code": null,
"e": 5915,
"s": 5786,
"text": "gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, "
},
{
"code": null,
"e": 5963,
"s": 5915,
"text": "Example 5: using a color parameter in the plot."
},
{
"code": null,
"e": 6021,
"s": 5963,
"text": "Using color attributes we are Color for all the elements."
},
{
"code": null,
"e": 6029,
"s": 6021,
"text": "Syntax:"
},
{
"code": null,
"e": 6066,
"s": 6029,
"text": "seaborn.countplot(x, y, data, color)"
},
{
"code": null,
"e": 6074,
"s": 6066,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.countplot(x = 'class', y = 'fare', hue = 'sex', data = df,color=\"salmon\") # Show the plotplt.show()",
"e": 6365,
"s": 6074,
"text": null
},
{
"code": null,
"e": 6373,
"s": 6365,
"text": "Output:"
},
{
"code": null,
"e": 6426,
"s": 6373,
"text": "Example 6: Using a saturation parameter in the plot."
},
{
"code": null,
"e": 6636,
"s": 6426,
"text": "Proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color spec."
},
{
"code": null,
"e": 6644,
"s": 6636,
"text": "Syntax:"
},
{
"code": null,
"e": 6686,
"s": 6644,
"text": "seaborn.colorplot(x, y, data, saturation)"
},
{
"code": null,
"e": 6694,
"s": 6686,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplotsns.countplot(x ='sex', data = df, color=\"salmon\", saturation = 0.1)# Show the plotplt.show()",
"e": 7005,
"s": 6694,
"text": null
},
{
"code": null,
"e": 7013,
"s": 7005,
"text": "Output:"
},
{
"code": null,
"e": 7088,
"s": 7013,
"text": "Example 7: Use matplotlib.axes.Axes.bar() parameters to control the style."
},
{
"code": null,
"e": 7249,
"s": 7088,
"text": "We can set Width of the gray lines that frame the plot elements using linewidth. Whenever we increase linewidth than the point also will increase automatically."
},
{
"code": null,
"e": 7257,
"s": 7249,
"text": "Syntax:"
},
{
"code": null,
"e": 7309,
"s": 7257,
"text": "seaborn.countplot(x, y, data, linewidth, edgecolor)"
},
{
"code": null,
"e": 7317,
"s": 7309,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplotsns.countplot(x ='sex', data = df,color=\"salmon\", facecolor=(0, 0, 0, 0), linewidth=5, edgecolor=sns.color_palette(\"BrBG\", 2))# Show the plotplt.show()",
"e": 7696,
"s": 7317,
"text": null
},
{
"code": null,
"e": 7704,
"s": 7696,
"text": "Output:"
},
{
"code": null,
"e": 7736,
"s": 7704,
"text": "Colormap Possible values are: "
},
{
"code": null,
"e": 7814,
"s": 7736,
"text": "Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, "
},
{
"code": null,
"e": 7898,
"s": 7814,
"text": "CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, "
},
{
"code": null,
"e": 7986,
"s": 7898,
"text": "OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, "
},
{
"code": null,
"e": 8072,
"s": 7986,
"text": "Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd,"
},
{
"code": null,
"e": 8160,
"s": 8072,
"text": "PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r,"
},
{
"code": null,
"e": 8244,
"s": 8160,
"text": "RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral,"
},
{
"code": null,
"e": 8259,
"s": 8246,
"text": "kumar_satyam"
},
{
"code": null,
"e": 8272,
"s": 8259,
"text": "simmytarika5"
},
{
"code": null,
"e": 8287,
"s": 8272,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 8294,
"s": 8287,
"text": "Python"
}
] |
HTML <a> target Attribute
|
21 Jun, 2022
The HTML <a> target Attribute is used to specify where to open the link.
Syntax:
<a target="_blank | _self | _parent | _top | framename"\>
Attribute Values:
_blank: It opens the link in a new window.
_self: It is the default value. It opens the linked document in the same frame.
_parent: It opens the linked document in the parent frameset.
_top: It opens the linked document in the full body of the window.
framename: It opens the linked document in the named frame.
Example: In this example, the GeeksforGeeks link will open in the new tab.
HTML
<!DOCTYPE html><html> <body> <h2>GeeksforGeeks</h2> <p>Welcome to <a href="https://www.geeksforgeeks.org/" target="_blank"> GeeksforGeeks </a> </p> </body> </html>
Output:
HTML <a> target attribute
Example: This example illustrates the use of the Target attribute in the <a> element.
HTML
<!DOCTYPE html><html> <head> <title> HTML a target Attribute </title></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>HTML a Target Attribute</h2> <p>Welcome to <a href="https://ide.geeksforgeeks.org/" id="GFG" target="_self"> GeeksforGeeks </a> </p> </center></body> </html>
Output:
HTML <a> target attribute
Supported Browsers:
Google Chrome version
Edge version 12 and above
Internet Explorer
Firefox version
Opera
Safari
arorakashish0911
shubhamyadav4
chhabradhanvi
bhaskargeeksforgeeks
satyamm09
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 102,
"s": 28,
"text": "The HTML <a> target Attribute is used to specify where to open the link. "
},
{
"code": null,
"e": 110,
"s": 102,
"text": "Syntax:"
},
{
"code": null,
"e": 169,
"s": 110,
"text": "<a target=\"_blank | _self | _parent | _top | framename\"\\> "
},
{
"code": null,
"e": 188,
"s": 169,
"text": "Attribute Values: "
},
{
"code": null,
"e": 231,
"s": 188,
"text": "_blank: It opens the link in a new window."
},
{
"code": null,
"e": 311,
"s": 231,
"text": "_self: It is the default value. It opens the linked document in the same frame."
},
{
"code": null,
"e": 373,
"s": 311,
"text": "_parent: It opens the linked document in the parent frameset."
},
{
"code": null,
"e": 440,
"s": 373,
"text": "_top: It opens the linked document in the full body of the window."
},
{
"code": null,
"e": 500,
"s": 440,
"text": "framename: It opens the linked document in the named frame."
},
{
"code": null,
"e": 575,
"s": 500,
"text": "Example: In this example, the GeeksforGeeks link will open in the new tab."
},
{
"code": null,
"e": 580,
"s": 575,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>GeeksforGeeks</h2> <p>Welcome to <a href=\"https://www.geeksforgeeks.org/\" target=\"_blank\"> GeeksforGeeks </a> </p> </body> </html>",
"e": 791,
"s": 580,
"text": null
},
{
"code": null,
"e": 799,
"s": 791,
"text": "Output:"
},
{
"code": null,
"e": 825,
"s": 799,
"text": "HTML <a> target attribute"
},
{
"code": null,
"e": 912,
"s": 825,
"text": "Example: This example illustrates the use of the Target attribute in the <a> element. "
},
{
"code": null,
"e": 917,
"s": 912,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML a target Attribute </title></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>HTML a Target Attribute</h2> <p>Welcome to <a href=\"https://ide.geeksforgeeks.org/\" id=\"GFG\" target=\"_self\"> GeeksforGeeks </a> </p> </center></body> </html>",
"e": 1301,
"s": 917,
"text": null
},
{
"code": null,
"e": 1309,
"s": 1301,
"text": "Output:"
},
{
"code": null,
"e": 1335,
"s": 1309,
"text": "HTML <a> target attribute"
},
{
"code": null,
"e": 1356,
"s": 1335,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 1378,
"s": 1356,
"text": "Google Chrome version"
},
{
"code": null,
"e": 1404,
"s": 1378,
"text": "Edge version 12 and above"
},
{
"code": null,
"e": 1423,
"s": 1404,
"text": "Internet Explorer "
},
{
"code": null,
"e": 1439,
"s": 1423,
"text": "Firefox version"
},
{
"code": null,
"e": 1446,
"s": 1439,
"text": "Opera "
},
{
"code": null,
"e": 1454,
"s": 1446,
"text": "Safari "
},
{
"code": null,
"e": 1471,
"s": 1454,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1485,
"s": 1471,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 1499,
"s": 1485,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 1520,
"s": 1499,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 1530,
"s": 1520,
"text": "satyamm09"
},
{
"code": null,
"e": 1546,
"s": 1530,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1551,
"s": 1546,
"text": "HTML"
},
{
"code": null,
"e": 1568,
"s": 1551,
"text": "Web Technologies"
},
{
"code": null,
"e": 1573,
"s": 1568,
"text": "HTML"
},
{
"code": null,
"e": 1671,
"s": 1573,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1695,
"s": 1671,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1745,
"s": 1695,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 1784,
"s": 1745,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1821,
"s": 1784,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 1871,
"s": 1821,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1904,
"s": 1871,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1965,
"s": 1904,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2008,
"s": 1965,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2080,
"s": 2008,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Python | Pandas Timedelta.days
|
14 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedelta and is interchangeable with it in most cases. Timedelta.days property in pandas.Timedelta is used to return Number of days.
Syntax: Timedelta.days
Parameters: None
Returns: return Number of days
Code #1:
# importing pandas as pd import pandas as pd # Create the Timedelta object td = pd.Timedelta('3 days 06:05:01.000030') # Print the Timedelta object print(td) print(td.days)
3 days 06:05:01.000030
3
Code #2:
# importing pandas as pd import pandas as pd # Create the Timedelta object td = pd.Timedelta('1 days 7 hours') # Print the Timedelta object print(td) print(td.days)
1 days 07:00:00
1
Code #3:
# importing pandas as pd import pandas as pd import datetime # Create the Timedelta object td = pd.Timedelta(datetime.timedelta(days = 3, hours = 7, seconds = 8)) # Print the Timedelta object print(td) print(td.days)
3 days 07:00:08
3
Python pandas-timedelta
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": "\n14 Jan, 2019"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 505,
"s": 242,
"text": "Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedelta and is interchangeable with it in most cases. Timedelta.days property in pandas.Timedelta is used to return Number of days."
},
{
"code": null,
"e": 528,
"s": 505,
"text": "Syntax: Timedelta.days"
},
{
"code": null,
"e": 545,
"s": 528,
"text": "Parameters: None"
},
{
"code": null,
"e": 576,
"s": 545,
"text": "Returns: return Number of days"
},
{
"code": null,
"e": 585,
"s": 576,
"text": "Code #1:"
},
{
"code": "# importing pandas as pd import pandas as pd # Create the Timedelta object td = pd.Timedelta('3 days 06:05:01.000030') # Print the Timedelta object print(td) print(td.days)",
"e": 764,
"s": 585,
"text": null
},
{
"code": null,
"e": 790,
"s": 764,
"text": "3 days 06:05:01.000030\n3\n"
},
{
"code": null,
"e": 799,
"s": 790,
"text": "Code #2:"
},
{
"code": "# importing pandas as pd import pandas as pd # Create the Timedelta object td = pd.Timedelta('1 days 7 hours') # Print the Timedelta object print(td) print(td.days)",
"e": 970,
"s": 799,
"text": null
},
{
"code": null,
"e": 989,
"s": 970,
"text": "1 days 07:00:00\n1\n"
},
{
"code": null,
"e": 998,
"s": 989,
"text": "Code #3:"
},
{
"code": "# importing pandas as pd import pandas as pd import datetime # Create the Timedelta object td = pd.Timedelta(datetime.timedelta(days = 3, hours = 7, seconds = 8)) # Print the Timedelta object print(td) print(td.days)",
"e": 1220,
"s": 998,
"text": null
},
{
"code": null,
"e": 1239,
"s": 1220,
"text": "3 days 07:00:08\n3\n"
},
{
"code": null,
"e": 1263,
"s": 1239,
"text": "Python pandas-timedelta"
},
{
"code": null,
"e": 1277,
"s": 1263,
"text": "Python-pandas"
},
{
"code": null,
"e": 1284,
"s": 1277,
"text": "Python"
}
] |
Python – Double each List element
|
01 Mar, 2020
Sometimes, while working with data, we have just a simple application in which we require to double the contents of a list and make it 100% increase in its magnitude. This is having application in web development and machine learning domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis the brute force way in which this task can be performed. In this, we just add the same element again to that index element and all the contents of list are added to itself i.e doubled.
# Python3 code to demonstrate # Double List# using loop # Initializing listtest_list = [12, 67, 98, 34, 43] # printing original listprint("The original list is : " + str(test_list)) # Double List# using loopres = []for ele in test_list: res.append(ele + ele) # printing result print ("Double List is : " + str(res))
The original list is : [12, 67, 98, 34, 43]
Double List is : [24, 134, 196, 68, 86]
Method #2 : Using list comprehensionThis task can also be performed using list comprehension. This is similar to above function. Just the difference is that its compact and one liner.
# Python3 code to demonstrate # Double List# using list comprehension # Initializing listtest_list = [12, 67, 98, 34, 43] # printing original listprint("The original list is : " + str(test_list)) # Double List# using list comprehensionres = [ele + ele for ele in test_list] # printing result print ("Double List is : " + str(res))
The original list is : [12, 67, 98, 34, 43]
Double List is : [24, 134, 196, 68, 86]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Mar, 2020"
},
{
"code": null,
"e": 335,
"s": 28,
"text": "Sometimes, while working with data, we have just a simple application in which we require to double the contents of a list and make it 100% increase in its magnitude. This is having application in web development and machine learning domains. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 547,
"s": 335,
"text": "Method #1 : Using loopThis the brute force way in which this task can be performed. In this, we just add the same element again to that index element and all the contents of list are added to itself i.e doubled."
},
{
"code": "# Python3 code to demonstrate # Double List# using loop # Initializing listtest_list = [12, 67, 98, 34, 43] # printing original listprint(\"The original list is : \" + str(test_list)) # Double List# using loopres = []for ele in test_list: res.append(ele + ele) # printing result print (\"Double List is : \" + str(res))",
"e": 874,
"s": 547,
"text": null
},
{
"code": null,
"e": 959,
"s": 874,
"text": "The original list is : [12, 67, 98, 34, 43]\nDouble List is : [24, 134, 196, 68, 86]\n"
},
{
"code": null,
"e": 1145,
"s": 961,
"text": "Method #2 : Using list comprehensionThis task can also be performed using list comprehension. This is similar to above function. Just the difference is that its compact and one liner."
},
{
"code": "# Python3 code to demonstrate # Double List# using list comprehension # Initializing listtest_list = [12, 67, 98, 34, 43] # printing original listprint(\"The original list is : \" + str(test_list)) # Double List# using list comprehensionres = [ele + ele for ele in test_list] # printing result print (\"Double List is : \" + str(res))",
"e": 1484,
"s": 1145,
"text": null
},
{
"code": null,
"e": 1569,
"s": 1484,
"text": "The original list is : [12, 67, 98, 34, 43]\nDouble List is : [24, 134, 196, 68, 86]\n"
},
{
"code": null,
"e": 1590,
"s": 1569,
"text": "Python list-programs"
},
{
"code": null,
"e": 1597,
"s": 1590,
"text": "Python"
},
{
"code": null,
"e": 1613,
"s": 1597,
"text": "Python Programs"
},
{
"code": null,
"e": 1711,
"s": 1613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1729,
"s": 1711,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1771,
"s": 1729,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1806,
"s": 1771,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1832,
"s": 1806,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1864,
"s": 1832,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1907,
"s": 1864,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1929,
"s": 1907,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1968,
"s": 1929,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2006,
"s": 1968,
"text": "Python | Convert a list to dictionary"
}
] |
Memory Leaks in Android
|
25 Sep, 2020
A memory leak is basically a failure of releasing unused objects from the memory. As a developer one does not need to think about memory allocation, memory deallocation, and garbage collection. All of these are the automatic process that the garbage collector does by itself, but the situation becomes difficult for the garbage collector when the user is referencing the object, which is in not use anymore, but since that object is being referenced by another object, garbage collector feels that the unused object is being used by another object and due to this garbage collector does not free-up the memory of that object, due to which available heap memory get decreases leading to memory shortage and memory leak. The unfreed object is basically called as leaks.
Memory leaks are the common causes of application crashes in android apps. Every developer must know how to avoid memory leaks and what are the circumstances which can lead to memory leaks in android applications. When the RAM resources are not released when they are no longer needed and if this is done several times, the part of the memory that the operating system has assigned to that particular application may exceed the upper limit and the system can terminate the application causing the application to crash. Holding the references of the object and resources that are no longer needed is the main cause of the memory leaks in android applications. As it is known that the memory for the particular object is allocated within the heap and the object point to certain resources using some object reference. But when the work is completed, the object references should be freed. But when it is not done, the heap space increases continuously and the rest of the application has to run on whatever heap space that is left, and ultimately there are high chances that it can lead to memory leaks in the application. Thus it can be said that memory leaks are a term used when our app goes short of the memory because some object which is not used but still there are being pointed out by the references and continually occupying the heap space, which ultimately leads to a shortage of space for the other components of the application and thus eventually causing the app to crash.
Note: One needs to remember that whenever there is a shortage of space in the heap and the system needs to allocate space for some new objects, the garbage collector is being called in the frequent intervals, causing to slow down of the application or sometime the application may crash.
1. Using Static Views
One should not use static views while developing the application, as static views are never destroyed.
2. Using Static Context
One should never use the Context as static, because that context will be available through the life of the application, and will not be restricted to the particular activity.
public class MainActivity extends AppCompatActivity {
// this should not be done
private static Button button;
}
3. Using Code Abstraction Frequently
Developers often take the advantage of the abstraction property because it provides the code maintenance and flexibility in code, but using abstraction might cost a bit to the developer, as while using abstraction one needs to write more code, more code means more time to execute the space and more RAM. So whenever one can avoid the abstraction in the code, it is code as it can lead to fewer memory leaks.
4. Unregistered Listeners
When the developer uses any kind of listener in his application code, then the developer should not forget to unregister the listener.
5. Unregistered Receivers
Many times the developer needs to register the local broadcast receiver in an activity. However, if the developer does not unregisters the broadcast receiver there is a strong chance that our app can lead to the memory leak problem as the receiver will hold a strong reference to the activity. So even if the activity is of no use, it will prevent the garbage collector to collect the activity for garbage collection, which will ultimately cause the memory leak.
Kotlin
// sample kotlin program for broadcast receiver import android.app.Activityimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.content.IntentFilterimport android.os.Bundleimport com.example.myapplication.R class LocalBroadcastReceiverActivity : Activity() { private var localBroadcastReceiver: BroadcastReceiver? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } private fun registerBroadCastReceiver() { localBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // Write your code here } } registerReceiver(localBroadcastReceiver, IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")) } override fun onStart() { super.onStart() // registering the broadcast receiver registerBroadCastReceiver() } override fun onStop() { super.onStop() // Broadcast receiver holds the implicit reference of Activity. // Therefore even if activity is destroy, // garbage collector will not be able to remove its instance. if (localBroadcastReceiver != null) { unregisterReceiver(localBroadcastReceiver) } }}
6. Inner class Reference
An inner class is often used by the android developers within their code. However, the nonstatic class will hold the implicit reference of the parent class which can cause the memory leak problem. So there can be two solutions that can be proposed to solve this problem:
One can make the inner class static
If one wants to pass the reference of the non-static inner class, then it can be passed using weak reference.
As it is known that when something cannot be seen, it is very difficult to fix it, same is the case with the memory leak, it cannot be seen, so it is very difficult to fix. But there are some tools that help us to detect the memory leaks in the android application and helps us to fix it. Let’s see some of the most popular tools:
1. Leak Canary
Leak Canary is a memory detection library in Android. It is developed by a square cup company. This library has a unique ability to decrease down the memory leak and helping developers to get less “MemoryOutOfError”. Leak canary even helps us to notify where the leak is actually happening. To use Leak-Canary, add the following dependency in the build.gradle(app level file).
dependencies {
// debugImplementation because LeakCanary should only run in debug builds.
debugImplementation ‘com.squareup.leakcanary:leakcanary-android:2.4’
}
Once the leak canary is installed it automatically detects and reports memory leaks in 4 steps:
Detecting retained objects.
Dumping the heap.
Analyzing the heap.
Categorizing leaks.
If one wants to dig deeper and learn how to leak canary report memory leaks can refer to the official documentation of leak canary.
2. Android Profiler
It is basically a tool that helps to keep track of memory usage of every application in android. It replaced Android Monitor in the android version 3.0 and higher. The Android Profiler is compatible with Android 5.0 (API level 21) and higher. Android Profiler detects the performance of the application in the real-time on the parameters like:
Battery
Memory (In MB)
CPU Usage (In %)
Network Rate(Rate of uploading and receiving)
To open the android profiler within the Android project in android studio, perform the following steps: Choose View > Tool Windows > Profiler > Select deployment target and choose the device. The performance of the app will be listed as shown as in the image below:
To know more about how the android profiler works, refer to the official documentation of the android profiler.
android
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Sep, 2020"
},
{
"code": null,
"e": 796,
"s": 28,
"text": "A memory leak is basically a failure of releasing unused objects from the memory. As a developer one does not need to think about memory allocation, memory deallocation, and garbage collection. All of these are the automatic process that the garbage collector does by itself, but the situation becomes difficult for the garbage collector when the user is referencing the object, which is in not use anymore, but since that object is being referenced by another object, garbage collector feels that the unused object is being used by another object and due to this garbage collector does not free-up the memory of that object, due to which available heap memory get decreases leading to memory shortage and memory leak. The unfreed object is basically called as leaks."
},
{
"code": null,
"e": 2282,
"s": 796,
"text": "Memory leaks are the common causes of application crashes in android apps. Every developer must know how to avoid memory leaks and what are the circumstances which can lead to memory leaks in android applications. When the RAM resources are not released when they are no longer needed and if this is done several times, the part of the memory that the operating system has assigned to that particular application may exceed the upper limit and the system can terminate the application causing the application to crash. Holding the references of the object and resources that are no longer needed is the main cause of the memory leaks in android applications. As it is known that the memory for the particular object is allocated within the heap and the object point to certain resources using some object reference. But when the work is completed, the object references should be freed. But when it is not done, the heap space increases continuously and the rest of the application has to run on whatever heap space that is left, and ultimately there are high chances that it can lead to memory leaks in the application. Thus it can be said that memory leaks are a term used when our app goes short of the memory because some object which is not used but still there are being pointed out by the references and continually occupying the heap space, which ultimately leads to a shortage of space for the other components of the application and thus eventually causing the app to crash."
},
{
"code": null,
"e": 2570,
"s": 2282,
"text": "Note: One needs to remember that whenever there is a shortage of space in the heap and the system needs to allocate space for some new objects, the garbage collector is being called in the frequent intervals, causing to slow down of the application or sometime the application may crash."
},
{
"code": null,
"e": 2592,
"s": 2570,
"text": "1. Using Static Views"
},
{
"code": null,
"e": 2695,
"s": 2592,
"text": "One should not use static views while developing the application, as static views are never destroyed."
},
{
"code": null,
"e": 2719,
"s": 2695,
"text": "2. Using Static Context"
},
{
"code": null,
"e": 2894,
"s": 2719,
"text": "One should never use the Context as static, because that context will be available through the life of the application, and will not be restricted to the particular activity."
},
{
"code": null,
"e": 2948,
"s": 2894,
"text": "public class MainActivity extends AppCompatActivity {"
},
{
"code": null,
"e": 2980,
"s": 2948,
"text": " // this should not be done"
},
{
"code": null,
"e": 3015,
"s": 2980,
"text": " private static Button button;"
},
{
"code": null,
"e": 3017,
"s": 3015,
"text": "}"
},
{
"code": null,
"e": 3055,
"s": 3017,
"text": "3. Using Code Abstraction Frequently "
},
{
"code": null,
"e": 3464,
"s": 3055,
"text": "Developers often take the advantage of the abstraction property because it provides the code maintenance and flexibility in code, but using abstraction might cost a bit to the developer, as while using abstraction one needs to write more code, more code means more time to execute the space and more RAM. So whenever one can avoid the abstraction in the code, it is code as it can lead to fewer memory leaks."
},
{
"code": null,
"e": 3491,
"s": 3464,
"text": "4. Unregistered Listeners"
},
{
"code": null,
"e": 3626,
"s": 3491,
"text": "When the developer uses any kind of listener in his application code, then the developer should not forget to unregister the listener."
},
{
"code": null,
"e": 3653,
"s": 3626,
"text": "5. Unregistered Receivers"
},
{
"code": null,
"e": 4116,
"s": 3653,
"text": "Many times the developer needs to register the local broadcast receiver in an activity. However, if the developer does not unregisters the broadcast receiver there is a strong chance that our app can lead to the memory leak problem as the receiver will hold a strong reference to the activity. So even if the activity is of no use, it will prevent the garbage collector to collect the activity for garbage collection, which will ultimately cause the memory leak."
},
{
"code": null,
"e": 4123,
"s": 4116,
"text": "Kotlin"
},
{
"code": "// sample kotlin program for broadcast receiver import android.app.Activityimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.content.IntentFilterimport android.os.Bundleimport com.example.myapplication.R class LocalBroadcastReceiverActivity : Activity() { private var localBroadcastReceiver: BroadcastReceiver? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } private fun registerBroadCastReceiver() { localBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // Write your code here } } registerReceiver(localBroadcastReceiver, IntentFilter(\"android.net.conn.CONNECTIVITY_CHANGE\")) } override fun onStart() { super.onStart() // registering the broadcast receiver registerBroadCastReceiver() } override fun onStop() { super.onStop() // Broadcast receiver holds the implicit reference of Activity. // Therefore even if activity is destroy, // garbage collector will not be able to remove its instance. if (localBroadcastReceiver != null) { unregisterReceiver(localBroadcastReceiver) } }}",
"e": 5519,
"s": 4123,
"text": null
},
{
"code": null,
"e": 5544,
"s": 5519,
"text": "6. Inner class Reference"
},
{
"code": null,
"e": 5815,
"s": 5544,
"text": "An inner class is often used by the android developers within their code. However, the nonstatic class will hold the implicit reference of the parent class which can cause the memory leak problem. So there can be two solutions that can be proposed to solve this problem:"
},
{
"code": null,
"e": 5851,
"s": 5815,
"text": "One can make the inner class static"
},
{
"code": null,
"e": 5961,
"s": 5851,
"text": "If one wants to pass the reference of the non-static inner class, then it can be passed using weak reference."
},
{
"code": null,
"e": 6292,
"s": 5961,
"text": "As it is known that when something cannot be seen, it is very difficult to fix it, same is the case with the memory leak, it cannot be seen, so it is very difficult to fix. But there are some tools that help us to detect the memory leaks in the android application and helps us to fix it. Let’s see some of the most popular tools:"
},
{
"code": null,
"e": 6307,
"s": 6292,
"text": "1. Leak Canary"
},
{
"code": null,
"e": 6684,
"s": 6307,
"text": "Leak Canary is a memory detection library in Android. It is developed by a square cup company. This library has a unique ability to decrease down the memory leak and helping developers to get less “MemoryOutOfError”. Leak canary even helps us to notify where the leak is actually happening. To use Leak-Canary, add the following dependency in the build.gradle(app level file)."
},
{
"code": null,
"e": 6699,
"s": 6684,
"text": "dependencies {"
},
{
"code": null,
"e": 6775,
"s": 6699,
"text": " // debugImplementation because LeakCanary should only run in debug builds."
},
{
"code": null,
"e": 6845,
"s": 6775,
"text": " debugImplementation ‘com.squareup.leakcanary:leakcanary-android:2.4’"
},
{
"code": null,
"e": 6847,
"s": 6845,
"text": "}"
},
{
"code": null,
"e": 6943,
"s": 6847,
"text": "Once the leak canary is installed it automatically detects and reports memory leaks in 4 steps:"
},
{
"code": null,
"e": 6971,
"s": 6943,
"text": "Detecting retained objects."
},
{
"code": null,
"e": 6989,
"s": 6971,
"text": "Dumping the heap."
},
{
"code": null,
"e": 7009,
"s": 6989,
"text": "Analyzing the heap."
},
{
"code": null,
"e": 7029,
"s": 7009,
"text": "Categorizing leaks."
},
{
"code": null,
"e": 7161,
"s": 7029,
"text": "If one wants to dig deeper and learn how to leak canary report memory leaks can refer to the official documentation of leak canary."
},
{
"code": null,
"e": 7181,
"s": 7161,
"text": "2. Android Profiler"
},
{
"code": null,
"e": 7525,
"s": 7181,
"text": "It is basically a tool that helps to keep track of memory usage of every application in android. It replaced Android Monitor in the android version 3.0 and higher. The Android Profiler is compatible with Android 5.0 (API level 21) and higher. Android Profiler detects the performance of the application in the real-time on the parameters like:"
},
{
"code": null,
"e": 7533,
"s": 7525,
"text": "Battery"
},
{
"code": null,
"e": 7548,
"s": 7533,
"text": "Memory (In MB)"
},
{
"code": null,
"e": 7565,
"s": 7548,
"text": "CPU Usage (In %)"
},
{
"code": null,
"e": 7611,
"s": 7565,
"text": "Network Rate(Rate of uploading and receiving)"
},
{
"code": null,
"e": 7878,
"s": 7611,
"text": "To open the android profiler within the Android project in android studio, perform the following steps: Choose View > Tool Windows > Profiler > Select deployment target and choose the device. The performance of the app will be listed as shown as in the image below: "
},
{
"code": null,
"e": 7990,
"s": 7878,
"text": "To know more about how the android profiler works, refer to the official documentation of the android profiler."
},
{
"code": null,
"e": 7998,
"s": 7990,
"text": "android"
},
{
"code": null,
"e": 8006,
"s": 7998,
"text": "Android"
},
{
"code": null,
"e": 8014,
"s": 8006,
"text": "Android"
}
] |
Python | sympy.bernoulli() method
|
14 Jul, 2019
With the help of sympy.bernoulli() method, we can find the Bernoulli number and Bernoulli polynomial in SymPy.
Syntax: bernoulli(n)
Parameter:n – It denotes the nth bernoulli number.
Returns: Returns the nth bernoulli number.
Example #1:
# import sympy from sympy import * n = 4print("Value of n = {}".format(n)) # Use sympy.bernoulli() method nth_bernoulli = bernoulli(n) print("Value of nth bernoulli number : {}".format(nth_bernoulli))
Output:
Value of n = 4
Value of nth bernoulli number : -1/30
Syntax: bernoulli(n, k)
Parameter:n – It denotes the order of the bernoulli polynomial.k – It denotes the variable in the bernoulli polynomial.
Returns: Returns the expression of the bernoulli polynomial or its value.
Example #2:
# import sympy from sympy import * n = 5k = symbols('x')print("Value of n = {} and k = {}".format(n, k)) # Use sympy.bernoulli() method nth_bernoulli_poly = bernoulli(n, k) print("The nth bernoulli polynomial : {}".format(nth_bernoulli_poly))
Output:
Value of n = 5 and k = x
The nth bernoulli polynomial : x**5 - 5*x**4/2 + 5*x**3/3 - x/6
Example #3:
# import sympy from sympy import * n = 4k = 3print("Value of n = {} and k = {}".format(n, k)) # Use sympy.bernoulli() method nth_bernoulli_poly = bernoulli(n, k) print("The nth bernoulli polynomial value : {}".format(nth_bell_poly))
Output:
Value of n = 4 and k = 3
The nth bernoulli polynomial value : 10*x1**2*x3 + 15*x1*x2**2
SymPy
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2019"
},
{
"code": null,
"e": 139,
"s": 28,
"text": "With the help of sympy.bernoulli() method, we can find the Bernoulli number and Bernoulli polynomial in SymPy."
},
{
"code": null,
"e": 160,
"s": 139,
"text": "Syntax: bernoulli(n)"
},
{
"code": null,
"e": 211,
"s": 160,
"text": "Parameter:n – It denotes the nth bernoulli number."
},
{
"code": null,
"e": 254,
"s": 211,
"text": "Returns: Returns the nth bernoulli number."
},
{
"code": null,
"e": 266,
"s": 254,
"text": "Example #1:"
},
{
"code": "# import sympy from sympy import * n = 4print(\"Value of n = {}\".format(n)) # Use sympy.bernoulli() method nth_bernoulli = bernoulli(n) print(\"Value of nth bernoulli number : {}\".format(nth_bernoulli)) ",
"e": 478,
"s": 266,
"text": null
},
{
"code": null,
"e": 486,
"s": 478,
"text": "Output:"
},
{
"code": null,
"e": 540,
"s": 486,
"text": "Value of n = 4\nValue of nth bernoulli number : -1/30\n"
},
{
"code": null,
"e": 564,
"s": 540,
"text": "Syntax: bernoulli(n, k)"
},
{
"code": null,
"e": 684,
"s": 564,
"text": "Parameter:n – It denotes the order of the bernoulli polynomial.k – It denotes the variable in the bernoulli polynomial."
},
{
"code": null,
"e": 758,
"s": 684,
"text": "Returns: Returns the expression of the bernoulli polynomial or its value."
},
{
"code": null,
"e": 770,
"s": 758,
"text": "Example #2:"
},
{
"code": "# import sympy from sympy import * n = 5k = symbols('x')print(\"Value of n = {} and k = {}\".format(n, k)) # Use sympy.bernoulli() method nth_bernoulli_poly = bernoulli(n, k) print(\"The nth bernoulli polynomial : {}\".format(nth_bernoulli_poly)) ",
"e": 1024,
"s": 770,
"text": null
},
{
"code": null,
"e": 1032,
"s": 1024,
"text": "Output:"
},
{
"code": null,
"e": 1122,
"s": 1032,
"text": "Value of n = 5 and k = x\nThe nth bernoulli polynomial : x**5 - 5*x**4/2 + 5*x**3/3 - x/6\n"
},
{
"code": null,
"e": 1134,
"s": 1122,
"text": "Example #3:"
},
{
"code": "# import sympy from sympy import * n = 4k = 3print(\"Value of n = {} and k = {}\".format(n, k)) # Use sympy.bernoulli() method nth_bernoulli_poly = bernoulli(n, k) print(\"The nth bernoulli polynomial value : {}\".format(nth_bell_poly)) ",
"e": 1378,
"s": 1134,
"text": null
},
{
"code": null,
"e": 1386,
"s": 1378,
"text": "Output:"
},
{
"code": null,
"e": 1475,
"s": 1386,
"text": "Value of n = 4 and k = 3\nThe nth bernoulli polynomial value : 10*x1**2*x3 + 15*x1*x2**2\n"
},
{
"code": null,
"e": 1481,
"s": 1475,
"text": "SymPy"
},
{
"code": null,
"e": 1488,
"s": 1481,
"text": "Python"
},
{
"code": null,
"e": 1586,
"s": 1488,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1604,
"s": 1586,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1646,
"s": 1604,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1668,
"s": 1646,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1703,
"s": 1668,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1729,
"s": 1703,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1761,
"s": 1729,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1790,
"s": 1761,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1820,
"s": 1790,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1847,
"s": 1820,
"text": "Python Classes and Objects"
}
] |
Convert Factor to Numeric and Numeric to Factor in R Programming
|
30 May, 2022
Factors are data structures which are implemented to categorize the data or represent categorical data and store it on multiple levels. They can be stored as integers with a corresponding label to every unique integer. Though factors may look similar to character vectors, they are integers, and care must be taken while using them as strings. The factor accepts only a restricted number of distinct values. It is helpful in categorizing data and storing it on multiple levels.
At times you require to explicitly change factors to either numbers or text. To achieve this, one has to use the functions as.character() or as.numeric(). There are two steps for converting factor to numeric: Step 1: Convert the data vector into a factor. The factor() command is used to create and modify factors in R. Step 2: The factor is converted into a numeric vector using as.numeric(). When a factor is converted into a numeric vector, the numeric codes corresponding to the factor levels will be returned. Example: Take a data vector ‘V’ consisting of directions and its factor will be converted into numeric.
Python3
# Data Vector 'V'V = c("North", "South", "East", "East") # Convert vector 'V' into a factordrn <- factor(V) # Converting a factor into a numeric vectoras.numeric(drn)
Output:
[1] 2 3 1 1
Converting a Factor that is a Number: If the factor is number, first convert it to a character vector and then to numeric. If a factor is a character then you need not convert it to a character. And if you try converting an alphabet character to numeric it will return NA. Example: Suppose we are taking costs of soaps of the various brands which are numbers with value s(29, 28, 210, 28, 29).
Python3
# Creating a Factorsoap_cost <- factor(c(29, 28, 210, 28, 29)) # Converting Factor to numericas.numeric(as.character(soap_cost))
Output:
[1] 29 28 210 28 29
However, if you simply use as. numeric(), the output is a vector of the internal level representations of the factor and not the original values.
Python3
# Creating a Factorsoap_cost <- factor(c(29, 28, 210, 28, 29)) # Converting Factor to Numericas.numeric(soap_cost)
Output:
[1] 2 1 3 1 2
For converting a numeric into factor we use cut() function. cut() divides the range of numeric vector(assume x) which is to be converted by cutting into intervals and codes its value (x) according to which interval they fall. Level one corresponds to the leftmost, level two corresponds to the next leftmost, and so on.
Syntax: cut.default(x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE, dig.lab = 3)
where,
When a number is given through ‘break=’ argument, the output factor is created by the division of the range of variables into that number of equal-length intervals.
In syntax include.lowest indicates whether an ‘x[i]’ which equals the lowest (for right= TRUE) break’s value should be included. And ‘right’ in the syntax indicates whether the intervals should be open on the left and closed on the right or vice versa.
If labels are not provided then dig.lab is used. The number of digits used in formatting the break numbers is determined through it.
Example 1: Lets us assume an employee data set of age, salary and gender. To create a factor corresponding to age with three equally spaced levels we can write in R as follows:
Python3
# Creating vectorsage <- c(40, 49, 48, 40, 67, 52, 53) salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220)gender <- c("male", "male", "transgender", "female", "male", "female", "transgender") # Creating data frame named employeeemployee<- data.frame(age, salary, gender) # Creating a factor corresponding to age# with three equally spaced levelswfact = cut(employee$age, 3)table(wfact)
Output:
wfact
(40,49] (49,58] (58,67]
4 2 1
Example 2: We will now put labels- young, medium and aged.
Python3
# Creating vectorsage <- c(40, 49, 48, 40, 67, 52, 53) salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220)gender <- c("male", "male", "transgender", "female", "male", "female", "transgender") # Creating data frame named employeeemployee<- data.frame(age, salary, gender) # Creating a factor corresponding to age with labelswfact = cut(employee$age, 3, labels=c('Young', 'Medium', 'Aged'))table(wfact)
Output:
wfact
Young Medium Aged
4 2 1
The next examples will use ‘norm()‘ for generating multivariate normal distributed random variants within the specified space. There are three arguments given to rnorm():
n: Number of random variables need to be generated
mean: Its value is 0 by default if not mentioned
sd: standard deviation value needs to be mentioned otherwise it is 1 by default
Syntax:
norm(n, mean, sd)
Python3
# Generating a vector with random numbersy <- rnorm(100) # the output factor is created by the division# of the range of variables into pi/3*(-3:3)# 4 equal-length intervalstable(cut(y, breaks = pi/3*(-3:3)))
Output:
(-3.14,-2.09] (-2.09,-1.05] (-1.05,0] (0,1.05] (1.05,2.09]
1 11 26 48 10
(2.09,3.14]
4
The output factor is created by the division of the range of variables into 5 equal-length intervals through break argument.
Python3
age <- c(40, 49, 48, 40, 67, 52, 53) gender <- c("male", "male", "transgender", "female", "male", "female", "transgender") # Data frame generated from the above vectorsemployee<- data.frame(age, gender) # the output factor is created by the division# of the range of variables into 5 equal-length intervalswfact = cut(employee$age, breaks=5)table(wfact)
Output:
wfact
(40,45.4] (45.4,50.8] (50.8,56.2] (56.2,61.6] (61.6,67]
2 2 2 0 1
Python3
y <- rnorm(100)table(cut(y, breaks = pi/3*(-3:3), dig.lab=5))
Output:
(-3.1416,-2.0944] (-2.0944,-1.0472] (-1.0472,0] (0,1.0472]
5 13 33 28
(1.0472,2.0944] (2.0944,3.1416]
19 2
rkbhola5
Picked
R-Factors
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?
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
R - if statement
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
Remove rows with NA in one column of R DataFrame
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 506,
"s": 28,
"text": "Factors are data structures which are implemented to categorize the data or represent categorical data and store it on multiple levels. They can be stored as integers with a corresponding label to every unique integer. Though factors may look similar to character vectors, they are integers, and care must be taken while using them as strings. The factor accepts only a restricted number of distinct values. It is helpful in categorizing data and storing it on multiple levels."
},
{
"code": null,
"e": 1126,
"s": 506,
"text": "At times you require to explicitly change factors to either numbers or text. To achieve this, one has to use the functions as.character() or as.numeric(). There are two steps for converting factor to numeric: Step 1: Convert the data vector into a factor. The factor() command is used to create and modify factors in R. Step 2: The factor is converted into a numeric vector using as.numeric(). When a factor is converted into a numeric vector, the numeric codes corresponding to the factor levels will be returned. Example: Take a data vector ‘V’ consisting of directions and its factor will be converted into numeric. "
},
{
"code": null,
"e": 1134,
"s": 1126,
"text": "Python3"
},
{
"code": "# Data Vector 'V'V = c(\"North\", \"South\", \"East\", \"East\") # Convert vector 'V' into a factordrn <- factor(V) # Converting a factor into a numeric vectoras.numeric(drn)",
"e": 1301,
"s": 1134,
"text": null
},
{
"code": null,
"e": 1309,
"s": 1301,
"text": "Output:"
},
{
"code": null,
"e": 1321,
"s": 1309,
"text": "[1] 2 3 1 1"
},
{
"code": null,
"e": 1716,
"s": 1321,
"text": "Converting a Factor that is a Number: If the factor is number, first convert it to a character vector and then to numeric. If a factor is a character then you need not convert it to a character. And if you try converting an alphabet character to numeric it will return NA. Example: Suppose we are taking costs of soaps of the various brands which are numbers with value s(29, 28, 210, 28, 29). "
},
{
"code": null,
"e": 1724,
"s": 1716,
"text": "Python3"
},
{
"code": "# Creating a Factorsoap_cost <- factor(c(29, 28, 210, 28, 29)) # Converting Factor to numericas.numeric(as.character(soap_cost))",
"e": 1853,
"s": 1724,
"text": null
},
{
"code": null,
"e": 1861,
"s": 1853,
"text": "Output:"
},
{
"code": null,
"e": 1885,
"s": 1861,
"text": "[1] 29 28 210 28 29"
},
{
"code": null,
"e": 2033,
"s": 1885,
"text": " However, if you simply use as. numeric(), the output is a vector of the internal level representations of the factor and not the original values. "
},
{
"code": null,
"e": 2041,
"s": 2033,
"text": "Python3"
},
{
"code": "# Creating a Factorsoap_cost <- factor(c(29, 28, 210, 28, 29)) # Converting Factor to Numericas.numeric(soap_cost)",
"e": 2156,
"s": 2041,
"text": null
},
{
"code": null,
"e": 2164,
"s": 2156,
"text": "Output:"
},
{
"code": null,
"e": 2178,
"s": 2164,
"text": "[1] 2 1 3 1 2"
},
{
"code": null,
"e": 2498,
"s": 2178,
"text": "For converting a numeric into factor we use cut() function. cut() divides the range of numeric vector(assume x) which is to be converted by cutting into intervals and codes its value (x) according to which interval they fall. Level one corresponds to the leftmost, level two corresponds to the next leftmost, and so on."
},
{
"code": null,
"e": 2595,
"s": 2498,
"text": "Syntax: cut.default(x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE, dig.lab = 3)"
},
{
"code": null,
"e": 2602,
"s": 2595,
"text": "where,"
},
{
"code": null,
"e": 2767,
"s": 2602,
"text": "When a number is given through ‘break=’ argument, the output factor is created by the division of the range of variables into that number of equal-length intervals."
},
{
"code": null,
"e": 3020,
"s": 2767,
"text": "In syntax include.lowest indicates whether an ‘x[i]’ which equals the lowest (for right= TRUE) break’s value should be included. And ‘right’ in the syntax indicates whether the intervals should be open on the left and closed on the right or vice versa."
},
{
"code": null,
"e": 3153,
"s": 3020,
"text": "If labels are not provided then dig.lab is used. The number of digits used in formatting the break numbers is determined through it."
},
{
"code": null,
"e": 3331,
"s": 3153,
"text": "Example 1: Lets us assume an employee data set of age, salary and gender. To create a factor corresponding to age with three equally spaced levels we can write in R as follows: "
},
{
"code": null,
"e": 3339,
"s": 3331,
"text": "Python3"
},
{
"code": "# Creating vectorsage <- c(40, 49, 48, 40, 67, 52, 53) salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220)gender <- c(\"male\", \"male\", \"transgender\", \"female\", \"male\", \"female\", \"transgender\") # Creating data frame named employeeemployee<- data.frame(age, salary, gender) # Creating a factor corresponding to age# with three equally spaced levelswfact = cut(employee$age, 3)table(wfact)",
"e": 3749,
"s": 3339,
"text": null
},
{
"code": null,
"e": 3757,
"s": 3749,
"text": "Output:"
},
{
"code": null,
"e": 3813,
"s": 3757,
"text": "wfact\n(40,49] (49,58] (58,67] \n 4 2 1 "
},
{
"code": null,
"e": 3873,
"s": 3813,
"text": "Example 2: We will now put labels- young, medium and aged. "
},
{
"code": null,
"e": 3881,
"s": 3873,
"text": "Python3"
},
{
"code": "# Creating vectorsage <- c(40, 49, 48, 40, 67, 52, 53) salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220)gender <- c(\"male\", \"male\", \"transgender\", \"female\", \"male\", \"female\", \"transgender\") # Creating data frame named employeeemployee<- data.frame(age, salary, gender) # Creating a factor corresponding to age with labelswfact = cut(employee$age, 3, labels=c('Young', 'Medium', 'Aged'))table(wfact)",
"e": 4306,
"s": 3881,
"text": null
},
{
"code": null,
"e": 4314,
"s": 4306,
"text": "Output:"
},
{
"code": null,
"e": 4364,
"s": 4314,
"text": "wfact\n Young Medium Aged \n 4 2 1 "
},
{
"code": null,
"e": 4535,
"s": 4364,
"text": "The next examples will use ‘norm()‘ for generating multivariate normal distributed random variants within the specified space. There are three arguments given to rnorm():"
},
{
"code": null,
"e": 4586,
"s": 4535,
"text": "n: Number of random variables need to be generated"
},
{
"code": null,
"e": 4635,
"s": 4586,
"text": "mean: Its value is 0 by default if not mentioned"
},
{
"code": null,
"e": 4715,
"s": 4635,
"text": "sd: standard deviation value needs to be mentioned otherwise it is 1 by default"
},
{
"code": null,
"e": 4723,
"s": 4715,
"text": "Syntax:"
},
{
"code": null,
"e": 4741,
"s": 4723,
"text": "norm(n, mean, sd)"
},
{
"code": null,
"e": 4749,
"s": 4741,
"text": "Python3"
},
{
"code": "# Generating a vector with random numbersy <- rnorm(100) # the output factor is created by the division# of the range of variables into pi/3*(-3:3)# 4 equal-length intervalstable(cut(y, breaks = pi/3*(-3:3)))",
"e": 4958,
"s": 4749,
"text": null
},
{
"code": null,
"e": 4966,
"s": 4958,
"text": "Output:"
},
{
"code": null,
"e": 5138,
"s": 4966,
"text": "(-3.14,-2.09] (-2.09,-1.05] (-1.05,0] (0,1.05] (1.05,2.09] \n 1 11 26 48 10 \n (2.09,3.14] \n 4 "
},
{
"code": null,
"e": 5264,
"s": 5138,
"text": "The output factor is created by the division of the range of variables into 5 equal-length intervals through break argument. "
},
{
"code": null,
"e": 5272,
"s": 5264,
"text": "Python3"
},
{
"code": "age <- c(40, 49, 48, 40, 67, 52, 53) gender <- c(\"male\", \"male\", \"transgender\", \"female\", \"male\", \"female\", \"transgender\") # Data frame generated from the above vectorsemployee<- data.frame(age, gender) # the output factor is created by the division# of the range of variables into 5 equal-length intervalswfact = cut(employee$age, breaks=5)table(wfact)",
"e": 5627,
"s": 5272,
"text": null
},
{
"code": null,
"e": 5635,
"s": 5627,
"text": "Output:"
},
{
"code": null,
"e": 5763,
"s": 5635,
"text": "wfact\n (40,45.4] (45.4,50.8] (50.8,56.2] (56.2,61.6] (61.6,67] \n 2 2 2 0 1 "
},
{
"code": null,
"e": 5771,
"s": 5763,
"text": "Python3"
},
{
"code": "y <- rnorm(100)table(cut(y, breaks = pi/3*(-3:3), dig.lab=5))",
"e": 5833,
"s": 5771,
"text": null
},
{
"code": null,
"e": 5841,
"s": 5833,
"text": "Output:"
},
{
"code": null,
"e": 6061,
"s": 5841,
"text": "(-3.1416,-2.0944] (-2.0944,-1.0472] (-1.0472,0] (0,1.0472] \n 5 13 33 28 \n (1.0472,2.0944] (2.0944,3.1416] \n 19 2 "
},
{
"code": null,
"e": 6070,
"s": 6061,
"text": "rkbhola5"
},
{
"code": null,
"e": 6077,
"s": 6070,
"text": "Picked"
},
{
"code": null,
"e": 6087,
"s": 6077,
"text": "R-Factors"
},
{
"code": null,
"e": 6098,
"s": 6087,
"text": "R Language"
},
{
"code": null,
"e": 6196,
"s": 6098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6248,
"s": 6196,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 6300,
"s": 6248,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 6358,
"s": 6300,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 6393,
"s": 6358,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 6437,
"s": 6393,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 6475,
"s": 6437,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 6492,
"s": 6475,
"text": "R - if statement"
},
{
"code": null,
"e": 6541,
"s": 6492,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 6578,
"s": 6541,
"text": "Logistic Regression in R Programming"
}
] |
Compare two Strings in Java
|
29 Mar, 2020
String is a sequence of characters. In Java, objects of String are immutable which means they are constant and cannot be changed once created.
Below are 5 ways to compare two Strings in Java:
Using user-defined function : Define a function to compare values with following conditions :if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.The value is calculated as (int)str1.charAt(i) – (int)str2.charAt(i)Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: -9
Input 1: Geeks
Input 2: Geeks
Output: 0
Input 1: GeeksforGeeks
Input 2: Geeks
Output: 8
Program:// Java program to Compare two strings// lexicographicallypublic class GFG { // This method compares two strings // lexicographically without using // library functions public static int stringCompare(String str1, String str2) { int l1 = str1.length(); int l2 = str2.length(); int lmin = Math.min(l1, l2); for (int i = 0; i < lmin; i++) { int str1_ch = (int)str1.charAt(i); int str2_ch = (int)str2.charAt(i); if (str1_ch != str2_ch) { return str1_ch - str2_ch; } } // Edge case for strings like // String 1="Geeks" and String 2="Geeksforgeeks" if (l1 != l2) { return l1 - l2; } // If none of the above conditions is true, // it implies both the strings are equal else { return 0; } } // Driver function to test the above program public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); // Comparing for String 1 < String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + stringCompare(string1, string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + stringCompare(string3, string4)); // Comparing for String 1 > String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + stringCompare(string1, string4)); }}Output:Comparing Geeksforgeeks and Practice : -9
Comparing Geeks and Geeks : 0
Comparing Geeksforgeeks and Geeks : 8
Using String.equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.Syntax:str1.equals(str2);Here str1 and str2 both are the strings which are to be compared.Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: false
Program:// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); String string5 = new String("geeks"); // Comparing for String 1 != String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + string1.equals(string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + string3.equals(string4)); // Comparing for String 4 != String 5 System.out.println("Comparing " + string4 + " and " + string5 + " : " + string4.equals(string5)); // Comparing for String 1 != String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + string1.equals(string4)); }}Output:Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : false
Comparing Geeksforgeeks and Geeks : false
Using String.equalsIgnoreCase() : The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false.Syntax:str2.equalsIgnoreCase(str1);Here str1 and str2 both are the strings which are to be compared.Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: true
Program:// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); String string5 = new String("geeks"); // Comparing for String 1 != String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + string1.equalsIgnoreCase(string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + string3.equalsIgnoreCase(string4)); // Comparing for String 4 = String 5 System.out.println("Comparing " + string4 + " and " + string5 + " : " + string4.equalsIgnoreCase(string5)); // Comparing for String 1 != String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + string1.equalsIgnoreCase(string4)); }}Output:Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : true
Comparing Geeksforgeeks and Geeks : false
Using Objects.equals() : Object.equals(Object a, Object b) method returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.Syntax:public static boolean equals(Object a, Object b)Here a and b both are the string objects which are to be compared.Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: null
Input 2: null
Output: true
Program:// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Geeks"); String string3 = new String("Geeks"); String string4 = null; String string5 = null; // Comparing for String 1 != String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + Objects.equals(string1, string2)); // Comparing for String 2 = String 3 System.out.println("Comparing " + string2 + " and " + string3 + " : " + Objects.equals(string2, string3)); // Comparing for String 1 != String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + Objects.equals(string1, string4)); // Comparing for String 4 = String 5 System.out.println("Comparing " + string4 + " and " + string5 + " : " + Objects.equals(string4, string5)); }}Output:Comparing Geeksforgeeks and Geeks : false
Comparing Geeks and Geeks : true
Comparing Geeksforgeeks and null : false
Comparing null and null : true
Using String.compareTo() :Syntax:int str1.compareTo(String str2)Working:It compares and returns the following values as follows:if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: -9
Input 1: Geeks
Input 2: Geeks
Output: 0
Input 1: GeeksforGeeks
Input 2: Geeks
Output: 8
Program:// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); // Comparing for String 1 < String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + string1.compareTo(string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + string3.compareTo(string4)); // Comparing for String 1 > String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + string1.compareTo(string4)); }}Output:Comparing Geeksforgeeks and Practice : -9
Comparing Geeks and Geeks : 0
Comparing Geeksforgeeks and Geeks : 8
Using user-defined function : Define a function to compare values with following conditions :if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.The value is calculated as (int)str1.charAt(i) – (int)str2.charAt(i)Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: -9
Input 1: Geeks
Input 2: Geeks
Output: 0
Input 1: GeeksforGeeks
Input 2: Geeks
Output: 8
Program:// Java program to Compare two strings// lexicographicallypublic class GFG { // This method compares two strings // lexicographically without using // library functions public static int stringCompare(String str1, String str2) { int l1 = str1.length(); int l2 = str2.length(); int lmin = Math.min(l1, l2); for (int i = 0; i < lmin; i++) { int str1_ch = (int)str1.charAt(i); int str2_ch = (int)str2.charAt(i); if (str1_ch != str2_ch) { return str1_ch - str2_ch; } } // Edge case for strings like // String 1="Geeks" and String 2="Geeksforgeeks" if (l1 != l2) { return l1 - l2; } // If none of the above conditions is true, // it implies both the strings are equal else { return 0; } } // Driver function to test the above program public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); // Comparing for String 1 < String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + stringCompare(string1, string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + stringCompare(string3, string4)); // Comparing for String 1 > String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + stringCompare(string1, string4)); }}Output:Comparing Geeksforgeeks and Practice : -9
Comparing Geeks and Geeks : 0
Comparing Geeksforgeeks and Geeks : 8
if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.
if (string1 > string2) it returns a positive value.
if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.
if (string1 < string2) it returns a negative value.
The value is calculated as (int)str1.charAt(i) – (int)str2.charAt(i)
Examples:
Input 1: GeeksforGeeks
Input 2: Practice
Output: -9
Input 1: Geeks
Input 2: Geeks
Output: 0
Input 1: GeeksforGeeks
Input 2: Geeks
Output: 8
Program:
// Java program to Compare two strings// lexicographicallypublic class GFG { // This method compares two strings // lexicographically without using // library functions public static int stringCompare(String str1, String str2) { int l1 = str1.length(); int l2 = str2.length(); int lmin = Math.min(l1, l2); for (int i = 0; i < lmin; i++) { int str1_ch = (int)str1.charAt(i); int str2_ch = (int)str2.charAt(i); if (str1_ch != str2_ch) { return str1_ch - str2_ch; } } // Edge case for strings like // String 1="Geeks" and String 2="Geeksforgeeks" if (l1 != l2) { return l1 - l2; } // If none of the above conditions is true, // it implies both the strings are equal else { return 0; } } // Driver function to test the above program public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); // Comparing for String 1 < String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + stringCompare(string1, string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + stringCompare(string3, string4)); // Comparing for String 1 > String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + stringCompare(string1, string4)); }}
Comparing Geeksforgeeks and Practice : -9
Comparing Geeks and Geeks : 0
Comparing Geeksforgeeks and Geeks : 8
Using String.equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.Syntax:str1.equals(str2);Here str1 and str2 both are the strings which are to be compared.Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: false
Program:// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); String string5 = new String("geeks"); // Comparing for String 1 != String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + string1.equals(string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + string3.equals(string4)); // Comparing for String 4 != String 5 System.out.println("Comparing " + string4 + " and " + string5 + " : " + string4.equals(string5)); // Comparing for String 1 != String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + string1.equals(string4)); }}Output:Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : false
Comparing Geeksforgeeks and Geeks : false
Syntax:
str1.equals(str2);
Here str1 and str2 both are the strings which are to be compared.
Examples:
Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: false
Program:
// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); String string5 = new String("geeks"); // Comparing for String 1 != String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + string1.equals(string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + string3.equals(string4)); // Comparing for String 4 != String 5 System.out.println("Comparing " + string4 + " and " + string5 + " : " + string4.equals(string5)); // Comparing for String 1 != String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + string1.equals(string4)); }}
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : false
Comparing Geeksforgeeks and Geeks : false
Using String.equalsIgnoreCase() : The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false.Syntax:str2.equalsIgnoreCase(str1);Here str1 and str2 both are the strings which are to be compared.Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: true
Program:// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); String string5 = new String("geeks"); // Comparing for String 1 != String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + string1.equalsIgnoreCase(string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + string3.equalsIgnoreCase(string4)); // Comparing for String 4 = String 5 System.out.println("Comparing " + string4 + " and " + string5 + " : " + string4.equalsIgnoreCase(string5)); // Comparing for String 1 != String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + string1.equalsIgnoreCase(string4)); }}Output:Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : true
Comparing Geeksforgeeks and Geeks : false
Syntax:
str2.equalsIgnoreCase(str1);
Here str1 and str2 both are the strings which are to be compared.
Examples:
Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: true
Program:
// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); String string5 = new String("geeks"); // Comparing for String 1 != String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + string1.equalsIgnoreCase(string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + string3.equalsIgnoreCase(string4)); // Comparing for String 4 = String 5 System.out.println("Comparing " + string4 + " and " + string5 + " : " + string4.equalsIgnoreCase(string5)); // Comparing for String 1 != String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + string1.equalsIgnoreCase(string4)); }}
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : true
Comparing Geeksforgeeks and Geeks : false
Using Objects.equals() : Object.equals(Object a, Object b) method returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.Syntax:public static boolean equals(Object a, Object b)Here a and b both are the string objects which are to be compared.Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: null
Input 2: null
Output: true
Program:// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Geeks"); String string3 = new String("Geeks"); String string4 = null; String string5 = null; // Comparing for String 1 != String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + Objects.equals(string1, string2)); // Comparing for String 2 = String 3 System.out.println("Comparing " + string2 + " and " + string3 + " : " + Objects.equals(string2, string3)); // Comparing for String 1 != String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + Objects.equals(string1, string4)); // Comparing for String 4 = String 5 System.out.println("Comparing " + string4 + " and " + string5 + " : " + Objects.equals(string4, string5)); }}Output:Comparing Geeksforgeeks and Geeks : false
Comparing Geeks and Geeks : true
Comparing Geeksforgeeks and null : false
Comparing null and null : true
Syntax:
public static boolean equals(Object a, Object b)
Here a and b both are the string objects which are to be compared.
Examples:
Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: null
Input 2: null
Output: true
Program:
// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Geeks"); String string3 = new String("Geeks"); String string4 = null; String string5 = null; // Comparing for String 1 != String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + Objects.equals(string1, string2)); // Comparing for String 2 = String 3 System.out.println("Comparing " + string2 + " and " + string3 + " : " + Objects.equals(string2, string3)); // Comparing for String 1 != String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + Objects.equals(string1, string4)); // Comparing for String 4 = String 5 System.out.println("Comparing " + string4 + " and " + string5 + " : " + Objects.equals(string4, string5)); }}
Comparing Geeksforgeeks and Geeks : false
Comparing Geeks and Geeks : true
Comparing Geeksforgeeks and null : false
Comparing null and null : true
Using String.compareTo() :Syntax:int str1.compareTo(String str2)Working:It compares and returns the following values as follows:if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.Examples:Input 1: GeeksforGeeks
Input 2: Practice
Output: -9
Input 1: Geeks
Input 2: Geeks
Output: 0
Input 1: GeeksforGeeks
Input 2: Geeks
Output: 8
Program:// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); // Comparing for String 1 < String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + string1.compareTo(string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + string3.compareTo(string4)); // Comparing for String 1 > String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + string1.compareTo(string4)); }}Output:Comparing Geeksforgeeks and Practice : -9
Comparing Geeks and Geeks : 0
Comparing Geeksforgeeks and Geeks : 8
Syntax:
int str1.compareTo(String str2)
Working:It compares and returns the following values as follows:
if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.
if (string1 > string2) it returns a positive value.
if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.
if (string1 < string2) it returns a negative value.
Examples:
Input 1: GeeksforGeeks
Input 2: Practice
Output: -9
Input 1: Geeks
Input 2: Geeks
Output: 0
Input 1: GeeksforGeeks
Input 2: Geeks
Output: 8
Program:
// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String("Geeksforgeeks"); String string2 = new String("Practice"); String string3 = new String("Geeks"); String string4 = new String("Geeks"); // Comparing for String 1 < String 2 System.out.println("Comparing " + string1 + " and " + string2 + " : " + string1.compareTo(string2)); // Comparing for String 3 = String 4 System.out.println("Comparing " + string3 + " and " + string4 + " : " + string3.compareTo(string4)); // Comparing for String 1 > String 4 System.out.println("Comparing " + string1 + " and " + string4 + " : " + string1.compareTo(string4)); }}
Comparing Geeksforgeeks and Practice : -9
Comparing Geeks and Geeks : 0
Comparing Geeksforgeeks and Geeks : 8
Why not to use == for comparison of Strings?
In general both equals() and “==” operator in Java are used to compare objects to check equality but here are some of the differences between the two:
Main difference between .equals() method and == operator is that one is method and other is operator.
One can use == operators for reference comparison (address comparison) and .equals() method for content comparison.
In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
Example:
// Java program to understand// why to avoid == operator public class Test { public static void main(String[] args) { String s1 = new String("HELLO"); String s2 = new String("HELLO"); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); }}
false
true
Explanation: Here two String objects are being created namely s1 and s2.
Both s1 and s2 refers to different objects.
When one uses == operator for s1 and s2 comparison then the result is false as both have different addresses in memory.
Using equals, the result is true because its only comparing the values given in s1 and s2.
zemiak
mpetrynski
Java-String-Programs
Java-Strings
Java
Java-Strings
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
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Mar, 2020"
},
{
"code": null,
"e": 195,
"s": 52,
"text": "String is a sequence of characters. In Java, objects of String are immutable which means they are constant and cannot be changed once created."
},
{
"code": null,
"e": 244,
"s": 195,
"text": "Below are 5 ways to compare two Strings in Java:"
},
{
"code": null,
"e": 9502,
"s": 244,
"text": "Using user-defined function : Define a function to compare values with following conditions :if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.The value is calculated as (int)str1.charAt(i) – (int)str2.charAt(i)Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: -9\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: 0\n\nInput 1: GeeksforGeeks\nInput 2: Geeks\nOutput: 8\nProgram:// Java program to Compare two strings// lexicographicallypublic class GFG { // This method compares two strings // lexicographically without using // library functions public static int stringCompare(String str1, String str2) { int l1 = str1.length(); int l2 = str2.length(); int lmin = Math.min(l1, l2); for (int i = 0; i < lmin; i++) { int str1_ch = (int)str1.charAt(i); int str2_ch = (int)str2.charAt(i); if (str1_ch != str2_ch) { return str1_ch - str2_ch; } } // Edge case for strings like // String 1=\"Geeks\" and String 2=\"Geeksforgeeks\" if (l1 != l2) { return l1 - l2; } // If none of the above conditions is true, // it implies both the strings are equal else { return 0; } } // Driver function to test the above program public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); // Comparing for String 1 < String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + stringCompare(string1, string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + stringCompare(string3, string4)); // Comparing for String 1 > String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + stringCompare(string1, string4)); }}Output:Comparing Geeksforgeeks and Practice : -9\nComparing Geeks and Geeks : 0\nComparing Geeksforgeeks and Geeks : 8\nUsing String.equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.Syntax:str1.equals(str2);Here str1 and str2 both are the strings which are to be compared.Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: false\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: true\n\nInput 1: geeks\nInput 2: Geeks\nOutput: false\nProgram:// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); String string5 = new String(\"geeks\"); // Comparing for String 1 != String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + string1.equals(string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + string3.equals(string4)); // Comparing for String 4 != String 5 System.out.println(\"Comparing \" + string4 + \" and \" + string5 + \" : \" + string4.equals(string5)); // Comparing for String 1 != String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + string1.equals(string4)); }}Output:Comparing Geeksforgeeks and Practice : false\nComparing Geeks and Geeks : true\nComparing Geeks and geeks : false\nComparing Geeksforgeeks and Geeks : false\nUsing String.equalsIgnoreCase() : The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false.Syntax:str2.equalsIgnoreCase(str1);Here str1 and str2 both are the strings which are to be compared.Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: false\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: true\n\nInput 1: geeks\nInput 2: Geeks\nOutput: true\nProgram:// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); String string5 = new String(\"geeks\"); // Comparing for String 1 != String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + string1.equalsIgnoreCase(string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + string3.equalsIgnoreCase(string4)); // Comparing for String 4 = String 5 System.out.println(\"Comparing \" + string4 + \" and \" + string5 + \" : \" + string4.equalsIgnoreCase(string5)); // Comparing for String 1 != String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + string1.equalsIgnoreCase(string4)); }}Output:Comparing Geeksforgeeks and Practice : false\nComparing Geeks and Geeks : true\nComparing Geeks and geeks : true\nComparing Geeksforgeeks and Geeks : false\nUsing Objects.equals() : Object.equals(Object a, Object b) method returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.Syntax:public static boolean equals(Object a, Object b)Here a and b both are the string objects which are to be compared.Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: false\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: true\n\nInput 1: null\nInput 2: null\nOutput: true\nProgram:// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Geeks\"); String string3 = new String(\"Geeks\"); String string4 = null; String string5 = null; // Comparing for String 1 != String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + Objects.equals(string1, string2)); // Comparing for String 2 = String 3 System.out.println(\"Comparing \" + string2 + \" and \" + string3 + \" : \" + Objects.equals(string2, string3)); // Comparing for String 1 != String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + Objects.equals(string1, string4)); // Comparing for String 4 = String 5 System.out.println(\"Comparing \" + string4 + \" and \" + string5 + \" : \" + Objects.equals(string4, string5)); }}Output:Comparing Geeksforgeeks and Geeks : false\nComparing Geeks and Geeks : true\nComparing Geeksforgeeks and null : false\nComparing null and null : true\nUsing String.compareTo() :Syntax:int str1.compareTo(String str2)Working:It compares and returns the following values as follows:if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: -9\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: 0\n\nInput 1: GeeksforGeeks\nInput 2: Geeks\nOutput: 8\nProgram:// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); // Comparing for String 1 < String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + string1.compareTo(string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + string3.compareTo(string4)); // Comparing for String 1 > String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + string1.compareTo(string4)); }}Output:Comparing Geeksforgeeks and Practice : -9\nComparing Geeks and Geeks : 0\nComparing Geeksforgeeks and Geeks : 8\n"
},
{
"code": null,
"e": 11861,
"s": 9502,
"text": "Using user-defined function : Define a function to compare values with following conditions :if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.The value is calculated as (int)str1.charAt(i) – (int)str2.charAt(i)Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: -9\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: 0\n\nInput 1: GeeksforGeeks\nInput 2: Geeks\nOutput: 8\nProgram:// Java program to Compare two strings// lexicographicallypublic class GFG { // This method compares two strings // lexicographically without using // library functions public static int stringCompare(String str1, String str2) { int l1 = str1.length(); int l2 = str2.length(); int lmin = Math.min(l1, l2); for (int i = 0; i < lmin; i++) { int str1_ch = (int)str1.charAt(i); int str2_ch = (int)str2.charAt(i); if (str1_ch != str2_ch) { return str1_ch - str2_ch; } } // Edge case for strings like // String 1=\"Geeks\" and String 2=\"Geeksforgeeks\" if (l1 != l2) { return l1 - l2; } // If none of the above conditions is true, // it implies both the strings are equal else { return 0; } } // Driver function to test the above program public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); // Comparing for String 1 < String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + stringCompare(string1, string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + stringCompare(string3, string4)); // Comparing for String 1 > String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + stringCompare(string1, string4)); }}Output:Comparing Geeksforgeeks and Practice : -9\nComparing Geeks and Geeks : 0\nComparing Geeksforgeeks and Geeks : 8\n"
},
{
"code": null,
"e": 12049,
"s": 11861,
"text": "if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value."
},
{
"code": null,
"e": 12101,
"s": 12049,
"text": "if (string1 > string2) it returns a positive value."
},
{
"code": null,
"e": 12187,
"s": 12101,
"text": "if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0."
},
{
"code": null,
"e": 12239,
"s": 12187,
"text": "if (string1 < string2) it returns a negative value."
},
{
"code": null,
"e": 12308,
"s": 12239,
"text": "The value is calculated as (int)str1.charAt(i) – (int)str2.charAt(i)"
},
{
"code": null,
"e": 12318,
"s": 12308,
"text": "Examples:"
},
{
"code": null,
"e": 12461,
"s": 12318,
"text": "Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: -9\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: 0\n\nInput 1: GeeksforGeeks\nInput 2: Geeks\nOutput: 8\n"
},
{
"code": null,
"e": 12470,
"s": 12461,
"text": "Program:"
},
{
"code": "// Java program to Compare two strings// lexicographicallypublic class GFG { // This method compares two strings // lexicographically without using // library functions public static int stringCompare(String str1, String str2) { int l1 = str1.length(); int l2 = str2.length(); int lmin = Math.min(l1, l2); for (int i = 0; i < lmin; i++) { int str1_ch = (int)str1.charAt(i); int str2_ch = (int)str2.charAt(i); if (str1_ch != str2_ch) { return str1_ch - str2_ch; } } // Edge case for strings like // String 1=\"Geeks\" and String 2=\"Geeksforgeeks\" if (l1 != l2) { return l1 - l2; } // If none of the above conditions is true, // it implies both the strings are equal else { return 0; } } // Driver function to test the above program public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); // Comparing for String 1 < String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + stringCompare(string1, string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + stringCompare(string3, string4)); // Comparing for String 1 > String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + stringCompare(string1, string4)); }}",
"e": 14205,
"s": 12470,
"text": null
},
{
"code": null,
"e": 14316,
"s": 14205,
"text": "Comparing Geeksforgeeks and Practice : -9\nComparing Geeks and Geeks : 0\nComparing Geeksforgeeks and Geeks : 8\n"
},
{
"code": null,
"e": 16058,
"s": 14316,
"text": "Using String.equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.Syntax:str1.equals(str2);Here str1 and str2 both are the strings which are to be compared.Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: false\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: true\n\nInput 1: geeks\nInput 2: Geeks\nOutput: false\nProgram:// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); String string5 = new String(\"geeks\"); // Comparing for String 1 != String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + string1.equals(string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + string3.equals(string4)); // Comparing for String 4 != String 5 System.out.println(\"Comparing \" + string4 + \" and \" + string5 + \" : \" + string4.equals(string5)); // Comparing for String 1 != String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + string1.equals(string4)); }}Output:Comparing Geeksforgeeks and Practice : false\nComparing Geeks and Geeks : true\nComparing Geeks and geeks : false\nComparing Geeksforgeeks and Geeks : false\n"
},
{
"code": null,
"e": 16066,
"s": 16058,
"text": "Syntax:"
},
{
"code": null,
"e": 16085,
"s": 16066,
"text": "str1.equals(str2);"
},
{
"code": null,
"e": 16151,
"s": 16085,
"text": "Here str1 and str2 both are the strings which are to be compared."
},
{
"code": null,
"e": 16161,
"s": 16151,
"text": "Examples:"
},
{
"code": null,
"e": 16306,
"s": 16161,
"text": "Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: false\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: true\n\nInput 1: geeks\nInput 2: Geeks\nOutput: false\n"
},
{
"code": null,
"e": 16315,
"s": 16306,
"text": "Program:"
},
{
"code": "// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); String string5 = new String(\"geeks\"); // Comparing for String 1 != String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + string1.equals(string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + string3.equals(string4)); // Comparing for String 4 != String 5 System.out.println(\"Comparing \" + string4 + \" and \" + string5 + \" : \" + string4.equals(string5)); // Comparing for String 1 != String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + string1.equals(string4)); }}",
"e": 17392,
"s": 16315,
"text": null
},
{
"code": null,
"e": 17547,
"s": 17392,
"text": "Comparing Geeksforgeeks and Practice : false\nComparing Geeks and Geeks : true\nComparing Geeks and geeks : false\nComparing Geeksforgeeks and Geeks : false\n"
},
{
"code": null,
"e": 19357,
"s": 17547,
"text": "Using String.equalsIgnoreCase() : The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false.Syntax:str2.equalsIgnoreCase(str1);Here str1 and str2 both are the strings which are to be compared.Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: false\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: true\n\nInput 1: geeks\nInput 2: Geeks\nOutput: true\nProgram:// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); String string5 = new String(\"geeks\"); // Comparing for String 1 != String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + string1.equalsIgnoreCase(string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + string3.equalsIgnoreCase(string4)); // Comparing for String 4 = String 5 System.out.println(\"Comparing \" + string4 + \" and \" + string5 + \" : \" + string4.equalsIgnoreCase(string5)); // Comparing for String 1 != String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + string1.equalsIgnoreCase(string4)); }}Output:Comparing Geeksforgeeks and Practice : false\nComparing Geeks and Geeks : true\nComparing Geeks and geeks : true\nComparing Geeksforgeeks and Geeks : false\n"
},
{
"code": null,
"e": 19365,
"s": 19357,
"text": "Syntax:"
},
{
"code": null,
"e": 19394,
"s": 19365,
"text": "str2.equalsIgnoreCase(str1);"
},
{
"code": null,
"e": 19460,
"s": 19394,
"text": "Here str1 and str2 both are the strings which are to be compared."
},
{
"code": null,
"e": 19470,
"s": 19460,
"text": "Examples:"
},
{
"code": null,
"e": 19614,
"s": 19470,
"text": "Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: false\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: true\n\nInput 1: geeks\nInput 2: Geeks\nOutput: true\n"
},
{
"code": null,
"e": 19623,
"s": 19614,
"text": "Program:"
},
{
"code": "// Java program to Compare two strings// lexicographicallypublic class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); String string5 = new String(\"geeks\"); // Comparing for String 1 != String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + string1.equalsIgnoreCase(string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + string3.equalsIgnoreCase(string4)); // Comparing for String 4 = String 5 System.out.println(\"Comparing \" + string4 + \" and \" + string5 + \" : \" + string4.equalsIgnoreCase(string5)); // Comparing for String 1 != String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + string1.equalsIgnoreCase(string4)); }}",
"e": 20739,
"s": 19623,
"text": null
},
{
"code": null,
"e": 20893,
"s": 20739,
"text": "Comparing Geeksforgeeks and Practice : false\nComparing Geeks and Geeks : true\nComparing Geeks and geeks : true\nComparing Geeksforgeeks and Geeks : false\n"
},
{
"code": null,
"e": 22769,
"s": 20893,
"text": "Using Objects.equals() : Object.equals(Object a, Object b) method returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.Syntax:public static boolean equals(Object a, Object b)Here a and b both are the string objects which are to be compared.Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: false\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: true\n\nInput 1: null\nInput 2: null\nOutput: true\nProgram:// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Geeks\"); String string3 = new String(\"Geeks\"); String string4 = null; String string5 = null; // Comparing for String 1 != String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + Objects.equals(string1, string2)); // Comparing for String 2 = String 3 System.out.println(\"Comparing \" + string2 + \" and \" + string3 + \" : \" + Objects.equals(string2, string3)); // Comparing for String 1 != String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + Objects.equals(string1, string4)); // Comparing for String 4 = String 5 System.out.println(\"Comparing \" + string4 + \" and \" + string5 + \" : \" + Objects.equals(string4, string5)); }}Output:Comparing Geeksforgeeks and Geeks : false\nComparing Geeks and Geeks : true\nComparing Geeksforgeeks and null : false\nComparing null and null : true\n"
},
{
"code": null,
"e": 22777,
"s": 22769,
"text": "Syntax:"
},
{
"code": null,
"e": 22826,
"s": 22777,
"text": "public static boolean equals(Object a, Object b)"
},
{
"code": null,
"e": 22893,
"s": 22826,
"text": "Here a and b both are the string objects which are to be compared."
},
{
"code": null,
"e": 22903,
"s": 22893,
"text": "Examples:"
},
{
"code": null,
"e": 23045,
"s": 22903,
"text": "Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: false\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: true\n\nInput 1: null\nInput 2: null\nOutput: true\n"
},
{
"code": null,
"e": 23054,
"s": 23045,
"text": "Program:"
},
{
"code": "// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Geeks\"); String string3 = new String(\"Geeks\"); String string4 = null; String string5 = null; // Comparing for String 1 != String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + Objects.equals(string1, string2)); // Comparing for String 2 = String 3 System.out.println(\"Comparing \" + string2 + \" and \" + string3 + \" : \" + Objects.equals(string2, string3)); // Comparing for String 1 != String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + Objects.equals(string1, string4)); // Comparing for String 4 = String 5 System.out.println(\"Comparing \" + string4 + \" and \" + string5 + \" : \" + Objects.equals(string4, string5)); }}",
"e": 24156,
"s": 23054,
"text": null
},
{
"code": null,
"e": 24304,
"s": 24156,
"text": "Comparing Geeksforgeeks and Geeks : false\nComparing Geeks and Geeks : true\nComparing Geeksforgeeks and null : false\nComparing null and null : true\n"
},
{
"code": null,
"e": 25779,
"s": 24304,
"text": "Using String.compareTo() :Syntax:int str1.compareTo(String str2)Working:It compares and returns the following values as follows:if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value.Examples:Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: -9\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: 0\n\nInput 1: GeeksforGeeks\nInput 2: Geeks\nOutput: 8\nProgram:// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); // Comparing for String 1 < String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + string1.compareTo(string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + string3.compareTo(string4)); // Comparing for String 1 > String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + string1.compareTo(string4)); }}Output:Comparing Geeksforgeeks and Practice : -9\nComparing Geeks and Geeks : 0\nComparing Geeksforgeeks and Geeks : 8\n"
},
{
"code": null,
"e": 25787,
"s": 25779,
"text": "Syntax:"
},
{
"code": null,
"e": 25819,
"s": 25787,
"text": "int str1.compareTo(String str2)"
},
{
"code": null,
"e": 25884,
"s": 25819,
"text": "Working:It compares and returns the following values as follows:"
},
{
"code": null,
"e": 26072,
"s": 25884,
"text": "if (string1 > string2) it returns a positive value.if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0.if (string1 < string2) it returns a negative value."
},
{
"code": null,
"e": 26124,
"s": 26072,
"text": "if (string1 > string2) it returns a positive value."
},
{
"code": null,
"e": 26210,
"s": 26124,
"text": "if both the strings are equal lexicographicallyi.e.(string1 == string2) it returns 0."
},
{
"code": null,
"e": 26262,
"s": 26210,
"text": "if (string1 < string2) it returns a negative value."
},
{
"code": null,
"e": 26272,
"s": 26262,
"text": "Examples:"
},
{
"code": null,
"e": 26415,
"s": 26272,
"text": "Input 1: GeeksforGeeks\nInput 2: Practice\nOutput: -9\n\nInput 1: Geeks\nInput 2: Geeks\nOutput: 0\n\nInput 1: GeeksforGeeks\nInput 2: Geeks\nOutput: 8\n"
},
{
"code": null,
"e": 26424,
"s": 26415,
"text": "Program:"
},
{
"code": "// Java program to Compare two strings// lexicographically import java.util.*; public class GFG { public static void main(String args[]) { String string1 = new String(\"Geeksforgeeks\"); String string2 = new String(\"Practice\"); String string3 = new String(\"Geeks\"); String string4 = new String(\"Geeks\"); // Comparing for String 1 < String 2 System.out.println(\"Comparing \" + string1 + \" and \" + string2 + \" : \" + string1.compareTo(string2)); // Comparing for String 3 = String 4 System.out.println(\"Comparing \" + string3 + \" and \" + string4 + \" : \" + string3.compareTo(string4)); // Comparing for String 1 > String 4 System.out.println(\"Comparing \" + string1 + \" and \" + string4 + \" : \" + string1.compareTo(string4)); }}",
"e": 27308,
"s": 26424,
"text": null
},
{
"code": null,
"e": 27419,
"s": 27308,
"text": "Comparing Geeksforgeeks and Practice : -9\nComparing Geeks and Geeks : 0\nComparing Geeksforgeeks and Geeks : 8\n"
},
{
"code": null,
"e": 27464,
"s": 27419,
"text": "Why not to use == for comparison of Strings?"
},
{
"code": null,
"e": 27615,
"s": 27464,
"text": "In general both equals() and “==” operator in Java are used to compare objects to check equality but here are some of the differences between the two:"
},
{
"code": null,
"e": 27717,
"s": 27615,
"text": "Main difference between .equals() method and == operator is that one is method and other is operator."
},
{
"code": null,
"e": 27833,
"s": 27717,
"text": "One can use == operators for reference comparison (address comparison) and .equals() method for content comparison."
},
{
"code": null,
"e": 27982,
"s": 27833,
"text": "In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects."
},
{
"code": null,
"e": 27991,
"s": 27982,
"text": "Example:"
},
{
"code": "// Java program to understand// why to avoid == operator public class Test { public static void main(String[] args) { String s1 = new String(\"HELLO\"); String s2 = new String(\"HELLO\"); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); }}",
"e": 28285,
"s": 27991,
"text": null
},
{
"code": null,
"e": 28297,
"s": 28285,
"text": "false\ntrue\n"
},
{
"code": null,
"e": 28370,
"s": 28297,
"text": "Explanation: Here two String objects are being created namely s1 and s2."
},
{
"code": null,
"e": 28414,
"s": 28370,
"text": "Both s1 and s2 refers to different objects."
},
{
"code": null,
"e": 28534,
"s": 28414,
"text": "When one uses == operator for s1 and s2 comparison then the result is false as both have different addresses in memory."
},
{
"code": null,
"e": 28625,
"s": 28534,
"text": "Using equals, the result is true because its only comparing the values given in s1 and s2."
},
{
"code": null,
"e": 28632,
"s": 28625,
"text": "zemiak"
},
{
"code": null,
"e": 28643,
"s": 28632,
"text": "mpetrynski"
},
{
"code": null,
"e": 28664,
"s": 28643,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 28677,
"s": 28664,
"text": "Java-Strings"
},
{
"code": null,
"e": 28682,
"s": 28677,
"text": "Java"
},
{
"code": null,
"e": 28695,
"s": 28682,
"text": "Java-Strings"
},
{
"code": null,
"e": 28700,
"s": 28695,
"text": "Java"
},
{
"code": null,
"e": 28798,
"s": 28700,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28849,
"s": 28798,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28880,
"s": 28849,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28899,
"s": 28880,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28929,
"s": 28899,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28944,
"s": 28929,
"text": "Stream In Java"
},
{
"code": null,
"e": 28962,
"s": 28944,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28982,
"s": 28962,
"text": "Collections in Java"
},
{
"code": null,
"e": 29006,
"s": 28982,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29038,
"s": 29006,
"text": "Multidimensional Arrays in Java"
}
] |
Java 8 | Collectors counting() with Examples
|
06 Dec, 2018
Collectors counting() method is used to count the number of elements passed in the stream as the parameter. It returns a Collector accepting elements of type T that counts the number of input elements. If no elements are present, the result is 0. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. It returns the total count of elements in the stream which reach the collect() method after undergoing various pipelined stream operations such as filtering, reduction etc.
Syntax:
public static <T> Collector<T, ?, Long> counting()
where the mentioned terms are as follows:
Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation.
T: The type of input elements to the reduction operation.
A: The mutable accumulation type of the reduction operation.
R: The result type of the reduction operation.
Long: The Long class wraps a value of the primitive type long in an object. An object of type Long contains a single field whose type is long. In addition, this class provides several methods for converting a long to a String and a String to a long, as well as other constants and methods useful when dealing with a long.
T: The type of the input elements.
Parameters: This method does not take any parameter.
Return Value: A Collector that counts the input elements. The count is returned as Long object.
Below are examples to illustrate counting() method:
Program 1:
// Java code to show the implementation of// Collectors counting() method import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a stream of strings Stream<String> s = Stream.of("1", "2", "3", "4"); // using Collectors counting() method to // count the number of input elements long ans = s.collect(Collectors.counting()); // displaying the required count System.out.println(ans); }}
4
Program 2: When no element is passed as input element.
// Java code to show the implementation of// Collectors counting() method import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a stream of strings Stream<String> s = Stream.of(); // using Collectors counting() method to // count the number of input elements long ans = s.collect(Collectors.counting()); // displaying the required count System.out.println(ans); }}
0
Java - util package
Java-Collectors
Java-Functions
java-stream
Java-Stream-Collectors
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 545,
"s": 28,
"text": "Collectors counting() method is used to count the number of elements passed in the stream as the parameter. It returns a Collector accepting elements of type T that counts the number of input elements. If no elements are present, the result is 0. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. It returns the total count of elements in the stream which reach the collect() method after undergoing various pipelined stream operations such as filtering, reduction etc."
},
{
"code": null,
"e": 553,
"s": 545,
"text": "Syntax:"
},
{
"code": null,
"e": 605,
"s": 553,
"text": "public static <T> Collector<T, ?, Long> counting()\n"
},
{
"code": null,
"e": 647,
"s": 605,
"text": "where the mentioned terms are as follows:"
},
{
"code": null,
"e": 1130,
"s": 647,
"text": "Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation."
},
{
"code": null,
"e": 1188,
"s": 1130,
"text": "T: The type of input elements to the reduction operation."
},
{
"code": null,
"e": 1249,
"s": 1188,
"text": "A: The mutable accumulation type of the reduction operation."
},
{
"code": null,
"e": 1296,
"s": 1249,
"text": "R: The result type of the reduction operation."
},
{
"code": null,
"e": 1618,
"s": 1296,
"text": "Long: The Long class wraps a value of the primitive type long in an object. An object of type Long contains a single field whose type is long. In addition, this class provides several methods for converting a long to a String and a String to a long, as well as other constants and methods useful when dealing with a long."
},
{
"code": null,
"e": 1653,
"s": 1618,
"text": "T: The type of the input elements."
},
{
"code": null,
"e": 1706,
"s": 1653,
"text": "Parameters: This method does not take any parameter."
},
{
"code": null,
"e": 1802,
"s": 1706,
"text": "Return Value: A Collector that counts the input elements. The count is returned as Long object."
},
{
"code": null,
"e": 1854,
"s": 1802,
"text": "Below are examples to illustrate counting() method:"
},
{
"code": null,
"e": 1865,
"s": 1854,
"text": "Program 1:"
},
{
"code": "// Java code to show the implementation of// Collectors counting() method import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a stream of strings Stream<String> s = Stream.of(\"1\", \"2\", \"3\", \"4\"); // using Collectors counting() method to // count the number of input elements long ans = s.collect(Collectors.counting()); // displaying the required count System.out.println(ans); }}",
"e": 2410,
"s": 1865,
"text": null
},
{
"code": null,
"e": 2413,
"s": 2410,
"text": "4\n"
},
{
"code": null,
"e": 2468,
"s": 2413,
"text": "Program 2: When no element is passed as input element."
},
{
"code": "// Java code to show the implementation of// Collectors counting() method import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a stream of strings Stream<String> s = Stream.of(); // using Collectors counting() method to // count the number of input elements long ans = s.collect(Collectors.counting()); // displaying the required count System.out.println(ans); }}",
"e": 2995,
"s": 2468,
"text": null
},
{
"code": null,
"e": 2998,
"s": 2995,
"text": "0\n"
},
{
"code": null,
"e": 3018,
"s": 2998,
"text": "Java - util package"
},
{
"code": null,
"e": 3034,
"s": 3018,
"text": "Java-Collectors"
},
{
"code": null,
"e": 3049,
"s": 3034,
"text": "Java-Functions"
},
{
"code": null,
"e": 3061,
"s": 3049,
"text": "java-stream"
},
{
"code": null,
"e": 3084,
"s": 3061,
"text": "Java-Stream-Collectors"
},
{
"code": null,
"e": 3089,
"s": 3084,
"text": "Java"
},
{
"code": null,
"e": 3094,
"s": 3089,
"text": "Java"
}
] |
Python | Sum of squares in list
|
12 Mar, 2019
Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of squares of list in just one line. Let’s discuss certain ways in which this can be performed.
Method #1 : Using reduce() + lambdaThe power of lambda functions to perform lengthy tasks in just one line, allows it combined with reduce which is used to accumulate the subproblem, to perform this task as well. Works with only Python 2.
# Python code to demonstrate # sum of squares # using reduce() + lambda # initializing listtest_list = [3, 5, 7, 9, 11] # printing original list print ("The original list is : " + str(test_list)) # using reduce() + lambda# sum of squares res = reduce(lambda i, j: i + j * j, [test_list[:1][0]**2]+test_list[1:]) # printing resultprint ("The sum of squares of list is : " + str(res))
The original list is : [3, 5, 7, 9, 11]
The sum of squares of list is : 285
Method #2 : Using map() + sum()The similar solution can also be obtained using the map function to integrate and sum function to perform the summation of the squared number.
# Python3 code to demonstrate # sum of squares # using sum() + max() # initializing listtest_list = [3, 5, 7, 9, 11] # printing original list print ("The original list is : " + str(test_list)) # using sum() + max()# sum of squares res = sum(map(lambda i : i * i, test_list)) # printing resultprint ("The sum of squares of list is : " + str(res))
The original list is : [3, 5, 7, 9, 11]
The sum of squares of list is : 285
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python | Split string into list of characters
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Mar, 2019"
},
{
"code": null,
"e": 374,
"s": 28,
"text": "Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of squares of list in just one line. Let’s discuss certain ways in which this can be performed."
},
{
"code": null,
"e": 613,
"s": 374,
"text": "Method #1 : Using reduce() + lambdaThe power of lambda functions to perform lengthy tasks in just one line, allows it combined with reduce which is used to accumulate the subproblem, to perform this task as well. Works with only Python 2."
},
{
"code": "# Python code to demonstrate # sum of squares # using reduce() + lambda # initializing listtest_list = [3, 5, 7, 9, 11] # printing original list print (\"The original list is : \" + str(test_list)) # using reduce() + lambda# sum of squares res = reduce(lambda i, j: i + j * j, [test_list[:1][0]**2]+test_list[1:]) # printing resultprint (\"The sum of squares of list is : \" + str(res))",
"e": 1001,
"s": 613,
"text": null
},
{
"code": null,
"e": 1078,
"s": 1001,
"text": "The original list is : [3, 5, 7, 9, 11]\nThe sum of squares of list is : 285\n"
},
{
"code": null,
"e": 1254,
"s": 1080,
"text": "Method #2 : Using map() + sum()The similar solution can also be obtained using the map function to integrate and sum function to perform the summation of the squared number."
},
{
"code": "# Python3 code to demonstrate # sum of squares # using sum() + max() # initializing listtest_list = [3, 5, 7, 9, 11] # printing original list print (\"The original list is : \" + str(test_list)) # using sum() + max()# sum of squares res = sum(map(lambda i : i * i, test_list)) # printing resultprint (\"The sum of squares of list is : \" + str(res))",
"e": 1605,
"s": 1254,
"text": null
},
{
"code": null,
"e": 1682,
"s": 1605,
"text": "The original list is : [3, 5, 7, 9, 11]\nThe sum of squares of list is : 285\n"
},
{
"code": null,
"e": 1703,
"s": 1682,
"text": "Python list-programs"
},
{
"code": null,
"e": 1710,
"s": 1703,
"text": "Python"
},
{
"code": null,
"e": 1726,
"s": 1710,
"text": "Python Programs"
},
{
"code": null,
"e": 1824,
"s": 1726,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1842,
"s": 1824,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1884,
"s": 1842,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1906,
"s": 1884,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1932,
"s": 1906,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1964,
"s": 1932,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1986,
"s": 1964,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2025,
"s": 1986,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2063,
"s": 2025,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2112,
"s": 2063,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Remove newline, space and tab characters from a string in Java
|
To remove newline, space and tab characters from a string, replace them with empty as shown below.
replaceAll("[\\n\\t ]", "");
Above, the new line, tab, and space will get replaced with empty, since we have used replaceAll()
The following is the complete example.
Live Demo
public class Demo {
public static void main(String[] args) {
String originalStr = "Demo\n\tText";
System.out.println("Original String with tabs, spaces and newline: \n"+originalStr);
originalStr = originalStr.replaceAll("[\\n\\t ]", "");
System.out.println("\nString after removing tabs, spaces and new line: "+originalStr);
}
}
Original String with tabs, spaces and newline:
Demo
Text
String after removing tabs, spaces and new line: DemoText
|
[
{
"code": null,
"e": 1286,
"s": 1187,
"text": "To remove newline, space and tab characters from a string, replace them with empty as shown below."
},
{
"code": null,
"e": 1315,
"s": 1286,
"text": "replaceAll(\"[\\\\n\\\\t ]\", \"\");"
},
{
"code": null,
"e": 1413,
"s": 1315,
"text": "Above, the new line, tab, and space will get replaced with empty, since we have used replaceAll()"
},
{
"code": null,
"e": 1452,
"s": 1413,
"text": "The following is the complete example."
},
{
"code": null,
"e": 1463,
"s": 1452,
"text": " Live Demo"
},
{
"code": null,
"e": 1822,
"s": 1463,
"text": "public class Demo {\n public static void main(String[] args) {\n String originalStr = \"Demo\\n\\tText\";\n System.out.println(\"Original String with tabs, spaces and newline: \\n\"+originalStr);\n originalStr = originalStr.replaceAll(\"[\\\\n\\\\t ]\", \"\");\n System.out.println(\"\\nString after removing tabs, spaces and new line: \"+originalStr);\n }\n}"
},
{
"code": null,
"e": 1937,
"s": 1822,
"text": "Original String with tabs, spaces and newline:\nDemo\nText\nString after removing tabs, spaces and new line: DemoText"
}
] |
Print the season name of the year based on the month number
|
06 Nov, 2021
Given the month number M, the task is to print the season name of the year based on the month number.Examples:
Input: M = 5
Output: SPRING
Input: M = 1
Output: WINTER
Approach:
There are 4 main seasons in a year, that is, Summer, Autumn, Winter and Spring.
The winter months are in December, January and February.
The spring months in March, April and May.
The summer months in June, July and August.
And the autumn months in September, October and November.
So map the month to the particular season respectively and print it.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to print the season// name based on the month number#include <bits/stdc++.h>using namespace std; void findSeason(int M){ // Checks out the season according // to the month number entered by the user switch (M) { case 12: case 1: case 2: cout << ("\nWINTER"); break; case 3: case 4: case 5: cout << ("\nSPRING"); break; case 6: case 7: case 8: cout << ("\nSUMMER"); break; case 9: case 10: case 11: cout << ("\nAUTUMN"); break; default: // Handles the condition if number entered // is not among the valid 12 months cout << ("\nInvalid Month number"); break; }} // Driver codeint main(){ int M = 5; cout << "For Month number: " << M; findSeason(M); M = 10; cout << "\nFor Month number: " << M; findSeason(M); return 0;} // This code is contributed by Rajput-Ji
// Java program to print the season// name based on the month number import java.util.*;public class Seasons { public static void findSeason(int M) { // Checks out the season according // to the month number entered by the user switch (M) { case 12: case 1: case 2: System.out.println("WINTER"); break; case 3: case 4: case 5: System.out.println("SPRING"); break; case 6: case 7: case 8: System.out.println("SUMMER"); break; case 9: case 10: case 11: System.out.println("AUTUMN"); break; default: // Handles the condition if number entered // is not among the valid 12 months System.out.println("Invalid Month number"); break; } } // Driver Code public static void main(String abc[]) { int M = 5; System.out.println("For Month number: " + M); findSeason(M); M = 10; System.out.println("For Month number: " + M); findSeason(M); }}
# Python3 program to print the season# name based on the month numberdef findseason (M) : # Taken all the possible # month numbers in the list. list1 = [[12 , 1 , 2], [3 , 4 , 5], [6 , 7 , 8], [9 , 10 , 11]] # Matching the month number # with the above list entries if M in list1[0] : print ( "WINTER" ) elif M in list1[1] : print ( "SPRING" ) elif M in list1[2] : print ( "SUMMER" ) elif M in list1[3] : print ( "AUTUMN" ) else : print ( "Invalid Month Number" ) # Driver CodeM = 5print("For Month number:", M);findseason ( M ) M = 10print("For Month number:", M);findseason ( M ) # This code is contributed by Abhishek
// C# program to print the season// name based on the month numberusing System; class GFG{public static void findSeason(int M){ // Checks out the season according // to the month number entered by the user switch (M) { case 12: case 1: case 2: Console.WriteLine("WINTER"); break; case 3: case 4: case 5: Console.WriteLine("SPRING"); break; case 6: case 7: case 8: Console.WriteLine("SUMMER"); break; case 9: case 10: case 11: Console.WriteLine("AUTUMN"); break; default: // Handles the condition if number entered // is not among the valid 12 months Console.WriteLine("Invalid Month number"); break; }} // Driver Codepublic static void Main(){ int M = 5; Console.WriteLine("For Month number: " + M); findSeason(M); M = 10; Console.WriteLine("For Month number: " + M); findSeason(M);}} // This code is contributed by AnkitRai01
<script> // Javascript program to print the season// name based on the month number function findSeason(M) { // Checks out the season according // to the month number entered by the user switch (M) { case 12: case 1: case 2: document.write("WLETER" + "<br/>"); break; case 3: case 4: case 5: document.write("SPRING" + "<br/>"); break; case 6: case 7: case 8: document.write("SUMMER" + "<br/>"); break; case 9: case 10: case 11: document.write("AUTUMN" + "<br/>"); break; default: // Handles the condition if number entered // is not among the valid 12 months document.write("Invalid Month number"); break; } } // Driver code let M = 5; document.write("For Month number: " + M + "<br/>"); findSeason(M); M = 10; document.write("For Month number: " + M + "<br/>"); findSeason(M); // This code is contributed by susmitakundugoaldanga.</script>
For Month number: 5
SPRING
For Month number: 10
AUTUMN
Time Complexity: O(1)
Auxiliary Space: O(1)
ankthon
Rajput-Ji
Abhishek_070
susmitakundugoaldanga
rohitsingh07052
Hash
School Programming
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Real-time application of Data Structures
Find k numbers with most occurrences in the given array
set vs unordered_set in C++ STL
Find the length of largest subarray with 0 sum
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Nov, 2021"
},
{
"code": null,
"e": 141,
"s": 28,
"text": "Given the month number M, the task is to print the season name of the year based on the month number.Examples: "
},
{
"code": null,
"e": 198,
"s": 141,
"text": "Input: M = 5\nOutput: SPRING\n\nInput: M = 1\nOutput: WINTER"
},
{
"code": null,
"e": 212,
"s": 200,
"text": "Approach: "
},
{
"code": null,
"e": 292,
"s": 212,
"text": "There are 4 main seasons in a year, that is, Summer, Autumn, Winter and Spring."
},
{
"code": null,
"e": 349,
"s": 292,
"text": "The winter months are in December, January and February."
},
{
"code": null,
"e": 392,
"s": 349,
"text": "The spring months in March, April and May."
},
{
"code": null,
"e": 436,
"s": 392,
"text": "The summer months in June, July and August."
},
{
"code": null,
"e": 494,
"s": 436,
"text": "And the autumn months in September, October and November."
},
{
"code": null,
"e": 563,
"s": 494,
"text": "So map the month to the particular season respectively and print it."
},
{
"code": null,
"e": 616,
"s": 563,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 620,
"s": 616,
"text": "C++"
},
{
"code": null,
"e": 625,
"s": 620,
"text": "Java"
},
{
"code": null,
"e": 633,
"s": 625,
"text": "Python3"
},
{
"code": null,
"e": 636,
"s": 633,
"text": "C#"
},
{
"code": null,
"e": 647,
"s": 636,
"text": "Javascript"
},
{
"code": "// C++ program to print the season// name based on the month number#include <bits/stdc++.h>using namespace std; void findSeason(int M){ // Checks out the season according // to the month number entered by the user switch (M) { case 12: case 1: case 2: cout << (\"\\nWINTER\"); break; case 3: case 4: case 5: cout << (\"\\nSPRING\"); break; case 6: case 7: case 8: cout << (\"\\nSUMMER\"); break; case 9: case 10: case 11: cout << (\"\\nAUTUMN\"); break; default: // Handles the condition if number entered // is not among the valid 12 months cout << (\"\\nInvalid Month number\"); break; }} // Driver codeint main(){ int M = 5; cout << \"For Month number: \" << M; findSeason(M); M = 10; cout << \"\\nFor Month number: \" << M; findSeason(M); return 0;} // This code is contributed by Rajput-Ji",
"e": 1692,
"s": 647,
"text": null
},
{
"code": "// Java program to print the season// name based on the month number import java.util.*;public class Seasons { public static void findSeason(int M) { // Checks out the season according // to the month number entered by the user switch (M) { case 12: case 1: case 2: System.out.println(\"WINTER\"); break; case 3: case 4: case 5: System.out.println(\"SPRING\"); break; case 6: case 7: case 8: System.out.println(\"SUMMER\"); break; case 9: case 10: case 11: System.out.println(\"AUTUMN\"); break; default: // Handles the condition if number entered // is not among the valid 12 months System.out.println(\"Invalid Month number\"); break; } } // Driver Code public static void main(String abc[]) { int M = 5; System.out.println(\"For Month number: \" + M); findSeason(M); M = 10; System.out.println(\"For Month number: \" + M); findSeason(M); }}",
"e": 2892,
"s": 1692,
"text": null
},
{
"code": "# Python3 program to print the season# name based on the month numberdef findseason (M) : # Taken all the possible # month numbers in the list. list1 = [[12 , 1 , 2], [3 , 4 , 5], [6 , 7 , 8], [9 , 10 , 11]] # Matching the month number # with the above list entries if M in list1[0] : print ( \"WINTER\" ) elif M in list1[1] : print ( \"SPRING\" ) elif M in list1[2] : print ( \"SUMMER\" ) elif M in list1[3] : print ( \"AUTUMN\" ) else : print ( \"Invalid Month Number\" ) # Driver CodeM = 5print(\"For Month number:\", M);findseason ( M ) M = 10print(\"For Month number:\", M);findseason ( M ) # This code is contributed by Abhishek",
"e": 3609,
"s": 2892,
"text": null
},
{
"code": "// C# program to print the season// name based on the month numberusing System; class GFG{public static void findSeason(int M){ // Checks out the season according // to the month number entered by the user switch (M) { case 12: case 1: case 2: Console.WriteLine(\"WINTER\"); break; case 3: case 4: case 5: Console.WriteLine(\"SPRING\"); break; case 6: case 7: case 8: Console.WriteLine(\"SUMMER\"); break; case 9: case 10: case 11: Console.WriteLine(\"AUTUMN\"); break; default: // Handles the condition if number entered // is not among the valid 12 months Console.WriteLine(\"Invalid Month number\"); break; }} // Driver Codepublic static void Main(){ int M = 5; Console.WriteLine(\"For Month number: \" + M); findSeason(M); M = 10; Console.WriteLine(\"For Month number: \" + M); findSeason(M);}} // This code is contributed by AnkitRai01",
"e": 4694,
"s": 3609,
"text": null
},
{
"code": "<script> // Javascript program to print the season// name based on the month number function findSeason(M) { // Checks out the season according // to the month number entered by the user switch (M) { case 12: case 1: case 2: document.write(\"WLETER\" + \"<br/>\"); break; case 3: case 4: case 5: document.write(\"SPRING\" + \"<br/>\"); break; case 6: case 7: case 8: document.write(\"SUMMER\" + \"<br/>\"); break; case 9: case 10: case 11: document.write(\"AUTUMN\" + \"<br/>\"); break; default: // Handles the condition if number entered // is not among the valid 12 months document.write(\"Invalid Month number\"); break; } } // Driver code let M = 5; document.write(\"For Month number: \" + M + \"<br/>\"); findSeason(M); M = 10; document.write(\"For Month number: \" + M + \"<br/>\"); findSeason(M); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 5917,
"s": 4694,
"text": null
},
{
"code": null,
"e": 5972,
"s": 5917,
"text": "For Month number: 5\nSPRING\nFor Month number: 10\nAUTUMN"
},
{
"code": null,
"e": 5996,
"s": 5974,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 6018,
"s": 5996,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6026,
"s": 6018,
"text": "ankthon"
},
{
"code": null,
"e": 6036,
"s": 6026,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6049,
"s": 6036,
"text": "Abhishek_070"
},
{
"code": null,
"e": 6071,
"s": 6049,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 6087,
"s": 6071,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 6092,
"s": 6087,
"text": "Hash"
},
{
"code": null,
"e": 6111,
"s": 6092,
"text": "School Programming"
},
{
"code": null,
"e": 6116,
"s": 6111,
"text": "Hash"
},
{
"code": null,
"e": 6214,
"s": 6116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6252,
"s": 6214,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6293,
"s": 6252,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 6349,
"s": 6293,
"text": "Find k numbers with most occurrences in the given array"
},
{
"code": null,
"e": 6381,
"s": 6349,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 6428,
"s": 6381,
"text": "Find the length of largest subarray with 0 sum"
},
{
"code": null,
"e": 6446,
"s": 6428,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6471,
"s": 6446,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6487,
"s": 6471,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 6510,
"s": 6487,
"text": "Introduction To PYTHON"
}
] |
Session Objects – Python requests
|
07 Jun, 2022
Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3’s connection pooling. So, if several requests are being made to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase. A session object all the methods as of requests.
Let us illustrate the use of session objects by setting a cookie to a URL and then making a request again to check if the cookie is set.
Python3
# import requests moduleimport requests # create a session objects = requests.Session() # make a get requests.get('https://httpbin.org / cookies / set / sessioncookie / 123456789') # again make a get requestr = s.get('https://httpbin.org / cookies') # check if cookie is still setprint(r.text)
Output One can check that cookie was still set when the request was made again. Sessions can also be used to provide default data to the request methods. This is done by providing data to the properties on a Session object:
Python3
# import requests moduleimport requests # create a session objects = requests.Session() # set username and passwords.auth = ('user', 'pass') # update headerss.headers.update({'x-test': 'true'}) # both 'x-test' and 'x-test2' are sents.get('https://httpbin.org / headers', headers ={'x-test2': 'true'}) # print objectprint(s)
Output
shreelakshmijoshi1
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 454,
"s": 54,
"text": "Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3’s connection pooling. So, if several requests are being made to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase. A session object all the methods as of requests."
},
{
"code": null,
"e": 592,
"s": 454,
"text": "Let us illustrate the use of session objects by setting a cookie to a URL and then making a request again to check if the cookie is set. "
},
{
"code": null,
"e": 600,
"s": 592,
"text": "Python3"
},
{
"code": "# import requests moduleimport requests # create a session objects = requests.Session() # make a get requests.get('https://httpbin.org / cookies / set / sessioncookie / 123456789') # again make a get requestr = s.get('https://httpbin.org / cookies') # check if cookie is still setprint(r.text)",
"e": 894,
"s": 600,
"text": null
},
{
"code": null,
"e": 1120,
"s": 894,
"text": "Output One can check that cookie was still set when the request was made again. Sessions can also be used to provide default data to the request methods. This is done by providing data to the properties on a Session object: "
},
{
"code": null,
"e": 1128,
"s": 1120,
"text": "Python3"
},
{
"code": "# import requests moduleimport requests # create a session objects = requests.Session() # set username and passwords.auth = ('user', 'pass') # update headerss.headers.update({'x-test': 'true'}) # both 'x-test' and 'x-test2' are sents.get('https://httpbin.org / headers', headers ={'x-test2': 'true'}) # print objectprint(s)",
"e": 1452,
"s": 1128,
"text": null
},
{
"code": null,
"e": 1460,
"s": 1452,
"text": "Output "
},
{
"code": null,
"e": 1479,
"s": 1460,
"text": "shreelakshmijoshi1"
},
{
"code": null,
"e": 1495,
"s": 1479,
"text": "Python-requests"
},
{
"code": null,
"e": 1502,
"s": 1495,
"text": "Python"
},
{
"code": null,
"e": 1600,
"s": 1502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1642,
"s": 1600,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1664,
"s": 1642,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1690,
"s": 1664,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1722,
"s": 1690,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1751,
"s": 1722,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1778,
"s": 1751,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1799,
"s": 1778,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1835,
"s": 1799,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1858,
"s": 1835,
"text": "Introduction To PYTHON"
}
] |
What is an Optional parameter in C#?
|
By default, all parameters of a method are required. A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments.
The optional parameter contains a default value in function definition. If we do not pass optional argument value at calling time, the default value is used.
Thera are different ways to make a parameter optional.
Live Demo
using System;
namespace DemoApplication{
class Demo{
static void Main(string[] args){
OptionalMethodWithDefaultValue(5);
//Value2 is not passed as it is optional
OptionalMethodWithDefaultValue(5, 10);
//Value2 is passed
Console.ReadLine();
}
public static void OptionalMethodWithDefaultValue(int value1, int value2 = 5){
Console.WriteLine($"Sum is {value1 + value2}");
}
}
}
The output of the above code is
Sum is 10
Sum is 15
In the above example, the method OptionalMethodWithDefaultValue(int value1, int value2 = 5) value2 is having default value 5. So if no arguments is passed for value2 while calling it will take the default value 5 and if an argument is passed for value2 then the default value is overridden.
Live Demo
using System;
using System.Runtime.InteropServices;
namespace DemoApplication{
class Demo{
static void Main(string[] args){
OptionalMethodWithDefaultValue(5);
OptionalMethodWithDefaultValue(5, 10);
Console.ReadLine();
}
public static void OptionalMethodWithDefaultValue(int value1, [Optional]int value2){
Console.WriteLine($"Sum is {value1 + value2}");
}
}
}
The output of the above code is
Sum is 5
Sum is 15
Here for the [Optional] attribute is used to specify the optional parameter.
Also, it should be noted that optional parameters should always be specified at the end of the parameters. For ex − OptionalMethodWithDefaultValue(int value1 = 5, int value2) will throw exception.
using System;
namespace DemoApplication{
class Demo{
static void Main(string[] args){
OptionalMethodWithDefaultValue(5);
OptionalMethodWithDefaultValue(5, 10);
Console.ReadLine();
}
public static void OptionalMethodWithDefaultValue(int value1 = 5, int value2){
Console.WriteLine($"Sum is {value1 + value2}");
}
}
}
Error − Optional Parameters must appear after all required parameters.
|
[
{
"code": null,
"e": 1388,
"s": 1187,
"text": "By default, all parameters of a method are required. A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments."
},
{
"code": null,
"e": 1546,
"s": 1388,
"text": "The optional parameter contains a default value in function definition. If we do not pass optional argument value at calling time, the default value is used."
},
{
"code": null,
"e": 1601,
"s": 1546,
"text": "Thera are different ways to make a parameter optional."
},
{
"code": null,
"e": 1612,
"s": 1601,
"text": " Live Demo"
},
{
"code": null,
"e": 2071,
"s": 1612,
"text": "using System;\nnamespace DemoApplication{\n class Demo{\n static void Main(string[] args){\n OptionalMethodWithDefaultValue(5);\n //Value2 is not passed as it is optional\n OptionalMethodWithDefaultValue(5, 10);\n //Value2 is passed\n Console.ReadLine();\n }\n public static void OptionalMethodWithDefaultValue(int value1, int value2 = 5){\n Console.WriteLine($\"Sum is {value1 + value2}\");\n }\n }\n}"
},
{
"code": null,
"e": 2103,
"s": 2071,
"text": "The output of the above code is"
},
{
"code": null,
"e": 2123,
"s": 2103,
"text": "Sum is 10\nSum is 15"
},
{
"code": null,
"e": 2414,
"s": 2123,
"text": "In the above example, the method OptionalMethodWithDefaultValue(int value1, int value2 = 5) value2 is having default value 5. So if no arguments is passed for value2 while calling it will take the default value 5 and if an argument is passed for value2 then the default value is overridden."
},
{
"code": null,
"e": 2425,
"s": 2414,
"text": " Live Demo"
},
{
"code": null,
"e": 2850,
"s": 2425,
"text": "using System;\nusing System.Runtime.InteropServices;\nnamespace DemoApplication{\n class Demo{\n static void Main(string[] args){\n OptionalMethodWithDefaultValue(5);\n OptionalMethodWithDefaultValue(5, 10);\n Console.ReadLine();\n }\n public static void OptionalMethodWithDefaultValue(int value1, [Optional]int value2){\n Console.WriteLine($\"Sum is {value1 + value2}\");\n }\n }\n}"
},
{
"code": null,
"e": 2882,
"s": 2850,
"text": "The output of the above code is"
},
{
"code": null,
"e": 2901,
"s": 2882,
"text": "Sum is 5\nSum is 15"
},
{
"code": null,
"e": 2978,
"s": 2901,
"text": "Here for the [Optional] attribute is used to specify the optional parameter."
},
{
"code": null,
"e": 3175,
"s": 2978,
"text": "Also, it should be noted that optional parameters should always be specified at the end of the parameters. For ex − OptionalMethodWithDefaultValue(int value1 = 5, int value2) will throw exception."
},
{
"code": null,
"e": 3556,
"s": 3175,
"text": "using System;\nnamespace DemoApplication{\n class Demo{\n static void Main(string[] args){\n OptionalMethodWithDefaultValue(5);\n OptionalMethodWithDefaultValue(5, 10);\n Console.ReadLine();\n }\n public static void OptionalMethodWithDefaultValue(int value1 = 5, int value2){\n Console.WriteLine($\"Sum is {value1 + value2}\");\n }\n }\n}"
},
{
"code": null,
"e": 3627,
"s": 3556,
"text": "Error − Optional Parameters must appear after all required parameters."
}
] |
Python | How and where to apply Feature Scaling?
|
27 Sep, 2021
Feature Scaling or Standardization: It is a step of Data Pre Processing that is applied to independent variables or features of data. It basically helps to normalize the data within a particular range. Sometimes, it also helps in speeding up the calculations in an algorithm.
Package Used:
sklearn.preprocessing
Import:
from sklearn.preprocessing import StandardScaler
The formula used in Backend Standardization replaces the values with their Z scores.
Mostly the Fit method is used for Feature scaling
fit(X, y = None)
Computes the mean and std to be used for later scaling.
Python
import pandas as pdfrom sklearn.preprocessing import StandardScaler # Read Data from CSVdata = read_csv('Geeksforgeeks.csv')data.head() # Initialise the Scalerscaler = StandardScaler() # To scale datascaler.fit(data)
Why and Where to Apply Feature Scaling? The real-world dataset contains features that highly vary in magnitudes, units, and range. Normalization should be performed when the scale of a feature is irrelevant or misleading and not should Normalise when the scale is meaningful.
The algorithms which use Euclidean Distance measures are sensitive to Magnitudes. Here feature scaling helps to weigh all the features equally.
Formally, If a feature in the dataset is big in scale compared to others then in algorithms where Euclidean distance is measured this big scaled feature becomes dominating and needs to be normalized.
Examples of Algorithms where Feature Scaling matters 1. K-Means uses the Euclidean distance measure here feature scaling matters. 2. K-Nearest-Neighbours also require feature scaling. 3. Principal Component Analysis (PCA): Tries to get the feature with maximum variance, here too feature scaling is required. 4. Gradient Descent: Calculation speed increase as Theta calculation becomes faster after feature scaling.
Note: Naive Bayes, Linear Discriminant Analysis, and Tree-Based models are not affected by feature scaling. In Short, any Algorithm which is Not Distance-based is Not affected by Feature Scaling.
Akanksha_Rai
marcosarcticseal
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Getting started with Machine Learning
Agents in Artificial Intelligence
Search Algorithms in AI
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Markov Decision Process
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 330,
"s": 54,
"text": "Feature Scaling or Standardization: It is a step of Data Pre Processing that is applied to independent variables or features of data. It basically helps to normalize the data within a particular range. Sometimes, it also helps in speeding up the calculations in an algorithm."
},
{
"code": null,
"e": 345,
"s": 330,
"text": "Package Used: "
},
{
"code": null,
"e": 367,
"s": 345,
"text": "sklearn.preprocessing"
},
{
"code": null,
"e": 377,
"s": 367,
"text": "Import: "
},
{
"code": null,
"e": 427,
"s": 377,
"text": " from sklearn.preprocessing import StandardScaler"
},
{
"code": null,
"e": 513,
"s": 427,
"text": "The formula used in Backend Standardization replaces the values with their Z scores. "
},
{
"code": null,
"e": 564,
"s": 513,
"text": "Mostly the Fit method is used for Feature scaling "
},
{
"code": null,
"e": 637,
"s": 564,
"text": "fit(X, y = None)\nComputes the mean and std to be used for later scaling."
},
{
"code": null,
"e": 644,
"s": 637,
"text": "Python"
},
{
"code": "import pandas as pdfrom sklearn.preprocessing import StandardScaler # Read Data from CSVdata = read_csv('Geeksforgeeks.csv')data.head() # Initialise the Scalerscaler = StandardScaler() # To scale datascaler.fit(data)",
"e": 861,
"s": 644,
"text": null
},
{
"code": null,
"e": 1137,
"s": 861,
"text": "Why and Where to Apply Feature Scaling? The real-world dataset contains features that highly vary in magnitudes, units, and range. Normalization should be performed when the scale of a feature is irrelevant or misleading and not should Normalise when the scale is meaningful."
},
{
"code": null,
"e": 1281,
"s": 1137,
"text": "The algorithms which use Euclidean Distance measures are sensitive to Magnitudes. Here feature scaling helps to weigh all the features equally."
},
{
"code": null,
"e": 1482,
"s": 1281,
"text": "Formally, If a feature in the dataset is big in scale compared to others then in algorithms where Euclidean distance is measured this big scaled feature becomes dominating and needs to be normalized. "
},
{
"code": null,
"e": 1898,
"s": 1482,
"text": "Examples of Algorithms where Feature Scaling matters 1. K-Means uses the Euclidean distance measure here feature scaling matters. 2. K-Nearest-Neighbours also require feature scaling. 3. Principal Component Analysis (PCA): Tries to get the feature with maximum variance, here too feature scaling is required. 4. Gradient Descent: Calculation speed increase as Theta calculation becomes faster after feature scaling."
},
{
"code": null,
"e": 2095,
"s": 1898,
"text": "Note: Naive Bayes, Linear Discriminant Analysis, and Tree-Based models are not affected by feature scaling. In Short, any Algorithm which is Not Distance-based is Not affected by Feature Scaling. "
},
{
"code": null,
"e": 2108,
"s": 2095,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2125,
"s": 2108,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 2151,
"s": 2125,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 2168,
"s": 2151,
"text": "Machine Learning"
},
{
"code": null,
"e": 2175,
"s": 2168,
"text": "Python"
},
{
"code": null,
"e": 2192,
"s": 2175,
"text": "Machine Learning"
},
{
"code": null,
"e": 2290,
"s": 2192,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2313,
"s": 2290,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 2339,
"s": 2313,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2375,
"s": 2339,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2399,
"s": 2375,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2437,
"s": 2399,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 2471,
"s": 2437,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 2495,
"s": 2471,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 2531,
"s": 2495,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2572,
"s": 2531,
"text": "Introduction to Recurrent Neural Network"
}
] |
Understanding Classes and Objects in Java
|
04 Oct, 2021
The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporates both data and behavior. Hence, Object_oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rules. Programs are organised around objects rather than action and logic. It increases the flexibility and maintainability of the program. Understanding the working of the program becomes easier, as OOPs brings data and its behavior(methods) into a single(objects) location.
Basic concepts of OOPs are:
ObjectClassEncapsulationInheritancePolymorphismAbstraction
Object
Class
Encapsulation
Inheritance
Polymorphism
Abstraction
This article deals with Objects and Classes in Java.
Requirements of Classes and Objects in Object Oriented Programming
Classes: A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. Classes are required in OOPs because:
It provides template for creating objects, which can bind code into data.
It has definitions of methods and data.
It supports inheritance property of Object Oriented Programming and hence can maintain class hierarchy.
It helps in maintaining the access specifications of member variables.
Objects: It is the basic unit of Object Oriented Programming and it represents the real life entities. Real-life entities share two characteristics: they all have attributes and behavior.
An object consists of:
State: It is represented by attributes of an object. It also shows properties of an object.
Behavior: It is represented by methods of an object. It shows response of an object with other objects.
Identity: It gives a unique name to an object. It also grants permission to one object to interact with other objects.
Objects are required in OOPs because they can be created to call a non-static function which are not present inside the Main Method but present inside the Class and also provide the name to the space which is being used to store the data.
Example : For addition of two numbers, it is required to store the two numbers separately from each other, so that they can be picked and the desired operations can be performed on them. Hence creating two different objects to store the two numbers will be an ideal solution for this scenario.
Example to demonstrate the use of Objects and classes in OOPs
Objects relate to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.
Example :
As we declare variables like (type name;). This notifies the compiler that we will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variable, type must be strictly a concrete class name. In general, we can’t create objects of an abstract class or an interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object.
Initializing an object using new
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.
Java
// Java program to illustrate the concept// of classes and objects // Class Declaration public class Dog { // Instance Variables String name; String breed; int age; String color; // Constructor Declaration of Class public Dog(String name, String breed, int age, String color) { this.name = name; this.breed = breed; this.age = age; this.color = color; } // method 1 public String getName() { return name; } // method 2 public String getBreed() { return breed; } // method 3 public int getAge() { return age; } // method 4 public String getColor() { return color; } @Override public String toString() { return ("Hi my name is " + this.getName() + ".\nMy breed, age and color are " + this.getBreed() + ", " + this.getAge() + ", " + this.getColor()); } public static void main(String[] args) { Dog tuffy = new Dog("tuffy", "papillon", 5, "white"); System.out.println(tuffy.toString()); }}
Hi my name is tuffy.
My breed, age and color are papillon, 5, white
This class contains a single constructor. We can recognize a constructor because its declaration uses the same name as the class and it has no return type. The Java compiler differentiates the constructors based on the number and the type of the arguments. The constructor in the Dog class takes four arguments. The following statement provides “tuffy”, “papillon”, 5, “white” as values for those arguments:
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
The result of executing this statement can be illustrated as :
Note : All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent’s no-argument constructor (as it contain only one statement i.e super();), or the Object class constructor if the class has no other parent (as Object class is parent of all classes either directly or indirectly).
Different ways to create Objects
Using new keyword: It is the simplest way to create object. By using this method, the desired constructor can be called.Syntax:
ClassName ReferenceVariable = new ClassName();
Java
// Java program to illustrate the// creating and accessing objects// using new keyword // base classclass Dog { // the class Dog has two fields String dogName; int dogAge; // the class Dog has one constructor Dog(String name, int age) { this.dogName = name; this.dogAge = age; }} // driver classpublic class Test { public static void main(String[] args) { // creating objects of the class Dog Dog ob1 = new Dog("Bravo", 4); Dog ob2 = new Dog("Oliver", 5); // accessing the object data through reference System.out.println(ob1.dogName + ", " + ob1.dogAge); System.out.println(ob2.dogName + ", " + ob2.dogAge); }}
Bravo, 4
Oliver, 5
Using Class.newInstance() method: It is used to create new class dynamically. It can invoke any no-argument constructor. This method return class Class object on which newInstance() method is called, which will return the object of that class which is being passed as command line argument.Reason for different exceptions raised:-ClassNotFoundException will occur if the passed class doesn’t exist. InstantiationException will occur, if the passed class doesn’t contain default constructor as newInstance() method internally calls the default constructor of that particular class. IllegalAccessException will occur, if the driving class doesn’t has the access to the definition of specified class definition.Syntax:
ClassName ReferenceVariable =
(ClassName) Class.forName("PackageName.ClassName").newInstance();
Java
// Java program to demonstrate// object creation using newInstance() method // Base classclass Example { void message() { System.out.println("Hello Geeks !!"); }} // Driver classclass Test { public static void main(String args[]) { try { Class c = Class.forName("Example"); Example s = (Example)c.newInstance(); s.message(); } catch (Exception e) { System.out.println(e); } }}
Hello Geeks !!
Using newInstance() method for Constructor class: It is a reflective way to create object. By using it one can call parameterized and private constructor. It wraps the thrown exception with an InvocationTargetException. It is used by different frameworks- Spring, Hibernate, Struts etc. Constructor.newInstance() method is preferred over Class.newInstance() method.Syntax:
Constructor constructor = ClassName.class.getConstructor();
ClassName ReferenceVariable = constructor.newInstance();
Example:
Java
// java program to demonstrate// creation of object// using Constructor.newInstance() method import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException; public class ConstructorExample { // different exception is thrown public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Constructor constructor = ExampleClass.class .getConstructor(String.class); ExampleClass exampleObject = (ExampleClass)constructor .newInstance("GeeksForGeeks"); System.out.println(exampleObject.getemp_name()); }} class ExampleClass { // private variable declared private String emp_name; public ExampleClass(String emp_name) { this.emp_name = emp_name; } // get method for emp_named to access // private variable emp_name public String getemp_name() { return emp_name; } // set method for emp_name to access // private variable emp_name public void setemp_name(String emp_name) { this.emp_name = emp_name; }}
GeeksForGeeks
Using clone() method: It is used to make clone of an object. It is the easiest and most efficient way to copy an object. In code, java.lang.Cloneable interface must be implemented by the class whose object clone is to be created. If Cloneable interface is not implemented, clone() method generates CloneNotSupportedException. Syntax:
ClassName ReferenceVariable = (ClassName) ReferenceVariable.clone();
Example:
Java
// java program to demonstrate// object creation using clone() method // employee class whose objects are clonedclass Employee implements Cloneable { int emp_id; String emp_name; // default constructor Employee(String emp_name, int emp_id) { this.emp_id = emp_id; this.emp_name = emp_name; } public Object clone() throws CloneNotSupportedException { return super.clone(); }} // driver classpublic class Test { public static void main(String args[]) { try { Employee ob1 = new Employee("Tom", 201); // Creating a new reference variable ob2 // which is pointing to the same address as ob1 Employee ob2 = (Employee)ob1.clone(); System.out.println(ob1.emp_id + ", " + ob1.emp_name); System.out.println(ob2.emp_id + ", " + ob2.emp_name); } catch (CloneNotSupportedException c) { System.out.println("Exception: " + c); } }}
201, Tom
201, Tom
Using deserialization: To deserialize an object, first implement a serializable interface in the class. No constructor is used to create an object in this method.Syntax:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(FileName));
ClassName ReferenceVariable = (ClassName) in.readObject();
Example:
Java
// Java code to demonstrate object// creation by deserialization import java.io.*; // Base classclass Example implements java.io.Serializable { public int emp_id; public String emp_name; // Default constructor public Example(int emp_id, String emp_name) { this.emp_id = emp_id; this.emp_name = emp_name; }} // Driver classclass Test { public static void main(String[] args) { Example object = new Example(1, "geeksforgeeks"); String filename = "file1.ser"; // Serialization try { // Saving of object in a file FileOutputStream file1 = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file1); // Method for serialization of object out.writeObject(object); out.close(); file1.close(); System.out.println("Object has been serialized"); } catch (IOException ex) { System.out.println("IOException is caught"); } Example object1 = null; // Deserialization try { // Reading object from a file FileInputStream file1 = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file1); // Method for deserialization of object object1 = (Example)in.readObject(); in.close(); file1.close(); System.out.println("Object has been deserialized"); System.out.println("Employee ID = " + object1.emp_id); System.out.println("Employee Name = " + object1.emp_name); } catch (IOException ex) { System.out.println("IOException is caught"); } catch (ClassNotFoundException ex) { System.out.println("ClassNotFoundException is caught"); } }}
Differences between Objects and Classes
nidhi_biet
anikaseth98
akshaysingh98088
Class and Object
Java-Class and Object
Picked
Java
Java-Class and Object
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 628,
"s": 54,
"text": "The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporates both data and behavior. Hence, Object_oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rules. Programs are organised around objects rather than action and logic. It increases the flexibility and maintainability of the program. Understanding the working of the program becomes easier, as OOPs brings data and its behavior(methods) into a single(objects) location."
},
{
"code": null,
"e": 657,
"s": 628,
"text": "Basic concepts of OOPs are: "
},
{
"code": null,
"e": 716,
"s": 657,
"text": "ObjectClassEncapsulationInheritancePolymorphismAbstraction"
},
{
"code": null,
"e": 723,
"s": 716,
"text": "Object"
},
{
"code": null,
"e": 729,
"s": 723,
"text": "Class"
},
{
"code": null,
"e": 743,
"s": 729,
"text": "Encapsulation"
},
{
"code": null,
"e": 755,
"s": 743,
"text": "Inheritance"
},
{
"code": null,
"e": 768,
"s": 755,
"text": "Polymorphism"
},
{
"code": null,
"e": 780,
"s": 768,
"text": "Abstraction"
},
{
"code": null,
"e": 833,
"s": 780,
"text": "This article deals with Objects and Classes in Java."
},
{
"code": null,
"e": 900,
"s": 833,
"text": "Requirements of Classes and Objects in Object Oriented Programming"
},
{
"code": null,
"e": 1119,
"s": 900,
"text": "Classes: A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. Classes are required in OOPs because:"
},
{
"code": null,
"e": 1193,
"s": 1119,
"text": "It provides template for creating objects, which can bind code into data."
},
{
"code": null,
"e": 1233,
"s": 1193,
"text": "It has definitions of methods and data."
},
{
"code": null,
"e": 1337,
"s": 1233,
"text": "It supports inheritance property of Object Oriented Programming and hence can maintain class hierarchy."
},
{
"code": null,
"e": 1408,
"s": 1337,
"text": "It helps in maintaining the access specifications of member variables."
},
{
"code": null,
"e": 1597,
"s": 1408,
"text": "Objects: It is the basic unit of Object Oriented Programming and it represents the real life entities. Real-life entities share two characteristics: they all have attributes and behavior. "
},
{
"code": null,
"e": 1622,
"s": 1597,
"text": "An object consists of: "
},
{
"code": null,
"e": 1714,
"s": 1622,
"text": "State: It is represented by attributes of an object. It also shows properties of an object."
},
{
"code": null,
"e": 1818,
"s": 1714,
"text": "Behavior: It is represented by methods of an object. It shows response of an object with other objects."
},
{
"code": null,
"e": 1937,
"s": 1818,
"text": "Identity: It gives a unique name to an object. It also grants permission to one object to interact with other objects."
},
{
"code": null,
"e": 2176,
"s": 1937,
"text": "Objects are required in OOPs because they can be created to call a non-static function which are not present inside the Main Method but present inside the Class and also provide the name to the space which is being used to store the data."
},
{
"code": null,
"e": 2470,
"s": 2176,
"text": "Example : For addition of two numbers, it is required to store the two numbers separately from each other, so that they can be picked and the desired operations can be performed on them. Hence creating two different objects to store the two numbers will be an ideal solution for this scenario."
},
{
"code": null,
"e": 2533,
"s": 2470,
"text": "Example to demonstrate the use of Objects and classes in OOPs "
},
{
"code": null,
"e": 2766,
"s": 2533,
"text": "Objects relate to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”. "
},
{
"code": null,
"e": 2820,
"s": 2766,
"text": "Declaring Objects (Also called instantiating a class)"
},
{
"code": null,
"e": 3094,
"s": 2820,
"text": "When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances."
},
{
"code": null,
"e": 3104,
"s": 3094,
"text": "Example :"
},
{
"code": null,
"e": 3485,
"s": 3104,
"text": "As we declare variables like (type name;). This notifies the compiler that we will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variable, type must be strictly a concrete class name. In general, we can’t create objects of an abstract class or an interface. "
},
{
"code": null,
"e": 3496,
"s": 3485,
"text": "Dog tuffy;"
},
{
"code": null,
"e": 3706,
"s": 3496,
"text": "If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. "
},
{
"code": null,
"e": 3739,
"s": 3706,
"text": "Initializing an object using new"
},
{
"code": null,
"e": 3911,
"s": 3739,
"text": "The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor. "
},
{
"code": null,
"e": 3916,
"s": 3911,
"text": "Java"
},
{
"code": "// Java program to illustrate the concept// of classes and objects // Class Declaration public class Dog { // Instance Variables String name; String breed; int age; String color; // Constructor Declaration of Class public Dog(String name, String breed, int age, String color) { this.name = name; this.breed = breed; this.age = age; this.color = color; } // method 1 public String getName() { return name; } // method 2 public String getBreed() { return breed; } // method 3 public int getAge() { return age; } // method 4 public String getColor() { return color; } @Override public String toString() { return (\"Hi my name is \" + this.getName() + \".\\nMy breed, age and color are \" + this.getBreed() + \", \" + this.getAge() + \", \" + this.getColor()); } public static void main(String[] args) { Dog tuffy = new Dog(\"tuffy\", \"papillon\", 5, \"white\"); System.out.println(tuffy.toString()); }}",
"e": 5015,
"s": 3916,
"text": null
},
{
"code": null,
"e": 5083,
"s": 5015,
"text": "Hi my name is tuffy.\nMy breed, age and color are papillon, 5, white"
},
{
"code": null,
"e": 5493,
"s": 5085,
"text": "This class contains a single constructor. We can recognize a constructor because its declaration uses the same name as the class and it has no return type. The Java compiler differentiates the constructors based on the number and the type of the arguments. The constructor in the Dog class takes four arguments. The following statement provides “tuffy”, “papillon”, 5, “white” as values for those arguments:"
},
{
"code": null,
"e": 5547,
"s": 5493,
"text": "Dog tuffy = new Dog(\"tuffy\", \"papillon\", 5, \"white\");"
},
{
"code": null,
"e": 5611,
"s": 5547,
"text": "The result of executing this statement can be illustrated as : "
},
{
"code": null,
"e": 6073,
"s": 5611,
"text": "Note : All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent’s no-argument constructor (as it contain only one statement i.e super();), or the Object class constructor if the class has no other parent (as Object class is parent of all classes either directly or indirectly). "
},
{
"code": null,
"e": 6106,
"s": 6073,
"text": "Different ways to create Objects"
},
{
"code": null,
"e": 6234,
"s": 6106,
"text": "Using new keyword: It is the simplest way to create object. By using this method, the desired constructor can be called.Syntax:"
},
{
"code": null,
"e": 6281,
"s": 6234,
"text": "ClassName ReferenceVariable = new ClassName();"
},
{
"code": null,
"e": 6286,
"s": 6281,
"text": "Java"
},
{
"code": "// Java program to illustrate the// creating and accessing objects// using new keyword // base classclass Dog { // the class Dog has two fields String dogName; int dogAge; // the class Dog has one constructor Dog(String name, int age) { this.dogName = name; this.dogAge = age; }} // driver classpublic class Test { public static void main(String[] args) { // creating objects of the class Dog Dog ob1 = new Dog(\"Bravo\", 4); Dog ob2 = new Dog(\"Oliver\", 5); // accessing the object data through reference System.out.println(ob1.dogName + \", \" + ob1.dogAge); System.out.println(ob2.dogName + \", \" + ob2.dogAge); }}",
"e": 6987,
"s": 6286,
"text": null
},
{
"code": null,
"e": 7006,
"s": 6987,
"text": "Bravo, 4\nOliver, 5"
},
{
"code": null,
"e": 7724,
"s": 7008,
"text": "Using Class.newInstance() method: It is used to create new class dynamically. It can invoke any no-argument constructor. This method return class Class object on which newInstance() method is called, which will return the object of that class which is being passed as command line argument.Reason for different exceptions raised:-ClassNotFoundException will occur if the passed class doesn’t exist. InstantiationException will occur, if the passed class doesn’t contain default constructor as newInstance() method internally calls the default constructor of that particular class. IllegalAccessException will occur, if the driving class doesn’t has the access to the definition of specified class definition.Syntax:"
},
{
"code": null,
"e": 7840,
"s": 7724,
"text": "ClassName ReferenceVariable = \n (ClassName) Class.forName(\"PackageName.ClassName\").newInstance();"
},
{
"code": null,
"e": 7845,
"s": 7840,
"text": "Java"
},
{
"code": "// Java program to demonstrate// object creation using newInstance() method // Base classclass Example { void message() { System.out.println(\"Hello Geeks !!\"); }} // Driver classclass Test { public static void main(String args[]) { try { Class c = Class.forName(\"Example\"); Example s = (Example)c.newInstance(); s.message(); } catch (Exception e) { System.out.println(e); } }}",
"e": 8319,
"s": 7845,
"text": null
},
{
"code": null,
"e": 8334,
"s": 8319,
"text": "Hello Geeks !!"
},
{
"code": null,
"e": 8709,
"s": 8336,
"text": "Using newInstance() method for Constructor class: It is a reflective way to create object. By using it one can call parameterized and private constructor. It wraps the thrown exception with an InvocationTargetException. It is used by different frameworks- Spring, Hibernate, Struts etc. Constructor.newInstance() method is preferred over Class.newInstance() method.Syntax:"
},
{
"code": null,
"e": 8827,
"s": 8709,
"text": "Constructor constructor = ClassName.class.getConstructor();\n ClassName ReferenceVariable = constructor.newInstance();"
},
{
"code": null,
"e": 8837,
"s": 8827,
"text": "Example: "
},
{
"code": null,
"e": 8842,
"s": 8837,
"text": "Java"
},
{
"code": "// java program to demonstrate// creation of object// using Constructor.newInstance() method import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException; public class ConstructorExample { // different exception is thrown public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Constructor constructor = ExampleClass.class .getConstructor(String.class); ExampleClass exampleObject = (ExampleClass)constructor .newInstance(\"GeeksForGeeks\"); System.out.println(exampleObject.getemp_name()); }} class ExampleClass { // private variable declared private String emp_name; public ExampleClass(String emp_name) { this.emp_name = emp_name; } // get method for emp_named to access // private variable emp_name public String getemp_name() { return emp_name; } // set method for emp_name to access // private variable emp_name public void setemp_name(String emp_name) { this.emp_name = emp_name; }}",
"e": 10149,
"s": 8842,
"text": null
},
{
"code": null,
"e": 10163,
"s": 10149,
"text": "GeeksForGeeks"
},
{
"code": null,
"e": 10499,
"s": 10165,
"text": "Using clone() method: It is used to make clone of an object. It is the easiest and most efficient way to copy an object. In code, java.lang.Cloneable interface must be implemented by the class whose object clone is to be created. If Cloneable interface is not implemented, clone() method generates CloneNotSupportedException. Syntax:"
},
{
"code": null,
"e": 10568,
"s": 10499,
"text": "ClassName ReferenceVariable = (ClassName) ReferenceVariable.clone();"
},
{
"code": null,
"e": 10578,
"s": 10568,
"text": "Example: "
},
{
"code": null,
"e": 10583,
"s": 10578,
"text": "Java"
},
{
"code": "// java program to demonstrate// object creation using clone() method // employee class whose objects are clonedclass Employee implements Cloneable { int emp_id; String emp_name; // default constructor Employee(String emp_name, int emp_id) { this.emp_id = emp_id; this.emp_name = emp_name; } public Object clone() throws CloneNotSupportedException { return super.clone(); }} // driver classpublic class Test { public static void main(String args[]) { try { Employee ob1 = new Employee(\"Tom\", 201); // Creating a new reference variable ob2 // which is pointing to the same address as ob1 Employee ob2 = (Employee)ob1.clone(); System.out.println(ob1.emp_id + \", \" + ob1.emp_name); System.out.println(ob2.emp_id + \", \" + ob2.emp_name); } catch (CloneNotSupportedException c) { System.out.println(\"Exception: \" + c); } }}",
"e": 11569,
"s": 10583,
"text": null
},
{
"code": null,
"e": 11587,
"s": 11569,
"text": "201, Tom\n201, Tom"
},
{
"code": null,
"e": 11759,
"s": 11589,
"text": "Using deserialization: To deserialize an object, first implement a serializable interface in the class. No constructor is used to create an object in this method.Syntax:"
},
{
"code": null,
"e": 11895,
"s": 11759,
"text": "ObjectInputStream in = new ObjectInputStream(new FileInputStream(FileName));\nClassName ReferenceVariable = (ClassName) in.readObject();"
},
{
"code": null,
"e": 11905,
"s": 11895,
"text": "Example: "
},
{
"code": null,
"e": 11910,
"s": 11905,
"text": "Java"
},
{
"code": "// Java code to demonstrate object// creation by deserialization import java.io.*; // Base classclass Example implements java.io.Serializable { public int emp_id; public String emp_name; // Default constructor public Example(int emp_id, String emp_name) { this.emp_id = emp_id; this.emp_name = emp_name; }} // Driver classclass Test { public static void main(String[] args) { Example object = new Example(1, \"geeksforgeeks\"); String filename = \"file1.ser\"; // Serialization try { // Saving of object in a file FileOutputStream file1 = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file1); // Method for serialization of object out.writeObject(object); out.close(); file1.close(); System.out.println(\"Object has been serialized\"); } catch (IOException ex) { System.out.println(\"IOException is caught\"); } Example object1 = null; // Deserialization try { // Reading object from a file FileInputStream file1 = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file1); // Method for deserialization of object object1 = (Example)in.readObject(); in.close(); file1.close(); System.out.println(\"Object has been deserialized\"); System.out.println(\"Employee ID = \" + object1.emp_id); System.out.println(\"Employee Name = \" + object1.emp_name); } catch (IOException ex) { System.out.println(\"IOException is caught\"); } catch (ClassNotFoundException ex) { System.out.println(\"ClassNotFoundException is caught\"); } }}",
"e": 13768,
"s": 11910,
"text": null
},
{
"code": null,
"e": 13808,
"s": 13768,
"text": "Differences between Objects and Classes"
},
{
"code": null,
"e": 13819,
"s": 13808,
"text": "nidhi_biet"
},
{
"code": null,
"e": 13831,
"s": 13819,
"text": "anikaseth98"
},
{
"code": null,
"e": 13848,
"s": 13831,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 13865,
"s": 13848,
"text": "Class and Object"
},
{
"code": null,
"e": 13887,
"s": 13865,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 13894,
"s": 13887,
"text": "Picked"
},
{
"code": null,
"e": 13899,
"s": 13894,
"text": "Java"
},
{
"code": null,
"e": 13921,
"s": 13899,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 13926,
"s": 13921,
"text": "Java"
},
{
"code": null,
"e": 14024,
"s": 13926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14039,
"s": 14024,
"text": "Arrays in Java"
},
{
"code": null,
"e": 14083,
"s": 14039,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 14119,
"s": 14083,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 14144,
"s": 14119,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 14195,
"s": 14144,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 14217,
"s": 14195,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 14248,
"s": 14217,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 14267,
"s": 14248,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 14297,
"s": 14267,
"text": "HashMap in Java with Examples"
}
] |
Deploy Machine Learning Pipeline on Google Kubernetes Engine | by Moez Ali | Towards Data Science
|
In our last post on deploying a machine learning pipeline in the cloud, we demonstrated how to develop a machine learning pipeline in PyCaret, containerize it with Docker and serve as a web app using Microsoft Azure Web App Services. If you haven’t heard about PyCaret before, please read this announcement to learn more.
In this tutorial, we will use the same machine learning pipeline and Flask app that we built and deployed previously. This time we will demonstrate how to containerize and deploy a machine learning pipeline on Google Kubernetes Engine.
Learn what is a Container, what is Docker, what is Kubernetes, and what is Google Kubernetes Engine?
Build a Docker image and upload it on Google Container Registry (GCR).
Create clusters and deploy a machine learning pipeline with a Flask app as a web service.
See a web app in action that uses a trained machine learning pipeline to predict new data points in real-time.
Previously we demonstrated how to deploy a ML pipeline on Heroku PaaS and how to deploy a ML pipeline on Azure Web Services with a Docker container.
This tutorial will cover the entire workflow starting from building a docker image, uploading it onto Google Container Registry and then deploying the pre-trained machine learning pipeline and Flask app onto Google Kubernetes Engine (GKE).
PyCaret is an open source, low-code machine learning library in Python that is used to train and deploy machine learning pipelines and models into production. PyCaret can be installed easily using pip.
pip install pycaret
Flask is a framework that allows you to build web applications. A web application can be a commercial website, blog, e-commerce system, or an application that generates predictions from data provided in real-time using trained models. If you don’t have Flask installed, you can use pip to install it.
Google Cloud Platform (GCP), offered by Google, is a suite of cloud computing services that runs on the same infrastructure that Google uses internally for its end-user products, such as Google Search, Gmail and YouTube. If you do not have an account with GCP, you can sign-up here. If you are signing up for the first time you will get free credits for 1 year.
Before we get into Kubernetes, let’s understand what a container is and why we would need one?
Have you ever had the problem where your code works fine on your computer but when a friend tries to run the exact same code, it doesn’t work? If your friend is repeating the exact same steps, he or she should get the same results, right? The one-word answer to this is the environment. Your friend’s environment is different than yours.
What does an environment include? → Programing language such as Python and all the libraries and dependencies with the exact versions using which application was built and tested.
If we can create an environment that we can transfer to other machines (for example: your friend’s computer or a cloud service provider like Google Cloud Platform), we can reproduce the results anywhere. Hence, a container is a type of software that packages up an application and all its dependencies so the application runs reliably from one computing environment to another.
What’s Docker then?
Docker is a company that provides software (also called Docker) that allows users to build, run and manage containers. While Docker’s container are the most common, there are other less famous alternatives such as LXD and LXC that provides container solution.
Now that you understand containers and docker specifically, let’s understand what Kubernetes is all about.
Kubernetes is a powerful open-source system developed by Google back in 2014, for managing containerized applications. In simple words, Kubernetes is a system for running and coordinating containerized applications across a cluster of machines. It is a platform designed to completely manage the life cycle of containerized applications.
✔️ Load Balancing: Automatically distributes the load between containers.
✔️ Scaling: Automatically scale up or down by adding or removing containers when demand changes such as peak hours, weekends and holidays.
✔️ Storage: Keeps storage consistent with multiple instances of an application.
✔️ Self-healing Automatically restarts containers that fail and kills containers that don’t respond to your user-defined health check.
✔️ Automated Rollouts you can automate Kubernetes to create new containers for your deployment, remove existing containers and adopt all of their resources to the new container.
Imagine a scenario where you have to run multiple docker containers on multiple machines to support an enterprise level ML application with varied workloads during day and night. As simple as it may sound, it is a lot of work to do manually.
You need to start the right containers at the right time, figure out how they can talk to each other, handle storage considerations, and deal with failed containers or hardware. This is the problem Kubernetes is solving by allowing large numbers of containers to work together in harmony, reducing the operational burden.
It’s a mistake to compare Docker with Kubernetes. These are two different technologies. Docker is a software that allows you to containerize applications while Kubernetes is a container management system that allows to create, scale and monitor hundreds and thousands of containers.
In the lifecycle of any application, Docker is used for packaging the application at the time of deployment, while kubernetes is used for rest of the life for managing the application.
Google Kubernetes Engine is implementation of Google’s open source Kubernetes on Google Cloud Platform. Simple!
Other popular alternatives to GKE are Amazon ECS and Microsoft Azure Kubernetes Service.
A Container is a type of software that packages up an application and all its dependencies so the application runs reliably from one computing environment to another.
Docker is a software used for building and managing containers.
Kubernetes is an open-source system for managing containerized applications in a clustered environment.
Google Kubernetes Engine is an implementation of the open source Kubernetes framework on Google Cloud Platform.
In this tutorial we will use Google Kubernetes Engine. In order to follow along, you must have a Google Cloud Platform account. Click here to sign-up for free.
An insurance company wants to improve its cash flow forecasting by better predicting patient charges using demographic and basic patient health risk metrics at the time of hospitalization.
(data source)
To build and deploy a web application where the demographic and health information of a patient is entered into a web-based form which then outputs a predicted charge amount.
Train and develop a machine learning pipeline for deployment.
Build a web app using a Flask framework. It will use the trained ML pipeline to generate predictions on new data points in real-time.
Build a docker image and upload a container onto Google Container Registry (GCR).
Create clusters and deploy the app on Google Kubernetes Engine.
Since we have already covered the first two tasks in our initial tutorial, we will quickly recap them and then focus on the remaining items in the list above. If you are interested in learning more about developing a machine learning pipeline in Python using PyCaret and building a web app using a Flask framework, please read this tutorial.
We are using PyCaret in Python for training and developing a machine learning pipeline which will be used as part of our web app. The Machine Learning Pipeline can be developed in an Integrated Development Environment (IDE) or Notebook. We have used a notebook to run the below code:
When you save a model in PyCaret, the entire transformation pipeline based on the configuration defined in the setup() function is created . All inter-dependencies are orchestrated automatically. See the pipeline and model stored in the ‘deployment_28042020’ variable:
This tutorial is not focused on building a Flask application. It is only discussed here for completeness. Now that our machine learning pipeline is ready we need a web application that can connect to our trained pipeline to generate predictions on new data points in real-time. We have created the web application using Flask framework in Python. There are two parts of this application:
Front-end (designed using HTML)
Back-end (developed using Flask)
This is how our web application looks:
If you haven’t followed along so far, no problem. You can simply fork this repository from GitHub. This is how your project folder should look at this point:
Now that we have a fully functional web application, we can start the process of containerizing and deploying the app on Google Kubernetes Engine.
Sign-in to your GCP console and go to Manage Resources
Click on Create New Project
Click the Activate Cloud Shell button at the top of the console window to open the Cloud Shell.
Execute the following code in Cloud Shell to clone the GitHub repository used in this tutorial.
git clone https://github.com/pycaret/pycaret-deployment-google.git
Execute the following code to set the PROJECT_ID environment variable.
export PROJECT_ID=pycaret-kubernetes-demo
pycaret-kubernetes-demo is the name of the project we chose in step 1 above.
Build the docker image of the application and tag it for uploading by executing the following code:
docker build -t gcr.io/${PROJECT_ID}/insurance-app:v1 .
You can check the available images by running the following code:
docker images
Authenticate to Container Registry (you need to run this only once):
Authenticate to Container Registry (you need to run this only once):
gcloud auth configure-docker
2. Execute the following code to upload the docker image to Google Container Registry:
docker push gcr.io/${PROJECT_ID}/insurance-app:v1
Now that the container is uploaded, you need a cluster to run the container. A cluster consists of a pool of Compute Engine VM instances, running Kubernetes.
Set your project ID and Compute Engine zone options for the gcloud tool:
Set your project ID and Compute Engine zone options for the gcloud tool:
gcloud config set project $PROJECT_ID gcloud config set compute/zone us-central1
2. Create a cluster by executing the following code:
gcloud container clusters create insurance-cluster --num-nodes=2
To deploy and manage applications on a GKE cluster, you must communicate with the Kubernetes cluster management system. Execute the following command to deploy the application:
kubectl create deployment insurance-app --image=gcr.io/${PROJECT_ID}/insurance-app:v1
By default, the containers you run on GKE are not accessible from the internet because they do not have external IP addresses. Execute the following code to expose the application to the internet:
kubectl expose deployment insurance-app --type=LoadBalancer --port 80 --target-port 8080
Execute the following code to get the status of the service. EXTERNAL-IP is the web address you can use in browser to view the published app.
kubectl get service
👉 Step 10— See the app in action on http://34.71.77.61:8080
Note: By the time this story is published, the app will be removed from the public address to restrict resource consumption.
Link to GitHub Repository for this tutorial
Link to GitHub Repository for Microsoft Azure Deployment
Link to GitHub Repository for Heroku Deployment
We have received overwhelming support and feedback from the community. We are actively working on improving PyCaret and preparing for our next release. PyCaret 1.0.1 will be bigger and better. If you would like to share your feedback and help us improve further, you may fill this form on the website or leave a comment on our GitHub or LinkedIn page.
Follow our LinkedIn and subscribe to our YouTube channel to learn more about PyCaret.
As of the first release 1.0.0, PyCaret has the following modules available for use. Click on the links below to see the documentation and working examples in Python.
ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining
PyCaret getting started tutorials in Notebook:
ClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule MiningRegressionClassification
PyCaret is an open source project. Everybody is welcome to contribute. If you would like contribute, please feel free to work on open issues. Pull requests are accepted with unit tests on dev-1.0.1 branch.
Please give us ⭐️ on our GitHub repo if you like PyCaret.
Medium : https://medium.com/@moez_62905/
LinkedIn : https://www.linkedin.com/in/profile-moez/
Twitter : https://twitter.com/moezpycaretorg1
|
[
{
"code": null,
"e": 494,
"s": 172,
"text": "In our last post on deploying a machine learning pipeline in the cloud, we demonstrated how to develop a machine learning pipeline in PyCaret, containerize it with Docker and serve as a web app using Microsoft Azure Web App Services. If you haven’t heard about PyCaret before, please read this announcement to learn more."
},
{
"code": null,
"e": 730,
"s": 494,
"text": "In this tutorial, we will use the same machine learning pipeline and Flask app that we built and deployed previously. This time we will demonstrate how to containerize and deploy a machine learning pipeline on Google Kubernetes Engine."
},
{
"code": null,
"e": 831,
"s": 730,
"text": "Learn what is a Container, what is Docker, what is Kubernetes, and what is Google Kubernetes Engine?"
},
{
"code": null,
"e": 902,
"s": 831,
"text": "Build a Docker image and upload it on Google Container Registry (GCR)."
},
{
"code": null,
"e": 992,
"s": 902,
"text": "Create clusters and deploy a machine learning pipeline with a Flask app as a web service."
},
{
"code": null,
"e": 1103,
"s": 992,
"text": "See a web app in action that uses a trained machine learning pipeline to predict new data points in real-time."
},
{
"code": null,
"e": 1252,
"s": 1103,
"text": "Previously we demonstrated how to deploy a ML pipeline on Heroku PaaS and how to deploy a ML pipeline on Azure Web Services with a Docker container."
},
{
"code": null,
"e": 1492,
"s": 1252,
"text": "This tutorial will cover the entire workflow starting from building a docker image, uploading it onto Google Container Registry and then deploying the pre-trained machine learning pipeline and Flask app onto Google Kubernetes Engine (GKE)."
},
{
"code": null,
"e": 1694,
"s": 1492,
"text": "PyCaret is an open source, low-code machine learning library in Python that is used to train and deploy machine learning pipelines and models into production. PyCaret can be installed easily using pip."
},
{
"code": null,
"e": 1714,
"s": 1694,
"text": "pip install pycaret"
},
{
"code": null,
"e": 2015,
"s": 1714,
"text": "Flask is a framework that allows you to build web applications. A web application can be a commercial website, blog, e-commerce system, or an application that generates predictions from data provided in real-time using trained models. If you don’t have Flask installed, you can use pip to install it."
},
{
"code": null,
"e": 2377,
"s": 2015,
"text": "Google Cloud Platform (GCP), offered by Google, is a suite of cloud computing services that runs on the same infrastructure that Google uses internally for its end-user products, such as Google Search, Gmail and YouTube. If you do not have an account with GCP, you can sign-up here. If you are signing up for the first time you will get free credits for 1 year."
},
{
"code": null,
"e": 2472,
"s": 2377,
"text": "Before we get into Kubernetes, let’s understand what a container is and why we would need one?"
},
{
"code": null,
"e": 2810,
"s": 2472,
"text": "Have you ever had the problem where your code works fine on your computer but when a friend tries to run the exact same code, it doesn’t work? If your friend is repeating the exact same steps, he or she should get the same results, right? The one-word answer to this is the environment. Your friend’s environment is different than yours."
},
{
"code": null,
"e": 2990,
"s": 2810,
"text": "What does an environment include? → Programing language such as Python and all the libraries and dependencies with the exact versions using which application was built and tested."
},
{
"code": null,
"e": 3368,
"s": 2990,
"text": "If we can create an environment that we can transfer to other machines (for example: your friend’s computer or a cloud service provider like Google Cloud Platform), we can reproduce the results anywhere. Hence, a container is a type of software that packages up an application and all its dependencies so the application runs reliably from one computing environment to another."
},
{
"code": null,
"e": 3388,
"s": 3368,
"text": "What’s Docker then?"
},
{
"code": null,
"e": 3648,
"s": 3388,
"text": "Docker is a company that provides software (also called Docker) that allows users to build, run and manage containers. While Docker’s container are the most common, there are other less famous alternatives such as LXD and LXC that provides container solution."
},
{
"code": null,
"e": 3755,
"s": 3648,
"text": "Now that you understand containers and docker specifically, let’s understand what Kubernetes is all about."
},
{
"code": null,
"e": 4093,
"s": 3755,
"text": "Kubernetes is a powerful open-source system developed by Google back in 2014, for managing containerized applications. In simple words, Kubernetes is a system for running and coordinating containerized applications across a cluster of machines. It is a platform designed to completely manage the life cycle of containerized applications."
},
{
"code": null,
"e": 4167,
"s": 4093,
"text": "✔️ Load Balancing: Automatically distributes the load between containers."
},
{
"code": null,
"e": 4306,
"s": 4167,
"text": "✔️ Scaling: Automatically scale up or down by adding or removing containers when demand changes such as peak hours, weekends and holidays."
},
{
"code": null,
"e": 4386,
"s": 4306,
"text": "✔️ Storage: Keeps storage consistent with multiple instances of an application."
},
{
"code": null,
"e": 4521,
"s": 4386,
"text": "✔️ Self-healing Automatically restarts containers that fail and kills containers that don’t respond to your user-defined health check."
},
{
"code": null,
"e": 4699,
"s": 4521,
"text": "✔️ Automated Rollouts you can automate Kubernetes to create new containers for your deployment, remove existing containers and adopt all of their resources to the new container."
},
{
"code": null,
"e": 4941,
"s": 4699,
"text": "Imagine a scenario where you have to run multiple docker containers on multiple machines to support an enterprise level ML application with varied workloads during day and night. As simple as it may sound, it is a lot of work to do manually."
},
{
"code": null,
"e": 5263,
"s": 4941,
"text": "You need to start the right containers at the right time, figure out how they can talk to each other, handle storage considerations, and deal with failed containers or hardware. This is the problem Kubernetes is solving by allowing large numbers of containers to work together in harmony, reducing the operational burden."
},
{
"code": null,
"e": 5546,
"s": 5263,
"text": "It’s a mistake to compare Docker with Kubernetes. These are two different technologies. Docker is a software that allows you to containerize applications while Kubernetes is a container management system that allows to create, scale and monitor hundreds and thousands of containers."
},
{
"code": null,
"e": 5731,
"s": 5546,
"text": "In the lifecycle of any application, Docker is used for packaging the application at the time of deployment, while kubernetes is used for rest of the life for managing the application."
},
{
"code": null,
"e": 5843,
"s": 5731,
"text": "Google Kubernetes Engine is implementation of Google’s open source Kubernetes on Google Cloud Platform. Simple!"
},
{
"code": null,
"e": 5932,
"s": 5843,
"text": "Other popular alternatives to GKE are Amazon ECS and Microsoft Azure Kubernetes Service."
},
{
"code": null,
"e": 6099,
"s": 5932,
"text": "A Container is a type of software that packages up an application and all its dependencies so the application runs reliably from one computing environment to another."
},
{
"code": null,
"e": 6163,
"s": 6099,
"text": "Docker is a software used for building and managing containers."
},
{
"code": null,
"e": 6267,
"s": 6163,
"text": "Kubernetes is an open-source system for managing containerized applications in a clustered environment."
},
{
"code": null,
"e": 6379,
"s": 6267,
"text": "Google Kubernetes Engine is an implementation of the open source Kubernetes framework on Google Cloud Platform."
},
{
"code": null,
"e": 6539,
"s": 6379,
"text": "In this tutorial we will use Google Kubernetes Engine. In order to follow along, you must have a Google Cloud Platform account. Click here to sign-up for free."
},
{
"code": null,
"e": 6728,
"s": 6539,
"text": "An insurance company wants to improve its cash flow forecasting by better predicting patient charges using demographic and basic patient health risk metrics at the time of hospitalization."
},
{
"code": null,
"e": 6742,
"s": 6728,
"text": "(data source)"
},
{
"code": null,
"e": 6917,
"s": 6742,
"text": "To build and deploy a web application where the demographic and health information of a patient is entered into a web-based form which then outputs a predicted charge amount."
},
{
"code": null,
"e": 6979,
"s": 6917,
"text": "Train and develop a machine learning pipeline for deployment."
},
{
"code": null,
"e": 7113,
"s": 6979,
"text": "Build a web app using a Flask framework. It will use the trained ML pipeline to generate predictions on new data points in real-time."
},
{
"code": null,
"e": 7195,
"s": 7113,
"text": "Build a docker image and upload a container onto Google Container Registry (GCR)."
},
{
"code": null,
"e": 7259,
"s": 7195,
"text": "Create clusters and deploy the app on Google Kubernetes Engine."
},
{
"code": null,
"e": 7601,
"s": 7259,
"text": "Since we have already covered the first two tasks in our initial tutorial, we will quickly recap them and then focus on the remaining items in the list above. If you are interested in learning more about developing a machine learning pipeline in Python using PyCaret and building a web app using a Flask framework, please read this tutorial."
},
{
"code": null,
"e": 7885,
"s": 7601,
"text": "We are using PyCaret in Python for training and developing a machine learning pipeline which will be used as part of our web app. The Machine Learning Pipeline can be developed in an Integrated Development Environment (IDE) or Notebook. We have used a notebook to run the below code:"
},
{
"code": null,
"e": 8154,
"s": 7885,
"text": "When you save a model in PyCaret, the entire transformation pipeline based on the configuration defined in the setup() function is created . All inter-dependencies are orchestrated automatically. See the pipeline and model stored in the ‘deployment_28042020’ variable:"
},
{
"code": null,
"e": 8542,
"s": 8154,
"text": "This tutorial is not focused on building a Flask application. It is only discussed here for completeness. Now that our machine learning pipeline is ready we need a web application that can connect to our trained pipeline to generate predictions on new data points in real-time. We have created the web application using Flask framework in Python. There are two parts of this application:"
},
{
"code": null,
"e": 8574,
"s": 8542,
"text": "Front-end (designed using HTML)"
},
{
"code": null,
"e": 8607,
"s": 8574,
"text": "Back-end (developed using Flask)"
},
{
"code": null,
"e": 8646,
"s": 8607,
"text": "This is how our web application looks:"
},
{
"code": null,
"e": 8804,
"s": 8646,
"text": "If you haven’t followed along so far, no problem. You can simply fork this repository from GitHub. This is how your project folder should look at this point:"
},
{
"code": null,
"e": 8951,
"s": 8804,
"text": "Now that we have a fully functional web application, we can start the process of containerizing and deploying the app on Google Kubernetes Engine."
},
{
"code": null,
"e": 9006,
"s": 8951,
"text": "Sign-in to your GCP console and go to Manage Resources"
},
{
"code": null,
"e": 9034,
"s": 9006,
"text": "Click on Create New Project"
},
{
"code": null,
"e": 9130,
"s": 9034,
"text": "Click the Activate Cloud Shell button at the top of the console window to open the Cloud Shell."
},
{
"code": null,
"e": 9226,
"s": 9130,
"text": "Execute the following code in Cloud Shell to clone the GitHub repository used in this tutorial."
},
{
"code": null,
"e": 9293,
"s": 9226,
"text": "git clone https://github.com/pycaret/pycaret-deployment-google.git"
},
{
"code": null,
"e": 9364,
"s": 9293,
"text": "Execute the following code to set the PROJECT_ID environment variable."
},
{
"code": null,
"e": 9406,
"s": 9364,
"text": "export PROJECT_ID=pycaret-kubernetes-demo"
},
{
"code": null,
"e": 9483,
"s": 9406,
"text": "pycaret-kubernetes-demo is the name of the project we chose in step 1 above."
},
{
"code": null,
"e": 9583,
"s": 9483,
"text": "Build the docker image of the application and tag it for uploading by executing the following code:"
},
{
"code": null,
"e": 9639,
"s": 9583,
"text": "docker build -t gcr.io/${PROJECT_ID}/insurance-app:v1 ."
},
{
"code": null,
"e": 9705,
"s": 9639,
"text": "You can check the available images by running the following code:"
},
{
"code": null,
"e": 9719,
"s": 9705,
"text": "docker images"
},
{
"code": null,
"e": 9788,
"s": 9719,
"text": "Authenticate to Container Registry (you need to run this only once):"
},
{
"code": null,
"e": 9857,
"s": 9788,
"text": "Authenticate to Container Registry (you need to run this only once):"
},
{
"code": null,
"e": 9886,
"s": 9857,
"text": "gcloud auth configure-docker"
},
{
"code": null,
"e": 9973,
"s": 9886,
"text": "2. Execute the following code to upload the docker image to Google Container Registry:"
},
{
"code": null,
"e": 10023,
"s": 9973,
"text": "docker push gcr.io/${PROJECT_ID}/insurance-app:v1"
},
{
"code": null,
"e": 10181,
"s": 10023,
"text": "Now that the container is uploaded, you need a cluster to run the container. A cluster consists of a pool of Compute Engine VM instances, running Kubernetes."
},
{
"code": null,
"e": 10254,
"s": 10181,
"text": "Set your project ID and Compute Engine zone options for the gcloud tool:"
},
{
"code": null,
"e": 10327,
"s": 10254,
"text": "Set your project ID and Compute Engine zone options for the gcloud tool:"
},
{
"code": null,
"e": 10408,
"s": 10327,
"text": "gcloud config set project $PROJECT_ID gcloud config set compute/zone us-central1"
},
{
"code": null,
"e": 10461,
"s": 10408,
"text": "2. Create a cluster by executing the following code:"
},
{
"code": null,
"e": 10526,
"s": 10461,
"text": "gcloud container clusters create insurance-cluster --num-nodes=2"
},
{
"code": null,
"e": 10703,
"s": 10526,
"text": "To deploy and manage applications on a GKE cluster, you must communicate with the Kubernetes cluster management system. Execute the following command to deploy the application:"
},
{
"code": null,
"e": 10789,
"s": 10703,
"text": "kubectl create deployment insurance-app --image=gcr.io/${PROJECT_ID}/insurance-app:v1"
},
{
"code": null,
"e": 10986,
"s": 10789,
"text": "By default, the containers you run on GKE are not accessible from the internet because they do not have external IP addresses. Execute the following code to expose the application to the internet:"
},
{
"code": null,
"e": 11075,
"s": 10986,
"text": "kubectl expose deployment insurance-app --type=LoadBalancer --port 80 --target-port 8080"
},
{
"code": null,
"e": 11217,
"s": 11075,
"text": "Execute the following code to get the status of the service. EXTERNAL-IP is the web address you can use in browser to view the published app."
},
{
"code": null,
"e": 11237,
"s": 11217,
"text": "kubectl get service"
},
{
"code": null,
"e": 11297,
"s": 11237,
"text": "👉 Step 10— See the app in action on http://34.71.77.61:8080"
},
{
"code": null,
"e": 11422,
"s": 11297,
"text": "Note: By the time this story is published, the app will be removed from the public address to restrict resource consumption."
},
{
"code": null,
"e": 11466,
"s": 11422,
"text": "Link to GitHub Repository for this tutorial"
},
{
"code": null,
"e": 11523,
"s": 11466,
"text": "Link to GitHub Repository for Microsoft Azure Deployment"
},
{
"code": null,
"e": 11571,
"s": 11523,
"text": "Link to GitHub Repository for Heroku Deployment"
},
{
"code": null,
"e": 11923,
"s": 11571,
"text": "We have received overwhelming support and feedback from the community. We are actively working on improving PyCaret and preparing for our next release. PyCaret 1.0.1 will be bigger and better. If you would like to share your feedback and help us improve further, you may fill this form on the website or leave a comment on our GitHub or LinkedIn page."
},
{
"code": null,
"e": 12009,
"s": 11923,
"text": "Follow our LinkedIn and subscribe to our YouTube channel to learn more about PyCaret."
},
{
"code": null,
"e": 12175,
"s": 12009,
"text": "As of the first release 1.0.0, PyCaret has the following modules available for use. Click on the links below to see the documentation and working examples in Python."
},
{
"code": null,
"e": 12277,
"s": 12175,
"text": "ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining"
},
{
"code": null,
"e": 12324,
"s": 12277,
"text": "PyCaret getting started tutorials in Notebook:"
},
{
"code": null,
"e": 12426,
"s": 12324,
"text": "ClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule MiningRegressionClassification"
},
{
"code": null,
"e": 12632,
"s": 12426,
"text": "PyCaret is an open source project. Everybody is welcome to contribute. If you would like contribute, please feel free to work on open issues. Pull requests are accepted with unit tests on dev-1.0.1 branch."
},
{
"code": null,
"e": 12690,
"s": 12632,
"text": "Please give us ⭐️ on our GitHub repo if you like PyCaret."
},
{
"code": null,
"e": 12731,
"s": 12690,
"text": "Medium : https://medium.com/@moez_62905/"
},
{
"code": null,
"e": 12784,
"s": 12731,
"text": "LinkedIn : https://www.linkedin.com/in/profile-moez/"
}
] |
Find comics of marvel superhero using marvel API in Python - GeeksforGeeks
|
06 Jun, 2021
In this article, we will find the comic of marvel by using python and marvel api. Marvel has provided an API that provides a look into their database consisting of various comics, movies, etc. We will be using that to find out your favorite marvel superhero comic books.
The Marvel Comics API is a tool to help developers everywhere create amazing, uncanny, and incredible websites and applications using data from the 70-plus years of the Marvel age of comics.
The Marvel Comics API is a RESTful service that provides methods for accessing specific resources at canonical URLs and for searching and filtering sets of resources by various criteria. All representations are encoded as JSON objects.
You can access six resource types using the API:
Comics: individual print and digital comic issues, collections, and graphic novels. For example: Amazing Fantasy #15.
Comic series: sequentially numbered (well, mostly sequentially numbered) groups comics with the same title. For example, Uncanny X-Men.
Comic stories: indivisible, reusable components of comics. For example, the cover from Amazing Fantasy #15 or the origin of the Spider-Man story from that comic.
Comic events and crossovers: big, universe-altering storylines. For example, Infinity
Creators: women, men, and organizations who create comics. For example, Jack Kirby.
Characters: the women, men, organizations, alien species, deities, animals, non-corporeal entities, trans-dimensional manifestations, abstract personifications, and green amorphous blobs which occupy the Marvel Universe (and various alternate universes, timelines, and altered realities therein). For example, Spider-Man.
In this article, we will try to fetch a particular character from the marvel API, and then we will generate the comics in which that particular character appeared.
Installation of marvel package
pip install marvel
Step 1: First go their website https://developer.marvel.com/, Now click on to top left “SIGN IN | JOIN” option and then click on to the “CREATE AN ACCOUNT” and now give your details and then click “CREATE ACCOUNT” option, which will look like this
Step 2: After signing in you will be redirected to their home page where it will show that your account is now logged in, but in order to get the API key first, you’ve to confirm the mail which marvel has sent you on your specified email address in order to verify it. Check your mailbox there will be a mail sent by marvel. Open it and then click “Confirm” option
Step 3: After that, you’ve to come back to your marvel developer portal where you’ve just created your account, and now on the top left side it will show your username instead of the sign-in option otherwise please refer to the steps again. After that in the middle center portion of the website, you will find an option “Get a Key”, click on that
Step 4: After that, you will be redirected to their terms of use page for the API. Just scroll down to the bottom (or you can give it a read if you want) and click on accept. Now, there we go, finally we will arrive at the page where it will show you the two most important keys and other important information. Just copy the Private and the public keys and store them in a secured folder on your computer. The page will look like this
Note: Keep these keys in a private folder and don’t share them with anyone else.
First import marvel from Marvel package
from marvel import Marvel
After that type your public and private keys like this
m = Marvel(PUBLIC_KEY, PRIVATE_KEY)
Now there are six objects presented namely, characters, comics, creators, events, series and stories. Check : https://pypi.org/project/marvel/ for more info
characters = m.characters comics = m.comics creators = m.creators events = m.events series = m.series stories = m.stories
Each of the above objects returns the appropriate response (JSON), but from here we are only interested in getting the characters object which is the first one.
Now every superhero has a serial number associated with it, find out about a rare superhero named “3-D Man” and discover his comics.
For getting the comics we have syntax like this
# where x is the serial code of your
# superhero
comics = characters.comics(1011334)
We will store this comics dictionary as all_characters dictionary in our code
Below is the implementation:
Python3
# importing the marvel modulefrom marvel import Marvel m = Marvel("8e6845d48fcb5b7dbec2bc3784b9d2be", "2a6e5c6ad9fb7000cbee68c881b0c8c816bc9eb7") # getting the characters objectcharacters = m.characters # serial code of your favourite character# this can be different according to your preferencex = 1011334 for n in range (0, 6): # serach for comics of this character all_characters=characters.comics(x) x = x+1 for i in range (1,12): print(all_characters['data']['results'][int(i)]['title'])
Output:
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 24483,
"s": 24212,
"text": "In this article, we will find the comic of marvel by using python and marvel api. Marvel has provided an API that provides a look into their database consisting of various comics, movies, etc. We will be using that to find out your favorite marvel superhero comic books."
},
{
"code": null,
"e": 24674,
"s": 24483,
"text": "The Marvel Comics API is a tool to help developers everywhere create amazing, uncanny, and incredible websites and applications using data from the 70-plus years of the Marvel age of comics."
},
{
"code": null,
"e": 24910,
"s": 24674,
"text": "The Marvel Comics API is a RESTful service that provides methods for accessing specific resources at canonical URLs and for searching and filtering sets of resources by various criteria. All representations are encoded as JSON objects."
},
{
"code": null,
"e": 24959,
"s": 24910,
"text": "You can access six resource types using the API:"
},
{
"code": null,
"e": 25077,
"s": 24959,
"text": "Comics: individual print and digital comic issues, collections, and graphic novels. For example: Amazing Fantasy #15."
},
{
"code": null,
"e": 25213,
"s": 25077,
"text": "Comic series: sequentially numbered (well, mostly sequentially numbered) groups comics with the same title. For example, Uncanny X-Men."
},
{
"code": null,
"e": 25375,
"s": 25213,
"text": "Comic stories: indivisible, reusable components of comics. For example, the cover from Amazing Fantasy #15 or the origin of the Spider-Man story from that comic."
},
{
"code": null,
"e": 25461,
"s": 25375,
"text": "Comic events and crossovers: big, universe-altering storylines. For example, Infinity"
},
{
"code": null,
"e": 25545,
"s": 25461,
"text": "Creators: women, men, and organizations who create comics. For example, Jack Kirby."
},
{
"code": null,
"e": 25867,
"s": 25545,
"text": "Characters: the women, men, organizations, alien species, deities, animals, non-corporeal entities, trans-dimensional manifestations, abstract personifications, and green amorphous blobs which occupy the Marvel Universe (and various alternate universes, timelines, and altered realities therein). For example, Spider-Man."
},
{
"code": null,
"e": 26031,
"s": 25867,
"text": "In this article, we will try to fetch a particular character from the marvel API, and then we will generate the comics in which that particular character appeared."
},
{
"code": null,
"e": 26062,
"s": 26031,
"text": "Installation of marvel package"
},
{
"code": null,
"e": 26081,
"s": 26062,
"text": "pip install marvel"
},
{
"code": null,
"e": 26329,
"s": 26081,
"text": "Step 1: First go their website https://developer.marvel.com/, Now click on to top left “SIGN IN | JOIN” option and then click on to the “CREATE AN ACCOUNT” and now give your details and then click “CREATE ACCOUNT” option, which will look like this"
},
{
"code": null,
"e": 26694,
"s": 26329,
"text": "Step 2: After signing in you will be redirected to their home page where it will show that your account is now logged in, but in order to get the API key first, you’ve to confirm the mail which marvel has sent you on your specified email address in order to verify it. Check your mailbox there will be a mail sent by marvel. Open it and then click “Confirm” option"
},
{
"code": null,
"e": 27042,
"s": 26694,
"text": "Step 3: After that, you’ve to come back to your marvel developer portal where you’ve just created your account, and now on the top left side it will show your username instead of the sign-in option otherwise please refer to the steps again. After that in the middle center portion of the website, you will find an option “Get a Key”, click on that"
},
{
"code": null,
"e": 27478,
"s": 27042,
"text": "Step 4: After that, you will be redirected to their terms of use page for the API. Just scroll down to the bottom (or you can give it a read if you want) and click on accept. Now, there we go, finally we will arrive at the page where it will show you the two most important keys and other important information. Just copy the Private and the public keys and store them in a secured folder on your computer. The page will look like this"
},
{
"code": null,
"e": 27560,
"s": 27478,
"text": "Note: Keep these keys in a private folder and don’t share them with anyone else. "
},
{
"code": null,
"e": 27600,
"s": 27560,
"text": "First import marvel from Marvel package"
},
{
"code": null,
"e": 27626,
"s": 27600,
"text": "from marvel import Marvel"
},
{
"code": null,
"e": 27681,
"s": 27626,
"text": "After that type your public and private keys like this"
},
{
"code": null,
"e": 27717,
"s": 27681,
"text": "m = Marvel(PUBLIC_KEY, PRIVATE_KEY)"
},
{
"code": null,
"e": 27874,
"s": 27717,
"text": "Now there are six objects presented namely, characters, comics, creators, events, series and stories. Check : https://pypi.org/project/marvel/ for more info"
},
{
"code": null,
"e": 27996,
"s": 27874,
"text": "characters = m.characters comics = m.comics creators = m.creators events = m.events series = m.series stories = m.stories"
},
{
"code": null,
"e": 28157,
"s": 27996,
"text": "Each of the above objects returns the appropriate response (JSON), but from here we are only interested in getting the characters object which is the first one."
},
{
"code": null,
"e": 28290,
"s": 28157,
"text": "Now every superhero has a serial number associated with it, find out about a rare superhero named “3-D Man” and discover his comics."
},
{
"code": null,
"e": 28338,
"s": 28290,
"text": "For getting the comics we have syntax like this"
},
{
"code": null,
"e": 28424,
"s": 28338,
"text": "# where x is the serial code of your \n# superhero\ncomics = characters.comics(1011334)"
},
{
"code": null,
"e": 28502,
"s": 28424,
"text": "We will store this comics dictionary as all_characters dictionary in our code"
},
{
"code": null,
"e": 28531,
"s": 28502,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 28539,
"s": 28531,
"text": "Python3"
},
{
"code": "# importing the marvel modulefrom marvel import Marvel m = Marvel(\"8e6845d48fcb5b7dbec2bc3784b9d2be\", \"2a6e5c6ad9fb7000cbee68c881b0c8c816bc9eb7\") # getting the characters objectcharacters = m.characters # serial code of your favourite character# this can be different according to your preferencex = 1011334 for n in range (0, 6): # serach for comics of this character all_characters=characters.comics(x) x = x+1 for i in range (1,12): print(all_characters['data']['results'][int(i)]['title'])",
"e": 29080,
"s": 28539,
"text": null
},
{
"code": null,
"e": 29088,
"s": 29080,
"text": "Output:"
},
{
"code": null,
"e": 29103,
"s": 29088,
"text": "python-modules"
},
{
"code": null,
"e": 29118,
"s": 29103,
"text": "python-utility"
},
{
"code": null,
"e": 29125,
"s": 29118,
"text": "Python"
},
{
"code": null,
"e": 29223,
"s": 29125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29232,
"s": 29223,
"text": "Comments"
},
{
"code": null,
"e": 29245,
"s": 29232,
"text": "Old Comments"
},
{
"code": null,
"e": 29277,
"s": 29245,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29333,
"s": 29277,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29354,
"s": 29333,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 29393,
"s": 29354,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29435,
"s": 29393,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29462,
"s": 29435,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29493,
"s": 29462,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29535,
"s": 29493,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29571,
"s": 29535,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Apache Pig Installation on Windows and Case Study - GeeksforGeeks
|
03 Dec, 2021
Apache Pig is a data manipulation tool that is built over Hadoop’s MapReduce. Pig provides us with a scripting language for easier and faster data manipulation. This scripting language is called Pig Latin.
Apache Pig scripts can be executed in 3 ways as follows:
Using Grunt Shell (Interactive Mode) – Write the commands in the grunt shell and get the output there itself using the DUMP command.
Using Pig Scripts (Batch Mode) – Write the pig latin commands in a single file with .pig extension and execute the script on the prompt.
Using User-Defined Functions (Embedded Mode) – Write your own Functions on languages like Java and then use them in the scripts.
Pig Installation:
Before proceeding you need to make sure that you have all these pre-requisites as follows.
Hadoop Ecosystem installed on your system and all the four components i.e. DataNode, NameNode, ResourceManager, TaskManager are working. If any one of them randomly shuts down then you need to fix that before proceeding.7-Zip is required to extract the .tar.gz files in windows.
Hadoop Ecosystem installed on your system and all the four components i.e. DataNode, NameNode, ResourceManager, TaskManager are working. If any one of them randomly shuts down then you need to fix that before proceeding.
7-Zip is required to extract the .tar.gz files in windows.
Let’s take a look at How to install Pig version (0.17.0) on Windows as follows.
Step 1: Download the Pig version 0.17.0 tar file from the official Apache pig site. Navigate to the website https://downloads.apache.org/pig/latest/. Download the file ‘pig-0.17.0.tar.gz’ from the website.
Then extract this tar file using 7-Zip tool (use 7-Zip for faster extraction. First we extract the .tar.gz file by right-clicking on it and clicking on ‘7-Zip → Extract Here’. Then we extract the .tar file in the same way). To have the same paths as you can see in the diagram then you need to extract in the C: drive.
Step 2: Add the path variables of PIG_HOME and PIG_HOME\bin
Click the Windows Button and in the search bar type ‘Environment Variables’. Then click on the ‘Edit the system environment variables’.
Then Click on ‘Environment Variables’ on the bottom of the tab. In the newly opened tab click on the ‘New’ button in the user variables section.
After hitting new Add the following values in the fields.
Variable Name - PIG_HOME
Variable value - C:\pig-0.17.0
All the path to the extracted pig folder in the Variable Value field. I extracted it in the ‘C’ directory. And then click OK.
Now click on the Path variable in the System variables. This will open a new tab. Then click the ‘New’ button. And add the value C:\pig-0.17.0\bin in the text box. Then hit OK until all tabs have closed.
Step 3: Correcting the Pig Command File
Find file ‘pig.cmd’ in the bin folder of the pig file ( C:\pig-0.17.0\bin)
set HADOOP_BIN_PATH = %HADOOP_HOME%\bin
Find the line:
set HADOOP_BIN_PATH=%HADOOP_HOME%\bin
Replace this line by:
set HADOOP_BIN_PATH=%HADOOP_HOME%\libexec
And save this file. We are finally here. Now you are all set to start exploring Pig and it’s environment.
There are 2 Ways of Invoking the grunt shell:
Local Mode: All the files are installed, accessed, and run in the local machine itself. No need to use HDFS. The command for running Pig in local mode is as follows.
pig -x local
MapReduce Mode: The files are all present on the HDFS . We need to load this data to process it. The command for running Pig in MapReduce/HDFS Mode is as follows.
pig -x mapreduce
Apache PIG CASE STUDY:
1. Download the dataset containing the Agriculture related data about crops in various regions and their area and produce. The link for dataset –https://www.kaggle.com/abhinand05/crop-production-in-india The dataset contains 7 columns namely as follows.
State_Name : chararray ;
District_Name : chararray ;
Crop_Year : int ;
Season : chararray ;
Crop : chararray ;
Area : int ;
Production : int
No of rows: 246092
No of columns: 7
2. Enter pig local mode using
grunt > pig -x local
3. Load the dataset in the local mode
grunt > agriculture= LOAD 'F:/csv files/crop_production.csv' using PigStorage (',')
as ( State_Name:chararray , District_Name:chararray , Crop_Year:int ,
Season:chararray , Crop:chararray , Area:int , Production:int ) ;
4. Dump and describe the data set agriculture using
grunt > dump agriculture;
grunt > describe agriculture;
5. Executing the PIG queries in local mode
You can follow these written queries to analyze the dataset using the various functions and operators in PIG. You need to follow all the above steps before proceeding.
Query 1: Grouping All Records State wise.
This command will group all the records by the column State_Name.
grunt > statewisecrop = GROUP agriculture BY State_Name;
grunt > DUMP statewisecrop;
grunt > DESCRIBE statewisecrop;
Now store the result of the query in a CSV file for better understanding. We have to mention the name of the object and the path where it needs to be stored.
pathname -> 'F:/csv files/statewiseoutput'
grunt > STORE statewisecrop INTO ‘F:/csv files/statewiseoutput’;
The output will be in a file named ‘part-r-00000’ which needs to be renamed as ‘part-r-00000.csv’ to be opened in the Excel format and to make it readable. You will find this file in the path that we have mentioned in the above query. In my case it was in the path ‘F:/csv files/statewiseoutput/’.
The output file will look something like this:
CSV file of output of query 1
You can also check the raw file by opening the command prompt in administrator mode and write the following command as follows.
C:\Users\Adhiksha\ > Head -2 ‘F:\csv files\statewiseoutput\part-r-00000.csv’;
This command returns the top 2 records of the state-wise output result file. Looks something like this.
Output of query number 1
Query 2: Generate Total Crop wise Production and Area
In the above query, we need to group by Crop type and then find the SUM of their Productions and Area.
grunt > cropinfo = FOREACH( GROUP agriculture BY Crop )
GENERATE group AS Crop, SUM(agriculture.Area) as AreaPerCrop ,
SUM(agriculture.Production) as ProductionPerCrop;
grunt > DESCRIBE cropinfo;
grunt > STORE cropinfo INTO ‘F:/csv files/cropinfooutput’;
The output will be in a file named ‘part-r-00000’ which needs to be renamed as ‘part-r-00000.csv’ to be opened in the Excel format and to make it readable.
You can check the csv output by opening the command prompt in administrator mode and running the command as follows.
C:\Users > cat ‘F:/csv files/cropinfooutput/part-r-00000.csv’
This will return all the output on the command prompt. You can see that we have three columns in the output.
Output:
Crop ,
AreaperCrop ,
ProductionPerCrop.
Query 3: The majority of crops are grown in a Season and in which year.
In this query, we need to group the crops by season and order them alphabetically. Also, this will tell us which crops are found in a season and with year.
grunt > seasonalcrops = FOREACH (GROUP agriculture by Season ){
order_crops = ORDER agriculture BY Crop ASC;
GENERATE group AS Season , order_crops.(Crop) AS Crops;
};
grunt > DESCRIBE seasonalcrops;
grunt > STORE seasonalcrops INTO ‘F:/csv files/seasonaloutput;
The output will be in a file named ‘part-r-00000’ which needs to be renamed as ‘part-r-00000.csv’ to be opened in the Excel format and to make it readable. You can check the csv output by opening the command prompt in administrator mode and running the command as follows.
C:\Users > cat ‘F:/csv files/seasonaloutput/part-r-00000.csv’
You can check the output from the ‘part-r-00000.csv’ by opening the file. You can see all the distinct seasons in the first row followed by all the crops and their years of production.
Output of this query number 3
Query 4: Average crop production in each district after the year 2000.
First, we need to group by district name and then find the average of the total crop production but only after the year 2000.
grunt > averagecrops = FOREACH (GROUP agriculture by District_Name){
after_year = FILTER agriculture BY Crop_Year>2000;
GENERATE group AS District_Name , AVG(after_year.(Production)) AS
AvgProd;
};
grunt > DESCRIBE averagecrops;
grunt > STORE averagecrops INTO ‘F:/csv files/averagecrops;
You can check the output from the ‘part-r-00000.csv’ by opening the file. This file will contain two columns. The first one has all distinct district names and the second one will have the average production of all crops in each district after the year 2000.
Output of the query number 4
Query 5: Highest produced crops and details from each State.
First, we need to group the input by the state name. Then iterate through each grouped record and then find the TOP 1 record with the highest Production from each state.
grunt > top_agri= GROUP agriculture BY State_Name;
grunt > data_top = FOREACH top_agri{
top = TOP(1, 6 , agriculture);
GENERATE top as Record;
}
grunt > DESCRIBE cropinfo;
grunt > STORE averagecrops INTO ‘F:/csv files/averagecrops;
You can check the output from the ‘part-r-00000.csv’ by opening the file. This file contains records from each unique state who are having the highest Production amount. Read above and follow the steps to create ‘part-r-00000.csv’. You can check the csv output by opening the command prompt in administrator mode and running the command:
C:\Users > cat ‘F:/csv files/top1prod/part-r-00000.csv’
sweetyty
prachisoda1234
Apache Pig
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
MapReduce - Combiners
Difference Between Hadoop 2.x vs Hadoop 3.x
Hadoop - mrjob Python Library For MapReduce With Example
Why a Block in HDFS is so Large?
Hadoop MapReduce - Data Flow
MapReduce Program - Finding The Average Age of Male and Female Died in Titanic Disaster
Hadoop | History or Evolution
What is Hadoop Streaming?
Hadoop - Rack and Rack Awareness
Installing and Setting Up Hadoop in Pseudo-Distributed Mode in Windows 10
|
[
{
"code": null,
"e": 23955,
"s": 23927,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 24161,
"s": 23955,
"text": "Apache Pig is a data manipulation tool that is built over Hadoop’s MapReduce. Pig provides us with a scripting language for easier and faster data manipulation. This scripting language is called Pig Latin."
},
{
"code": null,
"e": 24218,
"s": 24161,
"text": "Apache Pig scripts can be executed in 3 ways as follows:"
},
{
"code": null,
"e": 24351,
"s": 24218,
"text": "Using Grunt Shell (Interactive Mode) – Write the commands in the grunt shell and get the output there itself using the DUMP command."
},
{
"code": null,
"e": 24488,
"s": 24351,
"text": "Using Pig Scripts (Batch Mode) – Write the pig latin commands in a single file with .pig extension and execute the script on the prompt."
},
{
"code": null,
"e": 24617,
"s": 24488,
"text": "Using User-Defined Functions (Embedded Mode) – Write your own Functions on languages like Java and then use them in the scripts."
},
{
"code": null,
"e": 24635,
"s": 24617,
"text": "Pig Installation:"
},
{
"code": null,
"e": 24726,
"s": 24635,
"text": "Before proceeding you need to make sure that you have all these pre-requisites as follows."
},
{
"code": null,
"e": 25005,
"s": 24726,
"text": "Hadoop Ecosystem installed on your system and all the four components i.e. DataNode, NameNode, ResourceManager, TaskManager are working. If any one of them randomly shuts down then you need to fix that before proceeding.7-Zip is required to extract the .tar.gz files in windows."
},
{
"code": null,
"e": 25226,
"s": 25005,
"text": "Hadoop Ecosystem installed on your system and all the four components i.e. DataNode, NameNode, ResourceManager, TaskManager are working. If any one of them randomly shuts down then you need to fix that before proceeding."
},
{
"code": null,
"e": 25285,
"s": 25226,
"text": "7-Zip is required to extract the .tar.gz files in windows."
},
{
"code": null,
"e": 25365,
"s": 25285,
"text": "Let’s take a look at How to install Pig version (0.17.0) on Windows as follows."
},
{
"code": null,
"e": 25572,
"s": 25365,
"text": "Step 1: Download the Pig version 0.17.0 tar file from the official Apache pig site. Navigate to the website https://downloads.apache.org/pig/latest/. Download the file ‘pig-0.17.0.tar.gz’ from the website. "
},
{
"code": null,
"e": 25892,
"s": 25572,
"text": "Then extract this tar file using 7-Zip tool (use 7-Zip for faster extraction. First we extract the .tar.gz file by right-clicking on it and clicking on ‘7-Zip → Extract Here’. Then we extract the .tar file in the same way). To have the same paths as you can see in the diagram then you need to extract in the C: drive."
},
{
"code": null,
"e": 25952,
"s": 25892,
"text": "Step 2: Add the path variables of PIG_HOME and PIG_HOME\\bin"
},
{
"code": null,
"e": 26088,
"s": 25952,
"text": "Click the Windows Button and in the search bar type ‘Environment Variables’. Then click on the ‘Edit the system environment variables’."
},
{
"code": null,
"e": 26233,
"s": 26088,
"text": "Then Click on ‘Environment Variables’ on the bottom of the tab. In the newly opened tab click on the ‘New’ button in the user variables section."
},
{
"code": null,
"e": 26291,
"s": 26233,
"text": "After hitting new Add the following values in the fields."
},
{
"code": null,
"e": 26350,
"s": 26291,
"text": "Variable Name - PIG_HOME\nVariable value - C:\\pig-0.17.0"
},
{
"code": null,
"e": 26476,
"s": 26350,
"text": "All the path to the extracted pig folder in the Variable Value field. I extracted it in the ‘C’ directory. And then click OK."
},
{
"code": null,
"e": 26680,
"s": 26476,
"text": "Now click on the Path variable in the System variables. This will open a new tab. Then click the ‘New’ button. And add the value C:\\pig-0.17.0\\bin in the text box. Then hit OK until all tabs have closed."
},
{
"code": null,
"e": 26720,
"s": 26680,
"text": "Step 3: Correcting the Pig Command File"
},
{
"code": null,
"e": 26795,
"s": 26720,
"text": "Find file ‘pig.cmd’ in the bin folder of the pig file ( C:\\pig-0.17.0\\bin)"
},
{
"code": null,
"e": 26835,
"s": 26795,
"text": "set HADOOP_BIN_PATH = %HADOOP_HOME%\\bin"
},
{
"code": null,
"e": 26850,
"s": 26835,
"text": "Find the line:"
},
{
"code": null,
"e": 26889,
"s": 26850,
"text": "set HADOOP_BIN_PATH=%HADOOP_HOME%\\bin "
},
{
"code": null,
"e": 26911,
"s": 26889,
"text": "Replace this line by:"
},
{
"code": null,
"e": 26954,
"s": 26911,
"text": "set HADOOP_BIN_PATH=%HADOOP_HOME%\\libexec "
},
{
"code": null,
"e": 27060,
"s": 26954,
"text": "And save this file. We are finally here. Now you are all set to start exploring Pig and it’s environment."
},
{
"code": null,
"e": 27106,
"s": 27060,
"text": "There are 2 Ways of Invoking the grunt shell:"
},
{
"code": null,
"e": 27273,
"s": 27106,
"text": "Local Mode: All the files are installed, accessed, and run in the local machine itself. No need to use HDFS. The command for running Pig in local mode is as follows. "
},
{
"code": null,
"e": 27286,
"s": 27273,
"text": "pig -x local"
},
{
"code": null,
"e": 27450,
"s": 27286,
"text": "MapReduce Mode: The files are all present on the HDFS . We need to load this data to process it. The command for running Pig in MapReduce/HDFS Mode is as follows. "
},
{
"code": null,
"e": 27467,
"s": 27450,
"text": "pig -x mapreduce"
},
{
"code": null,
"e": 27490,
"s": 27467,
"text": "Apache PIG CASE STUDY:"
},
{
"code": null,
"e": 27744,
"s": 27490,
"text": "1. Download the dataset containing the Agriculture related data about crops in various regions and their area and produce. The link for dataset –https://www.kaggle.com/abhinand05/crop-production-in-india The dataset contains 7 columns namely as follows."
},
{
"code": null,
"e": 27893,
"s": 27744,
"text": "State_Name : chararray ; \nDistrict_Name : chararray ; \nCrop_Year : int ; \nSeason : chararray ; \nCrop : chararray ; \nArea : int ; \nProduction : int"
},
{
"code": null,
"e": 27930,
"s": 27893,
"text": "No of rows: 246092 \nNo of columns: 7"
},
{
"code": null,
"e": 27960,
"s": 27930,
"text": "2. Enter pig local mode using"
},
{
"code": null,
"e": 27981,
"s": 27960,
"text": "grunt > pig -x local"
},
{
"code": null,
"e": 28019,
"s": 27981,
"text": "3. Load the dataset in the local mode"
},
{
"code": null,
"e": 28257,
"s": 28019,
"text": "grunt > agriculture= LOAD 'F:/csv files/crop_production.csv' using PigStorage (',') \n as ( State_Name:chararray , District_Name:chararray , Crop_Year:int , \n Season:chararray , Crop:chararray , Area:int , Production:int ) ;"
},
{
"code": null,
"e": 28309,
"s": 28257,
"text": "4. Dump and describe the data set agriculture using"
},
{
"code": null,
"e": 28365,
"s": 28309,
"text": "grunt > dump agriculture;\ngrunt > describe agriculture;"
},
{
"code": null,
"e": 28408,
"s": 28365,
"text": "5. Executing the PIG queries in local mode"
},
{
"code": null,
"e": 28576,
"s": 28408,
"text": "You can follow these written queries to analyze the dataset using the various functions and operators in PIG. You need to follow all the above steps before proceeding."
},
{
"code": null,
"e": 28618,
"s": 28576,
"text": "Query 1: Grouping All Records State wise."
},
{
"code": null,
"e": 28685,
"s": 28618,
"text": " This command will group all the records by the column State_Name."
},
{
"code": null,
"e": 28802,
"s": 28685,
"text": "grunt > statewisecrop = GROUP agriculture BY State_Name;\ngrunt > DUMP statewisecrop;\ngrunt > DESCRIBE statewisecrop;"
},
{
"code": null,
"e": 28962,
"s": 28802,
"text": "Now store the result of the query in a CSV file for better understanding. We have to mention the name of the object and the path where it needs to be stored. "
},
{
"code": null,
"e": 29070,
"s": 28962,
"text": "pathname -> 'F:/csv files/statewiseoutput'\ngrunt > STORE statewisecrop INTO ‘F:/csv files/statewiseoutput’;"
},
{
"code": null,
"e": 29368,
"s": 29070,
"text": "The output will be in a file named ‘part-r-00000’ which needs to be renamed as ‘part-r-00000.csv’ to be opened in the Excel format and to make it readable. You will find this file in the path that we have mentioned in the above query. In my case it was in the path ‘F:/csv files/statewiseoutput/’."
},
{
"code": null,
"e": 29415,
"s": 29368,
"text": "The output file will look something like this:"
},
{
"code": null,
"e": 29445,
"s": 29415,
"text": "CSV file of output of query 1"
},
{
"code": null,
"e": 29573,
"s": 29445,
"text": "You can also check the raw file by opening the command prompt in administrator mode and write the following command as follows."
},
{
"code": null,
"e": 29652,
"s": 29573,
"text": " C:\\Users\\Adhiksha\\ > Head -2 ‘F:\\csv files\\statewiseoutput\\part-r-00000.csv’;"
},
{
"code": null,
"e": 29756,
"s": 29652,
"text": "This command returns the top 2 records of the state-wise output result file. Looks something like this."
},
{
"code": null,
"e": 29781,
"s": 29756,
"text": "Output of query number 1"
},
{
"code": null,
"e": 29835,
"s": 29781,
"text": "Query 2: Generate Total Crop wise Production and Area"
},
{
"code": null,
"e": 29938,
"s": 29835,
"text": "In the above query, we need to group by Crop type and then find the SUM of their Productions and Area."
},
{
"code": null,
"e": 30135,
"s": 29938,
"text": "grunt > cropinfo = FOREACH( GROUP agriculture BY Crop )\nGENERATE group AS Crop, SUM(agriculture.Area) as AreaPerCrop , \nSUM(agriculture.Production) as ProductionPerCrop;\ngrunt > DESCRIBE cropinfo;"
},
{
"code": null,
"e": 30194,
"s": 30135,
"text": "grunt > STORE cropinfo INTO ‘F:/csv files/cropinfooutput’;"
},
{
"code": null,
"e": 30350,
"s": 30194,
"text": "The output will be in a file named ‘part-r-00000’ which needs to be renamed as ‘part-r-00000.csv’ to be opened in the Excel format and to make it readable."
},
{
"code": null,
"e": 30467,
"s": 30350,
"text": "You can check the csv output by opening the command prompt in administrator mode and running the command as follows."
},
{
"code": null,
"e": 30529,
"s": 30467,
"text": "C:\\Users > cat ‘F:/csv files/cropinfooutput/part-r-00000.csv’"
},
{
"code": null,
"e": 30639,
"s": 30529,
"text": "This will return all the output on the command prompt. You can see that we have three columns in the output. "
},
{
"code": null,
"e": 30647,
"s": 30639,
"text": "Output:"
},
{
"code": null,
"e": 30689,
"s": 30647,
"text": "Crop , \nAreaperCrop , \nProductionPerCrop."
},
{
"code": null,
"e": 30761,
"s": 30689,
"text": "Query 3: The majority of crops are grown in a Season and in which year."
},
{
"code": null,
"e": 30917,
"s": 30761,
"text": "In this query, we need to group the crops by season and order them alphabetically. Also, this will tell us which crops are found in a season and with year."
},
{
"code": null,
"e": 31157,
"s": 30917,
"text": "grunt > seasonalcrops = FOREACH (GROUP agriculture by Season ){\n order_crops = ORDER agriculture BY Crop ASC;\n GENERATE group AS Season , order_crops.(Crop) AS Crops;\n };"
},
{
"code": null,
"e": 31189,
"s": 31157,
"text": "grunt > DESCRIBE seasonalcrops;"
},
{
"code": null,
"e": 31252,
"s": 31189,
"text": "grunt > STORE seasonalcrops INTO ‘F:/csv files/seasonaloutput;"
},
{
"code": null,
"e": 31525,
"s": 31252,
"text": "The output will be in a file named ‘part-r-00000’ which needs to be renamed as ‘part-r-00000.csv’ to be opened in the Excel format and to make it readable. You can check the csv output by opening the command prompt in administrator mode and running the command as follows."
},
{
"code": null,
"e": 31588,
"s": 31525,
"text": " C:\\Users > cat ‘F:/csv files/seasonaloutput/part-r-00000.csv’"
},
{
"code": null,
"e": 31773,
"s": 31588,
"text": "You can check the output from the ‘part-r-00000.csv’ by opening the file. You can see all the distinct seasons in the first row followed by all the crops and their years of production."
},
{
"code": null,
"e": 31803,
"s": 31773,
"text": "Output of this query number 3"
},
{
"code": null,
"e": 31874,
"s": 31803,
"text": "Query 4: Average crop production in each district after the year 2000."
},
{
"code": null,
"e": 32000,
"s": 31874,
"text": "First, we need to group by district name and then find the average of the total crop production but only after the year 2000."
},
{
"code": null,
"e": 32290,
"s": 32000,
"text": "grunt > averagecrops = FOREACH (GROUP agriculture by District_Name){\n after_year = FILTER agriculture BY Crop_Year>2000;\n GENERATE group AS District_Name , AVG(after_year.(Production)) AS\n AvgProd;\n };"
},
{
"code": null,
"e": 32322,
"s": 32290,
"text": " grunt > DESCRIBE averagecrops;"
},
{
"code": null,
"e": 32383,
"s": 32322,
"text": " grunt > STORE averagecrops INTO ‘F:/csv files/averagecrops;"
},
{
"code": null,
"e": 32642,
"s": 32383,
"text": "You can check the output from the ‘part-r-00000.csv’ by opening the file. This file will contain two columns. The first one has all distinct district names and the second one will have the average production of all crops in each district after the year 2000."
},
{
"code": null,
"e": 32671,
"s": 32642,
"text": "Output of the query number 4"
},
{
"code": null,
"e": 32732,
"s": 32671,
"text": "Query 5: Highest produced crops and details from each State."
},
{
"code": null,
"e": 32902,
"s": 32732,
"text": "First, we need to group the input by the state name. Then iterate through each grouped record and then find the TOP 1 record with the highest Production from each state."
},
{
"code": null,
"e": 33104,
"s": 32902,
"text": "grunt > top_agri= GROUP agriculture BY State_Name;\ngrunt > data_top = FOREACH top_agri{\n top = TOP(1, 6 , agriculture);\n GENERATE top as Record;\n }"
},
{
"code": null,
"e": 33131,
"s": 33104,
"text": "grunt > DESCRIBE cropinfo;"
},
{
"code": null,
"e": 33191,
"s": 33131,
"text": "grunt > STORE averagecrops INTO ‘F:/csv files/averagecrops;"
},
{
"code": null,
"e": 33529,
"s": 33191,
"text": "You can check the output from the ‘part-r-00000.csv’ by opening the file. This file contains records from each unique state who are having the highest Production amount. Read above and follow the steps to create ‘part-r-00000.csv’. You can check the csv output by opening the command prompt in administrator mode and running the command:"
},
{
"code": null,
"e": 33585,
"s": 33529,
"text": "C:\\Users > cat ‘F:/csv files/top1prod/part-r-00000.csv’"
},
{
"code": null,
"e": 33594,
"s": 33585,
"text": "sweetyty"
},
{
"code": null,
"e": 33609,
"s": 33594,
"text": "prachisoda1234"
},
{
"code": null,
"e": 33620,
"s": 33609,
"text": "Apache Pig"
},
{
"code": null,
"e": 33627,
"s": 33620,
"text": "Hadoop"
},
{
"code": null,
"e": 33634,
"s": 33627,
"text": "Hadoop"
},
{
"code": null,
"e": 33732,
"s": 33634,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33741,
"s": 33732,
"text": "Comments"
},
{
"code": null,
"e": 33754,
"s": 33741,
"text": "Old Comments"
},
{
"code": null,
"e": 33776,
"s": 33754,
"text": "MapReduce - Combiners"
},
{
"code": null,
"e": 33820,
"s": 33776,
"text": "Difference Between Hadoop 2.x vs Hadoop 3.x"
},
{
"code": null,
"e": 33877,
"s": 33820,
"text": "Hadoop - mrjob Python Library For MapReduce With Example"
},
{
"code": null,
"e": 33910,
"s": 33877,
"text": "Why a Block in HDFS is so Large?"
},
{
"code": null,
"e": 33939,
"s": 33910,
"text": "Hadoop MapReduce - Data Flow"
},
{
"code": null,
"e": 34027,
"s": 33939,
"text": "MapReduce Program - Finding The Average Age of Male and Female Died in Titanic Disaster"
},
{
"code": null,
"e": 34057,
"s": 34027,
"text": "Hadoop | History or Evolution"
},
{
"code": null,
"e": 34083,
"s": 34057,
"text": "What is Hadoop Streaming?"
},
{
"code": null,
"e": 34116,
"s": 34083,
"text": "Hadoop - Rack and Rack Awareness"
}
] |
Count the number of a special day between two dates by using PL/SQL - GeeksforGeeks
|
06 Dec, 2019
Prerequisite – PL/SQL Introduction, Decision Making in PL/SQL
Write a pl/sql program to input two dates and print number of Sundays between those two dates.
Explanation:Before each iteration of the loop, condition is evaluated. If it evaluates to TRUE, sequence_of_statements is executed. If condition evaluates to FALSE or NULL, the loop is finished and control resumes after the END LOOP statements.
Note:The only difference between simple loop and while loop is simple execute first and then it will check condition, so simple loop execute at least once and in while loop first it will check condition and then execute.
Example-1:
Input: Enter value for date1: 01-SEP-19
Enter value for date2: 29-SEP-19
Output: no of Sundays : 5
Example-2:
Input: Enter value for date1: 01-SEP-19
Enter value for date2: 15-SEP-19
Output: no of Sundays: 3
Code:
--declare the variables D1 and D2.--type of variable is Date.SQL> DECLARE D1 Date; D2 Date; Cnt Number:=0; BEGIN D1:='&Date1'; D2:='&Date2'; D1:=next_day(D1-1, 'SUNDAY'); --check the condition by using while loop. while(D1<=D2) LOOP Cnt:=Cnt+1; D1:=D1+7; END LOOP; dbms_output.put_line('no of Sundays:'||Cnt); END; /--end of program
Output:
Enter value for date1: 01-SEP-19
old 5: Begin D1:='&Date1';
new 5: Begin D1:='01-SEP-19';
Enter value for date2: 29-SEP-19
old 6: D2:='&Date2';
new 6: D2:='29-SEP-19';
no of Sundays:5
PL/SQL procedure successfully completed.
Advantages:-By using while loop first it checks condition and then execute, So We count easily the number of a special day between two dates.
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | DROP, TRUNCATE
Composite Key in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL indexes
SQL | Date functions
What is Temporary Table in SQL?
Window functions in SQL
SQL | ALTER (ADD, DROP, MODIFY)
|
[
{
"code": null,
"e": 23877,
"s": 23849,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 23939,
"s": 23877,
"text": "Prerequisite – PL/SQL Introduction, Decision Making in PL/SQL"
},
{
"code": null,
"e": 24034,
"s": 23939,
"text": "Write a pl/sql program to input two dates and print number of Sundays between those two dates."
},
{
"code": null,
"e": 24279,
"s": 24034,
"text": "Explanation:Before each iteration of the loop, condition is evaluated. If it evaluates to TRUE, sequence_of_statements is executed. If condition evaluates to FALSE or NULL, the loop is finished and control resumes after the END LOOP statements."
},
{
"code": null,
"e": 24500,
"s": 24279,
"text": "Note:The only difference between simple loop and while loop is simple execute first and then it will check condition, so simple loop execute at least once and in while loop first it will check condition and then execute."
},
{
"code": null,
"e": 24511,
"s": 24500,
"text": "Example-1:"
},
{
"code": null,
"e": 24619,
"s": 24511,
"text": "Input: Enter value for date1: 01-SEP-19 \n Enter value for date2: 29-SEP-19\n\nOutput: no of Sundays : 5 "
},
{
"code": null,
"e": 24630,
"s": 24619,
"text": "Example-2:"
},
{
"code": null,
"e": 24736,
"s": 24630,
"text": "Input: Enter value for date1: 01-SEP-19\n Enter value for date2: 15-SEP-19\n\nOutput: no of Sundays: 3 "
},
{
"code": null,
"e": 24742,
"s": 24736,
"text": "Code:"
},
{
"code": "--declare the variables D1 and D2.--type of variable is Date.SQL> DECLARE D1 Date; D2 Date; Cnt Number:=0; BEGIN D1:='&Date1'; D2:='&Date2'; D1:=next_day(D1-1, 'SUNDAY'); --check the condition by using while loop. while(D1<=D2) LOOP Cnt:=Cnt+1; D1:=D1+7; END LOOP; dbms_output.put_line('no of Sundays:'||Cnt); END; /--end of program",
"e": 25163,
"s": 24742,
"text": null
},
{
"code": null,
"e": 25171,
"s": 25163,
"text": "Output:"
},
{
"code": null,
"e": 25363,
"s": 25171,
"text": "Enter value for date1: 01-SEP-19\nold 5: Begin D1:='&Date1';\nnew 5: Begin D1:='01-SEP-19';\n\nEnter value for date2: 29-SEP-19\nold 6: D2:='&Date2';\nnew 6: D2:='29-SEP-19';\nno of Sundays:5 "
},
{
"code": null,
"e": 25404,
"s": 25363,
"text": "PL/SQL procedure successfully completed."
},
{
"code": null,
"e": 25546,
"s": 25404,
"text": "Advantages:-By using while loop first it checks condition and then execute, So We count easily the number of a special day between two dates."
},
{
"code": null,
"e": 25557,
"s": 25546,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 25561,
"s": 25557,
"text": "SQL"
},
{
"code": null,
"e": 25565,
"s": 25561,
"text": "SQL"
},
{
"code": null,
"e": 25663,
"s": 25565,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25672,
"s": 25663,
"text": "Comments"
},
{
"code": null,
"e": 25685,
"s": 25672,
"text": "Old Comments"
},
{
"code": null,
"e": 25751,
"s": 25685,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 25772,
"s": 25751,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 25793,
"s": 25772,
"text": "Composite Key in SQL"
},
{
"code": null,
"e": 25871,
"s": 25793,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 25888,
"s": 25871,
"text": "SQL using Python"
},
{
"code": null,
"e": 25900,
"s": 25888,
"text": "SQL indexes"
},
{
"code": null,
"e": 25921,
"s": 25900,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 25953,
"s": 25921,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 25977,
"s": 25953,
"text": "Window functions in SQL"
}
] |
Minimum Cost of ropes | Practice | GeeksforGeeks
|
There are given N ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost.
Example 1:
Input:
n = 4
arr[] = {4, 3, 2, 6}
Output:
29
Explanation:
For example if we are given 4
ropes of lengths 4, 3, 2 and 6. We can
connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3.
Now we have three ropes of lengths 4, 6
and 5.
2) Now connect ropes of lengths 4 and 5.
Now we have two ropes of lengths 6 and 9.
3) Finally connect the two ropes and all
ropes have connected.
Total cost for connecting all ropes is 5
+ 9 + 15 = 29. This is the optimized cost
for connecting ropes. Other ways of
connecting ropes would always have same
or more cost. For example, if we connect
4 and 6 first (we get three strings of 3,
2 and 10), then connect 10 and 3 (we get
two strings of 13 and 2). Finally we
connect 13 and 2. Total cost in this way
is 10 + 13 + 15 = 38.
Example 2:
Input:
n = 5
arr[] = {4, 2, 7, 6, 9}
Output:
62
Explanation:
First, connect ropes 4 and 2, which makes
the array {6,7,6,9}. Next, add ropes 6 and
6, which results in {12,7,9}. Then, add 7
and 9, which makes the array {12,16}. And
finally add these two which gives {28}.
Hence, the total cost is 6 + 12 + 16 +
28 = 62.
Your Task:
You don't need to read input or print anything. Your task isto complete the function minCost() which takes 2 arguments and returns the minimum cost.
Expected Time Complexity : O(nlogn)
Expected Auxilliary Space : O(n)
Constraints:
1 ≤ N ≤ 100000
1 ≤ arr[i] ≤ 106
0
himanshibaranwal05129in 9 hours
Can someone tell me why in c# i am getting this error?
prog.cs(46,22): error CS0246: The type or namespace name `PriorityQueue' could not be found. Are you missing an assembly reference?
This is anyways imported from System.Collections.Generic
public class Solution{ //Function to return the minimum cost of connecting the ropes. public long minCost(int[] arr, int n) { var rev = Comparer<long>.Create((x, y) => y.CompareTo(x)); var pQ = new PriorityQueue<long, long>(rev); for(int i=0; i<arr.Length; i++){ pQ.Enqueue(arr[i], arr[i]); } int ans = 0; while(pQ.Count!=1){ long min1 = pQ.Dequeue(); long min2 = pQ.Dequeue(); pQ.Enqueue(min1+min2 , min1+min2); } return ans; } }
0
koulikmaity5 days ago
long long minCost(long long arr[], long long n) { // create min-heap priority_queue<long long, vector<long long>, greater<long long> >pq; for(int i=0; i<n; i++) { pq.push(arr[i]); } long long cost = 0; while(pq.size() > 1) { long long a = pq.top(); pq.pop(); long long b = pq.top(); pq.pop(); long long sum = a+b; cost += sum; pq.push(sum); } return cost; }
0
amarrajsmart1971 week ago
//*simply use min heap*//
priority_queue<long long,vector<long long>,greater<long long>> pq; for(long long i=0;i<n;i++) { pq.push(arr[i]); } long long sum=0; while(pq.size()>=2) { long long curr=pq.top(); pq.pop(); curr+=pq.top(); pq.pop(); pq.push(curr); sum+=curr; } return sum; }
0
pavsevaibhav1 week ago
Simple idea is to use PriorityQueue.
First store all the array elements to priorityqueue. then traverse through the priorityqueue until its size is not equal to 1.
while : we pop first to elements from queue and add its sum to totalCost as well as back to queue also.
long minCost(long arr[], int n)
{
// your code here
PriorityQueue<Long> queue = new PriorityQueue<>();
for(long ele : arr) {
queue.add(ele);
}
long totalCost = 0;
while(queue.size() > 1) {
long rope1 = queue.poll();
long rope2 = queue.poll();
totalCost += rope1 + rope2;
queue.add(rope1 + rope2);
}
return totalCost;
}
Complexity :
Time : O(n*logn)
Space:O(n)
0
bhaskarmaheshwari81 week ago
long long cost=0; for(int j=0;j<n-1;j++) { // cout<<arr[0]<<endl; sort(arr,arr+n-j); for(int i=0;i<n-1;i++) { if(i==0) { arr[i]+=arr[i+1]; cost+=arr[i]; // cout<<cost<<endl; } else { arr[i]=arr[i+1]; } } } return cost;
0
harshscode1 week ago
again with the use of priority queue....
long long int sum=0,temp1=0; priority_queue<long long int,vector<long long int>,greater<long long int>> q; for(long long int i=0;i<n;i++) { q.push(a[i]); } for(int i=0;i<n-1;i++) { temp1=q.top(); q.pop(); temp1+=q.top(); q.pop(); q.push(temp1); sum+=temp1; } return sum; }
0
18951a04c32 weeks ago
Min Heap in Python
from heapq import heapify, heappush, heappop
class Solution:
def minCost(self,arr,n):
heap = []
heapify(heap)
for i in range(n):
heappush(heap,arr[i])
cost = 0
while(len(heap)>1):
cost1 = heappop(heap)
cost2 = heappop(heap)
curr_cost = cost1+cost2
cost+=curr_cost
heappush(heap,curr_cost)
return cost
0
hharshit81182 weeks ago
min_heap is created in O(nlogn);
traversing through the heap (n-1) time -
1- taking two min items at a time
2- adding to the result.
3- adding to min heap pq.
overall time complexity : O(nlogn)
class Solution{ public: long long minCost(long long arr[], long long n) { priority_queue<long long, vector<long long>, greater<long long>> pq; for(long long i = 0; i< n; i++){ pq.push(arr[i]); } long long sum = 0; for(long long i = 0; i<n-1; i++){ long long curr = pq.top();pq.pop(); curr += pq.top();pq.pop(); pq.push(curr); sum += curr; } return sum; }};
0
jaintanisha20134 weeks ago
C++ solution using minheap:
class Solution
{
public:
//Function to return the minimum cost of connecting the ropes.
long long minCost(long long arr[], long long n) {
priority_queue<long long,vector<long long>,greater<long long>>pq(arr,arr+n);
if(n<=1)
return 0;
long long ans=0;
while(pq.size()>=2)
{
long long first=pq.top();
pq.pop();
long long second=pq.top();
pq.pop();
ans=ans+first+second;
pq.push(first+second);
}
return ans;
// Your code here
}
};
0
987rashita12holkar1 month ago
My code in C++ using Min_HEAP c++ stl priority queue
long long minCost(long long arr[], long long n) { // Your code here priority_queue<long long,vector<long long>,greater<long long>>pq(arr,arr+n); long long ans=0; if(n==1||n==0) return 0; while(!pq.empty()) { long long a=pq.top(); pq.pop(); long long b=pq.top(); pq.pop(); ans+=(a+b); if(!pq.empty()) pq.push(a+b); } 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": 446,
"s": 238,
"text": "There are given N ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost."
},
{
"code": null,
"e": 457,
"s": 446,
"text": "Example 1:"
},
{
"code": null,
"e": 1241,
"s": 457,
"text": "Input:\nn = 4\narr[] = {4, 3, 2, 6}\nOutput: \n29\nExplanation:\nFor example if we are given 4\nropes of lengths 4, 3, 2 and 6. We can\nconnect the ropes in following ways.\n1) First connect ropes of lengths 2 and 3.\nNow we have three ropes of lengths 4, 6\nand 5.\n2) Now connect ropes of lengths 4 and 5.\nNow we have two ropes of lengths 6 and 9.\n3) Finally connect the two ropes and all\nropes have connected.\nTotal cost for connecting all ropes is 5\n+ 9 + 15 = 29. This is the optimized cost\nfor connecting ropes. Other ways of\nconnecting ropes would always have same\nor more cost. For example, if we connect\n4 and 6 first (we get three strings of 3,\n2 and 10), then connect 10 and 3 (we get\ntwo strings of 13 and 2). Finally we\nconnect 13 and 2. Total cost in this way\nis 10 + 13 + 15 = 38."
},
{
"code": null,
"e": 1252,
"s": 1241,
"text": "Example 2:"
},
{
"code": null,
"e": 1574,
"s": 1252,
"text": "Input:\nn = 5\narr[] = {4, 2, 7, 6, 9}\nOutput: \n62 \nExplanation:\nFirst, connect ropes 4 and 2, which makes\nthe array {6,7,6,9}. Next, add ropes 6 and\n6, which results in {12,7,9}. Then, add 7\nand 9, which makes the array {12,16}. And\nfinally add these two which gives {28}.\nHence, the total cost is 6 + 12 + 16 + \n28 = 62.\n"
},
{
"code": null,
"e": 1734,
"s": 1574,
"text": "Your Task:\nYou don't need to read input or print anything. Your task isto complete the function minCost() which takes 2 arguments and returns the minimum cost."
},
{
"code": null,
"e": 1803,
"s": 1734,
"text": "Expected Time Complexity : O(nlogn)\nExpected Auxilliary Space : O(n)"
},
{
"code": null,
"e": 1848,
"s": 1803,
"text": "Constraints:\n1 ≤ N ≤ 100000\n1 ≤ arr[i] ≤ 106"
},
{
"code": null,
"e": 1850,
"s": 1848,
"text": "0"
},
{
"code": null,
"e": 1882,
"s": 1850,
"text": "himanshibaranwal05129in 9 hours"
},
{
"code": null,
"e": 1938,
"s": 1882,
"text": "Can someone tell me why in c# i am getting this error? "
},
{
"code": null,
"e": 2072,
"s": 1940,
"text": "prog.cs(46,22): error CS0246: The type or namespace name `PriorityQueue' could not be found. Are you missing an assembly reference?"
},
{
"code": null,
"e": 2129,
"s": 2072,
"text": "This is anyways imported from System.Collections.Generic"
},
{
"code": null,
"e": 2687,
"s": 2133,
"text": "public class Solution{ //Function to return the minimum cost of connecting the ropes. public long minCost(int[] arr, int n) { var rev = Comparer<long>.Create((x, y) => y.CompareTo(x)); var pQ = new PriorityQueue<long, long>(rev); for(int i=0; i<arr.Length; i++){ pQ.Enqueue(arr[i], arr[i]); } int ans = 0; while(pQ.Count!=1){ long min1 = pQ.Dequeue(); long min2 = pQ.Dequeue(); pQ.Enqueue(min1+min2 , min1+min2); } return ans; } }"
},
{
"code": null,
"e": 2689,
"s": 2687,
"text": "0"
},
{
"code": null,
"e": 2711,
"s": 2689,
"text": "koulikmaity5 days ago"
},
{
"code": null,
"e": 3265,
"s": 2711,
"text": "long long minCost(long long arr[], long long n) { // create min-heap priority_queue<long long, vector<long long>, greater<long long> >pq; for(int i=0; i<n; i++) { pq.push(arr[i]); } long long cost = 0; while(pq.size() > 1) { long long a = pq.top(); pq.pop(); long long b = pq.top(); pq.pop(); long long sum = a+b; cost += sum; pq.push(sum); } return cost; }"
},
{
"code": null,
"e": 3267,
"s": 3265,
"text": "0"
},
{
"code": null,
"e": 3293,
"s": 3267,
"text": "amarrajsmart1971 week ago"
},
{
"code": null,
"e": 3321,
"s": 3295,
"text": "//*simply use min heap*//"
},
{
"code": null,
"e": 3701,
"s": 3321,
"text": " priority_queue<long long,vector<long long>,greater<long long>> pq; for(long long i=0;i<n;i++) { pq.push(arr[i]); } long long sum=0; while(pq.size()>=2) { long long curr=pq.top(); pq.pop(); curr+=pq.top(); pq.pop(); pq.push(curr); sum+=curr; } return sum; }"
},
{
"code": null,
"e": 3703,
"s": 3701,
"text": "0"
},
{
"code": null,
"e": 3726,
"s": 3703,
"text": "pavsevaibhav1 week ago"
},
{
"code": null,
"e": 3763,
"s": 3726,
"text": "Simple idea is to use PriorityQueue."
},
{
"code": null,
"e": 3890,
"s": 3763,
"text": "First store all the array elements to priorityqueue. then traverse through the priorityqueue until its size is not equal to 1."
},
{
"code": null,
"e": 3994,
"s": 3890,
"text": "while : we pop first to elements from queue and add its sum to totalCost as well as back to queue also."
},
{
"code": null,
"e": 4448,
"s": 3996,
"text": "long minCost(long arr[], int n) \n {\n // your code here\n PriorityQueue<Long> queue = new PriorityQueue<>();\n for(long ele : arr) {\n queue.add(ele);\n }\n long totalCost = 0;\n while(queue.size() > 1) {\n long rope1 = queue.poll();\n long rope2 = queue.poll();\n totalCost += rope1 + rope2;\n queue.add(rope1 + rope2);\n }\n return totalCost;\n }"
},
{
"code": null,
"e": 4462,
"s": 4448,
"text": "Complexity : "
},
{
"code": null,
"e": 4479,
"s": 4462,
"text": "Time : O(n*logn)"
},
{
"code": null,
"e": 4490,
"s": 4479,
"text": "Space:O(n)"
},
{
"code": null,
"e": 4492,
"s": 4490,
"text": "0"
},
{
"code": null,
"e": 4521,
"s": 4492,
"text": "bhaskarmaheshwari81 week ago"
},
{
"code": null,
"e": 5023,
"s": 4521,
"text": "long long cost=0; for(int j=0;j<n-1;j++) { // cout<<arr[0]<<endl; sort(arr,arr+n-j); for(int i=0;i<n-1;i++) { if(i==0) { arr[i]+=arr[i+1]; cost+=arr[i]; // cout<<cost<<endl; } else { arr[i]=arr[i+1]; } } } return cost;"
},
{
"code": null,
"e": 5025,
"s": 5023,
"text": "0"
},
{
"code": null,
"e": 5046,
"s": 5025,
"text": "harshscode1 week ago"
},
{
"code": null,
"e": 5087,
"s": 5046,
"text": "again with the use of priority queue...."
},
{
"code": null,
"e": 5586,
"s": 5089,
"text": " long long int sum=0,temp1=0; priority_queue<long long int,vector<long long int>,greater<long long int>> q; for(long long int i=0;i<n;i++) { q.push(a[i]); } for(int i=0;i<n-1;i++) { temp1=q.top(); q.pop(); temp1+=q.top(); q.pop(); q.push(temp1); sum+=temp1; } return sum; }"
},
{
"code": null,
"e": 5588,
"s": 5586,
"text": "0"
},
{
"code": null,
"e": 5610,
"s": 5588,
"text": "18951a04c32 weeks ago"
},
{
"code": null,
"e": 5629,
"s": 5610,
"text": "Min Heap in Python"
},
{
"code": null,
"e": 6054,
"s": 5629,
"text": "from heapq import heapify, heappush, heappop\nclass Solution:\n def minCost(self,arr,n):\n heap = []\n heapify(heap)\n for i in range(n):\n heappush(heap,arr[i])\n cost = 0\n while(len(heap)>1):\n cost1 = heappop(heap)\n cost2 = heappop(heap)\n curr_cost = cost1+cost2\n cost+=curr_cost\n heappush(heap,curr_cost)\n return cost"
},
{
"code": null,
"e": 6056,
"s": 6054,
"text": "0"
},
{
"code": null,
"e": 6080,
"s": 6056,
"text": "hharshit81182 weeks ago"
},
{
"code": null,
"e": 6113,
"s": 6080,
"text": "min_heap is created in O(nlogn);"
},
{
"code": null,
"e": 6155,
"s": 6113,
"text": "traversing through the heap (n-1) time - "
},
{
"code": null,
"e": 6189,
"s": 6155,
"text": "1- taking two min items at a time"
},
{
"code": null,
"e": 6214,
"s": 6189,
"text": "2- adding to the result."
},
{
"code": null,
"e": 6240,
"s": 6214,
"text": "3- adding to min heap pq."
},
{
"code": null,
"e": 6275,
"s": 6240,
"text": "overall time complexity : O(nlogn)"
},
{
"code": null,
"e": 6734,
"s": 6279,
"text": "class Solution{ public: long long minCost(long long arr[], long long n) { priority_queue<long long, vector<long long>, greater<long long>> pq; for(long long i = 0; i< n; i++){ pq.push(arr[i]); } long long sum = 0; for(long long i = 0; i<n-1; i++){ long long curr = pq.top();pq.pop(); curr += pq.top();pq.pop(); pq.push(curr); sum += curr; } return sum; }};"
},
{
"code": null,
"e": 6738,
"s": 6736,
"text": "0"
},
{
"code": null,
"e": 6765,
"s": 6738,
"text": "jaintanisha20134 weeks ago"
},
{
"code": null,
"e": 6793,
"s": 6765,
"text": "C++ solution using minheap:"
},
{
"code": null,
"e": 7381,
"s": 6793,
"text": "class Solution\n{\n public:\n //Function to return the minimum cost of connecting the ropes.\n long long minCost(long long arr[], long long n) {\n priority_queue<long long,vector<long long>,greater<long long>>pq(arr,arr+n);\n if(n<=1)\n return 0;\n long long ans=0;\n while(pq.size()>=2)\n {\n long long first=pq.top();\n pq.pop();\n long long second=pq.top();\n pq.pop();\n ans=ans+first+second;\n pq.push(first+second);\n }\n return ans;\n // Your code here\n }\n};"
},
{
"code": null,
"e": 7385,
"s": 7383,
"text": "0"
},
{
"code": null,
"e": 7415,
"s": 7385,
"text": "987rashita12holkar1 month ago"
},
{
"code": null,
"e": 7468,
"s": 7415,
"text": "My code in C++ using Min_HEAP c++ stl priority queue"
},
{
"code": null,
"e": 7924,
"s": 7468,
"text": "long long minCost(long long arr[], long long n) { // Your code here priority_queue<long long,vector<long long>,greater<long long>>pq(arr,arr+n); long long ans=0; if(n==1||n==0) return 0; while(!pq.empty()) { long long a=pq.top(); pq.pop(); long long b=pq.top(); pq.pop(); ans+=(a+b); if(!pq.empty()) pq.push(a+b); } return ans; }"
},
{
"code": null,
"e": 8070,
"s": 7924,
"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": 8106,
"s": 8070,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8116,
"s": 8106,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8126,
"s": 8116,
"text": "\nContest\n"
},
{
"code": null,
"e": 8189,
"s": 8126,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8337,
"s": 8189,
"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": 8545,
"s": 8337,
"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": 8651,
"s": 8545,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to determine Android device screen size category (small, normal, large, xlarge) programatically?
|
This example demonstrates how do I determine the Android device screen size category (small, normal, large, xlarge) programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnGetScreenSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="GetScreenSize"
android:text="Get ScreenSize" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnGetScreenSize"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:onClick="GetScreenDensity"
android:text="Get Screen Density" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Android device screen size category (small, normal, large, xlarge)"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold|italic" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void GetScreenSize(View view) {
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
Toast.makeText(this, "Large screen", Toast.LENGTH_LONG).show();
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Toast.makeText(this, "Normal sized screen", Toast.LENGTH_LONG).show();
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
Toast.makeText(this, "Small sized screen", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Screen size is neither large, normal or small", Toast.LENGTH_LONG).show();
}
}
public void GetScreenDensity(View view) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int density = metrics.densityDpi;
if (density == DisplayMetrics.DENSITY_HIGH) {
Toast.makeText(this, "DENSITY_HIGH... Density is " + (density), Toast.LENGTH_LONG).show();
}
else if (density == DisplayMetrics.DENSITY_MEDIUM) {
Toast.makeText(this, "DENSITY_MEDIUM... Density is " + (density), Toast.LENGTH_LONG).show();
}
else if (density == DisplayMetrics.DENSITY_LOW) {
Toast.makeText(this, "DENSITY_LOW... Density is " + (density), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "Density is neither HIGH, MEDIUM OR LOW. Density is " + (density), Toast.LENGTH_LONG).show();
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1196,
"s": 1062,
"text": "This example demonstrates how do I determine the Android device screen size category (small, normal, large, xlarge) programmatically."
},
{
"code": null,
"e": 1325,
"s": 1196,
"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": 1390,
"s": 1325,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2611,
"s": 1390,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnGetScreenSize\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:onClick=\"GetScreenSize\"\n android:text=\"Get ScreenSize\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btnGetScreenSize\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"10dp\"\n android:onClick=\"GetScreenDensity\"\n android:text=\"Get Screen Density\" />\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"40dp\"\n android:text=\"Android device screen size category (small, normal, large, xlarge)\"\n android:textAlignment=\"center\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold|italic\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2668,
"s": 2611,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4801,
"s": 2668,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.content.res.Configuration;\nimport android.os.Bundle;\nimport android.util.DisplayMetrics;\nimport android.view.View;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void GetScreenSize(View view) {\n if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {\n Toast.makeText(this, \"Large screen\", Toast.LENGTH_LONG).show();\n }\n else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {\n Toast.makeText(this, \"Normal sized screen\", Toast.LENGTH_LONG).show();\n }\n else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {\n Toast.makeText(this, \"Small sized screen\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(this, \"Screen size is neither large, normal or small\", Toast.LENGTH_LONG).show();\n }\n }\n public void GetScreenDensity(View view) {\n DisplayMetrics metrics = new DisplayMetrics();\n getWindowManager().getDefaultDisplay().getMetrics(metrics);\n int density = metrics.densityDpi;\n if (density == DisplayMetrics.DENSITY_HIGH) {\n Toast.makeText(this, \"DENSITY_HIGH... Density is \" + (density), Toast.LENGTH_LONG).show();\n }\n else if (density == DisplayMetrics.DENSITY_MEDIUM) {\n Toast.makeText(this, \"DENSITY_MEDIUM... Density is \" + (density), Toast.LENGTH_LONG).show();\n }\n else if (density == DisplayMetrics.DENSITY_LOW) {\n Toast.makeText(this, \"DENSITY_LOW... Density is \" + (density), Toast.LENGTH_LONG).show();\n }\n else {\n Toast.makeText(this, \"Density is neither HIGH, MEDIUM OR LOW. Density is \" + (density), Toast.LENGTH_LONG).show();\n }\n }\n}"
},
{
"code": null,
"e": 4856,
"s": 4801,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5526,
"s": 4856,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5877,
"s": 5526,
"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 the 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": 5918,
"s": 5877,
"text": "Click here to download the project code."
}
] |
Apache POI - Spreadsheets
|
This chapter explains how to create a spreadsheet and manipulate it using Java. Spreadsheet is a page in an Excel file; it contains rows and columns with specific names.
After completing this chapter, you will be able to create a spreadsheet and perform read operations on it.
First of all, let us create a spreadsheet using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a workbook first and then we can go on and create a sheet.
The following code snippet is used to create a spreadsheet.
//Create Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank spreadsheet
XSSFSheet spreadsheet = workbook.createSheet("Sheet Name");
Spreadsheets have a grid layout. The rows and columns are identified with specific names. The columns are identified with alphabets and rows with numbers.
The following code snippet is used to create a row.
XSSFRow row = spreadsheet.createRow((short)1);
Let us consider an example of employee data. Here the employee data is given in a tabular form.
The following code is used to write the above data into a spreadsheet.
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Writesheet {
public static void main(String[] args) throws Exception {
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet(" Employee Info ");
//Create row object
XSSFRow row;
//This data needs to be written (Object[])
Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();
empinfo.put( "1", new Object[] { "EMP ID", "EMP NAME", "DESIGNATION" });
empinfo.put( "2", new Object[] { "tp01", "Gopal", "Technical Manager" });
empinfo.put( "3", new Object[] { "tp02", "Manisha", "Proof Reader" });
empinfo.put( "4", new Object[] { "tp03", "Masthan", "Technical Writer" });
empinfo.put( "5", new Object[] { "tp04", "Satish", "Technical Writer" });
empinfo.put( "6", new Object[] { "tp05", "Krishna", "Technical Writer" });
//Iterate over data and write to sheet
Set < String > keyid = empinfo.keySet();
int rowid = 0;
for (String key : keyid) {
row = spreadsheet.createRow(rowid++);
Object [] objectArr = empinfo.get(key);
int cellid = 0;
for (Object obj : objectArr) {
Cell cell = row.createCell(cellid++);
cell.setCellValue((String)obj);
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("Writesheet.xlsx"));
workbook.write(out);
out.close();
System.out.println("Writesheet.xlsx written successfully");
}
}
Save the above Java code as Writesheet.java, and then compile and run it from the command prompt as follows −
$javac Writesheet.java
$java Writesheet
It will compile and execute to generate an Excel file named Writesheet.xlsx in your current directory and you will get the following output in the command prompt.
Writesheet.xlsx written successfully
The Writesheet.xlsx file looks as follows −
Let us consider the above excel file named Writesheet.xslx as input. Observe the following code; it is used for reading the data from a spreadsheet.
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Readsheet {
static XSSFRow row;
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream(new File("WriteSheet.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator < Row > rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
row = (XSSFRow) rowIterator.next();
Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case NUMERIC:
System.out.print(cell.getNumericCellValue() + " \t\t ");
break;
case STRING:
System.out.print(
cell.getStringCellValue() + " \t\t ");
break;
}
}
System.out.println();
}
fis.close();
}
}
Let us keep the above code in Readsheet.java file, and then compile and run it from the command prompt as follows −
$javac Readsheet.java
$java Readsheet
If your system environment is configured with the POI library, it will compile and execute to generate the following output in the command prompt.
EMP ID EMP NAME DESIGNATION
tp01 Gopal Technical Manager
tp02 Manisha Proof Reader
tp03 Masthan Technical Writer
tp04 Satish Technical Writer
tp05 Krishna Technical Writer
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2074,
"s": 1904,
"text": "This chapter explains how to create a spreadsheet and manipulate it using Java. Spreadsheet is a page in an Excel file; it contains rows and columns with specific names."
},
{
"code": null,
"e": 2181,
"s": 2074,
"text": "After completing this chapter, you will be able to create a spreadsheet and perform read operations on it."
},
{
"code": null,
"e": 2388,
"s": 2181,
"text": "First of all, let us create a spreadsheet using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a workbook first and then we can go on and create a sheet."
},
{
"code": null,
"e": 2448,
"s": 2388,
"text": "The following code snippet is used to create a spreadsheet."
},
{
"code": null,
"e": 2606,
"s": 2448,
"text": "//Create Blank workbook\nXSSFWorkbook workbook = new XSSFWorkbook();\n\n//Create a blank spreadsheet\nXSSFSheet spreadsheet = workbook.createSheet(\"Sheet Name\");"
},
{
"code": null,
"e": 2761,
"s": 2606,
"text": "Spreadsheets have a grid layout. The rows and columns are identified with specific names. The columns are identified with alphabets and rows with numbers."
},
{
"code": null,
"e": 2813,
"s": 2761,
"text": "The following code snippet is used to create a row."
},
{
"code": null,
"e": 2861,
"s": 2813,
"text": "XSSFRow row = spreadsheet.createRow((short)1);\n"
},
{
"code": null,
"e": 2957,
"s": 2861,
"text": "Let us consider an example of employee data. Here the employee data is given in a tabular form."
},
{
"code": null,
"e": 3028,
"s": 2957,
"text": "The following code is used to write the above data into a spreadsheet."
},
{
"code": null,
"e": 4929,
"s": 3028,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeMap;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.xssf.usermodel.XSSFRow;\nimport org.apache.poi.xssf.usermodel.XSSFSheet;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\n\npublic class Writesheet {\n public static void main(String[] args) throws Exception {\n //Create blank workbook\n XSSFWorkbook workbook = new XSSFWorkbook(); \n\n //Create a blank sheet\n XSSFSheet spreadsheet = workbook.createSheet(\" Employee Info \");\n\n //Create row object\n XSSFRow row;\n\n //This data needs to be written (Object[])\n Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();\n empinfo.put( \"1\", new Object[] { \"EMP ID\", \"EMP NAME\", \"DESIGNATION\" });\n empinfo.put( \"2\", new Object[] { \"tp01\", \"Gopal\", \"Technical Manager\" });\n empinfo.put( \"3\", new Object[] { \"tp02\", \"Manisha\", \"Proof Reader\" });\n empinfo.put( \"4\", new Object[] { \"tp03\", \"Masthan\", \"Technical Writer\" });\n empinfo.put( \"5\", new Object[] { \"tp04\", \"Satish\", \"Technical Writer\" });\n empinfo.put( \"6\", new Object[] { \"tp05\", \"Krishna\", \"Technical Writer\" });\n \n //Iterate over data and write to sheet\n Set < String > keyid = empinfo.keySet();\n int rowid = 0;\n\n for (String key : keyid) {\n row = spreadsheet.createRow(rowid++);\n Object [] objectArr = empinfo.get(key);\n int cellid = 0;\n\n for (Object obj : objectArr) {\n Cell cell = row.createCell(cellid++);\n cell.setCellValue((String)obj);\n }\n }\n //Write the workbook in file system\n FileOutputStream out = new FileOutputStream(new File(\"Writesheet.xlsx\"));\n workbook.write(out);\n out.close();\n System.out.println(\"Writesheet.xlsx written successfully\");\n }\n}"
},
{
"code": null,
"e": 5039,
"s": 4929,
"text": "Save the above Java code as Writesheet.java, and then compile and run it from the command prompt as follows −"
},
{
"code": null,
"e": 5080,
"s": 5039,
"text": "$javac Writesheet.java\n$java Writesheet\n"
},
{
"code": null,
"e": 5243,
"s": 5080,
"text": "It will compile and execute to generate an Excel file named Writesheet.xlsx in your current directory and you will get the following output in the command prompt."
},
{
"code": null,
"e": 5281,
"s": 5243,
"text": "Writesheet.xlsx written successfully\n"
},
{
"code": null,
"e": 5325,
"s": 5281,
"text": "The Writesheet.xlsx file looks as follows −"
},
{
"code": null,
"e": 5474,
"s": 5325,
"text": "Let us consider the above excel file named Writesheet.xslx as input. Observe the following code; it is used for reading the data from a spreadsheet."
},
{
"code": null,
"e": 6824,
"s": 5474,
"text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.util.Iterator;\nimport org.apache.poi.ss.usermodel.Cell;\nimport org.apache.poi.ss.usermodel.Row;\nimport org.apache.poi.xssf.usermodel.XSSFRow;\nimport org.apache.poi.xssf.usermodel.XSSFSheet;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\n\npublic class Readsheet {\n static XSSFRow row;\n public static void main(String[] args) throws Exception {\n FileInputStream fis = new FileInputStream(new File(\"WriteSheet.xlsx\"));\n XSSFWorkbook workbook = new XSSFWorkbook(fis);\n XSSFSheet spreadsheet = workbook.getSheetAt(0);\n Iterator < Row > rowIterator = spreadsheet.iterator();\n \n while (rowIterator.hasNext()) {\n row = (XSSFRow) rowIterator.next();\n Iterator < Cell > cellIterator = row.cellIterator();\n \n while ( cellIterator.hasNext()) {\n Cell cell = cellIterator.next();\n \n switch (cell.getCellType()) {\n case NUMERIC:\n System.out.print(cell.getNumericCellValue() + \" \\t\\t \");\n break;\n \n case STRING:\n System.out.print(\n cell.getStringCellValue() + \" \\t\\t \");\n break;\n }\n }\n System.out.println();\n }\n fis.close();\n }\n}"
},
{
"code": null,
"e": 6940,
"s": 6824,
"text": "Let us keep the above code in Readsheet.java file, and then compile and run it from the command prompt as follows −"
},
{
"code": null,
"e": 6979,
"s": 6940,
"text": "$javac Readsheet.java\n$java Readsheet\n"
},
{
"code": null,
"e": 7126,
"s": 6979,
"text": "If your system environment is configured with the POI library, it will compile and execute to generate the following output in the command prompt."
},
{
"code": null,
"e": 7360,
"s": 7126,
"text": "EMP ID EMP NAME DESIGNATION \n tp01 Gopal Technical Manager \n tp02 Manisha Proof Reader \n tp03 Masthan Technical Writer \n tp04 Satish Technical Writer \n tp05 Krishna Technical Writer\n"
},
{
"code": null,
"e": 7395,
"s": 7360,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7414,
"s": 7395,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7449,
"s": 7414,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7470,
"s": 7449,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 7503,
"s": 7470,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7516,
"s": 7503,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 7551,
"s": 7516,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7569,
"s": 7551,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7602,
"s": 7569,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7620,
"s": 7602,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7653,
"s": 7620,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7671,
"s": 7653,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7678,
"s": 7671,
"text": " Print"
},
{
"code": null,
"e": 7689,
"s": 7678,
"text": " Add Notes"
}
] |
Integer.MAX_VALUE and Integer.MIN_VALUE in Java with Examples - GeeksforGeeks
|
22 Jan, 2020
Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, Java has constants to represent these numbers, so that these can be directly assigned to the variable without actually typing the whole number.
Integer.MAX_VALUEInteger.MAX_VALUE is a constant in the Integer class of java.lang package that specifies that stores the maximum possible value for any integer variable in Java. The actual value of this is2^31-1 = 2147483647
Example 1:// Java program to show// the value of Integer.MAX_VALUE class GFG { // Driver code public static void main(String[] arg) { // Print the value of Integer.MAX_VALUE System.out.println("Integer.MAX_VALUE = " + Integer.MAX_VALUE); }}Output:Integer.MAX_VALUE = 2147483647
Any integer variable cannot store any value beyond this limit. Upon doing so, the memory will overflow and the value will get negative.Example 2: Trying to initialize a variable value Integer.MAX_VALUE + 1// Java program to show what happens when// a value greater than Integer.MAX_VALUE// is stored in an int variable class GFG { // Driver code public static void main(String[] arg) { try { System.out.println( "Trying to initialize" + " a N with value" + " Integer.MAX_VALUE + 1"); // Try to store value Integer.MAX_VALUE + 1 int N = Integer.MAX_VALUE + 1; // Print the value of N System.out.println("N = " + N); } catch (Exception e) { System.out.println(e); } }}Output:Trying to initialize a N with value Integer.MAX_VALUE + 1
N = -2147483648
2^31-1 = 2147483647
Example 1:
// Java program to show// the value of Integer.MAX_VALUE class GFG { // Driver code public static void main(String[] arg) { // Print the value of Integer.MAX_VALUE System.out.println("Integer.MAX_VALUE = " + Integer.MAX_VALUE); }}
Integer.MAX_VALUE = 2147483647
Any integer variable cannot store any value beyond this limit. Upon doing so, the memory will overflow and the value will get negative.
Example 2: Trying to initialize a variable value Integer.MAX_VALUE + 1
// Java program to show what happens when// a value greater than Integer.MAX_VALUE// is stored in an int variable class GFG { // Driver code public static void main(String[] arg) { try { System.out.println( "Trying to initialize" + " a N with value" + " Integer.MAX_VALUE + 1"); // Try to store value Integer.MAX_VALUE + 1 int N = Integer.MAX_VALUE + 1; // Print the value of N System.out.println("N = " + N); } catch (Exception e) { System.out.println(e); } }}
Trying to initialize a N with value Integer.MAX_VALUE + 1
N = -2147483648
Integer.MIN_VALUEInteger.MIN_VALUE is a constant in the Integer class of java.lang package that specifies that stores the minimum possible value for any integer variable in Java. The actual value of this is-2^31 = -2147483648
Example 3:// Java program to show// the value of Integer.MIN_VALUE class GFG { // Driver code public static void main(String[] arg) { // Print the value of Integer.MIN_VALUE System.out.println("Integer.MIN_VALUE = " + Integer.MIN_VALUE); }}Output:Integer.MIN_VALUE = -2147483648
Any integer variable cannot store any value below this limit. Upon doing so, the memory will overflow and the value will get positive.Example 2: Trying to initialize a variable value Integer.MIN_VALUE – 1// Java program to show what happens when// a value less than Integer.MIN_VALUE// is stored in an int variable class GFG { // Driver code public static void main(String[] arg) { try { System.out.println( "Trying to initialize" + " a N with value" + " Integer.MIN_VALUE - 1"); // Try to store value Integer.MIN_VALUE - 1 int N = Integer.MIN_VALUE - 1; // Print the value of N System.out.println("N = " + N); } catch (Exception e) { System.out.println(e); } }}Output:Trying to initialize a N with value Integer.MIN_VALUE - 1
N = 2147483647
-2^31 = -2147483648
Example 3:
// Java program to show// the value of Integer.MIN_VALUE class GFG { // Driver code public static void main(String[] arg) { // Print the value of Integer.MIN_VALUE System.out.println("Integer.MIN_VALUE = " + Integer.MIN_VALUE); }}
Integer.MIN_VALUE = -2147483648
Any integer variable cannot store any value below this limit. Upon doing so, the memory will overflow and the value will get positive.
Example 2: Trying to initialize a variable value Integer.MIN_VALUE – 1
// Java program to show what happens when// a value less than Integer.MIN_VALUE// is stored in an int variable class GFG { // Driver code public static void main(String[] arg) { try { System.out.println( "Trying to initialize" + " a N with value" + " Integer.MIN_VALUE - 1"); // Try to store value Integer.MIN_VALUE - 1 int N = Integer.MIN_VALUE - 1; // Print the value of N System.out.println("N = " + N); } catch (Exception e) { System.out.println(e); } }}
Trying to initialize a N with value Integer.MIN_VALUE - 1
N = 2147483647
Java-Integer
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
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 25811,
"s": 25783,
"text": "\n22 Jan, 2020"
},
{
"code": null,
"e": 26188,
"s": 25811,
"text": "Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, Java has constants to represent these numbers, so that these can be directly assigned to the variable without actually typing the whole number."
},
{
"code": null,
"e": 27659,
"s": 26188,
"text": "Integer.MAX_VALUEInteger.MAX_VALUE is a constant in the Integer class of java.lang package that specifies that stores the maximum possible value for any integer variable in Java. The actual value of this is2^31-1 = 2147483647\nExample 1:// Java program to show// the value of Integer.MAX_VALUE class GFG { // Driver code public static void main(String[] arg) { // Print the value of Integer.MAX_VALUE System.out.println(\"Integer.MAX_VALUE = \" + Integer.MAX_VALUE); }}Output:Integer.MAX_VALUE = 2147483647\nAny integer variable cannot store any value beyond this limit. Upon doing so, the memory will overflow and the value will get negative.Example 2: Trying to initialize a variable value Integer.MAX_VALUE + 1// Java program to show what happens when// a value greater than Integer.MAX_VALUE// is stored in an int variable class GFG { // Driver code public static void main(String[] arg) { try { System.out.println( \"Trying to initialize\" + \" a N with value\" + \" Integer.MAX_VALUE + 1\"); // Try to store value Integer.MAX_VALUE + 1 int N = Integer.MAX_VALUE + 1; // Print the value of N System.out.println(\"N = \" + N); } catch (Exception e) { System.out.println(e); } }}Output:Trying to initialize a N with value Integer.MAX_VALUE + 1\nN = -2147483648\n"
},
{
"code": null,
"e": 27680,
"s": 27659,
"text": "2^31-1 = 2147483647\n"
},
{
"code": null,
"e": 27691,
"s": 27680,
"text": "Example 1:"
},
{
"code": "// Java program to show// the value of Integer.MAX_VALUE class GFG { // Driver code public static void main(String[] arg) { // Print the value of Integer.MAX_VALUE System.out.println(\"Integer.MAX_VALUE = \" + Integer.MAX_VALUE); }}",
"e": 27979,
"s": 27691,
"text": null
},
{
"code": null,
"e": 28011,
"s": 27979,
"text": "Integer.MAX_VALUE = 2147483647\n"
},
{
"code": null,
"e": 28147,
"s": 28011,
"text": "Any integer variable cannot store any value beyond this limit. Upon doing so, the memory will overflow and the value will get negative."
},
{
"code": null,
"e": 28218,
"s": 28147,
"text": "Example 2: Trying to initialize a variable value Integer.MAX_VALUE + 1"
},
{
"code": "// Java program to show what happens when// a value greater than Integer.MAX_VALUE// is stored in an int variable class GFG { // Driver code public static void main(String[] arg) { try { System.out.println( \"Trying to initialize\" + \" a N with value\" + \" Integer.MAX_VALUE + 1\"); // Try to store value Integer.MAX_VALUE + 1 int N = Integer.MAX_VALUE + 1; // Print the value of N System.out.println(\"N = \" + N); } catch (Exception e) { System.out.println(e); } }}",
"e": 28842,
"s": 28218,
"text": null
},
{
"code": null,
"e": 28917,
"s": 28842,
"text": "Trying to initialize a N with value Integer.MAX_VALUE + 1\nN = -2147483648\n"
},
{
"code": null,
"e": 30384,
"s": 28917,
"text": "Integer.MIN_VALUEInteger.MIN_VALUE is a constant in the Integer class of java.lang package that specifies that stores the minimum possible value for any integer variable in Java. The actual value of this is-2^31 = -2147483648\nExample 3:// Java program to show// the value of Integer.MIN_VALUE class GFG { // Driver code public static void main(String[] arg) { // Print the value of Integer.MIN_VALUE System.out.println(\"Integer.MIN_VALUE = \" + Integer.MIN_VALUE); }}Output:Integer.MIN_VALUE = -2147483648\nAny integer variable cannot store any value below this limit. Upon doing so, the memory will overflow and the value will get positive.Example 2: Trying to initialize a variable value Integer.MIN_VALUE – 1// Java program to show what happens when// a value less than Integer.MIN_VALUE// is stored in an int variable class GFG { // Driver code public static void main(String[] arg) { try { System.out.println( \"Trying to initialize\" + \" a N with value\" + \" Integer.MIN_VALUE - 1\"); // Try to store value Integer.MIN_VALUE - 1 int N = Integer.MIN_VALUE - 1; // Print the value of N System.out.println(\"N = \" + N); } catch (Exception e) { System.out.println(e); } }}Output:Trying to initialize a N with value Integer.MIN_VALUE - 1\nN = 2147483647\n"
},
{
"code": null,
"e": 30405,
"s": 30384,
"text": "-2^31 = -2147483648\n"
},
{
"code": null,
"e": 30416,
"s": 30405,
"text": "Example 3:"
},
{
"code": "// Java program to show// the value of Integer.MIN_VALUE class GFG { // Driver code public static void main(String[] arg) { // Print the value of Integer.MIN_VALUE System.out.println(\"Integer.MIN_VALUE = \" + Integer.MIN_VALUE); }}",
"e": 30704,
"s": 30416,
"text": null
},
{
"code": null,
"e": 30737,
"s": 30704,
"text": "Integer.MIN_VALUE = -2147483648\n"
},
{
"code": null,
"e": 30872,
"s": 30737,
"text": "Any integer variable cannot store any value below this limit. Upon doing so, the memory will overflow and the value will get positive."
},
{
"code": null,
"e": 30943,
"s": 30872,
"text": "Example 2: Trying to initialize a variable value Integer.MIN_VALUE – 1"
},
{
"code": "// Java program to show what happens when// a value less than Integer.MIN_VALUE// is stored in an int variable class GFG { // Driver code public static void main(String[] arg) { try { System.out.println( \"Trying to initialize\" + \" a N with value\" + \" Integer.MIN_VALUE - 1\"); // Try to store value Integer.MIN_VALUE - 1 int N = Integer.MIN_VALUE - 1; // Print the value of N System.out.println(\"N = \" + N); } catch (Exception e) { System.out.println(e); } }}",
"e": 31564,
"s": 30943,
"text": null
},
{
"code": null,
"e": 31638,
"s": 31564,
"text": "Trying to initialize a N with value Integer.MIN_VALUE - 1\nN = 2147483647\n"
},
{
"code": null,
"e": 31651,
"s": 31638,
"text": "Java-Integer"
},
{
"code": null,
"e": 31656,
"s": 31651,
"text": "Java"
},
{
"code": null,
"e": 31661,
"s": 31656,
"text": "Java"
},
{
"code": null,
"e": 31759,
"s": 31661,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31810,
"s": 31759,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31840,
"s": 31810,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31855,
"s": 31840,
"text": "Stream In Java"
},
{
"code": null,
"e": 31874,
"s": 31855,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31905,
"s": 31874,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 31937,
"s": 31905,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31955,
"s": 31937,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31975,
"s": 31955,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31999,
"s": 31975,
"text": "Singleton Class in Java"
}
] |
How to calculate the date three months prior using JavaScript ? - GeeksforGeeks
|
19 Jun, 2019
Given a Date and the task is to get the date of three month prior using javascript.
Approach:
First select the date object.
Then use the getMonth() method to get the months.
Then subtract three months from the getMonth() method and return the date.
Example 1: This example uses getMonth() and setMonth() method to get and set the month date.
<!DOCTYPE HTML> <html> <head> <title> How to calculate the date three months prior to today </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var d = new Date(); up.innerHTML = "Today's Date= "+ d.toLocaleDateString(); function GFG_Fun() { d.setMonth(d.getMonth() - 3); down.innerHTML = "Before 3 Months, Date is " + d.toLocaleDateString(); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example uses getMonth() and setMonth() method to get and set the month date as provided.
<!DOCTYPE HTML> <html> <head> <title> How to calculate the date three months prior to today </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var d = new Date("2010/12/02"); up.innerHTML = "Date= "+ d.toLocaleDateString(); function GFG_Fun() { d.setMonth(d.getMonth() - 3); down.innerHTML = "Before 3 Months, Date is " + d.toLocaleDateString(); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-date
JavaScript
Web Technologies
Web technologies Questions
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 get character array from string in JavaScript?
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": 26569,
"s": 26541,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 26653,
"s": 26569,
"text": "Given a Date and the task is to get the date of three month prior using javascript."
},
{
"code": null,
"e": 26663,
"s": 26653,
"text": "Approach:"
},
{
"code": null,
"e": 26693,
"s": 26663,
"text": "First select the date object."
},
{
"code": null,
"e": 26743,
"s": 26693,
"text": "Then use the getMonth() method to get the months."
},
{
"code": null,
"e": 26818,
"s": 26743,
"text": "Then subtract three months from the getMonth() method and return the date."
},
{
"code": null,
"e": 26911,
"s": 26818,
"text": "Example 1: This example uses getMonth() and setMonth() method to get and set the month date."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to calculate the date three months prior to today </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var d = new Date(); up.innerHTML = \"Today's Date= \"+ d.toLocaleDateString(); function GFG_Fun() { d.setMonth(d.getMonth() - 3); down.innerHTML = \"Before 3 Months, Date is \" + d.toLocaleDateString(); } </script> </body> </html> ",
"e": 28032,
"s": 26911,
"text": null
},
{
"code": null,
"e": 28040,
"s": 28032,
"text": "Output:"
},
{
"code": null,
"e": 28071,
"s": 28040,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28101,
"s": 28071,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28206,
"s": 28101,
"text": "Example 2: This example uses getMonth() and setMonth() method to get and set the month date as provided."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to calculate the date three months prior to today </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var d = new Date(\"2010/12/02\"); up.innerHTML = \"Date= \"+ d.toLocaleDateString(); function GFG_Fun() { d.setMonth(d.getMonth() - 3); down.innerHTML = \"Before 3 Months, Date is \" + d.toLocaleDateString(); } </script> </body> </html> ",
"e": 29331,
"s": 28206,
"text": null
},
{
"code": null,
"e": 29339,
"s": 29331,
"text": "Output:"
},
{
"code": null,
"e": 29370,
"s": 29339,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29400,
"s": 29370,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29416,
"s": 29400,
"text": "javascript-date"
},
{
"code": null,
"e": 29427,
"s": 29416,
"text": "JavaScript"
},
{
"code": null,
"e": 29444,
"s": 29427,
"text": "Web Technologies"
},
{
"code": null,
"e": 29471,
"s": 29444,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29569,
"s": 29471,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29609,
"s": 29569,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29670,
"s": 29609,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29711,
"s": 29670,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29733,
"s": 29711,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 29787,
"s": 29733,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29827,
"s": 29787,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29860,
"s": 29827,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29903,
"s": 29860,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29953,
"s": 29903,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Assign other value to a variable from two possible values - GeeksforGeeks
|
05 May, 2021
Suppose a variable x can have only two possible values a and b, and you wish to assign to x the value other than its current one. Do it efficiently without using any conditional operator.Note: We are not allowed to check current value of x. Examples:
Input : a = 10, b = 15, x = a Output : x = 15 Explanation x = 10, currently x has value of a (which is 10), we need to change it to 15.Input : a = 9, b = 11, x = b Output : x = 9
We could solve this problem using if condition, but we are not allowed to do that.
if (x == a)
x = b;
else x = a;
We could have used Ternary operator, it also checks the current value of x and based on that it assigns new value. So we cannot use this approach as well
x = x == a ? b : a;
But, we are not allowed to check value of x, so none of the above solutions work.Solution 1: Using arithmetic operators only we can perform this operation
x = a + b - x
This way the content of x will alternate between a and b every time it gets executed
C++
Java
Python3
C#
PHP
Javascript
// CPP program to change value of x// according to its current value.#include <bits/stdc++.h>using namespace std; // Function to alternate the valuesvoid alternate(int& a, int& b, int& x){ x = a + b - x;} // Main functionint main(){ int a = -10; int b = 15; int x = a; cout << "x is : " << x; alternate(a, b, x); cout << "\nAfter change "; cout << "\nx is : " << x;}
// Java program to change value of x// according to its current value.import java.util.*; class solution{ // Function to alternate the valuesstatic void alternate(int a, int b, int x){ x = a + b - x; System.out.println("After change"+"\n"+" x is : "+x);} // Main functionpublic static void main(String args[]){ int a = -10; int b = 15; int x = a; System.out.println("x is : "+x); alternate(a, b, x);}}
# Python3 program to change value# of x according to its current value. # Function to alternate the valuesdef alternate(a,b,x): x = a+b-x print("After change x is:",x) # Driver codeif __name__=='__main__': a = -10 b = 15 x = a print("x is:",x) alternate(a,b,x) # This code is contributed by# Shrikant13
// C# program to change value of x// according to its current value. using System;class gfg{ // Function to alternate the values public void alternate(ref int a, ref int b, ref int x) //'ref' indicates the references { x = a + b - x; }} // Main functionclass geek{ public static int Main() { gfg g = new gfg(); int a = -10; int b = 15; int x = a; Console.WriteLine("x is : {0}" , x); g.alternate(ref a, ref b, ref x); Console.WriteLine ("After change "); Console.WriteLine("x is : {0}", x); return 0; }}//This code is contributed by Soumik
<?php// PHP program to change value of x// according to its current value. // Function to alternate the valuesfunction alternate (&$a, &$b, &$x){ $x = $a + $b - $x;} // Driver Code$a = -10;$b = 15;$x = $a;echo "x is : ", $x; alternate($a, $b, $x); echo "\nAfter change ";echo "\nx is : ", $x; // This code is contributed by ajit.?>
<script>// javascript program to change value of x// according to its current value. // Function to alternate the values function alternate(a , b , x) { x = a + b - x; document.write("After change" + "<br/>" + " x is : " + x); } // Main function var a = -10; var b = 15; var x = a; document.write("x is : " + x+"<br/>"); alternate(a, b, x); // This code is contributed by todaysgaurav</script>
x is : -10
After change
x is : 15
Time Complexity: The time complexity of this approach is O(1) Space Complexity: The space complexity of this approach is O(1)Solution 2: A better and efficient approach is using the bitwise XOR operation.x = a^b^x
C++
Java
Python3
C#
PHP
Javascript
// CPP program to change value of x// according to its current value.#include <bits/stdc++.h>using namespace std; // Function to alternate the valuesvoid alternate(int& a, int& b, int& x){ x = a ^ b ^ x;} // Main functionint main(){ int a = -10; int b = 15; int x = a; cout << "x is : " << x; alternate(a, b, x); cout << "\nAfter exchange "; cout << "\nx is : " << x; return 0;}
// Java program to change value of x// according to its current value. class GFG {// Function to alternate the values static int alternate(int a, int b, int x) { return x = a ^ b ^ x; } // Main function public static void main(String[] args) { int a = -10; int b = 15; int x = a; System.out.print("x is : " + x); x = alternate(a, b, x); System.out.print("\nAfter exchange "); System.out.print("\nx is : " + x); }} // This code is contributed by 29AjayKumar
# Python3 program to change value of x# according to its current value. # Function to alternate the valuesdef alternate(a, b, x): x = a ^ b ^ x print("After exchange") print("x is", x) # Driver codea = -10b = 15x = aprint("x is", x)alternate(a, b, x) # This code is contributed# by Shrikant13
// C# program to change value of x// according to its current value.using System;public class GFG {// Function to alternate the values static int alternate(int a, int b, int x) { return x = a ^ b ^ x; } // Main function public static void Main() { int a = -10; int b = 15; int x = a; Console.Write("x is : " + x); x = alternate(a, b, x); Console.Write("\nAfter exchange "); Console.Write("\nx is : " + x); }}/*This code is contributed by Rajput-Ji*/
<?php// PHP program to change value of x// according to its current value. // Function to alternate the valuesfunction alternate(&$a, &$b, &$x){ $x = $a ^ $b ^ $x;} // Driver Code$a = -10;$b = 15;$x = $a;echo "x is : ", $x; alternate($a, $b, $x); echo "\nAfter exchange ";echo "\nx is : ", $x; // This code is contributed// by akt_mit?>
<script> // Javascript program to change value of x// according to its current value. // Function to alternate the values function alternate(a , b , x) { return x = a ^ b ^ x; } // Main function var a = -10; var b = 15; var x = a; document.write("x is : " + x); x = alternate(a, b, x); document.write("<br/>After exchange "); document.write("<br/>x is : " + x); // This code contributed by Rajput-Ji </script>
x is : -10
After exchange
x is : 15
Time Complexity: The time complexity of this approach is O(1) Space Complexity: The space complexity of this approach is O(1)
shrikanth13
SoumikMondal
SURENDRA_GANGWAR
29AjayKumar
Rajput-Ji
jit_t
todaysgaurav
Bitwise-OR
programming-puzzle
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
Find the size of Largest Subset with positive Bitwise AND
Check whether bitwise AND of a number with any subset of an array is zero or not
Write an Efficient Method to Check if a Number is Multiple of 3
Highest power of 2 less than or equal to given number
Swap two nibbles in a byte
Swap bits in a given number
Check for Integer Overflow
Reverse actual bits of the given number
Find one extra character in a string
|
[
{
"code": null,
"e": 26277,
"s": 26249,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 26530,
"s": 26277,
"text": "Suppose a variable x can have only two possible values a and b, and you wish to assign to x the value other than its current one. Do it efficiently without using any conditional operator.Note: We are not allowed to check current value of x. Examples: "
},
{
"code": null,
"e": 26709,
"s": 26530,
"text": "Input : a = 10, b = 15, x = a Output : x = 15 Explanation x = 10, currently x has value of a (which is 10), we need to change it to 15.Input : a = 9, b = 11, x = b Output : x = 9"
},
{
"code": null,
"e": 26792,
"s": 26709,
"text": "We could solve this problem using if condition, but we are not allowed to do that."
},
{
"code": null,
"e": 26827,
"s": 26792,
"text": "if (x == a) \n x = b;\nelse x = a;"
},
{
"code": null,
"e": 26982,
"s": 26827,
"text": "We could have used Ternary operator, it also checks the current value of x and based on that it assigns new value. So we cannot use this approach as well "
},
{
"code": null,
"e": 27002,
"s": 26982,
"text": "x = x == a ? b : a;"
},
{
"code": null,
"e": 27159,
"s": 27002,
"text": "But, we are not allowed to check value of x, so none of the above solutions work.Solution 1: Using arithmetic operators only we can perform this operation "
},
{
"code": null,
"e": 27173,
"s": 27159,
"text": "x = a + b - x"
},
{
"code": null,
"e": 27259,
"s": 27173,
"text": "This way the content of x will alternate between a and b every time it gets executed "
},
{
"code": null,
"e": 27263,
"s": 27259,
"text": "C++"
},
{
"code": null,
"e": 27268,
"s": 27263,
"text": "Java"
},
{
"code": null,
"e": 27276,
"s": 27268,
"text": "Python3"
},
{
"code": null,
"e": 27279,
"s": 27276,
"text": "C#"
},
{
"code": null,
"e": 27283,
"s": 27279,
"text": "PHP"
},
{
"code": null,
"e": 27294,
"s": 27283,
"text": "Javascript"
},
{
"code": "// CPP program to change value of x// according to its current value.#include <bits/stdc++.h>using namespace std; // Function to alternate the valuesvoid alternate(int& a, int& b, int& x){ x = a + b - x;} // Main functionint main(){ int a = -10; int b = 15; int x = a; cout << \"x is : \" << x; alternate(a, b, x); cout << \"\\nAfter change \"; cout << \"\\nx is : \" << x;}",
"e": 27687,
"s": 27294,
"text": null
},
{
"code": "// Java program to change value of x// according to its current value.import java.util.*; class solution{ // Function to alternate the valuesstatic void alternate(int a, int b, int x){ x = a + b - x; System.out.println(\"After change\"+\"\\n\"+\" x is : \"+x);} // Main functionpublic static void main(String args[]){ int a = -10; int b = 15; int x = a; System.out.println(\"x is : \"+x); alternate(a, b, x);}}",
"e": 28110,
"s": 27687,
"text": null
},
{
"code": "# Python3 program to change value# of x according to its current value. # Function to alternate the valuesdef alternate(a,b,x): x = a+b-x print(\"After change x is:\",x) # Driver codeif __name__=='__main__': a = -10 b = 15 x = a print(\"x is:\",x) alternate(a,b,x) # This code is contributed by# Shrikant13",
"e": 28435,
"s": 28110,
"text": null
},
{
"code": "// C# program to change value of x// according to its current value. using System;class gfg{ // Function to alternate the values public void alternate(ref int a, ref int b, ref int x) //'ref' indicates the references { x = a + b - x; }} // Main functionclass geek{ public static int Main() { gfg g = new gfg(); int a = -10; int b = 15; int x = a; Console.WriteLine(\"x is : {0}\" , x); g.alternate(ref a, ref b, ref x); Console.WriteLine (\"After change \"); Console.WriteLine(\"x is : {0}\", x); return 0; }}//This code is contributed by Soumik",
"e": 29009,
"s": 28435,
"text": null
},
{
"code": "<?php// PHP program to change value of x// according to its current value. // Function to alternate the valuesfunction alternate (&$a, &$b, &$x){ $x = $a + $b - $x;} // Driver Code$a = -10;$b = 15;$x = $a;echo \"x is : \", $x; alternate($a, $b, $x); echo \"\\nAfter change \";echo \"\\nx is : \", $x; // This code is contributed by ajit.?>",
"e": 29344,
"s": 29009,
"text": null
},
{
"code": "<script>// javascript program to change value of x// according to its current value. // Function to alternate the values function alternate(a , b , x) { x = a + b - x; document.write(\"After change\" + \"<br/>\" + \" x is : \" + x); } // Main function var a = -10; var b = 15; var x = a; document.write(\"x is : \" + x+\"<br/>\"); alternate(a, b, x); // This code is contributed by todaysgaurav</script>",
"e": 29806,
"s": 29344,
"text": null
},
{
"code": null,
"e": 29841,
"s": 29806,
"text": "x is : -10\nAfter change \nx is : 15"
},
{
"code": null,
"e": 30058,
"s": 29843,
"text": "Time Complexity: The time complexity of this approach is O(1) Space Complexity: The space complexity of this approach is O(1)Solution 2: A better and efficient approach is using the bitwise XOR operation.x = a^b^x "
},
{
"code": null,
"e": 30062,
"s": 30058,
"text": "C++"
},
{
"code": null,
"e": 30067,
"s": 30062,
"text": "Java"
},
{
"code": null,
"e": 30075,
"s": 30067,
"text": "Python3"
},
{
"code": null,
"e": 30078,
"s": 30075,
"text": "C#"
},
{
"code": null,
"e": 30082,
"s": 30078,
"text": "PHP"
},
{
"code": null,
"e": 30093,
"s": 30082,
"text": "Javascript"
},
{
"code": "// CPP program to change value of x// according to its current value.#include <bits/stdc++.h>using namespace std; // Function to alternate the valuesvoid alternate(int& a, int& b, int& x){ x = a ^ b ^ x;} // Main functionint main(){ int a = -10; int b = 15; int x = a; cout << \"x is : \" << x; alternate(a, b, x); cout << \"\\nAfter exchange \"; cout << \"\\nx is : \" << x; return 0;}",
"e": 30506,
"s": 30093,
"text": null
},
{
"code": "// Java program to change value of x// according to its current value. class GFG {// Function to alternate the values static int alternate(int a, int b, int x) { return x = a ^ b ^ x; } // Main function public static void main(String[] args) { int a = -10; int b = 15; int x = a; System.out.print(\"x is : \" + x); x = alternate(a, b, x); System.out.print(\"\\nAfter exchange \"); System.out.print(\"\\nx is : \" + x); }} // This code is contributed by 29AjayKumar",
"e": 31035,
"s": 30506,
"text": null
},
{
"code": "# Python3 program to change value of x# according to its current value. # Function to alternate the valuesdef alternate(a, b, x): x = a ^ b ^ x print(\"After exchange\") print(\"x is\", x) # Driver codea = -10b = 15x = aprint(\"x is\", x)alternate(a, b, x) # This code is contributed# by Shrikant13",
"e": 31337,
"s": 31035,
"text": null
},
{
"code": " // C# program to change value of x// according to its current value.using System;public class GFG {// Function to alternate the values static int alternate(int a, int b, int x) { return x = a ^ b ^ x; } // Main function public static void Main() { int a = -10; int b = 15; int x = a; Console.Write(\"x is : \" + x); x = alternate(a, b, x); Console.Write(\"\\nAfter exchange \"); Console.Write(\"\\nx is : \" + x); }}/*This code is contributed by Rajput-Ji*/",
"e": 31864,
"s": 31337,
"text": null
},
{
"code": "<?php// PHP program to change value of x// according to its current value. // Function to alternate the valuesfunction alternate(&$a, &$b, &$x){ $x = $a ^ $b ^ $x;} // Driver Code$a = -10;$b = 15;$x = $a;echo \"x is : \", $x; alternate($a, $b, $x); echo \"\\nAfter exchange \";echo \"\\nx is : \", $x; // This code is contributed// by akt_mit?>",
"e": 32204,
"s": 31864,
"text": null
},
{
"code": "<script> // Javascript program to change value of x// according to its current value. // Function to alternate the values function alternate(a , b , x) { return x = a ^ b ^ x; } // Main function var a = -10; var b = 15; var x = a; document.write(\"x is : \" + x); x = alternate(a, b, x); document.write(\"<br/>After exchange \"); document.write(\"<br/>x is : \" + x); // This code contributed by Rajput-Ji </script>",
"e": 32689,
"s": 32204,
"text": null
},
{
"code": null,
"e": 32726,
"s": 32689,
"text": "x is : -10\nAfter exchange \nx is : 15"
},
{
"code": null,
"e": 32855,
"s": 32728,
"text": "Time Complexity: The time complexity of this approach is O(1) Space Complexity: The space complexity of this approach is O(1) "
},
{
"code": null,
"e": 32867,
"s": 32855,
"text": "shrikanth13"
},
{
"code": null,
"e": 32880,
"s": 32867,
"text": "SoumikMondal"
},
{
"code": null,
"e": 32897,
"s": 32880,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32909,
"s": 32897,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32919,
"s": 32909,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32925,
"s": 32919,
"text": "jit_t"
},
{
"code": null,
"e": 32938,
"s": 32925,
"text": "todaysgaurav"
},
{
"code": null,
"e": 32949,
"s": 32938,
"text": "Bitwise-OR"
},
{
"code": null,
"e": 32968,
"s": 32949,
"text": "programming-puzzle"
},
{
"code": null,
"e": 32992,
"s": 32968,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 33002,
"s": 32992,
"text": "Bit Magic"
},
{
"code": null,
"e": 33021,
"s": 33002,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33031,
"s": 33021,
"text": "Bit Magic"
},
{
"code": null,
"e": 33129,
"s": 33031,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33180,
"s": 33129,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 33238,
"s": 33180,
"text": "Find the size of Largest Subset with positive Bitwise AND"
},
{
"code": null,
"e": 33319,
"s": 33238,
"text": "Check whether bitwise AND of a number with any subset of an array is zero or not"
},
{
"code": null,
"e": 33383,
"s": 33319,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 33437,
"s": 33383,
"text": "Highest power of 2 less than or equal to given number"
},
{
"code": null,
"e": 33464,
"s": 33437,
"text": "Swap two nibbles in a byte"
},
{
"code": null,
"e": 33492,
"s": 33464,
"text": "Swap bits in a given number"
},
{
"code": null,
"e": 33519,
"s": 33492,
"text": "Check for Integer Overflow"
},
{
"code": null,
"e": 33559,
"s": 33519,
"text": "Reverse actual bits of the given number"
}
] |
GUI to generate and store passwords in SQLite using Python - GeeksforGeeks
|
06 Sep, 2021
In this century there are many social media accounts, websites, or any online account that needs a secure password. Often we use the same password for multiple accounts and the basic drawback to that is if somebody gets to know about your password then he/she has the access to all your accounts. It is hard to remember all the distinct passwords. We can achieve that by creating a simple GUI program using python, Tkinter, and SQLite.
This application will generate a password based on the desired length given as input by the user. It will also save the password along with account user_id and the name of the site to a database. You can even update your old password or username.
The user will specify the length of the password they want to generate. The program will generate a random string of the specified length using the random function. The user will provide the details of the user ID and the site name associated with the account, and hit the save to database button, which will trigger the insert() function of the backend.py file given in the latter part of this article. Hence, saving the data into the database without writing any SQL command.
webbrowser: This module is used to display the help.txt file in notepad.
Tkinter: Tkinter is GUI or graphical user interface package in python. It is used for creating GUI applications in python.
SQLite3: Sqlite is a lightweight and easy-to-use database engine, which follows similar syntax to that of Postgres SQL. SQLite3 module in python helps us to execute SQL commands using python codes.
ttkbootsrtap: This module changes the appearance of the GUI application. It’s similar to bootstrap in web development, which is used to give a promising look to web pages. This module can be installed in the following ways:
Syntax:
pip install ttkbootstrap
csv: This module will help to save the data of the database in a .csv format, which later on be viewed in excel.
Syntax:
pip install python-csv
First, all the required modules are imported. Then 4 lists to represent lowercase, uppercase alphabets, and symbols is initialized, inside the class window as class variables. Then, the whole layout of the application is created under the __init__ function so that all these Tkinter objects are created at the time of declaring an object of the class window.
Ttkbootstrap package allows you to change the style of the Tkinter objects this includes everything Tkinter has to offer. This will basically change the theme of the application. It comes with many inbuilt themes ex. cyborg, darkly etc.
Syntax with ttkbootstrap:
win=Style.theme(‘theme_name’).master
Earlier syntax without ttkbootstrap:
win =Tk()
Password generator Function- generator() runs a loop for chosen password length /4. The length given by the user will always be multiple of 4 since those are the only options given in the dropdown menu. With each iteration choose a random character from the class variable created, using a random function. ex. a0=random.choice(list_name). After choosing and storing the characters from 4 different lists(class variables) into 4 variables of suitable data type, concatenate the 4 variables and store the sum in another variable.
Below is the implementation:
Program: Window to generate passwords
Python3
import randomimport webbrowserfrom tkinter import *from tkinter import ttkfrom tkinter import messageboximport backimport csvfrom ttkbootstrap import * class window: # these are lists of initialized characters digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] lc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] uc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'p', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] sym = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>', '*', '<'] def __init__(self, root, geo, title) -> None: self.root = root self.root.title(title) self.root.geometry(geo) self.root.resizable(width=False, height=False) Label(self.root, text='Your Password').grid( row=0, column=0, padx=10, pady=10) Label(self.root, text='Corresponding User_id').grid( row=1, column=0, padx=10, pady=10) Label(self.root, text='Of').grid(row=2, column=0, padx=10, pady=10) self.pa = StringVar() self.user_id = StringVar() self.site = StringVar() ttk.Entry(self.root, width=30, textvariable=self.pa ).grid(row=0, column=1, padx=10, pady=10) ttk.Entry(self.root, width=30, textvariable=self.user_id ).grid(row=1, column=1, padx=10, pady=10) ttk.Entry(self.root, width=30, textvariable=self.site ).grid(row=2, column=1, padx=10, pady=10) self.length = StringVar() e = ttk.Combobox(self.root, values=['4', '8', '12', '16', '20', '24'], textvariable=self.length) e.grid(row=0, column=2) e['state'] = 'readonly' self.length.set('Set password length') ttk.Button(self.root, text='Generate', padding=5, style='success.Outline.TButton', width=20, command=self.generate).grid(row=1, column=2) ttk.Button(self.root, text='Save to Database', style='success.TButton', width=20, padding=5, command=self.save).grid(row=3, column=2) ttk.Button(self.root, text='Delete', width=20, style='danger.TButton', padding=5, command=self.erase).grid(row=2, column=2) ttk.Button(self.root, text='Show All', width=20, padding=5, command=self.view).grid(row=3, column=0) ttk.Button(self.root, text='Update', width=20, padding=5, command=self.update).grid(row=3, column=1) # ========self.tree view============= self.tree = ttk.Treeview(self.root, height=5) self.tree['columns'] = ('site', 'user', 'pas') self.tree.column('#0', width=0, stretch=NO) self.tree.column('site', width=160, anchor=W) self.tree.column('user', width=140, anchor=W) self.tree.column('pas', width=180, anchor=W) self.tree.heading('#0', text='') self.tree.heading('site', text='Site name') self.tree.heading('user', text='User Id') self.tree.heading('pas', text='Password') self.tree.grid(row=4, column=0, columnspan=3, pady=10) self.tree.bind("<ButtonRelease-1>", self.catch) # this command will call the catch function # this is right click pop-up menu self.menu = Menu(self.root, tearoff=False) self.menu.add_command(label='Refresh', command=self.refresh) self.menu.add_command(label='Insert', command=self.save) self.menu.add_command(label='Update', command=self.update) self.menu.add_separator() self.menu.add_command(label='Show All', command=self.view) self.menu.add_command(label='Clear Fields', command=self.clear) self.menu.add_command(label='Clear Table', command=self.table) self.menu.add_command(label='Export', command=self.export) self.menu.add_separator() self.menu.add_command(label='Delete', command=self.erase) self.menu.add_command(label='Help', command=self.help) self.menu.add_separator() self.menu.add_command(label='Exit', command=self.root.quit) # this binds the button 3 of the mouse with self.root.bind("<Button-3>", self.poppin) # poppin function def help(self): # this function will open the help.txt in # notepad when called webbrowser.open('help.txt') def refresh(self): # this function basically refreshes the table # or tree view self.table() self.view() def table(self): # this function will clear all the values # displayed in the table for r in self.tree.get_children(): self.tree.delete(r) def clear(self): # this function will clear all the entry # fields self.pa.set('') self.user_id.set('') self.site.set('') def poppin(self, e): # it triggers the right click pop-up menu self.menu.tk_popup(e.x_root, e.y_root) def catch(self, event): # this function will take all the selected data # from the table/ tree view and will fill up the # respective entry fields self.pa.set('') self.user_id.set('') self.site.set('') selected = self.tree.focus() value = self.tree.item(selected, 'value') self.site.set(value[0]) self.user_id.set(value[1]) self.pa.set(value[2]) def update(self): # this function will update database with new # values given by the user selected = self.tree.focus() value = self.tree.item(selected, 'value') back.edit(self.site.get(), self.user_id.get(), self.pa.get()) self.refresh() def view(self): # this will show all the data from the database # this is similar to "SELECT * FROM TABLE" sql # command if back.check() is False: messagebox.showerror('Attention Amigo!', 'Database is EMPTY!') else: for row in back.show(): self.tree.insert(parent='', text='', index='end', values=(row[0], row[1], row[2])) def erase(self): # this will delete or remove the selected tuple or # row from the database selected = self.tree.focus() value = self.tree.item(selected, 'value') back.Del(value[2]) self.refresh() def save(self): # this function will insert all the data into the # database back.enter(self.site.get(), self.user_id.get(), self.pa.get()) self.tree.insert(parent='', index='end', text='', values=(self.site.get(), self.user_id.get(), self.pa.get())) def generate(self): # this function will produce a random string which # will be used as password if self.length.get() == 'Set password length': messagebox.showerror('Attention!', "You forgot to SELECT") else: a = '' for x in range(int(int(self.length.get())/4)): a0 = random.choice(self.uc) a1 = random.choice(self.lc) a2 = random.choice(self.sym) a3 = random.choice(self.digits) a = a0+a1+a2+a3+a self.pa.set(a) def export(self): # this function will save all the data from the # database in a csv format which can be opened # in excel pop = Toplevel(self.root) pop.geometry('300x100') self.v = StringVar() Label(pop, text='Save File Name as').pack() ttk.Entry(pop, textvariable=self.v).pack() ttk.Button(pop, text='Save', width=18, command=lambda: exp(self.v.get())).pack(pady=5) def exp(x): with open(x + '.csv', 'w', newline='') as f: chompa = csv.writer(f, dialect='excel') for r in back.show(): chompa.writerow(r) messagebox.showinfo("File Saved", "Saved as " + x + ".csv") if __name__ == '__main__': win = Style(theme='darkly').master name = 'Password Generator' dimension = '565x320' app = window(win, dimension, name) win.mainloop()
Backend program using SQLite: Sqlite3 module of python allows us to execute sol commands using Python. Following is the syntax
It will make a connection to the SQLite database file
con=sqlite3.connect(‘database.db’)
Cursor for dataset traversal
c=conn.cursor()
To execute the SQL commands
c.execute(“SQL code”)
Commit or save the changes made
conn.commit()
This for closing the connection created with SQLite database file
conn.close()
Note: Here the password is been taken as a primary key. So to change the password you need to insert the new one and delete the old one from the database.
Program: Backend program using SQLite:
Python3
import sqlite3 as sq db = 'secure.db' def connect(): # used to connect to the secure.db database conn = sq.connect(db) # defined a cursor to retrieve one data/tuple at # a time c = conn.cursor() # execute will execute the entire sql command as # it is c.execute(""" CREATE TABLE IF NOT EXISTS data ( site text, user text, password text primary key ) """) # to commit the sql command, it will commit the # current transaction or conn.commit() conn.close() def enter(site, user, pas): conn = sq.connect(db) c = conn.cursor() c.execute("INSERT INTO data VALUES(?,?,?)", (site, user, pas)) conn.commit() conn.close() def show(): conn = sq.connect(db) c = conn.cursor() c.execute("SELECT * FROM data") # this will store all the data from the table to # the variable i in the form of 2d list i = c.fetchall() conn.commit() conn.close() return i def Del(password): conn = sq.connect(db) c = conn.cursor() c.execute("DELETE FROM data WHERE password=(?)", (password,)) conn.commit() conn.close() def edit(site, user, password): conn = sq.connect(db) c = conn.cursor() c.execute("UPDATE data SET site=?, user=(?) WHERE password=(?) ", (site, user, password)) conn.commit() conn.close() def check(): # this function will check whether the database # is empty or not if len(show()) == 0: return False else: return True # calling the connect function to create a table and# database if it doesn't existsconnect()
Output:
rajeev0719singh
anikaseth98
adnanirshad158
sagar0719kumar
Python Tkinter-exercises
Python-SQLite
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 25975,
"s": 25537,
"text": "In this century there are many social media accounts, websites, or any online account that needs a secure password. Often we use the same password for multiple accounts and the basic drawback to that is if somebody gets to know about your password then he/she has the access to all your accounts. It is hard to remember all the distinct passwords. We can achieve that by creating a simple GUI program using python, Tkinter, and SQLite. "
},
{
"code": null,
"e": 26223,
"s": 25975,
"text": "This application will generate a password based on the desired length given as input by the user. It will also save the password along with account user_id and the name of the site to a database. You can even update your old password or username. "
},
{
"code": null,
"e": 26703,
"s": 26223,
"text": "The user will specify the length of the password they want to generate. The program will generate a random string of the specified length using the random function. The user will provide the details of the user ID and the site name associated with the account, and hit the save to database button, which will trigger the insert() function of the backend.py file given in the latter part of this article. Hence, saving the data into the database without writing any SQL command. "
},
{
"code": null,
"e": 26776,
"s": 26703,
"text": "webbrowser: This module is used to display the help.txt file in notepad."
},
{
"code": null,
"e": 26899,
"s": 26776,
"text": "Tkinter: Tkinter is GUI or graphical user interface package in python. It is used for creating GUI applications in python."
},
{
"code": null,
"e": 27097,
"s": 26899,
"text": "SQLite3: Sqlite is a lightweight and easy-to-use database engine, which follows similar syntax to that of Postgres SQL. SQLite3 module in python helps us to execute SQL commands using python codes."
},
{
"code": null,
"e": 27322,
"s": 27097,
"text": "ttkbootsrtap: This module changes the appearance of the GUI application. It’s similar to bootstrap in web development, which is used to give a promising look to web pages. This module can be installed in the following ways:"
},
{
"code": null,
"e": 27330,
"s": 27322,
"text": "Syntax:"
},
{
"code": null,
"e": 27355,
"s": 27330,
"text": "pip install ttkbootstrap"
},
{
"code": null,
"e": 27468,
"s": 27355,
"text": "csv: This module will help to save the data of the database in a .csv format, which later on be viewed in excel."
},
{
"code": null,
"e": 27476,
"s": 27468,
"text": "Syntax:"
},
{
"code": null,
"e": 27499,
"s": 27476,
"text": "pip install python-csv"
},
{
"code": null,
"e": 27859,
"s": 27499,
"text": "First, all the required modules are imported. Then 4 lists to represent lowercase, uppercase alphabets, and symbols is initialized, inside the class window as class variables. Then, the whole layout of the application is created under the __init__ function so that all these Tkinter objects are created at the time of declaring an object of the class window. "
},
{
"code": null,
"e": 28098,
"s": 27859,
"text": "Ttkbootstrap package allows you to change the style of the Tkinter objects this includes everything Tkinter has to offer. This will basically change the theme of the application. It comes with many inbuilt themes ex. cyborg, darkly etc. "
},
{
"code": null,
"e": 28125,
"s": 28098,
"text": "Syntax with ttkbootstrap: "
},
{
"code": null,
"e": 28162,
"s": 28125,
"text": "win=Style.theme(‘theme_name’).master"
},
{
"code": null,
"e": 28199,
"s": 28162,
"text": "Earlier syntax without ttkbootstrap:"
},
{
"code": null,
"e": 28209,
"s": 28199,
"text": "win =Tk()"
},
{
"code": null,
"e": 28738,
"s": 28209,
"text": "Password generator Function- generator() runs a loop for chosen password length /4. The length given by the user will always be multiple of 4 since those are the only options given in the dropdown menu. With each iteration choose a random character from the class variable created, using a random function. ex. a0=random.choice(list_name). After choosing and storing the characters from 4 different lists(class variables) into 4 variables of suitable data type, concatenate the 4 variables and store the sum in another variable."
},
{
"code": null,
"e": 28767,
"s": 28738,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 28805,
"s": 28767,
"text": "Program: Window to generate passwords"
},
{
"code": null,
"e": 28813,
"s": 28805,
"text": "Python3"
},
{
"code": "import randomimport webbrowserfrom tkinter import *from tkinter import ttkfrom tkinter import messageboximport backimport csvfrom ttkbootstrap import * class window: # these are lists of initialized characters digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] lc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] uc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'p', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] sym = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>', '*', '<'] def __init__(self, root, geo, title) -> None: self.root = root self.root.title(title) self.root.geometry(geo) self.root.resizable(width=False, height=False) Label(self.root, text='Your Password').grid( row=0, column=0, padx=10, pady=10) Label(self.root, text='Corresponding User_id').grid( row=1, column=0, padx=10, pady=10) Label(self.root, text='Of').grid(row=2, column=0, padx=10, pady=10) self.pa = StringVar() self.user_id = StringVar() self.site = StringVar() ttk.Entry(self.root, width=30, textvariable=self.pa ).grid(row=0, column=1, padx=10, pady=10) ttk.Entry(self.root, width=30, textvariable=self.user_id ).grid(row=1, column=1, padx=10, pady=10) ttk.Entry(self.root, width=30, textvariable=self.site ).grid(row=2, column=1, padx=10, pady=10) self.length = StringVar() e = ttk.Combobox(self.root, values=['4', '8', '12', '16', '20', '24'], textvariable=self.length) e.grid(row=0, column=2) e['state'] = 'readonly' self.length.set('Set password length') ttk.Button(self.root, text='Generate', padding=5, style='success.Outline.TButton', width=20, command=self.generate).grid(row=1, column=2) ttk.Button(self.root, text='Save to Database', style='success.TButton', width=20, padding=5, command=self.save).grid(row=3, column=2) ttk.Button(self.root, text='Delete', width=20, style='danger.TButton', padding=5, command=self.erase).grid(row=2, column=2) ttk.Button(self.root, text='Show All', width=20, padding=5, command=self.view).grid(row=3, column=0) ttk.Button(self.root, text='Update', width=20, padding=5, command=self.update).grid(row=3, column=1) # ========self.tree view============= self.tree = ttk.Treeview(self.root, height=5) self.tree['columns'] = ('site', 'user', 'pas') self.tree.column('#0', width=0, stretch=NO) self.tree.column('site', width=160, anchor=W) self.tree.column('user', width=140, anchor=W) self.tree.column('pas', width=180, anchor=W) self.tree.heading('#0', text='') self.tree.heading('site', text='Site name') self.tree.heading('user', text='User Id') self.tree.heading('pas', text='Password') self.tree.grid(row=4, column=0, columnspan=3, pady=10) self.tree.bind(\"<ButtonRelease-1>\", self.catch) # this command will call the catch function # this is right click pop-up menu self.menu = Menu(self.root, tearoff=False) self.menu.add_command(label='Refresh', command=self.refresh) self.menu.add_command(label='Insert', command=self.save) self.menu.add_command(label='Update', command=self.update) self.menu.add_separator() self.menu.add_command(label='Show All', command=self.view) self.menu.add_command(label='Clear Fields', command=self.clear) self.menu.add_command(label='Clear Table', command=self.table) self.menu.add_command(label='Export', command=self.export) self.menu.add_separator() self.menu.add_command(label='Delete', command=self.erase) self.menu.add_command(label='Help', command=self.help) self.menu.add_separator() self.menu.add_command(label='Exit', command=self.root.quit) # this binds the button 3 of the mouse with self.root.bind(\"<Button-3>\", self.poppin) # poppin function def help(self): # this function will open the help.txt in # notepad when called webbrowser.open('help.txt') def refresh(self): # this function basically refreshes the table # or tree view self.table() self.view() def table(self): # this function will clear all the values # displayed in the table for r in self.tree.get_children(): self.tree.delete(r) def clear(self): # this function will clear all the entry # fields self.pa.set('') self.user_id.set('') self.site.set('') def poppin(self, e): # it triggers the right click pop-up menu self.menu.tk_popup(e.x_root, e.y_root) def catch(self, event): # this function will take all the selected data # from the table/ tree view and will fill up the # respective entry fields self.pa.set('') self.user_id.set('') self.site.set('') selected = self.tree.focus() value = self.tree.item(selected, 'value') self.site.set(value[0]) self.user_id.set(value[1]) self.pa.set(value[2]) def update(self): # this function will update database with new # values given by the user selected = self.tree.focus() value = self.tree.item(selected, 'value') back.edit(self.site.get(), self.user_id.get(), self.pa.get()) self.refresh() def view(self): # this will show all the data from the database # this is similar to \"SELECT * FROM TABLE\" sql # command if back.check() is False: messagebox.showerror('Attention Amigo!', 'Database is EMPTY!') else: for row in back.show(): self.tree.insert(parent='', text='', index='end', values=(row[0], row[1], row[2])) def erase(self): # this will delete or remove the selected tuple or # row from the database selected = self.tree.focus() value = self.tree.item(selected, 'value') back.Del(value[2]) self.refresh() def save(self): # this function will insert all the data into the # database back.enter(self.site.get(), self.user_id.get(), self.pa.get()) self.tree.insert(parent='', index='end', text='', values=(self.site.get(), self.user_id.get(), self.pa.get())) def generate(self): # this function will produce a random string which # will be used as password if self.length.get() == 'Set password length': messagebox.showerror('Attention!', \"You forgot to SELECT\") else: a = '' for x in range(int(int(self.length.get())/4)): a0 = random.choice(self.uc) a1 = random.choice(self.lc) a2 = random.choice(self.sym) a3 = random.choice(self.digits) a = a0+a1+a2+a3+a self.pa.set(a) def export(self): # this function will save all the data from the # database in a csv format which can be opened # in excel pop = Toplevel(self.root) pop.geometry('300x100') self.v = StringVar() Label(pop, text='Save File Name as').pack() ttk.Entry(pop, textvariable=self.v).pack() ttk.Button(pop, text='Save', width=18, command=lambda: exp(self.v.get())).pack(pady=5) def exp(x): with open(x + '.csv', 'w', newline='') as f: chompa = csv.writer(f, dialect='excel') for r in back.show(): chompa.writerow(r) messagebox.showinfo(\"File Saved\", \"Saved as \" + x + \".csv\") if __name__ == '__main__': win = Style(theme='darkly').master name = 'Password Generator' dimension = '565x320' app = window(win, dimension, name) win.mainloop()",
"e": 37075,
"s": 28813,
"text": null
},
{
"code": null,
"e": 37202,
"s": 37075,
"text": "Backend program using SQLite: Sqlite3 module of python allows us to execute sol commands using Python. Following is the syntax"
},
{
"code": null,
"e": 37256,
"s": 37202,
"text": "It will make a connection to the SQLite database file"
},
{
"code": null,
"e": 37293,
"s": 37256,
"text": "con=sqlite3.connect(‘database.db’) "
},
{
"code": null,
"e": 37322,
"s": 37293,
"text": "Cursor for dataset traversal"
},
{
"code": null,
"e": 37339,
"s": 37322,
"text": "c=conn.cursor() "
},
{
"code": null,
"e": 37367,
"s": 37339,
"text": "To execute the SQL commands"
},
{
"code": null,
"e": 37390,
"s": 37367,
"text": "c.execute(“SQL code”) "
},
{
"code": null,
"e": 37422,
"s": 37390,
"text": "Commit or save the changes made"
},
{
"code": null,
"e": 37437,
"s": 37422,
"text": "conn.commit() "
},
{
"code": null,
"e": 37503,
"s": 37437,
"text": "This for closing the connection created with SQLite database file"
},
{
"code": null,
"e": 37517,
"s": 37503,
"text": "conn.close() "
},
{
"code": null,
"e": 37672,
"s": 37517,
"text": "Note: Here the password is been taken as a primary key. So to change the password you need to insert the new one and delete the old one from the database."
},
{
"code": null,
"e": 37711,
"s": 37672,
"text": "Program: Backend program using SQLite:"
},
{
"code": null,
"e": 37719,
"s": 37711,
"text": "Python3"
},
{
"code": "import sqlite3 as sq db = 'secure.db' def connect(): # used to connect to the secure.db database conn = sq.connect(db) # defined a cursor to retrieve one data/tuple at # a time c = conn.cursor() # execute will execute the entire sql command as # it is c.execute(\"\"\" CREATE TABLE IF NOT EXISTS data ( site text, user text, password text primary key ) \"\"\") # to commit the sql command, it will commit the # current transaction or conn.commit() conn.close() def enter(site, user, pas): conn = sq.connect(db) c = conn.cursor() c.execute(\"INSERT INTO data VALUES(?,?,?)\", (site, user, pas)) conn.commit() conn.close() def show(): conn = sq.connect(db) c = conn.cursor() c.execute(\"SELECT * FROM data\") # this will store all the data from the table to # the variable i in the form of 2d list i = c.fetchall() conn.commit() conn.close() return i def Del(password): conn = sq.connect(db) c = conn.cursor() c.execute(\"DELETE FROM data WHERE password=(?)\", (password,)) conn.commit() conn.close() def edit(site, user, password): conn = sq.connect(db) c = conn.cursor() c.execute(\"UPDATE data SET site=?, user=(?) WHERE password=(?) \", (site, user, password)) conn.commit() conn.close() def check(): # this function will check whether the database # is empty or not if len(show()) == 0: return False else: return True # calling the connect function to create a table and# database if it doesn't existsconnect()",
"e": 39410,
"s": 37719,
"text": null
},
{
"code": null,
"e": 39421,
"s": 39413,
"text": "Output:"
},
{
"code": null,
"e": 39441,
"s": 39425,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 39453,
"s": 39441,
"text": "anikaseth98"
},
{
"code": null,
"e": 39468,
"s": 39453,
"text": "adnanirshad158"
},
{
"code": null,
"e": 39483,
"s": 39468,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 39508,
"s": 39483,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 39522,
"s": 39508,
"text": "Python-SQLite"
},
{
"code": null,
"e": 39537,
"s": 39522,
"text": "Python-tkinter"
},
{
"code": null,
"e": 39544,
"s": 39537,
"text": "Python"
},
{
"code": null,
"e": 39642,
"s": 39544,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39674,
"s": 39642,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 39716,
"s": 39674,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 39758,
"s": 39716,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 39785,
"s": 39758,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 39841,
"s": 39785,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 39880,
"s": 39841,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 39902,
"s": 39880,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 39933,
"s": 39902,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 39962,
"s": 39933,
"text": "Create a directory in Python"
}
] |
How to Hide Password in HTML ? - GeeksforGeeks
|
30 Jun, 2021
Hiding the password is commonly known as Password Masking. It is hiding the password characters when entered by the users by the use of bullets (•), an asterisk (*), or some other characters.
It is always a good practice to use password masking to ensure security and avoid its misuse. Generally, password masking is helpful to hide the characters from any user when the screen is exposed to being projected so that the password is not publicized.
In this article, we will learn to hide the password using HTML.
Approach:
Method 1: Using the input type = “password”
<input type="password" placeholder="Enter your Password">
Example:
HTML
<!DOCTYPE html><html> <head> <style> * { font-family: Arial; margin: 2px; padding: 10px; text-align: center; position: flex; } h2 { color: green; padding: 2px; } body { margin-top: 10%; } </style></head> <body> <h2>GeeksforGeeks</h2> <b>Hiding password</b> <form action="#" method="POST"> <label> <b>Username:</b> </label> <input type="text" placeholder="Enter Username" required /> <br /><br /> <label> <b>Password:</b> </label> <input type="password" placeholder="Enter Password" required /> <br /><br /> <button type="submit">Submit</button> </form></body> </html>
Output:
Method 2: Using the input type = “text”
This method is not very much preferred, in this method we would just be camouflaging the text into some characters of our own choice.
This method is deprived of security and is recommended only for password masking with other characters such as squares, circles, etc.For Squares: -webkit-text-security: squareFor Circles: -webkit-text-security: circle
For Squares: -webkit-text-security: squareFor Circles: -webkit-text-security: circle
For Squares: -webkit-text-security: square
For Squares: -webkit-text-security: square
For Circles: -webkit-text-security: circle
For Circles: -webkit-text-security: circle
Example:
HTML
<!DOCTYPE html><html> <head> <style> * { font-family: Arial; margin: 2px; padding: 10px; text-align: center; position: flex; } body { margin-top: 10%; } </style></head> <body> <form action="#" method="POST"> <label> <b>Username</b> </label> <input type="text" placeholder="Enter Username" required /> <br /><br /> <label> <b>Password</b> </label> <input type="text" style="-webkit-text-security: circle" placeholder="Enter Password" required /> <br /> <label> <b>Password</b> </label> <input type="text" style="-webkit-text-security: square" placeholder="Enter Password" required /> <br /><br /> <button type="submit">Submit</button> </form></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
HTML-Attributes
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
|
[
{
"code": null,
"e": 26647,
"s": 26619,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26839,
"s": 26647,
"text": "Hiding the password is commonly known as Password Masking. It is hiding the password characters when entered by the users by the use of bullets (•), an asterisk (*), or some other characters."
},
{
"code": null,
"e": 27095,
"s": 26839,
"text": "It is always a good practice to use password masking to ensure security and avoid its misuse. Generally, password masking is helpful to hide the characters from any user when the screen is exposed to being projected so that the password is not publicized."
},
{
"code": null,
"e": 27160,
"s": 27095,
"text": "In this article, we will learn to hide the password using HTML. "
},
{
"code": null,
"e": 27170,
"s": 27160,
"text": "Approach:"
},
{
"code": null,
"e": 27214,
"s": 27170,
"text": "Method 1: Using the input type = “password”"
},
{
"code": null,
"e": 27272,
"s": 27214,
"text": "<input type=\"password\" placeholder=\"Enter your Password\">"
},
{
"code": null,
"e": 27283,
"s": 27274,
"text": "Example:"
},
{
"code": null,
"e": 27288,
"s": 27283,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> * { font-family: Arial; margin: 2px; padding: 10px; text-align: center; position: flex; } h2 { color: green; padding: 2px; } body { margin-top: 10%; } </style></head> <body> <h2>GeeksforGeeks</h2> <b>Hiding password</b> <form action=\"#\" method=\"POST\"> <label> <b>Username:</b> </label> <input type=\"text\" placeholder=\"Enter Username\" required /> <br /><br /> <label> <b>Password:</b> </label> <input type=\"password\" placeholder=\"Enter Password\" required /> <br /><br /> <button type=\"submit\">Submit</button> </form></body> </html>",
"e": 28106,
"s": 27288,
"text": null
},
{
"code": null,
"e": 28114,
"s": 28106,
"text": "Output:"
},
{
"code": null,
"e": 28154,
"s": 28114,
"text": "Method 2: Using the input type = “text”"
},
{
"code": null,
"e": 28288,
"s": 28154,
"text": "This method is not very much preferred, in this method we would just be camouflaging the text into some characters of our own choice."
},
{
"code": null,
"e": 28507,
"s": 28288,
"text": "This method is deprived of security and is recommended only for password masking with other characters such as squares, circles, etc.For Squares: -webkit-text-security: squareFor Circles: -webkit-text-security: circle"
},
{
"code": null,
"e": 28593,
"s": 28507,
"text": "For Squares: -webkit-text-security: squareFor Circles: -webkit-text-security: circle"
},
{
"code": null,
"e": 28636,
"s": 28593,
"text": "For Squares: -webkit-text-security: square"
},
{
"code": null,
"e": 28679,
"s": 28636,
"text": "For Squares: -webkit-text-security: square"
},
{
"code": null,
"e": 28723,
"s": 28679,
"text": "For Circles: -webkit-text-security: circle"
},
{
"code": null,
"e": 28767,
"s": 28723,
"text": "For Circles: -webkit-text-security: circle"
},
{
"code": null,
"e": 28776,
"s": 28767,
"text": "Example:"
},
{
"code": null,
"e": 28781,
"s": 28776,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> * { font-family: Arial; margin: 2px; padding: 10px; text-align: center; position: flex; } body { margin-top: 10%; } </style></head> <body> <form action=\"#\" method=\"POST\"> <label> <b>Username</b> </label> <input type=\"text\" placeholder=\"Enter Username\" required /> <br /><br /> <label> <b>Password</b> </label> <input type=\"text\" style=\"-webkit-text-security: circle\" placeholder=\"Enter Password\" required /> <br /> <label> <b>Password</b> </label> <input type=\"text\" style=\"-webkit-text-security: square\" placeholder=\"Enter Password\" required /> <br /><br /> <button type=\"submit\">Submit</button> </form></body> </html>",
"e": 29693,
"s": 28781,
"text": null
},
{
"code": null,
"e": 29701,
"s": 29693,
"text": "Output:"
},
{
"code": null,
"e": 29838,
"s": 29701,
"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": 29853,
"s": 29838,
"text": "CSS-Properties"
},
{
"code": null,
"e": 29869,
"s": 29853,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 29884,
"s": 29869,
"text": "HTML-Questions"
},
{
"code": null,
"e": 29891,
"s": 29884,
"text": "Picked"
},
{
"code": null,
"e": 29895,
"s": 29891,
"text": "CSS"
},
{
"code": null,
"e": 29900,
"s": 29895,
"text": "HTML"
},
{
"code": null,
"e": 29917,
"s": 29900,
"text": "Web Technologies"
},
{
"code": null,
"e": 29922,
"s": 29917,
"text": "HTML"
},
{
"code": null,
"e": 30020,
"s": 29922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30057,
"s": 30020,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30096,
"s": 30057,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30125,
"s": 30096,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30167,
"s": 30125,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 30202,
"s": 30167,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 30262,
"s": 30202,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30315,
"s": 30262,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30376,
"s": 30315,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30426,
"s": 30376,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Angular Material - Menu Bar
|
The md-menu-bar an Angular directive, is a container component to hold multiple menus. Menu bar helps to create a operating system provided menu effect.
The following example shows the use of md-menu-bar directive and also the uses of menu-bar.
am_menubar.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('menubarController', menubarController);
function menubarController ($scope, $mdDialog) {
this.sampleAction = function(name, ev) {
$mdDialog.show($mdDialog.alert()
.title(name)
.textContent('Start learning "' + name + '!')
.ok('OK')
.targetEvent(ev)
);
};
}
</script>
</head>
<body ng-app = "firstApplication">
<div id = "menubarContainer" ng-controller = "menubarController as ctrl"
layout = "row" ng-cloak>
<md-toolbar class = "md-menu-toolbar">
<div layout = "row">
<div>
<h2 class = "md-toolbar-tools">Learn @TutorialsPoint</h2>
<md-menu-bar>
<md-menu>
<button ng-click = "$mdOpenMenu()">Tutorials</button>
<md-menu-content>
<md-menu-item>
<md-button ng-click = "ctrl.sampleAction('share', $event)">Share...</md-button>
</md-menu-item>
<md-menu-divider></md-menu-divider>
<md-menu-item>
<md-menu>
<md-button
ng-click = "$mdOpenMenu()">Learn</md-button>
<md-menu-content>
<md-menu-item>
<md-button
ng-click = "ctrl.sampleAction('HTML5', $event)">
HTML5</md-button>
</md-menu-item>
<md-menu-item>
<md-button
ng-click = "ctrl.sampleAction('jQuery', $event)">
jQuery</md-button>
</md-menu-item>
<md-menu-item>
<md-button
ng-click = "ctrl.sampleAction('AngularJS', $event)">
AngularJS</md-button>
</md-menu-item>
<md-menu-item>
<md-button disabled = "disabled"
ng-click = "ctrl.sampleAction('AngularJS 2.0', $event)">
AngularJS 2.0</md-button>
</md-menu-item>
<md-menu-divider></md-menu-divider>
<md-menu-item>
<md-button
ng-click = "ctrl.sampleAction('CSS', $event)">
CSS</md-button>
</md-menu-item>
</md-menu-content>
</md-menu>
</md-menu-item>
</md-menu-content>
</md-menu>
</md-menu-bar>
</div>
</div>
</md-toolbar>
</div>
</body>
</html>
Verify the result.
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": 2343,
"s": 2190,
"text": "The md-menu-bar an Angular directive, is a container component to hold multiple menus. Menu bar helps to create a operating system provided menu effect."
},
{
"code": null,
"e": 2435,
"s": 2343,
"text": "The following example shows the use of md-menu-bar directive and also the uses of menu-bar."
},
{
"code": null,
"e": 2450,
"s": 2435,
"text": "am_menubar.htm"
},
{
"code": null,
"e": 7094,
"s": 2450,
"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('menubarController', menubarController);\n\n function menubarController ($scope, $mdDialog) {\n this.sampleAction = function(name, ev) {\n $mdDialog.show($mdDialog.alert()\n .title(name) \n .textContent('Start learning \"' + name + '!')\n .ok('OK')\n .targetEvent(ev)\n );\n };\n } \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"menubarContainer\" ng-controller = \"menubarController as ctrl\"\n layout = \"row\" ng-cloak>\n <md-toolbar class = \"md-menu-toolbar\">\n <div layout = \"row\">\n <div>\n <h2 class = \"md-toolbar-tools\">Learn @TutorialsPoint</h2>\n <md-menu-bar>\n <md-menu>\n <button ng-click = \"$mdOpenMenu()\">Tutorials</button>\n <md-menu-content>\n \n <md-menu-item>\n <md-button ng-click = \"ctrl.sampleAction('share', $event)\">Share...</md-button>\n </md-menu-item>\n \n <md-menu-divider></md-menu-divider>\n <md-menu-item>\n <md-menu>\n <md-button\n ng-click = \"$mdOpenMenu()\">Learn</md-button>\n <md-menu-content>\n <md-menu-item>\n <md-button\n ng-click = \"ctrl.sampleAction('HTML5', $event)\">\n HTML5</md-button>\n </md-menu-item>\n \n <md-menu-item>\n <md-button\n ng-click = \"ctrl.sampleAction('jQuery', $event)\">\n jQuery</md-button>\n </md-menu-item>\n \n <md-menu-item>\n <md-button\n ng-click = \"ctrl.sampleAction('AngularJS', $event)\">\n AngularJS</md-button>\n </md-menu-item>\n \n <md-menu-item>\n <md-button disabled = \"disabled\"\n ng-click = \"ctrl.sampleAction('AngularJS 2.0', $event)\">\n AngularJS 2.0</md-button>\n </md-menu-item>\n \n <md-menu-divider></md-menu-divider>\n <md-menu-item>\n <md-button\n ng-click = \"ctrl.sampleAction('CSS', $event)\">\n CSS</md-button>\n </md-menu-item>\n </md-menu-content>\n </md-menu>\n </md-menu-item>\n \n </md-menu-content>\n </md-menu>\n </md-menu-bar>\n </div>\n </div>\n </md-toolbar>\t \t\t \n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 7113,
"s": 7094,
"text": "Verify the result."
},
{
"code": null,
"e": 7148,
"s": 7113,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7162,
"s": 7148,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7197,
"s": 7162,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7211,
"s": 7197,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7246,
"s": 7211,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7266,
"s": 7246,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7301,
"s": 7266,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7318,
"s": 7301,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7351,
"s": 7318,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7363,
"s": 7351,
"text": " Senol Atac"
},
{
"code": null,
"e": 7398,
"s": 7363,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7410,
"s": 7398,
"text": " Senol Atac"
},
{
"code": null,
"e": 7417,
"s": 7410,
"text": " Print"
},
{
"code": null,
"e": 7428,
"s": 7417,
"text": " Add Notes"
}
] |
Count distinct elements from a range of a sorted sequence from a given frequency array - GeeksforGeeks
|
12 Jun, 2021
Given two integers L and R and an array arr[] consisting of N positive integers( 1-based indexing ) such that the frequency of ith element of a sorted sequence, say A[], is arr[i]. The task is to find the number of distinct elements from the range [L, R] in the sequence A[].
Examples:
Input: arr[] = {3, 6, 7, 1, 8}, L = 3, R = 7Output: 2Explanation: From the given frequency array, the sorted array will be {1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, ....}. Now, the number of distinct elements from the range [3, 7] is 2( = {1, 2}).
Input: arr[] = {1, 2, 3, 4}, L = 3, R = 4Output: 1
Naive Approach: The simplest approach to solve the given problem is to construct the sorted sequence from the given array arr[] using the given frequencies and then traverse the constructed array over the range [L, R] to count the number of distinct elements.
Time Complexity: O(N + R – L)Auxiliary Space: O(S), where S is the sum of the array elements.
Efficient Approach: The above approach can be optimized by using the Binary Search and the prefix sum technique to find the number of distinct elements over the range [L, R]. Follow the steps below to solve the given problem:
Initialize an auxiliary array, say prefix[] that stores the prefix sum of the given array elements.
Find the prefix sum of the given array and stored it in the array prefix[].
By using binary search, find the first index at which the value in prefix[] is at least L, say left.
By using binary search, find the first index at which the value in prefix[] is at least R, say right.
After completing the above steps, print the value of (right – left + 1) as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the first index// with value is at least elementint binarysearch(int array[], int right, int element){ // Update the value of left int left = 1; // Update the value of right // Binary search for the element while (left <= right) { // Find the middle element int mid = (left + right / 2); if (array[mid] == element) { return mid; } // Check if the value lies // between the elements at // index mid - 1 and mid if (mid - 1 > 0 && array[mid] > element && array[mid - 1] < element) { return mid; } // Check in the right subarray else if (array[mid] < element) { // Update the value // of left left = mid + 1; } // Check in left subarray else { // Update the value of // right right = mid - 1; } } return 1;} // Function to count the number of// distinct elements over the range// [L, R] in the sorted sequencevoid countDistinct(vector<int> arr, int L, int R){ // Stores the count of distinct // elements int count = 0; // Create the prefix sum array int pref[arr.size() + 1]; for(int i = 1; i <= arr.size(); ++i) { // Update the value of count count += arr[i - 1]; // Update the value of pref[i] pref[i] = count; } // Calculating the first index // of L and R using binary search int left = binarysearch(pref, arr.size() + 1, L); int right = binarysearch(pref, arr.size() + 1, R); // Print the resultant count cout << right - left + 1;} // Driver Codeint main(){ vector<int> arr{ 3, 6, 7, 1, 8 }; int L = 3; int R = 7; countDistinct(arr, L, R);} // This code is contributed by ipg2016107
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to find the first index // with value is at least element static int binarysearch(int array[], int element) { // Update the value of left int left = 1; // Update the value of right int right = array.length - 1; // Binary search for the element while (left <= right) { // Find the middle element int mid = (int)(left + right / 2); if (array[mid] == element) { return mid; } // Check if the value lies // between the elements at // index mid - 1 and mid if (mid - 1 > 0 && array[mid] > element && array[mid - 1] < element) { return mid; } // Check in the right subarray else if (array[mid] < element) { // Update the value // of left left = mid + 1; } // Check in left subarray else { // Update the value of // right right = mid - 1; } } return 1; } // Function to count the number of // distinct elements over the range // [L, R] in the sorted sequence static void countDistinct(int arr[], int L, int R) { // Stores the count of distinct // elements int count = 0; // Create the prefix sum array int pref[] = new int[arr.length + 1]; for (int i = 1; i <= arr.length; ++i) { // Update the value of count count += arr[i - 1]; // Update the value of pref[i] pref[i] = count; } // Calculating the first index // of L and R using binary search int left = binarysearch(pref, L); int right = binarysearch(pref, R); // Print the resultant count System.out.println( (right - left) + 1); } // Driver Code public static void main(String[] args) { int arr[] = { 3, 6, 7, 1, 8 }; int L = 3; int R = 7; countDistinct(arr, L, R); }}
# Python3 program for the above approach # Function to find the first index# with value is at least elementdef binarysearch(array, right, element): # Update the value of left left = 1 # Update the value of right # Binary search for the element while (left <= right): # Find the middle element mid = (left + right // 2) if (array[mid] == element): return mid # Check if the value lies # between the elements at # index mid - 1 and mid if (mid - 1 > 0 and array[mid] > element and array[mid - 1] < element): return mid # Check in the right subarray elif (array[mid] < element): # Update the value # of left left = mid + 1 # Check in left subarray else: # Update the value of # right right = mid - 1 return 1 # Function to count the number of# distinct elements over the range# [L, R] in the sorted sequencedef countDistinct(arr, L, R): # Stores the count of distinct # elements count = 0 # Create the prefix sum array pref = [0] * (len(arr) + 1) for i in range(1, len(arr) + 1): # Update the value of count count += arr[i - 1] # Update the value of pref[i] pref[i] = count # Calculating the first index # of L and R using binary search left = binarysearch(pref, len(arr) + 1, L) right = binarysearch(pref, len(arr) + 1, R) # Print the resultant count print(right - left + 1) # Driver Codeif __name__ == "__main__": arr = [ 3, 6, 7, 1, 8 ] L = 3 R = 7 countDistinct(arr, L, R) # This code is contributed by ukasp
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the first index// with value is at least elementstatic int binarysearch(int []array, int right, int element){ // Update the value of left int left = 1; // Update the value of right // Binary search for the element while (left <= right) { // Find the middle element int mid = (left + right / 2); if (array[mid] == element) { return mid; } // Check if the value lies // between the elements at // index mid - 1 and mid if (mid - 1 > 0 && array[mid] > element && array[mid - 1] < element) { return mid; } // Check in the right subarray else if (array[mid] < element) { // Update the value // of left left = mid + 1; } // Check in left subarray else { // Update the value of // right right = mid - 1; } } return 1;} // Function to count the number of// distinct elements over the range// [L, R] in the sorted sequencestatic void countDistinct(List<int> arr, int L, int R){ // Stores the count of distinct // elements int count = 0; // Create the prefix sum array int []pref = new int[arr.Count + 1]; for(int i = 1; i <= arr.Count; ++i) { // Update the value of count count += arr[i - 1]; // Update the value of pref[i] pref[i] = count; } // Calculating the first index // of L and R using binary search int left = binarysearch(pref, arr.Count + 1, L); int right = binarysearch(pref, arr.Count + 1, R); // Print the resultant count Console.Write(right - left + 1);} // Driver Codepublic static void Main(){ List<int> arr = new List<int>(){ 3, 6, 7, 1, 8 }; int L = 3; int R = 7; countDistinct(arr, L, R);}} // This code is contributed by SURENDRA_GANGWAR
<script> // Javascript program for the above approach // Function to find the first index// with value is at least elementfunction binarysearch(array, right, element){ // Update the value of left let left = 1; // Update the value of right // Binary search for the element while (left <= right) { // Find the middle element let mid = Math.floor((left + right / 2)); if (array[mid] == element) { return mid; } // Check if the value lies // between the elements at // index mid - 1 and mid if (mid - 1 > 0 && array[mid] > element && array[mid - 1] < element) { return mid; } // Check in the right subarray else if (array[mid] < element) { // Update the value // of left left = mid + 1; } // Check in left subarray else { // Update the value of // right right = mid - 1; } } return 1;} // Function to count the number of// distinct elements over the range// [L, R] in the sorted sequencefunction countDistinct(arr, L, R){ // Stores the count of distinct // elements let count = 0; // Create the prefix sum array let pref = Array.from( {length: arr.length + 1}, (_, i) => 0); for(let i = 1; i <= arr.length; ++i) { // Update the value of count count += arr[i - 1]; // Update the value of pref[i] pref[i] = count; } // Calculating the first index // of L and R using binary search let left = binarysearch(pref, arr.length + 1, L); let right = binarysearch(pref, arr.length + 1, R); // Print the resultant count document.write((right - left) + 1);} // Driver Codelet arr = [ 3, 6, 7, 1, 8 ];let L = 3;let R = 7; countDistinct(arr, L, R); // This code is contributed by susmitakundugoaldanga </script>
2
Time Complexity: O(N)Auxiliary Space: O(N)
ipg2016107
SURENDRA_GANGWAR
susmitakundugoaldanga
ukasp
Binary Search
prefix
prefix-sum
Arrays
Mathematical
Searching
prefix-sum
Arrays
Searching
Mathematical
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n12 Jun, 2021"
},
{
"code": null,
"e": 25098,
"s": 24822,
"text": "Given two integers L and R and an array arr[] consisting of N positive integers( 1-based indexing ) such that the frequency of ith element of a sorted sequence, say A[], is arr[i]. The task is to find the number of distinct elements from the range [L, R] in the sequence A[]."
},
{
"code": null,
"e": 25108,
"s": 25098,
"text": "Examples:"
},
{
"code": null,
"e": 25351,
"s": 25108,
"text": "Input: arr[] = {3, 6, 7, 1, 8}, L = 3, R = 7Output: 2Explanation: From the given frequency array, the sorted array will be {1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, ....}. Now, the number of distinct elements from the range [3, 7] is 2( = {1, 2})."
},
{
"code": null,
"e": 25402,
"s": 25351,
"text": "Input: arr[] = {1, 2, 3, 4}, L = 3, R = 4Output: 1"
},
{
"code": null,
"e": 25662,
"s": 25402,
"text": "Naive Approach: The simplest approach to solve the given problem is to construct the sorted sequence from the given array arr[] using the given frequencies and then traverse the constructed array over the range [L, R] to count the number of distinct elements."
},
{
"code": null,
"e": 25756,
"s": 25662,
"text": "Time Complexity: O(N + R – L)Auxiliary Space: O(S), where S is the sum of the array elements."
},
{
"code": null,
"e": 25982,
"s": 25756,
"text": "Efficient Approach: The above approach can be optimized by using the Binary Search and the prefix sum technique to find the number of distinct elements over the range [L, R]. Follow the steps below to solve the given problem:"
},
{
"code": null,
"e": 26082,
"s": 25982,
"text": "Initialize an auxiliary array, say prefix[] that stores the prefix sum of the given array elements."
},
{
"code": null,
"e": 26158,
"s": 26082,
"text": "Find the prefix sum of the given array and stored it in the array prefix[]."
},
{
"code": null,
"e": 26259,
"s": 26158,
"text": "By using binary search, find the first index at which the value in prefix[] is at least L, say left."
},
{
"code": null,
"e": 26361,
"s": 26259,
"text": "By using binary search, find the first index at which the value in prefix[] is at least R, say right."
},
{
"code": null,
"e": 26448,
"s": 26361,
"text": "After completing the above steps, print the value of (right – left + 1) as the result."
},
{
"code": null,
"e": 26499,
"s": 26448,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26503,
"s": 26499,
"text": "C++"
},
{
"code": null,
"e": 26508,
"s": 26503,
"text": "Java"
},
{
"code": null,
"e": 26516,
"s": 26508,
"text": "Python3"
},
{
"code": null,
"e": 26519,
"s": 26516,
"text": "C#"
},
{
"code": null,
"e": 26530,
"s": 26519,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the first index// with value is at least elementint binarysearch(int array[], int right, int element){ // Update the value of left int left = 1; // Update the value of right // Binary search for the element while (left <= right) { // Find the middle element int mid = (left + right / 2); if (array[mid] == element) { return mid; } // Check if the value lies // between the elements at // index mid - 1 and mid if (mid - 1 > 0 && array[mid] > element && array[mid - 1] < element) { return mid; } // Check in the right subarray else if (array[mid] < element) { // Update the value // of left left = mid + 1; } // Check in left subarray else { // Update the value of // right right = mid - 1; } } return 1;} // Function to count the number of// distinct elements over the range// [L, R] in the sorted sequencevoid countDistinct(vector<int> arr, int L, int R){ // Stores the count of distinct // elements int count = 0; // Create the prefix sum array int pref[arr.size() + 1]; for(int i = 1; i <= arr.size(); ++i) { // Update the value of count count += arr[i - 1]; // Update the value of pref[i] pref[i] = count; } // Calculating the first index // of L and R using binary search int left = binarysearch(pref, arr.size() + 1, L); int right = binarysearch(pref, arr.size() + 1, R); // Print the resultant count cout << right - left + 1;} // Driver Codeint main(){ vector<int> arr{ 3, 6, 7, 1, 8 }; int L = 3; int R = 7; countDistinct(arr, L, R);} // This code is contributed by ipg2016107",
"e": 28569,
"s": 26530,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to find the first index // with value is at least element static int binarysearch(int array[], int element) { // Update the value of left int left = 1; // Update the value of right int right = array.length - 1; // Binary search for the element while (left <= right) { // Find the middle element int mid = (int)(left + right / 2); if (array[mid] == element) { return mid; } // Check if the value lies // between the elements at // index mid - 1 and mid if (mid - 1 > 0 && array[mid] > element && array[mid - 1] < element) { return mid; } // Check in the right subarray else if (array[mid] < element) { // Update the value // of left left = mid + 1; } // Check in left subarray else { // Update the value of // right right = mid - 1; } } return 1; } // Function to count the number of // distinct elements over the range // [L, R] in the sorted sequence static void countDistinct(int arr[], int L, int R) { // Stores the count of distinct // elements int count = 0; // Create the prefix sum array int pref[] = new int[arr.length + 1]; for (int i = 1; i <= arr.length; ++i) { // Update the value of count count += arr[i - 1]; // Update the value of pref[i] pref[i] = count; } // Calculating the first index // of L and R using binary search int left = binarysearch(pref, L); int right = binarysearch(pref, R); // Print the resultant count System.out.println( (right - left) + 1); } // Driver Code public static void main(String[] args) { int arr[] = { 3, 6, 7, 1, 8 }; int L = 3; int R = 7; countDistinct(arr, L, R); }}",
"e": 30851,
"s": 28569,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the first index# with value is at least elementdef binarysearch(array, right, element): # Update the value of left left = 1 # Update the value of right # Binary search for the element while (left <= right): # Find the middle element mid = (left + right // 2) if (array[mid] == element): return mid # Check if the value lies # between the elements at # index mid - 1 and mid if (mid - 1 > 0 and array[mid] > element and array[mid - 1] < element): return mid # Check in the right subarray elif (array[mid] < element): # Update the value # of left left = mid + 1 # Check in left subarray else: # Update the value of # right right = mid - 1 return 1 # Function to count the number of# distinct elements over the range# [L, R] in the sorted sequencedef countDistinct(arr, L, R): # Stores the count of distinct # elements count = 0 # Create the prefix sum array pref = [0] * (len(arr) + 1) for i in range(1, len(arr) + 1): # Update the value of count count += arr[i - 1] # Update the value of pref[i] pref[i] = count # Calculating the first index # of L and R using binary search left = binarysearch(pref, len(arr) + 1, L) right = binarysearch(pref, len(arr) + 1, R) # Print the resultant count print(right - left + 1) # Driver Codeif __name__ == \"__main__\": arr = [ 3, 6, 7, 1, 8 ] L = 3 R = 7 countDistinct(arr, L, R) # This code is contributed by ukasp",
"e": 32580,
"s": 30851,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the first index// with value is at least elementstatic int binarysearch(int []array, int right, int element){ // Update the value of left int left = 1; // Update the value of right // Binary search for the element while (left <= right) { // Find the middle element int mid = (left + right / 2); if (array[mid] == element) { return mid; } // Check if the value lies // between the elements at // index mid - 1 and mid if (mid - 1 > 0 && array[mid] > element && array[mid - 1] < element) { return mid; } // Check in the right subarray else if (array[mid] < element) { // Update the value // of left left = mid + 1; } // Check in left subarray else { // Update the value of // right right = mid - 1; } } return 1;} // Function to count the number of// distinct elements over the range// [L, R] in the sorted sequencestatic void countDistinct(List<int> arr, int L, int R){ // Stores the count of distinct // elements int count = 0; // Create the prefix sum array int []pref = new int[arr.Count + 1]; for(int i = 1; i <= arr.Count; ++i) { // Update the value of count count += arr[i - 1]; // Update the value of pref[i] pref[i] = count; } // Calculating the first index // of L and R using binary search int left = binarysearch(pref, arr.Count + 1, L); int right = binarysearch(pref, arr.Count + 1, R); // Print the resultant count Console.Write(right - left + 1);} // Driver Codepublic static void Main(){ List<int> arr = new List<int>(){ 3, 6, 7, 1, 8 }; int L = 3; int R = 7; countDistinct(arr, L, R);}} // This code is contributed by SURENDRA_GANGWAR",
"e": 34705,
"s": 32580,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the first index// with value is at least elementfunction binarysearch(array, right, element){ // Update the value of left let left = 1; // Update the value of right // Binary search for the element while (left <= right) { // Find the middle element let mid = Math.floor((left + right / 2)); if (array[mid] == element) { return mid; } // Check if the value lies // between the elements at // index mid - 1 and mid if (mid - 1 > 0 && array[mid] > element && array[mid - 1] < element) { return mid; } // Check in the right subarray else if (array[mid] < element) { // Update the value // of left left = mid + 1; } // Check in left subarray else { // Update the value of // right right = mid - 1; } } return 1;} // Function to count the number of// distinct elements over the range// [L, R] in the sorted sequencefunction countDistinct(arr, L, R){ // Stores the count of distinct // elements let count = 0; // Create the prefix sum array let pref = Array.from( {length: arr.length + 1}, (_, i) => 0); for(let i = 1; i <= arr.length; ++i) { // Update the value of count count += arr[i - 1]; // Update the value of pref[i] pref[i] = count; } // Calculating the first index // of L and R using binary search let left = binarysearch(pref, arr.length + 1, L); let right = binarysearch(pref, arr.length + 1, R); // Print the resultant count document.write((right - left) + 1);} // Driver Codelet arr = [ 3, 6, 7, 1, 8 ];let L = 3;let R = 7; countDistinct(arr, L, R); // This code is contributed by susmitakundugoaldanga </script>",
"e": 36724,
"s": 34705,
"text": null
},
{
"code": null,
"e": 36726,
"s": 36724,
"text": "2"
},
{
"code": null,
"e": 36771,
"s": 36728,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 36782,
"s": 36771,
"text": "ipg2016107"
},
{
"code": null,
"e": 36799,
"s": 36782,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 36821,
"s": 36799,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 36827,
"s": 36821,
"text": "ukasp"
},
{
"code": null,
"e": 36841,
"s": 36827,
"text": "Binary Search"
},
{
"code": null,
"e": 36848,
"s": 36841,
"text": "prefix"
},
{
"code": null,
"e": 36859,
"s": 36848,
"text": "prefix-sum"
},
{
"code": null,
"e": 36866,
"s": 36859,
"text": "Arrays"
},
{
"code": null,
"e": 36879,
"s": 36866,
"text": "Mathematical"
},
{
"code": null,
"e": 36889,
"s": 36879,
"text": "Searching"
},
{
"code": null,
"e": 36900,
"s": 36889,
"text": "prefix-sum"
},
{
"code": null,
"e": 36907,
"s": 36900,
"text": "Arrays"
},
{
"code": null,
"e": 36917,
"s": 36907,
"text": "Searching"
},
{
"code": null,
"e": 36930,
"s": 36917,
"text": "Mathematical"
},
{
"code": null,
"e": 36944,
"s": 36930,
"text": "Binary Search"
},
{
"code": null,
"e": 37042,
"s": 36944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37067,
"s": 37042,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 37087,
"s": 37067,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 37125,
"s": 37087,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 37210,
"s": 37125,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 37259,
"s": 37210,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 37289,
"s": 37259,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 37349,
"s": 37289,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37364,
"s": 37349,
"text": "C++ Data Types"
},
{
"code": null,
"e": 37407,
"s": 37364,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Clear LRU Cache in Python - GeeksforGeeks
|
10 Jul, 2020
The LRU is the Least Recently Used cache. LRU Cache is a type of high-speed memory, that is used to quicken the retrieval speed of frequently used data. It is implemented with the help of Queue and Hash data structures.
Note: For more information, refer to Python – LRU Cache
Python’s functool module has provided functionality to interact with the LRU Cache since Python 3.2. The functool module offers a decorator that can be placed atop a Class of a function in Python. When used on functions that require large amounts of variable access and change operations, using the LRU Cache offers massive speed-up.
Example:
import functools @functools.lru_cache(maxsize = None)def gfg(): # insert function logic here pass
Alternatively, the maxsize can be changed to suit one’s own preference. The value is measured in kbs, and maxsize takes an integer argument
After the use of the cache, cache_clear() can be used for clearing or invalidating the cache.
Example 1:
import functools @functools.lru_cache(maxsize = None)def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) fib(30) # Before Clearingprint(fib.cache_info()) fib.cache_clear() # After Clearingprint(fib.cache_info())
Output:
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)
CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)
Example 2: Additionally one can also call cache_clear() from another function as well
import functools @functools.lru_cache(maxsize = None)def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) def gfg(): fib.cache_clear() fib(30) # Before Clearingprint(fib.cache_info()) gfg() # After Clearingprint(fib.cache_info())
Output:
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)
CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)
These methods have limitations as they are individualized, and the cache_clear() function must be typed out for each and every LRU Cache utilizing the function. We can overcome this problem, by using Python’s inbuilt garbage collection module to collect all objects that have LRU Cache Wrappers, and iteratively clear each object’s cache.
Example:
import gcimport functools @functools.lru_cache(maxsize = None)def gfg(): # insert function logic here pass @functools.lru_cache(maxsize = None)def gfg1(): # insert function logic here pass @functools.lru_cache(maxsize = None)def gfg2(): # insert function logic here pass gfg()gfg1()gfg2() gc.collect() # All objects collectedobjects = [i for i in gc.get_objects() if isinstance(i, functools._lru_cache_wrapper)] # All objects clearedfor object in objects: object.cache_clear()
Python functools-module
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
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24400,
"s": 24372,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 24620,
"s": 24400,
"text": "The LRU is the Least Recently Used cache. LRU Cache is a type of high-speed memory, that is used to quicken the retrieval speed of frequently used data. It is implemented with the help of Queue and Hash data structures."
},
{
"code": null,
"e": 24676,
"s": 24620,
"text": "Note: For more information, refer to Python – LRU Cache"
},
{
"code": null,
"e": 25010,
"s": 24676,
"text": "Python’s functool module has provided functionality to interact with the LRU Cache since Python 3.2. The functool module offers a decorator that can be placed atop a Class of a function in Python. When used on functions that require large amounts of variable access and change operations, using the LRU Cache offers massive speed-up."
},
{
"code": null,
"e": 25019,
"s": 25010,
"text": "Example:"
},
{
"code": "import functools @functools.lru_cache(maxsize = None)def gfg(): # insert function logic here pass",
"e": 25124,
"s": 25019,
"text": null
},
{
"code": null,
"e": 25264,
"s": 25124,
"text": "Alternatively, the maxsize can be changed to suit one’s own preference. The value is measured in kbs, and maxsize takes an integer argument"
},
{
"code": null,
"e": 25358,
"s": 25264,
"text": "After the use of the cache, cache_clear() can be used for clearing or invalidating the cache."
},
{
"code": null,
"e": 25369,
"s": 25358,
"text": "Example 1:"
},
{
"code": "import functools @functools.lru_cache(maxsize = None)def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) fib(30) # Before Clearingprint(fib.cache_info()) fib.cache_clear() # After Clearingprint(fib.cache_info())",
"e": 25609,
"s": 25369,
"text": null
},
{
"code": null,
"e": 25617,
"s": 25609,
"text": "Output:"
},
{
"code": null,
"e": 25728,
"s": 25617,
"text": "CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)\nCacheInfo(hits=0, misses=0, maxsize=None, currsize=0)"
},
{
"code": null,
"e": 25814,
"s": 25728,
"text": "Example 2: Additionally one can also call cache_clear() from another function as well"
},
{
"code": "import functools @functools.lru_cache(maxsize = None)def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) def gfg(): fib.cache_clear() fib(30) # Before Clearingprint(fib.cache_info()) gfg() # After Clearingprint(fib.cache_info())",
"e": 26075,
"s": 25814,
"text": null
},
{
"code": null,
"e": 26083,
"s": 26075,
"text": "Output:"
},
{
"code": null,
"e": 26194,
"s": 26083,
"text": "CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)\nCacheInfo(hits=0, misses=0, maxsize=None, currsize=0)"
},
{
"code": null,
"e": 26533,
"s": 26194,
"text": "These methods have limitations as they are individualized, and the cache_clear() function must be typed out for each and every LRU Cache utilizing the function. We can overcome this problem, by using Python’s inbuilt garbage collection module to collect all objects that have LRU Cache Wrappers, and iteratively clear each object’s cache."
},
{
"code": null,
"e": 26542,
"s": 26533,
"text": "Example:"
},
{
"code": "import gcimport functools @functools.lru_cache(maxsize = None)def gfg(): # insert function logic here pass @functools.lru_cache(maxsize = None)def gfg1(): # insert function logic here pass @functools.lru_cache(maxsize = None)def gfg2(): # insert function logic here pass gfg()gfg1()gfg2() gc.collect() # All objects collectedobjects = [i for i in gc.get_objects() if isinstance(i, functools._lru_cache_wrapper)] # All objects clearedfor object in objects: object.cache_clear()",
"e": 27058,
"s": 26542,
"text": null
},
{
"code": null,
"e": 27082,
"s": 27058,
"text": "Python functools-module"
},
{
"code": null,
"e": 27089,
"s": 27082,
"text": "Python"
},
{
"code": null,
"e": 27187,
"s": 27089,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27196,
"s": 27187,
"text": "Comments"
},
{
"code": null,
"e": 27209,
"s": 27196,
"text": "Old Comments"
},
{
"code": null,
"e": 27227,
"s": 27209,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27262,
"s": 27227,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27294,
"s": 27262,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27316,
"s": 27294,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27346,
"s": 27316,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27388,
"s": 27346,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27414,
"s": 27388,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27457,
"s": 27414,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27494,
"s": 27457,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Advance Features of Python - GeeksforGeeks
|
19 Feb, 2020
Python is a high-level, interpreted programming language that has easy syntax. Python codes are compiled line-by-line which makes the debugging of errors much easier and efficient. Python works on almost all types of platforms such as Windows, Mac, Linux, Raspberry Pi, etc. Python supports modules and packages, which encourages program modularity and code reuse. Python can be used to deal with large amounts of data and perform complex mathematical problems and can also be used for the development of applications.
Generator functions allow us to declare a function that behaves the same as an iterator, i.e. it can be used in place of a for loop. Generators are iterators, but they can only iterate over them once. Generators introduce the yield statement in Python which works a bit like return because it returns a value. A generator will create elements and store them in memory only as it needs them i.e one at a time. That means, if you have to create a large amount of floating-point numbers, you’ll only be storing them in memory one at a time!. This greatly simplifies the code and makes the code more efficient than a simple for loop.Example 1:-
# A simple generator functiondef my_func(): n = 1 print('First Number') # Generator function contains yield statements yield n n += 1 print('Second Number ') yield n n += 1 print('Last Number ') yield n # Using for loopfor number in my_func(): print(number)
Output:
First Number
1
Second Number
2
Last Number
3
Example 2:-
def str(my_str): length = len(my_str) for i in range(0, length ): yield my_str[i] # For loop to print the string as # it is using generators and for loop.for char in str("Shivam And Sachin"): print(char, end ="")
Output:
Shivam And Sachin
Note: For more information, refer to Generators in Python
Decorators are amongst the significant part of Python. They are very helpful to add functionality to a function that is implemented before without making any change to the original function. In Decorators, functions are passed as the argument into another function and then called inside the wrapper function. They allow us to wrap another function in order to extend the functionality of a wrapped function, without permanently modifying it. Decorators are usually called before the definition of a function you want to decorate. A decorator is very efficient when you want to give an updated code to existing code.
Example 1:-
def decorator(a_func): def wrapper(): print("Before executing function requiring decoration.") a_func() print("After executing requiring decoration.") return wrapper def function(): print("Function requiring decoration.") function() function = decorator(function) function()
Output:
Function requiring decoration.
Before executing function requiring decoration.
Function requiring decoration.
After executing requiring decoration.
Example 2:-
def flowerDecorator(func): def newFlowerPot(n): print("We are decorating the flower vase.") print("You wanted to keep % d flowers in the vase." % n) func(n) print("Our decoration is done.") return newFlowerPot def flowerPot(n): print("We have a flower vase.") flowerPot = flowerDecorator(flowerPot)flowerPot(5)
Output:
We are decorating the flower vase.
You wanted to keep 5 flowers in the vase.
We have a flower vase.
Our decoration is done.
Note: For more information, refer to Decorators in Python
Lambda function is a small anonymous function. These types of function can take any number of arguments but can have only one expression. Normal functions are defined using the def keyword whereas anonymous functions are defined using the keyword “lambda“. Lambda functions do not require the return statement, they always return the value obtained by evaluating the lambda expression.
Example:- Code for multiplying 3 numbers.
x = lambda a, b, c : a * b*cprint(x(5, 4, 3))
Output:
60
Example:- Code for adding 3 numbers.
x = lambda a, b, c : a + b+cprint(x(12, 40, 8))
Output:
60
Note: For more information, refer to Python lambda
Map() is an inbuilt Python function used to apply a function to a sequence of elements such as a list or a dictionary and returns a list of the results. Python map object is an iterator, so we can iterate over its elements. We can also convert map objects to sequence objects such as list, tuple, etc. It’s an easy and efficient way to perform operations such as mapping two lists or sequencing elements of a list or dictionary.
Example:- Code to convert string to its length.
def func(n): return len(n) a =('Singla', 'Shivam', 'Sachin')x = map(func, a)print(a) # convert the map into a list,# for readability:print(list(x))
Output:
('Singla', 'Shivam', 'Sachin')
[6, 6, 6]
Example:- Code to map number to its cube.
numbers = (1, 2, 3, 4)res = map(lambda x: x * x*x, numbers) # converting map object to listnumbersCube = list(res)print(numbersCube)
Output:
[1, 8, 27, 64]
Note: For more information, refer to Python map() function
Filter() is an inbuilt function that is quite similar to the Map function as it applies a function to a sequence (tuple, dictionary, list). The key difference is that filter() function takes a function and a sequence as arguments and returns an iterable, only yielding the items in sequence for which function returns True and all the items of the sequence which evaluates to False are removed. In simple words filter() method constructs an iterator from elements of an iterable for which a function returns true.
Example 1:-
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] # Function that filters out all # numbers which are multiple of 4def filter_numbers(num): if num % 4 == 0: return True else: return False filtered_numbers = filter(filter_numbers, numbers)filters = list(filtered_numbers)print(filters)
Output:
[4, 8, 12, 16, 20]
Example 2:-
# To sort all ages which # are above 20 yearsages = [35, 21, 17, 18, 24, 32, 50, 59, 26, 6, 14] def Func(x): if x < 20: return False else: return True adults = filter(Func, ages) for z in adults: print(z)
Output:
35
21
24
32
50
59
26
Note: For more information, refer to filter() in python
Zip() is an inbuilt Python function that gives us an iterator of tuples. Zip is a kind of container that holds real data within. It takes iterable elements as an input and returns an iterator on them (an iterator of tuples). It evaluates the iterable from left to right. We can use the resulting iterator to quickly and efficiently solve common programming problems, like creating dictionaries. Unzipping is just the reverse process of zipping and for unzipping we use the * character with the zip() function.
Example 1:-
# ZIPPING a = ("SHIVAM", "SACHIN", "VIKALP", "RAGHAV", "PRANAY")b = ("SINGLA", "SINGLA", "GARG", "GUPTA", "GUPTA") x = zip(a, b) # use the tuple() function to display# a readable version of the result:print(tuple(x))
Output:
((‘SHIVAM’, ‘SINGLA’), (‘SACHIN’, ‘SINGLA’), (‘VIKALP’, ‘GARG’), (‘RAGHAV’, ‘GUPTA’), (‘PRANAY’, ‘GUPTA’))
Example 2:-
# ZIPPING AND UNZIPPINGname = ['sachin', 'shivam', 'vikalp']age = [20, 18, 19] result = zip(name, age)result_list = list(result)print(result_list) n, a = zip(*result_list) print('name =', n)print('age =', a)
Output:
[('sachin', 20), ('shivam', 18), ('vikalp', 19)]
name = ('sachin', 'shivam', 'vikalp')
age = (20, 18, 19)
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
|
[
{
"code": null,
"e": 24032,
"s": 24004,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 24551,
"s": 24032,
"text": "Python is a high-level, interpreted programming language that has easy syntax. Python codes are compiled line-by-line which makes the debugging of errors much easier and efficient. Python works on almost all types of platforms such as Windows, Mac, Linux, Raspberry Pi, etc. Python supports modules and packages, which encourages program modularity and code reuse. Python can be used to deal with large amounts of data and perform complex mathematical problems and can also be used for the development of applications."
},
{
"code": null,
"e": 25192,
"s": 24551,
"text": "Generator functions allow us to declare a function that behaves the same as an iterator, i.e. it can be used in place of a for loop. Generators are iterators, but they can only iterate over them once. Generators introduce the yield statement in Python which works a bit like return because it returns a value. A generator will create elements and store them in memory only as it needs them i.e one at a time. That means, if you have to create a large amount of floating-point numbers, you’ll only be storing them in memory one at a time!. This greatly simplifies the code and makes the code more efficient than a simple for loop.Example 1:-"
},
{
"code": "# A simple generator functiondef my_func(): n = 1 print('First Number') # Generator function contains yield statements yield n n += 1 print('Second Number ') yield n n += 1 print('Last Number ') yield n # Using for loopfor number in my_func(): print(number) ",
"e": 25492,
"s": 25192,
"text": null
},
{
"code": null,
"e": 25500,
"s": 25492,
"text": "Output:"
},
{
"code": null,
"e": 25548,
"s": 25500,
"text": "First Number\n1\nSecond Number \n2\nLast Number \n3\n"
},
{
"code": null,
"e": 25560,
"s": 25548,
"text": "Example 2:-"
},
{
"code": "def str(my_str): length = len(my_str) for i in range(0, length ): yield my_str[i] # For loop to print the string as # it is using generators and for loop.for char in str(\"Shivam And Sachin\"): print(char, end =\"\")",
"e": 25790,
"s": 25560,
"text": null
},
{
"code": null,
"e": 25798,
"s": 25790,
"text": "Output:"
},
{
"code": null,
"e": 25817,
"s": 25798,
"text": "Shivam And Sachin\n"
},
{
"code": null,
"e": 25875,
"s": 25817,
"text": "Note: For more information, refer to Generators in Python"
},
{
"code": null,
"e": 26492,
"s": 25875,
"text": "Decorators are amongst the significant part of Python. They are very helpful to add functionality to a function that is implemented before without making any change to the original function. In Decorators, functions are passed as the argument into another function and then called inside the wrapper function. They allow us to wrap another function in order to extend the functionality of a wrapped function, without permanently modifying it. Decorators are usually called before the definition of a function you want to decorate. A decorator is very efficient when you want to give an updated code to existing code."
},
{
"code": null,
"e": 26504,
"s": 26492,
"text": "Example 1:-"
},
{
"code": "def decorator(a_func): def wrapper(): print(\"Before executing function requiring decoration.\") a_func() print(\"After executing requiring decoration.\") return wrapper def function(): print(\"Function requiring decoration.\") function() function = decorator(function) function()",
"e": 26821,
"s": 26504,
"text": null
},
{
"code": null,
"e": 26829,
"s": 26821,
"text": "Output:"
},
{
"code": null,
"e": 26978,
"s": 26829,
"text": "Function requiring decoration.\nBefore executing function requiring decoration.\nFunction requiring decoration.\nAfter executing requiring decoration.\n"
},
{
"code": null,
"e": 26990,
"s": 26978,
"text": "Example 2:-"
},
{
"code": "def flowerDecorator(func): def newFlowerPot(n): print(\"We are decorating the flower vase.\") print(\"You wanted to keep % d flowers in the vase.\" % n) func(n) print(\"Our decoration is done.\") return newFlowerPot def flowerPot(n): print(\"We have a flower vase.\") flowerPot = flowerDecorator(flowerPot)flowerPot(5)",
"e": 27346,
"s": 26990,
"text": null
},
{
"code": null,
"e": 27354,
"s": 27346,
"text": "Output:"
},
{
"code": null,
"e": 27479,
"s": 27354,
"text": "We are decorating the flower vase.\nYou wanted to keep 5 flowers in the vase.\nWe have a flower vase.\nOur decoration is done.\n"
},
{
"code": null,
"e": 27537,
"s": 27479,
"text": "Note: For more information, refer to Decorators in Python"
},
{
"code": null,
"e": 27923,
"s": 27537,
"text": "Lambda function is a small anonymous function. These types of function can take any number of arguments but can have only one expression. Normal functions are defined using the def keyword whereas anonymous functions are defined using the keyword “lambda“. Lambda functions do not require the return statement, they always return the value obtained by evaluating the lambda expression."
},
{
"code": null,
"e": 27965,
"s": 27923,
"text": "Example:- Code for multiplying 3 numbers."
},
{
"code": "x = lambda a, b, c : a * b*cprint(x(5, 4, 3))",
"e": 28011,
"s": 27965,
"text": null
},
{
"code": null,
"e": 28019,
"s": 28011,
"text": "Output:"
},
{
"code": null,
"e": 28023,
"s": 28019,
"text": "60\n"
},
{
"code": null,
"e": 28060,
"s": 28023,
"text": "Example:- Code for adding 3 numbers."
},
{
"code": "x = lambda a, b, c : a + b+cprint(x(12, 40, 8))",
"e": 28108,
"s": 28060,
"text": null
},
{
"code": null,
"e": 28116,
"s": 28108,
"text": "Output:"
},
{
"code": null,
"e": 28120,
"s": 28116,
"text": "60\n"
},
{
"code": null,
"e": 28171,
"s": 28120,
"text": "Note: For more information, refer to Python lambda"
},
{
"code": null,
"e": 28600,
"s": 28171,
"text": "Map() is an inbuilt Python function used to apply a function to a sequence of elements such as a list or a dictionary and returns a list of the results. Python map object is an iterator, so we can iterate over its elements. We can also convert map objects to sequence objects such as list, tuple, etc. It’s an easy and efficient way to perform operations such as mapping two lists or sequencing elements of a list or dictionary."
},
{
"code": null,
"e": 28648,
"s": 28600,
"text": "Example:- Code to convert string to its length."
},
{
"code": "def func(n): return len(n) a =('Singla', 'Shivam', 'Sachin')x = map(func, a)print(a) # convert the map into a list,# for readability:print(list(x))",
"e": 28802,
"s": 28648,
"text": null
},
{
"code": null,
"e": 28810,
"s": 28802,
"text": "Output:"
},
{
"code": null,
"e": 28852,
"s": 28810,
"text": "('Singla', 'Shivam', 'Sachin')\n[6, 6, 6]\n"
},
{
"code": null,
"e": 28894,
"s": 28852,
"text": "Example:- Code to map number to its cube."
},
{
"code": "numbers = (1, 2, 3, 4)res = map(lambda x: x * x*x, numbers) # converting map object to listnumbersCube = list(res)print(numbersCube)",
"e": 29028,
"s": 28894,
"text": null
},
{
"code": null,
"e": 29036,
"s": 29028,
"text": "Output:"
},
{
"code": null,
"e": 29052,
"s": 29036,
"text": "[1, 8, 27, 64]\n"
},
{
"code": null,
"e": 29111,
"s": 29052,
"text": "Note: For more information, refer to Python map() function"
},
{
"code": null,
"e": 29625,
"s": 29111,
"text": "Filter() is an inbuilt function that is quite similar to the Map function as it applies a function to a sequence (tuple, dictionary, list). The key difference is that filter() function takes a function and a sequence as arguments and returns an iterable, only yielding the items in sequence for which function returns True and all the items of the sequence which evaluates to False are removed. In simple words filter() method constructs an iterator from elements of an iterable for which a function returns true."
},
{
"code": null,
"e": 29637,
"s": 29625,
"text": "Example 1:-"
},
{
"code": "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] # Function that filters out all # numbers which are multiple of 4def filter_numbers(num): if num % 4 == 0: return True else: return False filtered_numbers = filter(filter_numbers, numbers)filters = list(filtered_numbers)print(filters)",
"e": 29987,
"s": 29637,
"text": null
},
{
"code": null,
"e": 29995,
"s": 29987,
"text": "Output:"
},
{
"code": null,
"e": 30015,
"s": 29995,
"text": "[4, 8, 12, 16, 20]\n"
},
{
"code": null,
"e": 30027,
"s": 30015,
"text": "Example 2:-"
},
{
"code": "# To sort all ages which # are above 20 yearsages = [35, 21, 17, 18, 24, 32, 50, 59, 26, 6, 14] def Func(x): if x < 20: return False else: return True adults = filter(Func, ages) for z in adults: print(z)",
"e": 30251,
"s": 30027,
"text": null
},
{
"code": null,
"e": 30259,
"s": 30251,
"text": "Output:"
},
{
"code": null,
"e": 30281,
"s": 30259,
"text": "35\n21\n24\n32\n50\n59\n26\n"
},
{
"code": null,
"e": 30337,
"s": 30281,
"text": "Note: For more information, refer to filter() in python"
},
{
"code": null,
"e": 30847,
"s": 30337,
"text": "Zip() is an inbuilt Python function that gives us an iterator of tuples. Zip is a kind of container that holds real data within. It takes iterable elements as an input and returns an iterator on them (an iterator of tuples). It evaluates the iterable from left to right. We can use the resulting iterator to quickly and efficiently solve common programming problems, like creating dictionaries. Unzipping is just the reverse process of zipping and for unzipping we use the * character with the zip() function."
},
{
"code": null,
"e": 30859,
"s": 30847,
"text": "Example 1:-"
},
{
"code": "# ZIPPING a = (\"SHIVAM\", \"SACHIN\", \"VIKALP\", \"RAGHAV\", \"PRANAY\")b = (\"SINGLA\", \"SINGLA\", \"GARG\", \"GUPTA\", \"GUPTA\") x = zip(a, b) # use the tuple() function to display# a readable version of the result:print(tuple(x))",
"e": 31079,
"s": 30859,
"text": null
},
{
"code": null,
"e": 31087,
"s": 31079,
"text": "Output:"
},
{
"code": null,
"e": 31194,
"s": 31087,
"text": "((‘SHIVAM’, ‘SINGLA’), (‘SACHIN’, ‘SINGLA’), (‘VIKALP’, ‘GARG’), (‘RAGHAV’, ‘GUPTA’), (‘PRANAY’, ‘GUPTA’))"
},
{
"code": null,
"e": 31206,
"s": 31194,
"text": "Example 2:-"
},
{
"code": "# ZIPPING AND UNZIPPINGname = ['sachin', 'shivam', 'vikalp']age = [20, 18, 19] result = zip(name, age)result_list = list(result)print(result_list) n, a = zip(*result_list) print('name =', n)print('age =', a)",
"e": 31417,
"s": 31206,
"text": null
},
{
"code": null,
"e": 31425,
"s": 31417,
"text": "Output:"
},
{
"code": null,
"e": 31532,
"s": 31425,
"text": "[('sachin', 20), ('shivam', 18), ('vikalp', 19)]\nname = ('sachin', 'shivam', 'vikalp')\nage = (20, 18, 19)\n"
},
{
"code": null,
"e": 31556,
"s": 31532,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 31563,
"s": 31556,
"text": "Python"
},
{
"code": null,
"e": 31582,
"s": 31563,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31680,
"s": 31582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31689,
"s": 31680,
"text": "Comments"
},
{
"code": null,
"e": 31702,
"s": 31689,
"text": "Old Comments"
},
{
"code": null,
"e": 31737,
"s": 31702,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31759,
"s": 31737,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31791,
"s": 31759,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31821,
"s": 31791,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31863,
"s": 31821,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31889,
"s": 31863,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31932,
"s": 31889,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 31969,
"s": 31932,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 32013,
"s": 31969,
"text": "Reading and Writing to text files in Python"
}
] |
Bar chart using Plotly in Python - GeeksforGeeks
|
08 Jul, 2021
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library.
In a bar chart the data categories are displayed on the vertical axis and the data values are displayed on the horizontal axis. Labels are easier to display and with a big data set they impel to work better in a narrow layout such as mobile view.
Syntax: plotly.express.bar(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, hover_name=None, hover_data=None, custom_data=None, text=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, color_discrete_sequence=None, color_discrete_map={}, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, opacity=None, orientation=None, barmode=’relative’, log_x=False, log_y=False, range_x=None, range_y=None, title=None, template=None, width=None, height=None)
Parameters:
In this example, we are going to use Plotly express to plot a bar chart.
Python3
import plotly.express as pximport numpy # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1, 101, 100)random_y= np.random.randint(1, 101, 100) fig = px.bar(random_x, y = random_y)fig.show()
Output:
Example 1: In this example, we will use the iris data set and convert it into the dataframe to plot bar chart.
Python3
import plotly.express as px df = px.data.iris() fig = px.bar(df, x = "sepal_width", y = "sepal_length")fig.show()
Output:
Example 2: In this example, we will see long-form data. long-form data has one row per observation, and one column per variable. This is suitable for storing and displaying multivariate data i.e. with dimensions greater than 2. This format is sometimes called “tidy”.
Python3
import plotly.express as pxlong_df = px.data.medals_long() fig = px.bar(long_df, x = "nation", y = "count", color = "medal", title = "Long-Form Input")fig.show()
Output:
Example 3: In this example, we will see wide-from data. wide-form data has one row per value of one of the first variable, and one column per value of the second variable. This is suitable for storing and displaying 2-dimensional data.
Python3
import plotly.express as pxdf = px.data.medals_wide() fig = px.bar(df, x="nation", y=["gold", "silver", "bronze"], title="Wide Form Data")fig.show()
Output:
In plotly, to create the facetted subplots facet_row argument is used, where different values correspond to different rows of the dataframe columns.
Example:
Python3
import plotly.express as px df = px.data.iris() fig = px.bar(df, x="sepal_width", y="sepal_length", color="species", barmode="group", facet_row="species", facet_col="species_id") fig.show()
Output:
By using keyword arguments the bar mode can be customized. Let’s see the examples given below:
Example 1: In this example, the bar is customizing according to the color attributes.
Python3
import plotly.express as px df = px.data.iris() fig = px.bar(df, x="sepal_width", y="sepal_length", color="species")fig.show()
Output:
Example 2: In this example, we will use barmode = “group”. With “group”, the bars are grouped with one another
Python3
import plotly.express as px df = px.data.iris() fig = px.bar(df, x="sepal_width", y="sepal_length", color="species", barmode = 'group')fig.show()
Output:
Example 3: Here, we will use “overlay” With “overlay”, the bars are overlaid with another. Here we see easily “opacity” to see multiple bars.
Python3
import plotly.express as px df = px.data.iris() fig = px.bar(df, x="sepal_width", y="sepal_length", color="species", barmode='overlay')fig.show()
Output:
kumar_satyam
sooda367
akshaysingh98088
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
|
[
{
"code": null,
"e": 24068,
"s": 24040,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 24372,
"s": 24068,
"text": "Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library. "
},
{
"code": null,
"e": 24620,
"s": 24372,
"text": "In a bar chart the data categories are displayed on the vertical axis and the data values are displayed on the horizontal axis. Labels are easier to display and with a big data set they impel to work better in a narrow layout such as mobile view. "
},
{
"code": null,
"e": 25238,
"s": 24620,
"text": "Syntax: plotly.express.bar(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, hover_name=None, hover_data=None, custom_data=None, text=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, color_discrete_sequence=None, color_discrete_map={}, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, opacity=None, orientation=None, barmode=’relative’, log_x=False, log_y=False, range_x=None, range_y=None, title=None, template=None, width=None, height=None)"
},
{
"code": null,
"e": 25250,
"s": 25238,
"text": "Parameters:"
},
{
"code": null,
"e": 25323,
"s": 25250,
"text": "In this example, we are going to use Plotly express to plot a bar chart."
},
{
"code": null,
"e": 25331,
"s": 25323,
"text": "Python3"
},
{
"code": "import plotly.express as pximport numpy # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1, 101, 100)random_y= np.random.randint(1, 101, 100) fig = px.bar(random_x, y = random_y)fig.show()",
"e": 25586,
"s": 25331,
"text": null
},
{
"code": null,
"e": 25595,
"s": 25586,
"text": " Output:"
},
{
"code": null,
"e": 25708,
"s": 25597,
"text": "Example 1: In this example, we will use the iris data set and convert it into the dataframe to plot bar chart."
},
{
"code": null,
"e": 25716,
"s": 25708,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.bar(df, x = \"sepal_width\", y = \"sepal_length\")fig.show()",
"e": 25830,
"s": 25716,
"text": null
},
{
"code": null,
"e": 25839,
"s": 25830,
"text": " Output:"
},
{
"code": null,
"e": 26107,
"s": 25839,
"text": "Example 2: In this example, we will see long-form data. long-form data has one row per observation, and one column per variable. This is suitable for storing and displaying multivariate data i.e. with dimensions greater than 2. This format is sometimes called “tidy”."
},
{
"code": null,
"e": 26115,
"s": 26107,
"text": "Python3"
},
{
"code": "import plotly.express as pxlong_df = px.data.medals_long() fig = px.bar(long_df, x = \"nation\", y = \"count\", color = \"medal\", title = \"Long-Form Input\")fig.show()",
"e": 26289,
"s": 26115,
"text": null
},
{
"code": null,
"e": 26297,
"s": 26289,
"text": "Output:"
},
{
"code": null,
"e": 26533,
"s": 26297,
"text": "Example 3: In this example, we will see wide-from data. wide-form data has one row per value of one of the first variable, and one column per value of the second variable. This is suitable for storing and displaying 2-dimensional data."
},
{
"code": null,
"e": 26541,
"s": 26533,
"text": "Python3"
},
{
"code": "import plotly.express as pxdf = px.data.medals_wide() fig = px.bar(df, x=\"nation\", y=[\"gold\", \"silver\", \"bronze\"], title=\"Wide Form Data\")fig.show()",
"e": 26714,
"s": 26541,
"text": null
},
{
"code": null,
"e": 26722,
"s": 26714,
"text": "Output:"
},
{
"code": null,
"e": 26871,
"s": 26722,
"text": "In plotly, to create the facetted subplots facet_row argument is used, where different values correspond to different rows of the dataframe columns."
},
{
"code": null,
"e": 26880,
"s": 26871,
"text": "Example:"
},
{
"code": null,
"e": 26888,
"s": 26880,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.bar(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\", barmode=\"group\", facet_row=\"species\", facet_col=\"species_id\") fig.show()",
"e": 27102,
"s": 26888,
"text": null
},
{
"code": null,
"e": 27111,
"s": 27102,
"text": " Output:"
},
{
"code": null,
"e": 27206,
"s": 27111,
"text": "By using keyword arguments the bar mode can be customized. Let’s see the examples given below:"
},
{
"code": null,
"e": 27293,
"s": 27206,
"text": "Example 1: In this example, the bar is customizing according to the color attributes. "
},
{
"code": null,
"e": 27301,
"s": 27293,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.bar(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\")fig.show()",
"e": 27428,
"s": 27301,
"text": null
},
{
"code": null,
"e": 27437,
"s": 27428,
"text": " Output:"
},
{
"code": null,
"e": 27548,
"s": 27437,
"text": "Example 2: In this example, we will use barmode = “group”. With “group”, the bars are grouped with one another"
},
{
"code": null,
"e": 27556,
"s": 27548,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.bar(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\", barmode = 'group')fig.show()",
"e": 27714,
"s": 27556,
"text": null
},
{
"code": null,
"e": 27722,
"s": 27714,
"text": "Output:"
},
{
"code": null,
"e": 27864,
"s": 27722,
"text": "Example 3: Here, we will use “overlay” With “overlay”, the bars are overlaid with another. Here we see easily “opacity” to see multiple bars."
},
{
"code": null,
"e": 27872,
"s": 27864,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() fig = px.bar(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\", barmode='overlay')fig.show()",
"e": 28030,
"s": 27872,
"text": null
},
{
"code": null,
"e": 28038,
"s": 28030,
"text": "Output:"
},
{
"code": null,
"e": 28053,
"s": 28040,
"text": "kumar_satyam"
},
{
"code": null,
"e": 28062,
"s": 28053,
"text": "sooda367"
},
{
"code": null,
"e": 28079,
"s": 28062,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 28093,
"s": 28079,
"text": "Python-Plotly"
},
{
"code": null,
"e": 28100,
"s": 28093,
"text": "Python"
},
{
"code": null,
"e": 28198,
"s": 28100,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28207,
"s": 28198,
"text": "Comments"
},
{
"code": null,
"e": 28220,
"s": 28207,
"text": "Old Comments"
},
{
"code": null,
"e": 28248,
"s": 28220,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28298,
"s": 28248,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28320,
"s": 28298,
"text": "Python map() function"
},
{
"code": null,
"e": 28364,
"s": 28320,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 28382,
"s": 28364,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28405,
"s": 28382,
"text": "Taking input in Python"
},
{
"code": null,
"e": 28440,
"s": 28405,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28472,
"s": 28440,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28494,
"s": 28472,
"text": "Enumerate() in Python"
}
] |
How to Enable Webcam in Angular 10 using ngx-webcam ? - GeeksforGeeks
|
21 Aug, 2020
ngx-webcam component provides access of webcam to take snapshots simply via actions and event-bindings in Angular 10. This component gives us full control and permission to capture images in an easy way.
Steps to add webcam to your application:
Install Angular 10
Create a Angular CLI Project
Install the package by standard npm command :npm i ngx-webcam
npm i ngx-webcam
Add the WebcamModule component import to app.module.ts file as shown below:
Now add the WebcamImage component from ngx-webcam package library in app.component.ts file and use it in AppComponent Class to handle the functionality of webcam.import { Component } from '@angular/core';import {WebcamImage} from 'ngx-webcam';import {Subject, Observable} from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent { title = 'gfgangularwebcam'; public webcamImage: WebcamImage = null; private trigger: Subject<void> = new Subject<void>(); triggerSnapshot(): void { this.trigger.next(); } handleImage(webcamImage: WebcamImage): void { console.info('Saved webcam image', webcamImage); this.webcamImage = webcamImage; } public get triggerObservable(): Observable<void> { return this.trigger.asObservable(); }}
import { Component } from '@angular/core';import {WebcamImage} from 'ngx-webcam';import {Subject, Observable} from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent { title = 'gfgangularwebcam'; public webcamImage: WebcamImage = null; private trigger: Subject<void> = new Subject<void>(); triggerSnapshot(): void { this.trigger.next(); } handleImage(webcamImage: WebcamImage): void { console.info('Saved webcam image', webcamImage); this.webcamImage = webcamImage; } public get triggerObservable(): Observable<void> { return this.trigger.asObservable(); }}
Below is the app.component.html code:<div><webcam [height]="400" [width]="1000" [trigger]="triggerObservable" (imageCapture)="handleImage($event)"> </webcam> <button class="actionBtn" (click)="triggerSnapshot();"> Click Here and take the Shot</button> <div class="snapshot" *ngIf="webcamImage"> <h2>Here is your image!</h2> <img [src]="webcamImage.imageAsDataUrl"/></div>
<div><webcam [height]="400" [width]="1000" [trigger]="triggerObservable" (imageCapture)="handleImage($event)"> </webcam> <button class="actionBtn" (click)="triggerSnapshot();"> Click Here and take the Shot</button> <div class="snapshot" *ngIf="webcamImage"> <h2>Here is your image!</h2> <img [src]="webcamImage.imageAsDataUrl"/></div>
To run this application, run the following command at the terminal:ng serve --open
ng serve --open
Go to the browser and open the Localhost:4200:
Press the button and see the output snapshot:
AngularJS-Misc
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
How to set focus on input field automatically on page load in AngularJS ?
How to bundle an Angular app for production?
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
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24249,
"s": 24221,
"text": "\n21 Aug, 2020"
},
{
"code": null,
"e": 24453,
"s": 24249,
"text": "ngx-webcam component provides access of webcam to take snapshots simply via actions and event-bindings in Angular 10. This component gives us full control and permission to capture images in an easy way."
},
{
"code": null,
"e": 24494,
"s": 24453,
"text": "Steps to add webcam to your application:"
},
{
"code": null,
"e": 24513,
"s": 24494,
"text": "Install Angular 10"
},
{
"code": null,
"e": 24542,
"s": 24513,
"text": "Create a Angular CLI Project"
},
{
"code": null,
"e": 24604,
"s": 24542,
"text": "Install the package by standard npm command :npm i ngx-webcam"
},
{
"code": null,
"e": 24621,
"s": 24604,
"text": "npm i ngx-webcam"
},
{
"code": null,
"e": 24697,
"s": 24621,
"text": "Add the WebcamModule component import to app.module.ts file as shown below:"
},
{
"code": null,
"e": 25535,
"s": 24697,
"text": "Now add the WebcamImage component from ngx-webcam package library in app.component.ts file and use it in AppComponent Class to handle the functionality of webcam.import { Component } from '@angular/core';import {WebcamImage} from 'ngx-webcam';import {Subject, Observable} from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent { title = 'gfgangularwebcam'; public webcamImage: WebcamImage = null; private trigger: Subject<void> = new Subject<void>(); triggerSnapshot(): void { this.trigger.next(); } handleImage(webcamImage: WebcamImage): void { console.info('Saved webcam image', webcamImage); this.webcamImage = webcamImage; } public get triggerObservable(): Observable<void> { return this.trigger.asObservable(); }}"
},
{
"code": "import { Component } from '@angular/core';import {WebcamImage} from 'ngx-webcam';import {Subject, Observable} from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent { title = 'gfgangularwebcam'; public webcamImage: WebcamImage = null; private trigger: Subject<void> = new Subject<void>(); triggerSnapshot(): void { this.trigger.next(); } handleImage(webcamImage: WebcamImage): void { console.info('Saved webcam image', webcamImage); this.webcamImage = webcamImage; } public get triggerObservable(): Observable<void> { return this.trigger.asObservable(); }}",
"e": 26211,
"s": 25535,
"text": null
},
{
"code": null,
"e": 26617,
"s": 26211,
"text": "Below is the app.component.html code:<div><webcam [height]=\"400\" [width]=\"1000\" [trigger]=\"triggerObservable\" (imageCapture)=\"handleImage($event)\"> </webcam> <button class=\"actionBtn\" (click)=\"triggerSnapshot();\"> Click Here and take the Shot</button> <div class=\"snapshot\" *ngIf=\"webcamImage\"> <h2>Here is your image!</h2> <img [src]=\"webcamImage.imageAsDataUrl\"/></div>"
},
{
"code": "<div><webcam [height]=\"400\" [width]=\"1000\" [trigger]=\"triggerObservable\" (imageCapture)=\"handleImage($event)\"> </webcam> <button class=\"actionBtn\" (click)=\"triggerSnapshot();\"> Click Here and take the Shot</button> <div class=\"snapshot\" *ngIf=\"webcamImage\"> <h2>Here is your image!</h2> <img [src]=\"webcamImage.imageAsDataUrl\"/></div>",
"e": 26986,
"s": 26617,
"text": null
},
{
"code": null,
"e": 27069,
"s": 26986,
"text": "To run this application, run the following command at the terminal:ng serve --open"
},
{
"code": null,
"e": 27085,
"s": 27069,
"text": "ng serve --open"
},
{
"code": null,
"e": 27132,
"s": 27085,
"text": "Go to the browser and open the Localhost:4200:"
},
{
"code": null,
"e": 27178,
"s": 27132,
"text": "Press the button and see the output snapshot:"
},
{
"code": null,
"e": 27193,
"s": 27178,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 27203,
"s": 27193,
"text": "AngularJS"
},
{
"code": null,
"e": 27220,
"s": 27203,
"text": "Web Technologies"
},
{
"code": null,
"e": 27318,
"s": 27220,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27362,
"s": 27318,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 27393,
"s": 27362,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 27435,
"s": 27393,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 27509,
"s": 27435,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 27554,
"s": 27509,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 27596,
"s": 27554,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27629,
"s": 27596,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27672,
"s": 27629,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27734,
"s": 27672,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Multi-Class Text Classification with SKlearn and NLTK in python| A Software Engineering Use Case | by Nasir Safdari | Towards Data Science
|
Recently, I worked on a software engineering research project. one of the main objectives of the project was to understand the focus areas of work in the development teams. when the size of a software project becomes large, managing the workflow and the development process is more challenging. therefore, it is essential for the management team and lead developers to understand the type of work that is carried out by the software developers.
In more simple words, any developer at any time during different phases of the project can write pieces of code that aims to implement one of the followings:
Adding new features
Design improvements
Bug fixing
improving non-functional requirements
Now one might ask, are the above four categories the only types of software development activities done by the developers? and the answer is: No. the goal here is to come up with some general categories of work that encompasses the majority of development tasks.
Understanding how the work of development team is distributed regarding the mentioned four categories, can help the management to make better decisions on managing the growth of the software while continuously developing its functionalities. for example, if most of the work of development team is done toward bug-fixing, the management can take necessary actions to prevent faults and defects in the software and provide guidelines to the lead developers to pay more attention to the quality.
and the answer is: we can look at the commit messages; developers provide a commit message along with every commit they make to the repository. These commit messages are usually written using natural language, and generally convey some information about the commit they represent. we can build a classifier using some labeled data and then automatically classify future commits.
we collected around 4000 commit messages from several open source Java projects on github. we picked commit messages using an advanced search criteria based on specific key words for each category. then we assigned each category of commit messages to experienced developers to check commits one by one if they belong to their categories. after that, we cross checked the process by exchanging categories of commit messages among the developers to mitigate the subjectivity involved with manual labeling. finally, we ended up with almost 3400 commit messages including 282 commits that belonged to no category; we decided to add that as a label in the classification task so later on we can detect similar commit messages.
Let’s have a look at the data:
import pandas as pdimport reimport numpy as npimport matplotlib.pyplot as pltfrom nltk.corpus import stopwordsfrom nltk.stem import PorterStemmerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.pipeline import Pipelinefrom sklearn.metrics import classification_report, confusion_matrixfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_selection import SelectKBest, chi2from sqlite3 import Errorfrom sklearn.ensemble import RandomForestClassifierimport sqlite3import pickle%matplotlib inlinetry: conn = sqlite3.connect("training_V2.db")except Error as e: print(e)#reading the data from the table that contains the labels df = pd.read_sql_query('SELECT * FROM filtered', conn)df.drop(['id'], 1, inplace=True)df.head()
as you can see, we imported so many packages and we are going to use all of them to achieve our goal. looking at the top five rows of the dataframe, we can see that it has only two columns: text (the commit messages) and class (the labels).
1 represents commit messages for bug fixing.
2 represents commits that belong to no category.
3 represents commit messages for design improvement.
4 represents commit messages for adding new features.
5 represents commit messages for improving non-functional requirements.
lets have a look at their distribution:
df.groupby('class').text.count().plot.bar(ylim=0)plt.show()
it is natural to have a little bit of imbalance in the dataset since the commits were collected randomly from random open source projects.
now lets build our classifier. but hold on... our data is in natural text but it needs to be formatted into a columnar structure in order to work as input to the classification algorithms.
here is how it works:
first, we remove the punctuation, numbers, and stop words from each commit message.
second, all the words are converted to lower case and then stemmed using the Porter Stemmer in the NLTK package. The goal of stemming is to reduce the number of inflectional forms of words appearing in the commit; it will cause words such as “performance” and “performing” to syntactically match one another by reducing them to their base word “perform”. This helps decrease the size of the vocabulary space and improve the volume of the feature space in the corpus.
Finally, each corpus is transformed into vector space model (VSM) using the tf-idf vectorizer in Python’s SKlearn package to extract the features.
all of this is done in just few lines of code and that is the beauty of python.
stemmer = PorterStemmer()words = stopwords.words("english")df['cleaned'] = df['text'].apply(lambda x: " ".join([stemmer.stem(i) for i in re.sub("[^a-zA-Z]", " ", x).split() if i not in words]).lower())
vectorizer = TfidfVectorizer(min_df= 3, stop_words="english", sublinear_tf=True, norm='l2', ngram_range=(1, 2))final_features = vectorizer.fit_transform(df['cleaned']).toarray()final_features.shape(3377, 2389)
so we ended up with 2389 features after converting the text into vectors. now we proceed with building our model and fit the model with our data. another important question that we should ask here is that do we really need to use all 2389 features? when dealing with very long vectors, sometimes it might be better to select your best features instead of using all of them. to do so, we use the SelectKbest method from SKlearn.feature_selection package. then we use the Chi2 score that can be used to select the n_features features with the highest values for the test chi-squared. “ chi-square test measures dependence between stochastic variables, so using this function “weeds out” the features that are the most likely to be independent of class and therefore irrelevant for classification.” quoted from sklearn documentation.
while building the model, we can choose from a wide range of classification algorithms. we tested four different algorithm: KNN, Multinomial Naive Bayes, Linear SVC, and Random Forrest. I investigated each classifier and came to the conclusion using common statistical measures (precision and recall) of classification performance to compare each and Random Forrest seemed to perform better than the rest. based on my own experience, Random Forrest does a better job when you have a multi-class problem. you can test other classification algorithm and let me know if you find some that provide better results.
now let’s put everything into a pipeline. here we are performing a sequence of transformations: first we transform the tfidf vectorizer, then we select K best features, and finally we use the classifier to fit the data. so we do all of them at once using a pipeline:
#first we split our dataset into testing and training set:# this block is to split the dataset into training and testing set X = df['cleaned']Y = df['class']X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.25)# instead of doing these steps one at a time, we can use a pipeline to complete them all at oncepipeline = Pipeline([('vect', vectorizer), ('chi', SelectKBest(chi2, k=1200)), ('clf', RandomForestClassifier())])# fitting our model and save it in a pickle for later usemodel = pipeline.fit(X_train, y_train)with open('RandomForest.pickle', 'wb') as f: pickle.dump(model, f)ytest = np.array(y_test)# confusion matrix and classification report(precision, recall, F1-score)print(classification_report(ytest, model.predict(X_test)))print(confusion_matrix(ytest, model.predict(X_test))) precision recall f1-score support 1 0.99 0.98 0.99 271 2 0.91 0.91 0.91 47 3 0.98 1.00 0.99 116 4 0.99 0.99 0.99 143 5 0.98 0.99 0.98 268avg / total 0.98 0.98 0.98 845Confusion Matrix: 1 2 3 4 51[[266 1 0 0 4] 2[ 2 43 0 1 1] 3[ 0 0 116 0 0] 4[ 0 2 0 141 0] 5[ 0 1 2 1 264]]
0.98 precision and recall ...!!! hmmm ... that as my first reaction. but then I looked over the confusion matrix and saw that there are not many missclassifications for each class and I think we are in a good place. we achieved high precision and recall without even doing any parameter tuning for the classification algorithm!
Now I really want to check if this is going to work for another dataset. moreover, I would like to evaluate this using other metrics like: AUC score and have a look at the ROC curve since the data is a bit imbalanced. two more things to do to have a more complete understanding: first is to use gridsearch to tune the parameters and see if it actually helps improving the results. second, it will be good to have maybe top 5 most important keywords for each class so later on we can use those keywords for future searching purposes. but this article is already long enough so I will answer to those questions in my next article. stay tuned!
your feedback and questions are highly appreciated.
The source code, python notebook, and datasets for this project are available on my github.
|
[
{
"code": null,
"e": 617,
"s": 172,
"text": "Recently, I worked on a software engineering research project. one of the main objectives of the project was to understand the focus areas of work in the development teams. when the size of a software project becomes large, managing the workflow and the development process is more challenging. therefore, it is essential for the management team and lead developers to understand the type of work that is carried out by the software developers."
},
{
"code": null,
"e": 775,
"s": 617,
"text": "In more simple words, any developer at any time during different phases of the project can write pieces of code that aims to implement one of the followings:"
},
{
"code": null,
"e": 795,
"s": 775,
"text": "Adding new features"
},
{
"code": null,
"e": 815,
"s": 795,
"text": "Design improvements"
},
{
"code": null,
"e": 826,
"s": 815,
"text": "Bug fixing"
},
{
"code": null,
"e": 864,
"s": 826,
"text": "improving non-functional requirements"
},
{
"code": null,
"e": 1127,
"s": 864,
"text": "Now one might ask, are the above four categories the only types of software development activities done by the developers? and the answer is: No. the goal here is to come up with some general categories of work that encompasses the majority of development tasks."
},
{
"code": null,
"e": 1621,
"s": 1127,
"text": "Understanding how the work of development team is distributed regarding the mentioned four categories, can help the management to make better decisions on managing the growth of the software while continuously developing its functionalities. for example, if most of the work of development team is done toward bug-fixing, the management can take necessary actions to prevent faults and defects in the software and provide guidelines to the lead developers to pay more attention to the quality."
},
{
"code": null,
"e": 2000,
"s": 1621,
"text": "and the answer is: we can look at the commit messages; developers provide a commit message along with every commit they make to the repository. These commit messages are usually written using natural language, and generally convey some information about the commit they represent. we can build a classifier using some labeled data and then automatically classify future commits."
},
{
"code": null,
"e": 2722,
"s": 2000,
"text": "we collected around 4000 commit messages from several open source Java projects on github. we picked commit messages using an advanced search criteria based on specific key words for each category. then we assigned each category of commit messages to experienced developers to check commits one by one if they belong to their categories. after that, we cross checked the process by exchanging categories of commit messages among the developers to mitigate the subjectivity involved with manual labeling. finally, we ended up with almost 3400 commit messages including 282 commits that belonged to no category; we decided to add that as a label in the classification task so later on we can detect similar commit messages."
},
{
"code": null,
"e": 2753,
"s": 2722,
"text": "Let’s have a look at the data:"
},
{
"code": null,
"e": 3521,
"s": 2753,
"text": "import pandas as pdimport reimport numpy as npimport matplotlib.pyplot as pltfrom nltk.corpus import stopwordsfrom nltk.stem import PorterStemmerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.pipeline import Pipelinefrom sklearn.metrics import classification_report, confusion_matrixfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_selection import SelectKBest, chi2from sqlite3 import Errorfrom sklearn.ensemble import RandomForestClassifierimport sqlite3import pickle%matplotlib inlinetry: conn = sqlite3.connect(\"training_V2.db\")except Error as e: print(e)#reading the data from the table that contains the labels df = pd.read_sql_query('SELECT * FROM filtered', conn)df.drop(['id'], 1, inplace=True)df.head()"
},
{
"code": null,
"e": 3762,
"s": 3521,
"text": "as you can see, we imported so many packages and we are going to use all of them to achieve our goal. looking at the top five rows of the dataframe, we can see that it has only two columns: text (the commit messages) and class (the labels)."
},
{
"code": null,
"e": 3807,
"s": 3762,
"text": "1 represents commit messages for bug fixing."
},
{
"code": null,
"e": 3856,
"s": 3807,
"text": "2 represents commits that belong to no category."
},
{
"code": null,
"e": 3909,
"s": 3856,
"text": "3 represents commit messages for design improvement."
},
{
"code": null,
"e": 3963,
"s": 3909,
"text": "4 represents commit messages for adding new features."
},
{
"code": null,
"e": 4035,
"s": 3963,
"text": "5 represents commit messages for improving non-functional requirements."
},
{
"code": null,
"e": 4075,
"s": 4035,
"text": "lets have a look at their distribution:"
},
{
"code": null,
"e": 4135,
"s": 4075,
"text": "df.groupby('class').text.count().plot.bar(ylim=0)plt.show()"
},
{
"code": null,
"e": 4274,
"s": 4135,
"text": "it is natural to have a little bit of imbalance in the dataset since the commits were collected randomly from random open source projects."
},
{
"code": null,
"e": 4463,
"s": 4274,
"text": "now lets build our classifier. but hold on... our data is in natural text but it needs to be formatted into a columnar structure in order to work as input to the classification algorithms."
},
{
"code": null,
"e": 4485,
"s": 4463,
"text": "here is how it works:"
},
{
"code": null,
"e": 4569,
"s": 4485,
"text": "first, we remove the punctuation, numbers, and stop words from each commit message."
},
{
"code": null,
"e": 5036,
"s": 4569,
"text": "second, all the words are converted to lower case and then stemmed using the Porter Stemmer in the NLTK package. The goal of stemming is to reduce the number of inflectional forms of words appearing in the commit; it will cause words such as “performance” and “performing” to syntactically match one another by reducing them to their base word “perform”. This helps decrease the size of the vocabulary space and improve the volume of the feature space in the corpus."
},
{
"code": null,
"e": 5183,
"s": 5036,
"text": "Finally, each corpus is transformed into vector space model (VSM) using the tf-idf vectorizer in Python’s SKlearn package to extract the features."
},
{
"code": null,
"e": 5263,
"s": 5183,
"text": "all of this is done in just few lines of code and that is the beauty of python."
},
{
"code": null,
"e": 5465,
"s": 5263,
"text": "stemmer = PorterStemmer()words = stopwords.words(\"english\")df['cleaned'] = df['text'].apply(lambda x: \" \".join([stemmer.stem(i) for i in re.sub(\"[^a-zA-Z]\", \" \", x).split() if i not in words]).lower())"
},
{
"code": null,
"e": 5675,
"s": 5465,
"text": "vectorizer = TfidfVectorizer(min_df= 3, stop_words=\"english\", sublinear_tf=True, norm='l2', ngram_range=(1, 2))final_features = vectorizer.fit_transform(df['cleaned']).toarray()final_features.shape(3377, 2389)"
},
{
"code": null,
"e": 6506,
"s": 5675,
"text": "so we ended up with 2389 features after converting the text into vectors. now we proceed with building our model and fit the model with our data. another important question that we should ask here is that do we really need to use all 2389 features? when dealing with very long vectors, sometimes it might be better to select your best features instead of using all of them. to do so, we use the SelectKbest method from SKlearn.feature_selection package. then we use the Chi2 score that can be used to select the n_features features with the highest values for the test chi-squared. “ chi-square test measures dependence between stochastic variables, so using this function “weeds out” the features that are the most likely to be independent of class and therefore irrelevant for classification.” quoted from sklearn documentation."
},
{
"code": null,
"e": 7116,
"s": 6506,
"text": "while building the model, we can choose from a wide range of classification algorithms. we tested four different algorithm: KNN, Multinomial Naive Bayes, Linear SVC, and Random Forrest. I investigated each classifier and came to the conclusion using common statistical measures (precision and recall) of classification performance to compare each and Random Forrest seemed to perform better than the rest. based on my own experience, Random Forrest does a better job when you have a multi-class problem. you can test other classification algorithm and let me know if you find some that provide better results."
},
{
"code": null,
"e": 7383,
"s": 7116,
"text": "now let’s put everything into a pipeline. here we are performing a sequence of transformations: first we transform the tfidf vectorizer, then we select K best features, and finally we use the classifier to fit the data. so we do all of them at once using a pipeline:"
},
{
"code": null,
"e": 8758,
"s": 7383,
"text": "#first we split our dataset into testing and training set:# this block is to split the dataset into training and testing set X = df['cleaned']Y = df['class']X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.25)# instead of doing these steps one at a time, we can use a pipeline to complete them all at oncepipeline = Pipeline([('vect', vectorizer), ('chi', SelectKBest(chi2, k=1200)), ('clf', RandomForestClassifier())])# fitting our model and save it in a pickle for later usemodel = pipeline.fit(X_train, y_train)with open('RandomForest.pickle', 'wb') as f: pickle.dump(model, f)ytest = np.array(y_test)# confusion matrix and classification report(precision, recall, F1-score)print(classification_report(ytest, model.predict(X_test)))print(confusion_matrix(ytest, model.predict(X_test))) precision recall f1-score support 1 0.99 0.98 0.99 271 2 0.91 0.91 0.91 47 3 0.98 1.00 0.99 116 4 0.99 0.99 0.99 143 5 0.98 0.99 0.98 268avg / total 0.98 0.98 0.98 845Confusion Matrix: 1 2 3 4 51[[266 1 0 0 4] 2[ 2 43 0 1 1] 3[ 0 0 116 0 0] 4[ 0 2 0 141 0] 5[ 0 1 2 1 264]]"
},
{
"code": null,
"e": 9086,
"s": 8758,
"text": "0.98 precision and recall ...!!! hmmm ... that as my first reaction. but then I looked over the confusion matrix and saw that there are not many missclassifications for each class and I think we are in a good place. we achieved high precision and recall without even doing any parameter tuning for the classification algorithm!"
},
{
"code": null,
"e": 9727,
"s": 9086,
"text": "Now I really want to check if this is going to work for another dataset. moreover, I would like to evaluate this using other metrics like: AUC score and have a look at the ROC curve since the data is a bit imbalanced. two more things to do to have a more complete understanding: first is to use gridsearch to tune the parameters and see if it actually helps improving the results. second, it will be good to have maybe top 5 most important keywords for each class so later on we can use those keywords for future searching purposes. but this article is already long enough so I will answer to those questions in my next article. stay tuned!"
},
{
"code": null,
"e": 9779,
"s": 9727,
"text": "your feedback and questions are highly appreciated."
}
] |
Big Data Analytics - Text Analytics
|
In this chapter, we will be using the data scraped in the part 1 of the book. The data has text that describes profiles of freelancers, and the hourly rate they are charging in USD. The idea of the following section is to fit a model that given the skills of a freelancer, we are able to predict its hourly salary.
The following code shows how to convert the raw text that in this case has skills of a user in a bag of words matrix. For this we use an R library called tm. This means that for each word in the corpus we create variable with the amount of occurrences of each variable.
library(tm)
library(data.table)
source('text_analytics/text_analytics_functions.R')
data = fread('text_analytics/data/profiles.txt')
rate = as.numeric(data$rate)
keep = !is.na(rate)
rate = rate[keep]
### Make bag of words of title and body
X_all = bag_words(data$user_skills[keep])
X_all = removeSparseTerms(X_all, 0.999)
X_all
# <<DocumentTermMatrix (documents: 389, terms: 1422)>>
# Non-/sparse entries: 4057/549101
# Sparsity : 99%
# Maximal term length: 80
# Weighting : term frequency - inverse document frequency (normalized) (tf-idf)
### Make a sparse matrix with all the data
X_all <- as_sparseMatrix(X_all)
Now that we have the text represented as a sparse matrix we can fit a model that will give a sparse solution. A good alternative for this case is using the LASSO (least absolute shrinkage and selection operator). This is a regression model that is able to select the most relevant features to predict the target.
train_inx = 1:200
X_train = X_all[train_inx, ]
y_train = rate[train_inx]
X_test = X_all[-train_inx, ]
y_test = rate[-train_inx]
# Train a regression model
library(glmnet)
fit <- cv.glmnet(x = X_train, y = y_train,
family = 'gaussian', alpha = 1,
nfolds = 3, type.measure = 'mae')
plot(fit)
# Make predictions
predictions = predict(fit, newx = X_test)
predictions = as.vector(predictions[,1])
head(predictions)
# 36.23598 36.43046 51.69786 26.06811 35.13185 37.66367
# We can compute the mean absolute error for the test data
mean(abs(y_test - predictions))
# 15.02175
Now we have a model that given a set of skills is able to predict the hourly salary of a freelancer. If more data is collected, the performance of the model will improve, but the code to implement this pipeline would be the same.
65 Lectures
6 hours
Arnab Chakraborty
18 Lectures
1.5 hours
Pranjal Srivastava, Harshit Srivastava
23 Lectures
2 hours
John Shea
18 Lectures
1.5 hours
Pranjal Srivastava
46 Lectures
3.5 hours
Pranjal Srivastava
37 Lectures
3.5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2869,
"s": 2554,
"text": "In this chapter, we will be using the data scraped in the part 1 of the book. The data has text that describes profiles of freelancers, and the hourly rate they are charging in USD. The idea of the following section is to fit a model that given the skills of a freelancer, we are able to predict its hourly salary."
},
{
"code": null,
"e": 3139,
"s": 2869,
"text": "The following code shows how to convert the raw text that in this case has skills of a user in a bag of words matrix. For this we use an R library called tm. This means that for each word in the corpus we create variable with the amount of occurrences of each variable."
},
{
"code": null,
"e": 3799,
"s": 3139,
"text": "library(tm)\nlibrary(data.table) \n\nsource('text_analytics/text_analytics_functions.R') \ndata = fread('text_analytics/data/profiles.txt') \nrate = as.numeric(data$rate) \nkeep = !is.na(rate) \nrate = rate[keep] \n\n### Make bag of words of title and body \nX_all = bag_words(data$user_skills[keep]) \nX_all = removeSparseTerms(X_all, 0.999) \nX_all \n\n# <<DocumentTermMatrix (documents: 389, terms: 1422)>> \n# Non-/sparse entries: 4057/549101 \n# Sparsity : 99% \n# Maximal term length: 80 \n# Weighting : term frequency - inverse document frequency (normalized) (tf-idf) \n\n### Make a sparse matrix with all the data \nX_all <- as_sparseMatrix(X_all)\n"
},
{
"code": null,
"e": 4112,
"s": 3799,
"text": "Now that we have the text represented as a sparse matrix we can fit a model that will give a sparse solution. A good alternative for this case is using the LASSO (least absolute shrinkage and selection operator). This is a regression model that is able to select the most relevant features to predict the target."
},
{
"code": null,
"e": 4713,
"s": 4112,
"text": "train_inx = 1:200\nX_train = X_all[train_inx, ] \ny_train = rate[train_inx] \nX_test = X_all[-train_inx, ] \ny_test = rate[-train_inx] \n\n# Train a regression model \nlibrary(glmnet) \nfit <- cv.glmnet(x = X_train, y = y_train, \n family = 'gaussian', alpha = 1, \n nfolds = 3, type.measure = 'mae') \nplot(fit) \n\n# Make predictions \npredictions = predict(fit, newx = X_test) \npredictions = as.vector(predictions[,1]) \nhead(predictions) \n\n# 36.23598 36.43046 51.69786 26.06811 35.13185 37.66367 \n# We can compute the mean absolute error for the test data \nmean(abs(y_test - predictions)) \n# 15.02175\n"
},
{
"code": null,
"e": 4943,
"s": 4713,
"text": "Now we have a model that given a set of skills is able to predict the hourly salary of a freelancer. If more data is collected, the performance of the model will improve, but the code to implement this pipeline would be the same."
},
{
"code": null,
"e": 4976,
"s": 4943,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4995,
"s": 4976,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5030,
"s": 4995,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5070,
"s": 5030,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 5103,
"s": 5070,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5114,
"s": 5103,
"text": " John Shea"
},
{
"code": null,
"e": 5149,
"s": 5114,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5169,
"s": 5149,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5204,
"s": 5169,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5224,
"s": 5204,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5259,
"s": 5224,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5299,
"s": 5259,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 5306,
"s": 5299,
"text": " Print"
},
{
"code": null,
"e": 5317,
"s": 5306,
"text": " Add Notes"
}
] |
8051 Program to Multiply two 8 Bit numbers
|
Now we will try to multiply two 8-bit numbers using this 8051 microcontroller. The register A and B will be used for multiplication. No other registers can be used for multiplication. The result of the multiplication may exceed the 8-bit size. So the higher order byte is stored at register B, and lower order byte will be in the Accumulator A after multiplication.
We are taking two number FFH and FFH at location 20H and 21H, After multiplying the result will be stored at location 30H and 31H.
MOV R0, #20H;set source address 20H to R0
MOV R1, #30H;set destination address 30H to R1
MOV A, @R0;take the first operand from source to register A
INCR0; Point to the next location
MOV B,@R0;take the second operand from source to register B
MUL AB ;Multiply A and B
MOV @R1, B; Store higher order byte to 30H
INC R1; Increase R1 to point to the next location
MOV @R1, A;Store lower order byte to 31H
HALT: SJMP HALT ; Stop the program
8051 provides MULAB instruction. By using this instruction, the multiplication can be done. In some other microprocessors like8085, there was no MUL instruction. In that microprocessor, we need to use repetitive ADD operations to get the result of the multiplication.
When the result is below255, the overflow flag OV is low, otherwise, it is 1.
|
[
{
"code": null,
"e": 1428,
"s": 1062,
"text": "Now we will try to multiply two 8-bit numbers using this 8051 microcontroller. The register A and B will be used for multiplication. No other registers can be used for multiplication. The result of the multiplication may exceed the 8-bit size. So the higher order byte is stored at register B, and lower order byte will be in the Accumulator A after multiplication."
},
{
"code": null,
"e": 1561,
"s": 1428,
"text": "We are taking two number FFH and FFH at location 20H and 21H, After multiplying the result will be stored at location 30H and 31H. "
},
{
"code": null,
"e": 2071,
"s": 1561,
"text": " MOV R0, #20H;set source address 20H to R0\n MOV R1, #30H;set destination address 30H to R1\n\n MOV A, @R0;take the first operand from source to register A\n INCR0; Point to the next location\n MOV B,@R0;take the second operand from source to register B\n\n MUL AB ;Multiply A and B\n\n MOV @R1, B; Store higher order byte to 30H\n INC R1; Increase R1 to point to the next location\n MOV @R1, A;Store lower order byte to 31H\nHALT: SJMP HALT ; Stop the program"
},
{
"code": null,
"e": 2340,
"s": 2071,
"text": "8051 provides MULAB instruction. By using this instruction, the multiplication can be done. In some other microprocessors like8085, there was no MUL instruction. In that microprocessor, we need to use repetitive ADD operations to get the result of the multiplication. "
},
{
"code": null,
"e": 2418,
"s": 2340,
"text": "When the result is below255, the overflow flag OV is low, otherwise, it is 1."
}
] |
How to convert a JSON string into a JavaScript object?
|
Javascript has provided JSON.parse() method to convert a JSON into an object. Once JSON is parsed we can able to access the elements in the JSON.
var obj = JSON.parse(JSON);
It takes a JSON and parses it into an object so as to access the elements in the provided JSON.
In the following example, a JOSN is assigned to a variable and converted it into an object and later on displayed the values of the elements in the JSON as shown in the output.
Live Demo
<html>
<body>
<script>
var json = '{"name": "Malinga", "age": 32, "country": "srilanka"}';
var obj = JSON.parse(json);
document.write(obj.name + "</br>");
document.write(obj.age + "</br>");
document.write(obj.country);
</script>
</body>
</html>
Malinga
32
srilanka
Live Demo
<html>
<body>
<script>
var json = '{"company": "Tutorialspoint", "Product": "Tutorix", "city": "Hyderabad"}';
var obj = JSON.parse(json);
document.write(obj.company+ "</br>");
document.write(obj.Product+ "</br>");
document.write(obj.city);
</script>
</body>
</html>
Tutorialspoint
Tutorix
Hyderabad
|
[
{
"code": null,
"e": 1208,
"s": 1062,
"text": "Javascript has provided JSON.parse() method to convert a JSON into an object. Once JSON is parsed we can able to access the elements in the JSON."
},
{
"code": null,
"e": 1236,
"s": 1208,
"text": "var obj = JSON.parse(JSON);"
},
{
"code": null,
"e": 1332,
"s": 1236,
"text": "It takes a JSON and parses it into an object so as to access the elements in the provided JSON."
},
{
"code": null,
"e": 1509,
"s": 1332,
"text": "In the following example, a JOSN is assigned to a variable and converted it into an object and later on displayed the values of the elements in the JSON as shown in the output."
},
{
"code": null,
"e": 1519,
"s": 1509,
"text": "Live Demo"
},
{
"code": null,
"e": 1779,
"s": 1519,
"text": "<html>\n<body>\n<script>\n var json = '{\"name\": \"Malinga\", \"age\": 32, \"country\": \"srilanka\"}';\n var obj = JSON.parse(json);\n document.write(obj.name + \"</br>\");\n document.write(obj.age + \"</br>\");\n document.write(obj.country);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1799,
"s": 1779,
"text": "Malinga\n32\nsrilanka"
},
{
"code": null,
"e": 1809,
"s": 1799,
"text": "Live Demo"
},
{
"code": null,
"e": 2090,
"s": 1809,
"text": "<html>\n<body>\n<script>\n var json = '{\"company\": \"Tutorialspoint\", \"Product\": \"Tutorix\", \"city\": \"Hyderabad\"}';\n var obj = JSON.parse(json);\n document.write(obj.company+ \"</br>\");\n document.write(obj.Product+ \"</br>\");\n document.write(obj.city);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2123,
"s": 2090,
"text": "Tutorialspoint\nTutorix\nHyderabad"
}
] |
Decision Tree Classifier and Cost Computation Pruning using Python | by Angel Das | Towards Data Science
|
Decision tree classifiers are supervised learning models that are useful when we care about interpretability. Think of it like, breaking down the data by making decisions based on multiple questions at each level. This is one of the widely used algorithms for handling classification problems. To understand it better let’s take a look at the example below.
Decision Tree usually consists of:
Root Node — Represents the sample or the population that gets divided into further homogeneous groups
Splitting — Process of dividing the nodes into two sub-nodes
Decision Node — When a sub-node splits into further sub-nodes based on a certain condition, it is called a decision node
Leaf or Terminal Node — Sub nodes that don’t split further
Information Gain — To split the nodes using a condition (say most informative feature) we need to define an objective function that can be optimized. In the decision tree algorithm, we tend to maximize the information gain at each split. Three impurity measures are used commonly in measuring the information gain. They are the Gini impurity, Entropy, and the Classification error
towardsdatascience.com
To understand how decision trees are developed, we need to have a deeper understanding of how information gain is maximized at each step using one of the impurity measures at each step. Let’s take an example where we have training data comprising student information like gender, grade, and a dependent variable or a classifier variable the identifies if a student is a foodie or not. We have with us the following information outlined below.
Total Students — 20Total Students Categorized as Foodie — 10Total Student not Categorized as Foodie — 10P(Foodie), probability of a student being foodie = (10/20) = 0.5Q(Not Foodie, or 1-P), probability of a student not being foodie = (10/20) = 0.5
Total Students — 20
Total Students Categorized as Foodie — 10
Total Student not Categorized as Foodie — 10
P(Foodie), probability of a student being foodie = (10/20) = 0.5
Q(Not Foodie, or 1-P), probability of a student not being foodie = (10/20) = 0.5
Let’s divide the students based on their gender into two nodes and recalculate the above metrics.
Male Students (Node A)
Total Students — 10Total Students Categorized as Foodie — 8Total Student not Categorized as Foodie — 2P(Foodie), probability of a student being foodie = (8/10) = 0.8Q(Not Foodie, or 1-P), probability of a student not being foodie = (2/10) = 0.2
Total Students — 10
Total Students Categorized as Foodie — 8
Total Student not Categorized as Foodie — 2
P(Foodie), probability of a student being foodie = (8/10) = 0.8
Q(Not Foodie, or 1-P), probability of a student not being foodie = (2/10) = 0.2
Female Students (Node B)
Total Students — 10Total Students Categorized as Foodie — 4Total Student not Categorized as Foodie — 6P(Foodie), probability of a student being foodie = (4/10) = 0.4Q(Not Foodie, or 1-P), probability of a student not being foodie = (6/10) = 0.6
Total Students — 10
Total Students Categorized as Foodie — 4
Total Student not Categorized as Foodie — 6
P(Foodie), probability of a student being foodie = (4/10) = 0.4
Q(Not Foodie, or 1-P), probability of a student not being foodie = (6/10) = 0.6
Gini Index (GIn) for Node A or the Male Students = P2 + Q2, where P and Q are the probability of a student being a foodie and a non-foodie. GIn (Node A) = 0.82 + 0.22 = 0.68
Gini Impurity (GIp) for Node A = 1-Gini Index = 1–0.68 = 0.32
Gini Index (GIn) for Node B or the Female Students = P2 + Q2, where P and Q are the probability of a student being a foodie and a non-foodie. GIn (Node B) = 0.42 + 0.62= 0.52
Gini Impurity (GIp) for Node B= 1-Gini Index = 1–0.52 = 0.48
What we observe above is that when we split the students based on their gender (Male and Female) into Nodes A and B respectively, we have a Gini impurity score for two nodes separately. Now to decide if gender is the right variable to split the students into foodie and non-foodie we need a weighted Gini Impurity Score which is calculated using the formula outlined below.
Weighted Gini Impurity = (Total samples in Node A / Total Samples in the data set) * Gini Impurity (Node A) + (Total samples in Node B/ Total Samples in the data set) * Gini Impurity (Node B)
Using this formulation to calculate the Weighted Gini Impurity Score of the above example, Weighted Gini Impurity Score when Students are divided based on Gender = (10/20)*0.32 + (10/20)*0.48 = 0.4
A classification problem works with multiple independent variables. The variables can be categorical or continuous. Decision trees are well adapted to handle variables of different data types. A decision tree algorithm takes into consideration all possible variables while deciding the split of each node. Variables using which maximum Weighted Impurity Gain can be achieved, is used as a decision variable for a particular node.
In the example above the Weighted Impurity Gain using “gender” as the decision variable is 0.4, however, say using “grade” as the decision variable we manage to achieve a Weighted Impurity Gain of 0.56, the algorithm will use “grade” as the decision variable for creating the first split. A similar methodology is followed for all subsequent steps until every node is homogeneous.
Decision trees are prone to overfitting as the algorithm continues to split nodes into sub-nodes till each node becomes homogeneousThe accuracy of training data is much higher when compared to the test set, hence decision trees should be pruned to prevent the model from overfitting. Pruning can be achieved by controlling the depth of the tree, maximum/minimum number of samples in each node, minimum impurity gain for a node to split, and the maximum leaf nodesPython allows users to develop a decision tree using the Gini Impurity or Entropy as the Information Gain CriterionA decision tree can be fine-tuned using a Grid Search or a Randomized Search CV. CV stands for cross-validation
Decision trees are prone to overfitting as the algorithm continues to split nodes into sub-nodes till each node becomes homogeneous
The accuracy of training data is much higher when compared to the test set, hence decision trees should be pruned to prevent the model from overfitting. Pruning can be achieved by controlling the depth of the tree, maximum/minimum number of samples in each node, minimum impurity gain for a node to split, and the maximum leaf nodes
Python allows users to develop a decision tree using the Gini Impurity or Entropy as the Information Gain Criterion
A decision tree can be fine-tuned using a Grid Search or a Randomized Search CV. CV stands for cross-validation
The code snippet outlined below provides a visual comparison of different impurity criterion and how they change with different probability values. Note the code below is adapted from Python: Deeper Insights into Machine Learning by S.Raschka, D.Julian, and J.Hearty, 2016.
import matplotlib.pyplot as pltimport numpy as np#-----Calculating Gini Indexdef gini(p): return (p)*(1 - (p)) + (1 - p)*(1 - (1-p))#-----Calculating Entropydef entropy(p): return - p*np.log2(p) - (1 - p)*np.log2((1 - p))#-----Calculating Classification Errordef classification_error(p): return 1 - np.max([p, 1 - p])#----Creating a Numpy Array of probability values from 0 to 1, with an increment of 0.01x = np.arange(0.0, 1.0, 0.01)#---Obtaining Entropy for different values of pent = [entropy(p) if p != 0 else None for p in x]#---Obtaining scaled entropysc_ent = [e*0.5 if e else None for e in ent]#--Classification Errorerr = [classification_error(i) for i in x]#--Plottingfig = plt.figure();plt.figure(figsize=(10,8));ax = plt.subplot(111);for i, lab, ls, c, in zip([ent, sc_ent, gini(x), err], ['Entropy', 'Entropy (scaled)','Gini Impurity', 'Misclassification Error'],['-', '-', '--', '-.'], ['black', 'darkgray','blue', 'brown', 'cyan']): line = ax.plot(x, i, label=lab, linestyle=ls, lw=2, color=c) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15), ncol=3, fancybox=True, shadow=False)ax.axhline(y=0.5, linewidth=1, color='k', linestyle='--')ax.axhline(y=1.0, linewidth=1, color='k', linestyle='--')plt.ylim([0, 1.1])plt.xlabel('p(i=1)')plt.ylabel('Impurity Index')plt.show()
The problem statement aims at developing a classification model to predict the quality of red wine. Details about the problem statement can be found here. This is a classic example of a multi-class classification problem. Note that all machine learning models are sensitive to Outliers, hence features/independent variables consisting of outliers should be treated before building the tree.
An important aspect of different features/independent variables is how they interact. Pearson correlation can be used to determine the degree of association between two features from a data set. However, for a decision-based algorithm like a decision tree, we won’t be dropping highly correlated variables.
#---------------------------------------------Importing Required Libraries-----------------------------------%matplotlib inlineimport numpy as npimport pandas as pdfrom sklearn.tree import DecisionTreeClassifierimport numpy as npimport pandas as pdimport seaborn as snssns.set(color_codes=True)from matplotlib import pyplot as pltfrom sklearn.model_selection import train_test_split #--------------splitting data into test and trainfrom sklearn.tree import DecisionTreeClassifier #-----------Building decision tree modelfrom sklearn import metricsfrom sklearn.metrics import accuracy_score,f1_score,recall_score,precision_score, confusion_matrix #-----model validation scores%matplotlib inlinefrom IPython.display import display #---------------------for displaying multiple data frames in one outputfrom sklearn.feature_extraction.text import CountVectorizer #DT does not take strings as input for the model fit stepimport missingno as msno_plot #--------------plotting missing valueswine_df = pd.read_csv('winequality-red.csv',sep=';')
Quick descriptive statistics of the data
wine_df.describe().transpose().round(2)
Checking Missing Values
#-------------------------------------------Barplot of non-missing values--------------------------------plt.title('#Non-missing Values by Columns')msno_plot.bar(wine_df);
Outlier check & Treatment
#--Checking Outliersplt.figure(figsize=(15,15))pos = 1for i in wine_df.columns: plt.subplot(3, 4, pos) sns.boxplot(wine_df[i]) pos += 1
col_names=['fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol']display(col_names)for i in col_names: q1, q2, q3 = wine_df[i].quantile([0.25,0.5,0.75]) IQR = q3 - q1 lower_cap=q1-1.5*IQR upper_cap=q3+1.5*IQR wine_df[i]=wine_df[i].apply(lambda x: upper_cap if x>(upper_cap) else (lower_cap if x<(lower_cap) else x))
Outliers above are winsorized using Q1–1.5*IQR and Q3+1.5*IQR values. Q1, Q3, and IQR stand for Quartile 1, Quartile 3, and Inter Quartile Range respectively.
sns.pairplot(wine_df);
Understanding the relationship between different variables. Note — In Decision Trees, we need not remove highly correlated variables as nodes are divided into sub-nodes using one independent variable only, hence even if two or more variables are highly correlated, the variable producing the highest information gain will be used for the analysis.
plt.figure(figsize=(10,8))sns.heatmap(wine_df.corr(), annot=True, linewidths=.5, center=0, cbar=False, cmap="YlGnBu")plt.show()
Classification problems are sensitive to class imbalance. A class imbalance is a scenario when the dependent attribute has a higher proportion of ones than zeros or vice versa. In a multiclass problem, class imbalance occurs when the proportion of one of the class values is much higher. Class balance is induced by combining values of the attribute “quality” which is the dependent variable in this problem statement.
plt.figure(figsize=(10,8))sns.countplot(wine_df['quality']);
wine_df['quality'] = wine_df['quality'].replace(8,7)wine_df['quality'] = wine_df['quality'].replace(3,5)wine_df['quality'] = wine_df['quality'].replace(4,5)wine_df['quality'].value_counts(normalize=True)
Data is divided into train and test set to check the accuracy of the model and look for overfitting or under fitting if any.
# splitting data into training and test set for independent attributesfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test =train_test_split(wine_df.drop('quality',axis=1), wine_df['quality'], test_size=.3, random_state=22)X_train.shape,X_test.shape
A decision tree model is developed using the Gini criterion. Note that for the sake of simplicity we have pruned the tree to a maximum depth of three. This will help us visualize the tree and tie it back to the concepts we covered in the initial segments.
clf_pruned = DecisionTreeClassifier(criterion = "gini", random_state = 100, max_depth=3, min_samples_leaf=5)clf_pruned.fit(X_train, y_train)
Note that the following parameters can be tuned to improve the model output (Scikit Learn, 2019).
criterion — Gini impurity is used to decide the variables based on which root node and following decision nodes should be splitclass_weight — None; All classes are assigned weight 1max_depth — 3; Pruning is done. When “None”, it signifies that nodes will be expanded till all leaves are homogeneousmax_features — None; All features or independent variables are considered while deciding split of a nodemax_leaf_nodes — None;min_impurity_decrease — 0.0; A node is split only when the split ensures a decrease in the impurity of greater than or equal to zeromin_impurity_split — None;min_samples_leaf — 1; Minimum number of samples required for a leaf to existsmin_samples_split — 2; If min_samples_leaf =1, it signifies that the right and the left node should have 1 sample each, i.e. the parent node or the root node should have at least two samplessplitter — ‘best’; Strategy used to choose the split at each node. Best ensure that all features are considered while deciding the split
criterion — Gini impurity is used to decide the variables based on which root node and following decision nodes should be split
class_weight — None; All classes are assigned weight 1
max_depth — 3; Pruning is done. When “None”, it signifies that nodes will be expanded till all leaves are homogeneous
max_features — None; All features or independent variables are considered while deciding split of a node
max_leaf_nodes — None;
min_impurity_decrease — 0.0; A node is split only when the split ensures a decrease in the impurity of greater than or equal to zero
min_impurity_split — None;
min_samples_leaf — 1; Minimum number of samples required for a leaf to exists
min_samples_split — 2; If min_samples_leaf =1, it signifies that the right and the left node should have 1 sample each, i.e. the parent node or the root node should have at least two samples
splitter — ‘best’; Strategy used to choose the split at each node. Best ensure that all features are considered while deciding the split
from sklearn.tree import export_graphvizfrom sklearn.externals.six import StringIO from IPython.display import Image import pydotplusimport graphvizxvar = wine_df.drop('quality', axis=1)feature_cols = xvar.columnsdot_data = StringIO()export_graphviz(clf_pruned, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1','2'])from pydot import graph_from_dot_data(graph, ) = graph_from_dot_data(dot_data.getvalue())Image(graph.create_png())
preds_pruned = clf_pruned.predict(X_test)preds_pruned_train = clf_pruned.predict(X_train)print(accuracy_score(y_test,preds_pruned))print(accuracy_score(y_train,preds_pruned_train))
The accuracy score of the model on training and test data turned out to be 0.60 and 0.62 respectively.
Feature importance refers to a class of techniques for assigning scores to input features of a predictive model that indicates the relative importance of each feature when making a prediction.
## Calculating feature importancefeat_importance = clf_pruned.tree_.compute_feature_importances(normalize=False)feat_imp_dict = dict(zip(feature_cols, clf_pruned.feature_importances_))feat_imp = pd.DataFrame.from_dict(feat_imp_dict, orient='index')feat_imp.rename(columns = {0:'FeatureImportance'}, inplace = True)feat_imp.sort_values(by=['FeatureImportance'], ascending=False).head()
The DecisionTreeClassifier() provides parameters such as min_samples_leaf and max_depth to prevent a tree from overfitting. Think of it as a scenario where we explicitly define the depth and the maximum leaves in the tree. However, the biggest challenge is to determine the optimum depth and leaves a tree should contain. In the example above we used max_depth=3, min_samples_leaf=5. These numbers are just example figures to see how the tree behaves. But if in reality we were asked to work on this model and come up with an optimum value for the model parameters, it is challenging but not impossible (decision tree models can be fine-tuned using GridSearchCV algorithm).
The other way of doing it is by using the Cost Complexity Pruning (CCP).
Cost complexity pruning provides another option to control the size of a tree. In DecisionTreeClassifier, this pruning technique is parameterized by the cost complexity parameter, ccp_alpha. Greater values of ccp_alpha increase the number of nodes pruned (Scikit Learn, n.d.).
In simpler terms, cost complexity is a threshold value. The model split a node further into its child node only when the overall impurity of the model is improved by a value greater than this threshold else it stops.
Lower the CCP, lower is the impurity. How?
When the value of CCP is lower the model will split a node into its child nodes even if the impurity doesn’t decrease much. This is evident as the depth of the tree increases, i.e. as we go down a decision tree, we will find that split doesn’t contribute much to the change in the overall impurity of the model. However higher split ensures that the classes are categorized correctly, i.e. accuracy is more.
When CCP values are low, a higher number of nodes are created. Higher the nodes, the higher is the depth of the tree as well.
The code below (Scikit Learn, n.d.) illustrates how alpha can be tuned to obtain a model with an improved accuracy score.
path = model_gini.cost_complexity_pruning_path(X_train, y_train)ccp_alphas, impurities = path.ccp_alphas, path.impuritiesfig, ax = plt.subplots(figsize=(16,8));ax.plot(ccp_alphas[:-1], impurities[:-1], marker='o', drawstyle="steps-post");ax.set_xlabel("effective alpha");ax.set_ylabel("total impurity of leaves");ax.set_title("Total Impurity vs effective alpha for training set");
Let’s understand the variation of depth and the number of nodes with change in alpha.
clfs = clfs[:-1]ccp_alphas = ccp_alphas[:-1]node_counts = [clf.tree_.node_count for clf in clfs]depth = [clf.tree_.max_depth for clf in clfs]fig, ax = plt.subplots(2, 1,figsize=(16,8))ax[0].plot(ccp_alphas, node_counts, marker='o', drawstyle="steps-post")ax[0].set_xlabel("alpha")ax[0].set_ylabel("number of nodes")ax[0].set_title("Number of nodes vs alpha")ax[1].plot(ccp_alphas, depth, marker='o', drawstyle="steps-post")ax[1].set_xlabel("alpha")ax[1].set_ylabel("depth of tree")ax[1].set_title("Depth vs alpha")fig.tight_layout()
Understanding the variation in accuracy when alpha is increased.
fig, ax = plt.subplots(figsize=(16,8)); #-----------------Setting size of the canvastrain_scores = [clf.score(X_train, y_train) for clf in clfs]test_scores = [clf.score(X_test, y_test) for clf in clfs]ax.set_xlabel("alpha")ax.set_ylabel("accuracy")ax.set_title("Accuracy vs alpha for training and testing sets")ax.plot(ccp_alphas, train_scores, marker='o', label="train", drawstyle="steps-post")ax.plot(ccp_alphas, test_scores, marker='o', label="test", drawstyle="steps-post")ax.legend()plt.show()
i = np.arange(len(ccp_alphas))ccp = pd.DataFrame({'Depth': pd.Series(depth,index=i),'Node' : pd.Series(node_counts, index=i),\ 'ccp' : pd.Series(ccp_alphas, index = i),'train_scores' : pd.Series(train_scores, index = i), 'test_scores' : pd.Series(test_scores, index = i)})ccp.tail()ccp[ccp['test_scores']==ccp['test_scores'].max()]
The above code provides the cost computation pruning value that produces the highest accuracy in the test data.
Raschka, S., Julian, D. and Hearty, J. (2016). Python : deeper insights into machine learning : leverage benefits of machine learning techniques using Python : a course in three modules. Birmingham, Uk: Packt Publishing, pp.83, 88, 89.Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011.Scikit Learn (2019). sklearn.tree.DecisionTreeClassifier — scikit-learn 0.22.1 documentation. [online] Scikit-learn.org. Available at: https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html.Scikit Learn (n.d.). Post pruning decision trees with cost complexity pruning. [online] Available at: https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py.
Raschka, S., Julian, D. and Hearty, J. (2016). Python : deeper insights into machine learning : leverage benefits of machine learning techniques using Python : a course in three modules. Birmingham, Uk: Packt Publishing, pp.83, 88, 89.
Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011.
Scikit Learn (2019). sklearn.tree.DecisionTreeClassifier — scikit-learn 0.22.1 documentation. [online] Scikit-learn.org. Available at: https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html.
Scikit Learn (n.d.). Post pruning decision trees with cost complexity pruning. [online] Available at: https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py.
About the Author: Advanced analytics professional and management consultant helping companies find solutions for diverse problems through a mix of business, technology, and math on organizational data. A Data Science enthusiast, here to share, learn and contribute; You can connect with me on Linked and Twitter;
|
[
{
"code": null,
"e": 530,
"s": 172,
"text": "Decision tree classifiers are supervised learning models that are useful when we care about interpretability. Think of it like, breaking down the data by making decisions based on multiple questions at each level. This is one of the widely used algorithms for handling classification problems. To understand it better let’s take a look at the example below."
},
{
"code": null,
"e": 565,
"s": 530,
"text": "Decision Tree usually consists of:"
},
{
"code": null,
"e": 667,
"s": 565,
"text": "Root Node — Represents the sample or the population that gets divided into further homogeneous groups"
},
{
"code": null,
"e": 728,
"s": 667,
"text": "Splitting — Process of dividing the nodes into two sub-nodes"
},
{
"code": null,
"e": 849,
"s": 728,
"text": "Decision Node — When a sub-node splits into further sub-nodes based on a certain condition, it is called a decision node"
},
{
"code": null,
"e": 908,
"s": 849,
"text": "Leaf or Terminal Node — Sub nodes that don’t split further"
},
{
"code": null,
"e": 1289,
"s": 908,
"text": "Information Gain — To split the nodes using a condition (say most informative feature) we need to define an objective function that can be optimized. In the decision tree algorithm, we tend to maximize the information gain at each split. Three impurity measures are used commonly in measuring the information gain. They are the Gini impurity, Entropy, and the Classification error"
},
{
"code": null,
"e": 1312,
"s": 1289,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1755,
"s": 1312,
"text": "To understand how decision trees are developed, we need to have a deeper understanding of how information gain is maximized at each step using one of the impurity measures at each step. Let’s take an example where we have training data comprising student information like gender, grade, and a dependent variable or a classifier variable the identifies if a student is a foodie or not. We have with us the following information outlined below."
},
{
"code": null,
"e": 2004,
"s": 1755,
"text": "Total Students — 20Total Students Categorized as Foodie — 10Total Student not Categorized as Foodie — 10P(Foodie), probability of a student being foodie = (10/20) = 0.5Q(Not Foodie, or 1-P), probability of a student not being foodie = (10/20) = 0.5"
},
{
"code": null,
"e": 2024,
"s": 2004,
"text": "Total Students — 20"
},
{
"code": null,
"e": 2066,
"s": 2024,
"text": "Total Students Categorized as Foodie — 10"
},
{
"code": null,
"e": 2111,
"s": 2066,
"text": "Total Student not Categorized as Foodie — 10"
},
{
"code": null,
"e": 2176,
"s": 2111,
"text": "P(Foodie), probability of a student being foodie = (10/20) = 0.5"
},
{
"code": null,
"e": 2257,
"s": 2176,
"text": "Q(Not Foodie, or 1-P), probability of a student not being foodie = (10/20) = 0.5"
},
{
"code": null,
"e": 2355,
"s": 2257,
"text": "Let’s divide the students based on their gender into two nodes and recalculate the above metrics."
},
{
"code": null,
"e": 2378,
"s": 2355,
"text": "Male Students (Node A)"
},
{
"code": null,
"e": 2623,
"s": 2378,
"text": "Total Students — 10Total Students Categorized as Foodie — 8Total Student not Categorized as Foodie — 2P(Foodie), probability of a student being foodie = (8/10) = 0.8Q(Not Foodie, or 1-P), probability of a student not being foodie = (2/10) = 0.2"
},
{
"code": null,
"e": 2643,
"s": 2623,
"text": "Total Students — 10"
},
{
"code": null,
"e": 2684,
"s": 2643,
"text": "Total Students Categorized as Foodie — 8"
},
{
"code": null,
"e": 2728,
"s": 2684,
"text": "Total Student not Categorized as Foodie — 2"
},
{
"code": null,
"e": 2792,
"s": 2728,
"text": "P(Foodie), probability of a student being foodie = (8/10) = 0.8"
},
{
"code": null,
"e": 2872,
"s": 2792,
"text": "Q(Not Foodie, or 1-P), probability of a student not being foodie = (2/10) = 0.2"
},
{
"code": null,
"e": 2897,
"s": 2872,
"text": "Female Students (Node B)"
},
{
"code": null,
"e": 3142,
"s": 2897,
"text": "Total Students — 10Total Students Categorized as Foodie — 4Total Student not Categorized as Foodie — 6P(Foodie), probability of a student being foodie = (4/10) = 0.4Q(Not Foodie, or 1-P), probability of a student not being foodie = (6/10) = 0.6"
},
{
"code": null,
"e": 3162,
"s": 3142,
"text": "Total Students — 10"
},
{
"code": null,
"e": 3203,
"s": 3162,
"text": "Total Students Categorized as Foodie — 4"
},
{
"code": null,
"e": 3247,
"s": 3203,
"text": "Total Student not Categorized as Foodie — 6"
},
{
"code": null,
"e": 3311,
"s": 3247,
"text": "P(Foodie), probability of a student being foodie = (4/10) = 0.4"
},
{
"code": null,
"e": 3391,
"s": 3311,
"text": "Q(Not Foodie, or 1-P), probability of a student not being foodie = (6/10) = 0.6"
},
{
"code": null,
"e": 3565,
"s": 3391,
"text": "Gini Index (GIn) for Node A or the Male Students = P2 + Q2, where P and Q are the probability of a student being a foodie and a non-foodie. GIn (Node A) = 0.82 + 0.22 = 0.68"
},
{
"code": null,
"e": 3627,
"s": 3565,
"text": "Gini Impurity (GIp) for Node A = 1-Gini Index = 1–0.68 = 0.32"
},
{
"code": null,
"e": 3802,
"s": 3627,
"text": "Gini Index (GIn) for Node B or the Female Students = P2 + Q2, where P and Q are the probability of a student being a foodie and a non-foodie. GIn (Node B) = 0.42 + 0.62= 0.52"
},
{
"code": null,
"e": 3863,
"s": 3802,
"text": "Gini Impurity (GIp) for Node B= 1-Gini Index = 1–0.52 = 0.48"
},
{
"code": null,
"e": 4237,
"s": 3863,
"text": "What we observe above is that when we split the students based on their gender (Male and Female) into Nodes A and B respectively, we have a Gini impurity score for two nodes separately. Now to decide if gender is the right variable to split the students into foodie and non-foodie we need a weighted Gini Impurity Score which is calculated using the formula outlined below."
},
{
"code": null,
"e": 4429,
"s": 4237,
"text": "Weighted Gini Impurity = (Total samples in Node A / Total Samples in the data set) * Gini Impurity (Node A) + (Total samples in Node B/ Total Samples in the data set) * Gini Impurity (Node B)"
},
{
"code": null,
"e": 4627,
"s": 4429,
"text": "Using this formulation to calculate the Weighted Gini Impurity Score of the above example, Weighted Gini Impurity Score when Students are divided based on Gender = (10/20)*0.32 + (10/20)*0.48 = 0.4"
},
{
"code": null,
"e": 5057,
"s": 4627,
"text": "A classification problem works with multiple independent variables. The variables can be categorical or continuous. Decision trees are well adapted to handle variables of different data types. A decision tree algorithm takes into consideration all possible variables while deciding the split of each node. Variables using which maximum Weighted Impurity Gain can be achieved, is used as a decision variable for a particular node."
},
{
"code": null,
"e": 5438,
"s": 5057,
"text": "In the example above the Weighted Impurity Gain using “gender” as the decision variable is 0.4, however, say using “grade” as the decision variable we manage to achieve a Weighted Impurity Gain of 0.56, the algorithm will use “grade” as the decision variable for creating the first split. A similar methodology is followed for all subsequent steps until every node is homogeneous."
},
{
"code": null,
"e": 6128,
"s": 5438,
"text": "Decision trees are prone to overfitting as the algorithm continues to split nodes into sub-nodes till each node becomes homogeneousThe accuracy of training data is much higher when compared to the test set, hence decision trees should be pruned to prevent the model from overfitting. Pruning can be achieved by controlling the depth of the tree, maximum/minimum number of samples in each node, minimum impurity gain for a node to split, and the maximum leaf nodesPython allows users to develop a decision tree using the Gini Impurity or Entropy as the Information Gain CriterionA decision tree can be fine-tuned using a Grid Search or a Randomized Search CV. CV stands for cross-validation"
},
{
"code": null,
"e": 6260,
"s": 6128,
"text": "Decision trees are prone to overfitting as the algorithm continues to split nodes into sub-nodes till each node becomes homogeneous"
},
{
"code": null,
"e": 6593,
"s": 6260,
"text": "The accuracy of training data is much higher when compared to the test set, hence decision trees should be pruned to prevent the model from overfitting. Pruning can be achieved by controlling the depth of the tree, maximum/minimum number of samples in each node, minimum impurity gain for a node to split, and the maximum leaf nodes"
},
{
"code": null,
"e": 6709,
"s": 6593,
"text": "Python allows users to develop a decision tree using the Gini Impurity or Entropy as the Information Gain Criterion"
},
{
"code": null,
"e": 6821,
"s": 6709,
"text": "A decision tree can be fine-tuned using a Grid Search or a Randomized Search CV. CV stands for cross-validation"
},
{
"code": null,
"e": 7095,
"s": 6821,
"text": "The code snippet outlined below provides a visual comparison of different impurity criterion and how they change with different probability values. Note the code below is adapted from Python: Deeper Insights into Machine Learning by S.Raschka, D.Julian, and J.Hearty, 2016."
},
{
"code": null,
"e": 8487,
"s": 7095,
"text": "import matplotlib.pyplot as pltimport numpy as np#-----Calculating Gini Indexdef gini(p): return (p)*(1 - (p)) + (1 - p)*(1 - (1-p))#-----Calculating Entropydef entropy(p): return - p*np.log2(p) - (1 - p)*np.log2((1 - p))#-----Calculating Classification Errordef classification_error(p): return 1 - np.max([p, 1 - p])#----Creating a Numpy Array of probability values from 0 to 1, with an increment of 0.01x = np.arange(0.0, 1.0, 0.01)#---Obtaining Entropy for different values of pent = [entropy(p) if p != 0 else None for p in x]#---Obtaining scaled entropysc_ent = [e*0.5 if e else None for e in ent]#--Classification Errorerr = [classification_error(i) for i in x]#--Plottingfig = plt.figure();plt.figure(figsize=(10,8));ax = plt.subplot(111);for i, lab, ls, c, in zip([ent, sc_ent, gini(x), err], ['Entropy', 'Entropy (scaled)','Gini Impurity', 'Misclassification Error'],['-', '-', '--', '-.'], ['black', 'darkgray','blue', 'brown', 'cyan']): line = ax.plot(x, i, label=lab, linestyle=ls, lw=2, color=c) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15), ncol=3, fancybox=True, shadow=False)ax.axhline(y=0.5, linewidth=1, color='k', linestyle='--')ax.axhline(y=1.0, linewidth=1, color='k', linestyle='--')plt.ylim([0, 1.1])plt.xlabel('p(i=1)')plt.ylabel('Impurity Index')plt.show()"
},
{
"code": null,
"e": 8878,
"s": 8487,
"text": "The problem statement aims at developing a classification model to predict the quality of red wine. Details about the problem statement can be found here. This is a classic example of a multi-class classification problem. Note that all machine learning models are sensitive to Outliers, hence features/independent variables consisting of outliers should be treated before building the tree."
},
{
"code": null,
"e": 9185,
"s": 8878,
"text": "An important aspect of different features/independent variables is how they interact. Pearson correlation can be used to determine the degree of association between two features from a data set. However, for a decision-based algorithm like a decision tree, we won’t be dropping highly correlated variables."
},
{
"code": null,
"e": 10224,
"s": 9185,
"text": "#---------------------------------------------Importing Required Libraries-----------------------------------%matplotlib inlineimport numpy as npimport pandas as pdfrom sklearn.tree import DecisionTreeClassifierimport numpy as npimport pandas as pdimport seaborn as snssns.set(color_codes=True)from matplotlib import pyplot as pltfrom sklearn.model_selection import train_test_split #--------------splitting data into test and trainfrom sklearn.tree import DecisionTreeClassifier #-----------Building decision tree modelfrom sklearn import metricsfrom sklearn.metrics import accuracy_score,f1_score,recall_score,precision_score, confusion_matrix #-----model validation scores%matplotlib inlinefrom IPython.display import display #---------------------for displaying multiple data frames in one outputfrom sklearn.feature_extraction.text import CountVectorizer #DT does not take strings as input for the model fit stepimport missingno as msno_plot #--------------plotting missing valueswine_df = pd.read_csv('winequality-red.csv',sep=';')"
},
{
"code": null,
"e": 10265,
"s": 10224,
"text": "Quick descriptive statistics of the data"
},
{
"code": null,
"e": 10305,
"s": 10265,
"text": "wine_df.describe().transpose().round(2)"
},
{
"code": null,
"e": 10329,
"s": 10305,
"text": "Checking Missing Values"
},
{
"code": null,
"e": 10501,
"s": 10329,
"text": "#-------------------------------------------Barplot of non-missing values--------------------------------plt.title('#Non-missing Values by Columns')msno_plot.bar(wine_df);"
},
{
"code": null,
"e": 10527,
"s": 10501,
"text": "Outlier check & Treatment"
},
{
"code": null,
"e": 10672,
"s": 10527,
"text": "#--Checking Outliersplt.figure(figsize=(15,15))pos = 1for i in wine_df.columns: plt.subplot(3, 4, pos) sns.boxplot(wine_df[i]) pos += 1"
},
{
"code": null,
"e": 11131,
"s": 10672,
"text": "col_names=['fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol']display(col_names)for i in col_names: q1, q2, q3 = wine_df[i].quantile([0.25,0.5,0.75]) IQR = q3 - q1 lower_cap=q1-1.5*IQR upper_cap=q3+1.5*IQR wine_df[i]=wine_df[i].apply(lambda x: upper_cap if x>(upper_cap) else (lower_cap if x<(lower_cap) else x))"
},
{
"code": null,
"e": 11290,
"s": 11131,
"text": "Outliers above are winsorized using Q1–1.5*IQR and Q3+1.5*IQR values. Q1, Q3, and IQR stand for Quartile 1, Quartile 3, and Inter Quartile Range respectively."
},
{
"code": null,
"e": 11313,
"s": 11290,
"text": "sns.pairplot(wine_df);"
},
{
"code": null,
"e": 11661,
"s": 11313,
"text": "Understanding the relationship between different variables. Note — In Decision Trees, we need not remove highly correlated variables as nodes are divided into sub-nodes using one independent variable only, hence even if two or more variables are highly correlated, the variable producing the highest information gain will be used for the analysis."
},
{
"code": null,
"e": 11844,
"s": 11661,
"text": "plt.figure(figsize=(10,8))sns.heatmap(wine_df.corr(), annot=True, linewidths=.5, center=0, cbar=False, cmap=\"YlGnBu\")plt.show()"
},
{
"code": null,
"e": 12263,
"s": 11844,
"text": "Classification problems are sensitive to class imbalance. A class imbalance is a scenario when the dependent attribute has a higher proportion of ones than zeros or vice versa. In a multiclass problem, class imbalance occurs when the proportion of one of the class values is much higher. Class balance is induced by combining values of the attribute “quality” which is the dependent variable in this problem statement."
},
{
"code": null,
"e": 12324,
"s": 12263,
"text": "plt.figure(figsize=(10,8))sns.countplot(wine_df['quality']);"
},
{
"code": null,
"e": 12528,
"s": 12324,
"text": "wine_df['quality'] = wine_df['quality'].replace(8,7)wine_df['quality'] = wine_df['quality'].replace(3,5)wine_df['quality'] = wine_df['quality'].replace(4,5)wine_df['quality'].value_counts(normalize=True)"
},
{
"code": null,
"e": 12653,
"s": 12528,
"text": "Data is divided into train and test set to check the accuracy of the model and look for overfitting or under fitting if any."
},
{
"code": null,
"e": 12985,
"s": 12653,
"text": "# splitting data into training and test set for independent attributesfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test =train_test_split(wine_df.drop('quality',axis=1), wine_df['quality'], test_size=.3, random_state=22)X_train.shape,X_test.shape"
},
{
"code": null,
"e": 13241,
"s": 12985,
"text": "A decision tree model is developed using the Gini criterion. Note that for the sake of simplicity we have pruned the tree to a maximum depth of three. This will help us visualize the tree and tie it back to the concepts we covered in the initial segments."
},
{
"code": null,
"e": 13412,
"s": 13241,
"text": "clf_pruned = DecisionTreeClassifier(criterion = \"gini\", random_state = 100, max_depth=3, min_samples_leaf=5)clf_pruned.fit(X_train, y_train)"
},
{
"code": null,
"e": 13510,
"s": 13412,
"text": "Note that the following parameters can be tuned to improve the model output (Scikit Learn, 2019)."
},
{
"code": null,
"e": 14496,
"s": 13510,
"text": "criterion — Gini impurity is used to decide the variables based on which root node and following decision nodes should be splitclass_weight — None; All classes are assigned weight 1max_depth — 3; Pruning is done. When “None”, it signifies that nodes will be expanded till all leaves are homogeneousmax_features — None; All features or independent variables are considered while deciding split of a nodemax_leaf_nodes — None;min_impurity_decrease — 0.0; A node is split only when the split ensures a decrease in the impurity of greater than or equal to zeromin_impurity_split — None;min_samples_leaf — 1; Minimum number of samples required for a leaf to existsmin_samples_split — 2; If min_samples_leaf =1, it signifies that the right and the left node should have 1 sample each, i.e. the parent node or the root node should have at least two samplessplitter — ‘best’; Strategy used to choose the split at each node. Best ensure that all features are considered while deciding the split"
},
{
"code": null,
"e": 14624,
"s": 14496,
"text": "criterion — Gini impurity is used to decide the variables based on which root node and following decision nodes should be split"
},
{
"code": null,
"e": 14679,
"s": 14624,
"text": "class_weight — None; All classes are assigned weight 1"
},
{
"code": null,
"e": 14797,
"s": 14679,
"text": "max_depth — 3; Pruning is done. When “None”, it signifies that nodes will be expanded till all leaves are homogeneous"
},
{
"code": null,
"e": 14902,
"s": 14797,
"text": "max_features — None; All features or independent variables are considered while deciding split of a node"
},
{
"code": null,
"e": 14925,
"s": 14902,
"text": "max_leaf_nodes — None;"
},
{
"code": null,
"e": 15058,
"s": 14925,
"text": "min_impurity_decrease — 0.0; A node is split only when the split ensures a decrease in the impurity of greater than or equal to zero"
},
{
"code": null,
"e": 15085,
"s": 15058,
"text": "min_impurity_split — None;"
},
{
"code": null,
"e": 15163,
"s": 15085,
"text": "min_samples_leaf — 1; Minimum number of samples required for a leaf to exists"
},
{
"code": null,
"e": 15354,
"s": 15163,
"text": "min_samples_split — 2; If min_samples_leaf =1, it signifies that the right and the left node should have 1 sample each, i.e. the parent node or the root node should have at least two samples"
},
{
"code": null,
"e": 15491,
"s": 15354,
"text": "splitter — ‘best’; Strategy used to choose the split at each node. Best ensure that all features are considered while deciding the split"
},
{
"code": null,
"e": 16027,
"s": 15491,
"text": "from sklearn.tree import export_graphvizfrom sklearn.externals.six import StringIO from IPython.display import Image import pydotplusimport graphvizxvar = wine_df.drop('quality', axis=1)feature_cols = xvar.columnsdot_data = StringIO()export_graphviz(clf_pruned, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1','2'])from pydot import graph_from_dot_data(graph, ) = graph_from_dot_data(dot_data.getvalue())Image(graph.create_png())"
},
{
"code": null,
"e": 16208,
"s": 16027,
"text": "preds_pruned = clf_pruned.predict(X_test)preds_pruned_train = clf_pruned.predict(X_train)print(accuracy_score(y_test,preds_pruned))print(accuracy_score(y_train,preds_pruned_train))"
},
{
"code": null,
"e": 16311,
"s": 16208,
"text": "The accuracy score of the model on training and test data turned out to be 0.60 and 0.62 respectively."
},
{
"code": null,
"e": 16504,
"s": 16311,
"text": "Feature importance refers to a class of techniques for assigning scores to input features of a predictive model that indicates the relative importance of each feature when making a prediction."
},
{
"code": null,
"e": 16889,
"s": 16504,
"text": "## Calculating feature importancefeat_importance = clf_pruned.tree_.compute_feature_importances(normalize=False)feat_imp_dict = dict(zip(feature_cols, clf_pruned.feature_importances_))feat_imp = pd.DataFrame.from_dict(feat_imp_dict, orient='index')feat_imp.rename(columns = {0:'FeatureImportance'}, inplace = True)feat_imp.sort_values(by=['FeatureImportance'], ascending=False).head()"
},
{
"code": null,
"e": 17563,
"s": 16889,
"text": "The DecisionTreeClassifier() provides parameters such as min_samples_leaf and max_depth to prevent a tree from overfitting. Think of it as a scenario where we explicitly define the depth and the maximum leaves in the tree. However, the biggest challenge is to determine the optimum depth and leaves a tree should contain. In the example above we used max_depth=3, min_samples_leaf=5. These numbers are just example figures to see how the tree behaves. But if in reality we were asked to work on this model and come up with an optimum value for the model parameters, it is challenging but not impossible (decision tree models can be fine-tuned using GridSearchCV algorithm)."
},
{
"code": null,
"e": 17636,
"s": 17563,
"text": "The other way of doing it is by using the Cost Complexity Pruning (CCP)."
},
{
"code": null,
"e": 17913,
"s": 17636,
"text": "Cost complexity pruning provides another option to control the size of a tree. In DecisionTreeClassifier, this pruning technique is parameterized by the cost complexity parameter, ccp_alpha. Greater values of ccp_alpha increase the number of nodes pruned (Scikit Learn, n.d.)."
},
{
"code": null,
"e": 18130,
"s": 17913,
"text": "In simpler terms, cost complexity is a threshold value. The model split a node further into its child node only when the overall impurity of the model is improved by a value greater than this threshold else it stops."
},
{
"code": null,
"e": 18173,
"s": 18130,
"text": "Lower the CCP, lower is the impurity. How?"
},
{
"code": null,
"e": 18581,
"s": 18173,
"text": "When the value of CCP is lower the model will split a node into its child nodes even if the impurity doesn’t decrease much. This is evident as the depth of the tree increases, i.e. as we go down a decision tree, we will find that split doesn’t contribute much to the change in the overall impurity of the model. However higher split ensures that the classes are categorized correctly, i.e. accuracy is more."
},
{
"code": null,
"e": 18707,
"s": 18581,
"text": "When CCP values are low, a higher number of nodes are created. Higher the nodes, the higher is the depth of the tree as well."
},
{
"code": null,
"e": 18829,
"s": 18707,
"text": "The code below (Scikit Learn, n.d.) illustrates how alpha can be tuned to obtain a model with an improved accuracy score."
},
{
"code": null,
"e": 19210,
"s": 18829,
"text": "path = model_gini.cost_complexity_pruning_path(X_train, y_train)ccp_alphas, impurities = path.ccp_alphas, path.impuritiesfig, ax = plt.subplots(figsize=(16,8));ax.plot(ccp_alphas[:-1], impurities[:-1], marker='o', drawstyle=\"steps-post\");ax.set_xlabel(\"effective alpha\");ax.set_ylabel(\"total impurity of leaves\");ax.set_title(\"Total Impurity vs effective alpha for training set\");"
},
{
"code": null,
"e": 19296,
"s": 19210,
"text": "Let’s understand the variation of depth and the number of nodes with change in alpha."
},
{
"code": null,
"e": 19829,
"s": 19296,
"text": "clfs = clfs[:-1]ccp_alphas = ccp_alphas[:-1]node_counts = [clf.tree_.node_count for clf in clfs]depth = [clf.tree_.max_depth for clf in clfs]fig, ax = plt.subplots(2, 1,figsize=(16,8))ax[0].plot(ccp_alphas, node_counts, marker='o', drawstyle=\"steps-post\")ax[0].set_xlabel(\"alpha\")ax[0].set_ylabel(\"number of nodes\")ax[0].set_title(\"Number of nodes vs alpha\")ax[1].plot(ccp_alphas, depth, marker='o', drawstyle=\"steps-post\")ax[1].set_xlabel(\"alpha\")ax[1].set_ylabel(\"depth of tree\")ax[1].set_title(\"Depth vs alpha\")fig.tight_layout()"
},
{
"code": null,
"e": 19894,
"s": 19829,
"text": "Understanding the variation in accuracy when alpha is increased."
},
{
"code": null,
"e": 20407,
"s": 19894,
"text": "fig, ax = plt.subplots(figsize=(16,8)); #-----------------Setting size of the canvastrain_scores = [clf.score(X_train, y_train) for clf in clfs]test_scores = [clf.score(X_test, y_test) for clf in clfs]ax.set_xlabel(\"alpha\")ax.set_ylabel(\"accuracy\")ax.set_title(\"Accuracy vs alpha for training and testing sets\")ax.plot(ccp_alphas, train_scores, marker='o', label=\"train\", drawstyle=\"steps-post\")ax.plot(ccp_alphas, test_scores, marker='o', label=\"test\", drawstyle=\"steps-post\")ax.legend()plt.show()"
},
{
"code": null,
"e": 20776,
"s": 20407,
"text": "i = np.arange(len(ccp_alphas))ccp = pd.DataFrame({'Depth': pd.Series(depth,index=i),'Node' : pd.Series(node_counts, index=i),\\ 'ccp' : pd.Series(ccp_alphas, index = i),'train_scores' : pd.Series(train_scores, index = i), 'test_scores' : pd.Series(test_scores, index = i)})ccp.tail()ccp[ccp['test_scores']==ccp['test_scores'].max()]"
},
{
"code": null,
"e": 20888,
"s": 20776,
"text": "The above code provides the cost computation pruning value that produces the highest accuracy in the test data."
},
{
"code": null,
"e": 21687,
"s": 20888,
"text": "Raschka, S., Julian, D. and Hearty, J. (2016). Python : deeper insights into machine learning : leverage benefits of machine learning techniques using Python : a course in three modules. Birmingham, Uk: Packt Publishing, pp.83, 88, 89.Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011.Scikit Learn (2019). sklearn.tree.DecisionTreeClassifier — scikit-learn 0.22.1 documentation. [online] Scikit-learn.org. Available at: https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html.Scikit Learn (n.d.). Post pruning decision trees with cost complexity pruning. [online] Available at: https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py."
},
{
"code": null,
"e": 21923,
"s": 21687,
"text": "Raschka, S., Julian, D. and Hearty, J. (2016). Python : deeper insights into machine learning : leverage benefits of machine learning techniques using Python : a course in three modules. Birmingham, Uk: Packt Publishing, pp.83, 88, 89."
},
{
"code": null,
"e": 22014,
"s": 21923,
"text": "Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011."
},
{
"code": null,
"e": 22241,
"s": 22014,
"text": "Scikit Learn (2019). sklearn.tree.DecisionTreeClassifier — scikit-learn 0.22.1 documentation. [online] Scikit-learn.org. Available at: https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html."
},
{
"code": null,
"e": 22489,
"s": 22241,
"text": "Scikit Learn (n.d.). Post pruning decision trees with cost complexity pruning. [online] Available at: https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py."
}
] |
Diagnose the Generalized Linear Models | by Yufeng | Towards Data Science
|
Generalized Linear Model (GLM) is popular because it can deal with a wide range of data with different response variable types (such as binomial, Poisson, or multinomial).
Comparing to the non-linear models, such as the neural networks or tree-based models, the linear models may not be that powerful in terms of prediction. But the easiness in interpretation makes it still attractive, especially when we need to understand how each of the predictors is influencing the outcome.
The shortcomings of GLM are as obvious as its advantages. The linear relationship may not always hold and it is really sensitive to outliers. Therefore, it’s not wise to fit a GLM without diagnosing.
In this post, I am going to briefly talk about how to diagnose a generalized linear model. The implementation will be shown in R codes.
There are mainly two types of diagnostic methods. One is outliers detection, and the other one is model assumptions checking.
Before diving into the diagnoses, we need to be familiar with several types of residuals because we will use them throughout the post. In the Gaussian linear model, the concept of residual is very straight forward which basically describes the difference between the predicted value (by the fitted model) and the data.
In the GLM, it is called “response” residuals, which is just a notation to be differentiated from other types of residuals.
The variance of the response is no more constant in GLM, which leads us to make some modifications to the residuals.
If we rescale the response residual by the standard error of the estimates, it becomes the Pearson residual.
You may see some people use the square root of the estimates instead of the standard error as the denominator in the equation above. That’s because they are using the Poisson model where the estimated variance equals the estimated mean. So, don’t be confused, they are the same thing.
One of the characters of the Pearson residuals is that the sum of squared Pearson residuals approximately follows the chi-squared distribution.
This character inspires researchers to use another type of residual named deviance residual, the sum of squared of which also follows the chi-squared distribution.
Note: The deviance of a model simply describes the goodness of fit, which specifically calculates the difference between the log-likelihood for the full (saturated) model and that for the model under consideration (the model you built for fitting). High deviance indicates a bad fitted model.
Each data point has its own contribution to the model’s deviance. If we assign a direction to each of these individual deviance based on the difference between the fitted value and the data, we get the deviance residual.
Usually, the deviance residual is preferable to the other types of residuals in the diagnostics of GLMs.
In R, it’s simple to implement these different types of residuals using the ‘residuals’ function.
# R code# Suppose your fitted model is modresiduals(mod,type = "response") ## response residualsresiduals(mod,type = "pearson") ## pearson residualsresiduals(mod,type = "deviance") ## deviance residuals
The default performance of the function ‘residuals’ is deviance residual, so don’t worry if you forget to pass the ‘type’ argument to the function.
The plot of residuals against fitted values is the most important graphic in the diagnostics. The plot aims to check whether there is evidence of nonlinearity between the residuals and the fitted values.
One difference between the GLMs and the Gaussian linear models is that the fitted values in GLM should be that before the transformation by the link function, however in the Gaussian model, the fitted values are the predicted responses.
Let’s check the following Poisson model as an example. Remember the Poisson regression model is like this:
Let’s plot the residuals against estimates (mu_i) first.
# R codemod_pois = glm(Species ~ ., family=poisson,gala) # gala is the example dataset in package "faraway"plot(residuals(mod_pois) ~ predict(mod_pois,type="response"),xlab=expression(hat(mu)),ylab="Deviance residuals",pch=20,col="red")
We can see that most points are squeezed at the left side of the plot, which makes it hard to interpret. Therefore, it’s better to check that without the link function’s transformation.
# R codeplot(residuals(mod_pois) ~ predict(mod_pois,type="link"),xlab=expression(hat(eta)),ylab="Deviance residuals",pch=20,col="blue")
If the model’s assumption is met, we do expect a constant variation in the plot because the deviance residuals should not have the nonconstant variation that is already rescaled out. If there’s an obvious nonlinearity in the plot, it will raise the warning sign. However, this plot looks OK without any nonlinearity.
Let’s say if there is an obvious nonlinearity in the plot, what should we do?
Usually, it’s not wise to start with changing the link function or transform the response variables. The selection of the link function is usually limited with the natural features of your response data, for example, the Poisson model will require the response variable to be positive. Similarly, the transformation of the response variable will violate the assumed distribution of the response.
It’s worth trying two things:
change the model type. For example, utilize a negative binomial model instead of the Poisson model.Do some transformation to the predictors, like log(), sqrt(), and so on...
change the model type. For example, utilize a negative binomial model instead of the Poisson model.
Do some transformation to the predictors, like log(), sqrt(), and so on...
Another important part of diagnostics on GLMs is to detect the outliers. It could be done either quantitatively or graphically.
In the quantitative way of detecting the outliers, the basic idea is to find those points that have an abnormally large influence on the model or those that the fitted model is most sensitive to.
Two metrics could be used on a fitted model: the leverage and the Cook’s distance. Here are the codes in R.
# R codei_n = influence(mod_pois)$hat # calculate the influence of data pointswhich.max(i_n)
which yields,
## SantaCruz ## 25
It means the data point “SantaCruz” has the largest influence on the fitted Poisson model.
If we apply the Cook’s distance metric, it will yield the same result.
# R codec_d = cooks.distance(mod_pois)which.max(c_d)
the result is,
## SantaCruz ## 25
We can also detect outliers graphically, which uses the QQ plot. One difference from the Gaussian linear models’ diagnostics, we are not looking for a straight line in the QQ plot in GLM diagnostics because the residuals are not expected to be normally distributed. The only purpose of the QQ plot in GLM is to find the outliers in the data.
# R codehalfnorm((i_n))
# R codehalfnorm((c_d))
These methods suggest further investigation on the data point “25 SantaCruz”.
It’s important to run the diagnostics in the GLMs.Two aspects need investigation: model assumptions and outliers.Transformation on predictors but not on response variables if necessary.Remove outliers that are detected both quantitatively and graphically.
It’s important to run the diagnostics in the GLMs.
Two aspects need investigation: model assumptions and outliers.
Transformation on predictors but not on response variables if necessary.
Remove outliers that are detected both quantitatively and graphically.
Hope this post is helpful to you.
Faraway, Julian J. Extending the linear model with R: generalized linear, mixed effects and nonparametric regression models. CRC press, 2016.
|
[
{
"code": null,
"e": 343,
"s": 171,
"text": "Generalized Linear Model (GLM) is popular because it can deal with a wide range of data with different response variable types (such as binomial, Poisson, or multinomial)."
},
{
"code": null,
"e": 651,
"s": 343,
"text": "Comparing to the non-linear models, such as the neural networks or tree-based models, the linear models may not be that powerful in terms of prediction. But the easiness in interpretation makes it still attractive, especially when we need to understand how each of the predictors is influencing the outcome."
},
{
"code": null,
"e": 851,
"s": 651,
"text": "The shortcomings of GLM are as obvious as its advantages. The linear relationship may not always hold and it is really sensitive to outliers. Therefore, it’s not wise to fit a GLM without diagnosing."
},
{
"code": null,
"e": 987,
"s": 851,
"text": "In this post, I am going to briefly talk about how to diagnose a generalized linear model. The implementation will be shown in R codes."
},
{
"code": null,
"e": 1113,
"s": 987,
"text": "There are mainly two types of diagnostic methods. One is outliers detection, and the other one is model assumptions checking."
},
{
"code": null,
"e": 1432,
"s": 1113,
"text": "Before diving into the diagnoses, we need to be familiar with several types of residuals because we will use them throughout the post. In the Gaussian linear model, the concept of residual is very straight forward which basically describes the difference between the predicted value (by the fitted model) and the data."
},
{
"code": null,
"e": 1556,
"s": 1432,
"text": "In the GLM, it is called “response” residuals, which is just a notation to be differentiated from other types of residuals."
},
{
"code": null,
"e": 1673,
"s": 1556,
"text": "The variance of the response is no more constant in GLM, which leads us to make some modifications to the residuals."
},
{
"code": null,
"e": 1782,
"s": 1673,
"text": "If we rescale the response residual by the standard error of the estimates, it becomes the Pearson residual."
},
{
"code": null,
"e": 2067,
"s": 1782,
"text": "You may see some people use the square root of the estimates instead of the standard error as the denominator in the equation above. That’s because they are using the Poisson model where the estimated variance equals the estimated mean. So, don’t be confused, they are the same thing."
},
{
"code": null,
"e": 2211,
"s": 2067,
"text": "One of the characters of the Pearson residuals is that the sum of squared Pearson residuals approximately follows the chi-squared distribution."
},
{
"code": null,
"e": 2375,
"s": 2211,
"text": "This character inspires researchers to use another type of residual named deviance residual, the sum of squared of which also follows the chi-squared distribution."
},
{
"code": null,
"e": 2668,
"s": 2375,
"text": "Note: The deviance of a model simply describes the goodness of fit, which specifically calculates the difference between the log-likelihood for the full (saturated) model and that for the model under consideration (the model you built for fitting). High deviance indicates a bad fitted model."
},
{
"code": null,
"e": 2889,
"s": 2668,
"text": "Each data point has its own contribution to the model’s deviance. If we assign a direction to each of these individual deviance based on the difference between the fitted value and the data, we get the deviance residual."
},
{
"code": null,
"e": 2994,
"s": 2889,
"text": "Usually, the deviance residual is preferable to the other types of residuals in the diagnostics of GLMs."
},
{
"code": null,
"e": 3092,
"s": 2994,
"text": "In R, it’s simple to implement these different types of residuals using the ‘residuals’ function."
},
{
"code": null,
"e": 3295,
"s": 3092,
"text": "# R code# Suppose your fitted model is modresiduals(mod,type = \"response\") ## response residualsresiduals(mod,type = \"pearson\") ## pearson residualsresiduals(mod,type = \"deviance\") ## deviance residuals"
},
{
"code": null,
"e": 3443,
"s": 3295,
"text": "The default performance of the function ‘residuals’ is deviance residual, so don’t worry if you forget to pass the ‘type’ argument to the function."
},
{
"code": null,
"e": 3647,
"s": 3443,
"text": "The plot of residuals against fitted values is the most important graphic in the diagnostics. The plot aims to check whether there is evidence of nonlinearity between the residuals and the fitted values."
},
{
"code": null,
"e": 3884,
"s": 3647,
"text": "One difference between the GLMs and the Gaussian linear models is that the fitted values in GLM should be that before the transformation by the link function, however in the Gaussian model, the fitted values are the predicted responses."
},
{
"code": null,
"e": 3991,
"s": 3884,
"text": "Let’s check the following Poisson model as an example. Remember the Poisson regression model is like this:"
},
{
"code": null,
"e": 4048,
"s": 3991,
"text": "Let’s plot the residuals against estimates (mu_i) first."
},
{
"code": null,
"e": 4285,
"s": 4048,
"text": "# R codemod_pois = glm(Species ~ ., family=poisson,gala) # gala is the example dataset in package \"faraway\"plot(residuals(mod_pois) ~ predict(mod_pois,type=\"response\"),xlab=expression(hat(mu)),ylab=\"Deviance residuals\",pch=20,col=\"red\")"
},
{
"code": null,
"e": 4471,
"s": 4285,
"text": "We can see that most points are squeezed at the left side of the plot, which makes it hard to interpret. Therefore, it’s better to check that without the link function’s transformation."
},
{
"code": null,
"e": 4607,
"s": 4471,
"text": "# R codeplot(residuals(mod_pois) ~ predict(mod_pois,type=\"link\"),xlab=expression(hat(eta)),ylab=\"Deviance residuals\",pch=20,col=\"blue\")"
},
{
"code": null,
"e": 4924,
"s": 4607,
"text": "If the model’s assumption is met, we do expect a constant variation in the plot because the deviance residuals should not have the nonconstant variation that is already rescaled out. If there’s an obvious nonlinearity in the plot, it will raise the warning sign. However, this plot looks OK without any nonlinearity."
},
{
"code": null,
"e": 5002,
"s": 4924,
"text": "Let’s say if there is an obvious nonlinearity in the plot, what should we do?"
},
{
"code": null,
"e": 5398,
"s": 5002,
"text": "Usually, it’s not wise to start with changing the link function or transform the response variables. The selection of the link function is usually limited with the natural features of your response data, for example, the Poisson model will require the response variable to be positive. Similarly, the transformation of the response variable will violate the assumed distribution of the response."
},
{
"code": null,
"e": 5428,
"s": 5398,
"text": "It’s worth trying two things:"
},
{
"code": null,
"e": 5602,
"s": 5428,
"text": "change the model type. For example, utilize a negative binomial model instead of the Poisson model.Do some transformation to the predictors, like log(), sqrt(), and so on..."
},
{
"code": null,
"e": 5702,
"s": 5602,
"text": "change the model type. For example, utilize a negative binomial model instead of the Poisson model."
},
{
"code": null,
"e": 5777,
"s": 5702,
"text": "Do some transformation to the predictors, like log(), sqrt(), and so on..."
},
{
"code": null,
"e": 5905,
"s": 5777,
"text": "Another important part of diagnostics on GLMs is to detect the outliers. It could be done either quantitatively or graphically."
},
{
"code": null,
"e": 6101,
"s": 5905,
"text": "In the quantitative way of detecting the outliers, the basic idea is to find those points that have an abnormally large influence on the model or those that the fitted model is most sensitive to."
},
{
"code": null,
"e": 6209,
"s": 6101,
"text": "Two metrics could be used on a fitted model: the leverage and the Cook’s distance. Here are the codes in R."
},
{
"code": null,
"e": 6302,
"s": 6209,
"text": "# R codei_n = influence(mod_pois)$hat # calculate the influence of data pointswhich.max(i_n)"
},
{
"code": null,
"e": 6316,
"s": 6302,
"text": "which yields,"
},
{
"code": null,
"e": 6342,
"s": 6316,
"text": "## SantaCruz ## 25"
},
{
"code": null,
"e": 6433,
"s": 6342,
"text": "It means the data point “SantaCruz” has the largest influence on the fitted Poisson model."
},
{
"code": null,
"e": 6504,
"s": 6433,
"text": "If we apply the Cook’s distance metric, it will yield the same result."
},
{
"code": null,
"e": 6557,
"s": 6504,
"text": "# R codec_d = cooks.distance(mod_pois)which.max(c_d)"
},
{
"code": null,
"e": 6572,
"s": 6557,
"text": "the result is,"
},
{
"code": null,
"e": 6598,
"s": 6572,
"text": "## SantaCruz ## 25"
},
{
"code": null,
"e": 6940,
"s": 6598,
"text": "We can also detect outliers graphically, which uses the QQ plot. One difference from the Gaussian linear models’ diagnostics, we are not looking for a straight line in the QQ plot in GLM diagnostics because the residuals are not expected to be normally distributed. The only purpose of the QQ plot in GLM is to find the outliers in the data."
},
{
"code": null,
"e": 6964,
"s": 6940,
"text": "# R codehalfnorm((i_n))"
},
{
"code": null,
"e": 6988,
"s": 6964,
"text": "# R codehalfnorm((c_d))"
},
{
"code": null,
"e": 7066,
"s": 6988,
"text": "These methods suggest further investigation on the data point “25 SantaCruz”."
},
{
"code": null,
"e": 7322,
"s": 7066,
"text": "It’s important to run the diagnostics in the GLMs.Two aspects need investigation: model assumptions and outliers.Transformation on predictors but not on response variables if necessary.Remove outliers that are detected both quantitatively and graphically."
},
{
"code": null,
"e": 7373,
"s": 7322,
"text": "It’s important to run the diagnostics in the GLMs."
},
{
"code": null,
"e": 7437,
"s": 7373,
"text": "Two aspects need investigation: model assumptions and outliers."
},
{
"code": null,
"e": 7510,
"s": 7437,
"text": "Transformation on predictors but not on response variables if necessary."
},
{
"code": null,
"e": 7581,
"s": 7510,
"text": "Remove outliers that are detected both quantitatively and graphically."
},
{
"code": null,
"e": 7615,
"s": 7581,
"text": "Hope this post is helpful to you."
}
] |
How BEFORE INSERT triggers can be used to emulate CHECK CONSTRAINT for inserting values in the table?
|
As we know that MySQL supports foreign key for referential integrity but it does not support CHECK constraint. But we can emulate them by using triggers. It can be illustrated with the help of an example given below −
Suppose we have a table named ‘car’ which can have the fix syntax registration number like two letters, a dash, three digits, a dash, two letters as follows −
mysql> Create table car (number char(9));
Query OK, 0 rows affected (0.32 sec)
mysql> Insert into car values('AB-235-YZ');
Query OK, 1 row affected (0.10 sec)
The above value is a valid one but what about the value that we are going to insert in the next query.
mysql> insert into car values('AB-2X5-YZ');
Query OK, 1 row affected (0.04 sec)
The above value is not a valid one because it contains a character between digits which is against the fixed syntax we are using.
Creating BEFORE INSERT trigger to emulate CHECK CONSTRAINT for inserting the values −
Now, we can create a trigger as follows to prevent such kind of insertion −
mysql> delimiter //
mysql> create trigger car_insert_value before insert on car
-> for each row
-> begin
-> if new.number not rlike '^[[:alpha:]]{2}-[[:digit:]]{3}-[[:alpha:]]{2}$'
-> then
-> signal sqlstate '45000' set message_text = 'Not a valid Number';
-> end if;
-> end //
Query OK, 0 rows affected (0.15 sec)
mysql> Delimiter ;
mysql> Delete from car;
Query OK, 2 rows affected (0.06 sec)
Now, when we will try to insert the incorrect number, the above-created trigger will stop us to do so and will throw an error as follows −
mysql> insert into car values('AB-2X5-YZ');
ERROR 1644 (45000): Not a Valid Number
But, we can insert the valid values as follows −
mysql> insert into car values('AB-235-YZ');
Query OK, 1 row affected (0.04 sec)
|
[
{
"code": null,
"e": 1280,
"s": 1062,
"text": "As we know that MySQL supports foreign key for referential integrity but it does not support CHECK constraint. But we can emulate them by using triggers. It can be illustrated with the help of an example given below −"
},
{
"code": null,
"e": 1439,
"s": 1280,
"text": "Suppose we have a table named ‘car’ which can have the fix syntax registration number like two letters, a dash, three digits, a dash, two letters as follows −"
},
{
"code": null,
"e": 1599,
"s": 1439,
"text": "mysql> Create table car (number char(9));\nQuery OK, 0 rows affected (0.32 sec)\n\nmysql> Insert into car values('AB-235-YZ');\nQuery OK, 1 row affected (0.10 sec)"
},
{
"code": null,
"e": 1702,
"s": 1599,
"text": "The above value is a valid one but what about the value that we are going to insert in the next query."
},
{
"code": null,
"e": 1782,
"s": 1702,
"text": "mysql> insert into car values('AB-2X5-YZ');\nQuery OK, 1 row affected (0.04 sec)"
},
{
"code": null,
"e": 1912,
"s": 1782,
"text": "The above value is not a valid one because it contains a character between digits which is against the fixed syntax we are using."
},
{
"code": null,
"e": 1998,
"s": 1912,
"text": "Creating BEFORE INSERT trigger to emulate CHECK CONSTRAINT for inserting the values −"
},
{
"code": null,
"e": 2074,
"s": 1998,
"text": "Now, we can create a trigger as follows to prevent such kind of insertion −"
},
{
"code": null,
"e": 2518,
"s": 2074,
"text": "mysql> delimiter //\nmysql> create trigger car_insert_value before insert on car\n -> for each row\n -> begin\n -> if new.number not rlike '^[[:alpha:]]{2}-[[:digit:]]{3}-[[:alpha:]]{2}$'\n -> then\n -> signal sqlstate '45000' set message_text = 'Not a valid Number';\n -> end if;\n -> end //\nQuery OK, 0 rows affected (0.15 sec)\nmysql> Delimiter ;\n\nmysql> Delete from car;\nQuery OK, 2 rows affected (0.06 sec)"
},
{
"code": null,
"e": 2657,
"s": 2518,
"text": "Now, when we will try to insert the incorrect number, the above-created trigger will stop us to do so and will throw an error as follows −"
},
{
"code": null,
"e": 2740,
"s": 2657,
"text": "mysql> insert into car values('AB-2X5-YZ');\nERROR 1644 (45000): Not a Valid Number"
},
{
"code": null,
"e": 2789,
"s": 2740,
"text": "But, we can insert the valid values as follows −"
},
{
"code": null,
"e": 2869,
"s": 2789,
"text": "mysql> insert into car values('AB-235-YZ');\nQuery OK, 1 row affected (0.04 sec)"
}
] |
BigDecimal intvalueExact() Method in Java - GeeksforGeeks
|
04 Dec, 2018
The java.math.BigDecimal.intValueExact() is an inbuilt function which converts this BigDecimal to an integer value as well as checks for the lost information. This function throws an Arithmetic Exception if there is any fractional part of this BigDecimal or if the result of the conversion is too big to be represented as an integer value.
Syntax:
public int intValueExact()
Parameters: This function accepts no parameters.
Return Value: This function returns the integer value of this BigDecimal.
Exception: The function throws an ArithmeticException if there is a non-zero fractional part in this BigDecimal or its value is too big to be represented as an integer.
Examples:
Input : "19878124"
Output : 19878124
Input : "721111"
Output : 721111
Below programs illustrate the use of java.math.BigDecimal.intValueExact() method:Program 1:
// Java program to illustrate// intValueExact() methodimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal("19878124"); b2 = new BigDecimal("721111"); // Displaying their respective Integer Values System.out.println("Exact Integer Value of " + b1 + " is " + b1.intValueExact()); System.out.println("Exact Integer Value of " + b2 + " is " + b2.intValueExact()); }}
Exact Integer Value of 19878124 is 19878124
Exact Integer Value of 721111 is 721111
Note: Unlike intValue() function which function discards any fractional part of this BigDecimal and returns only the lower-order 32 bits when result of the conversion is too big to be represented as a an integer value, this function throws Arithmetic Exception in such occurrences.
Program 2: This program will illustrate when this function throws Exception.
// Java program to illustrate// Arithmetic Exception occurrence// in intValueExact() methodimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal("3232435121868179"); b2 = new BigDecimal("84561789104423214"); // Displaying their respective Integer Values // using intValue() System.out.println("Output by intValue() Function"); System.out.println("The Integer Value of " + b1 + " is " + b1.intValue()); System.out.println("The Integer Value of " + b2 + " is " + b2.intValue()); // Exception handling System.out.println("\nOutput by intValueExact() Function"); try { System.out.println("Exact Integer Value of " + b1 + " is " + b1.intValueExact()); System.out.println("Exact Integer Value of " + b2 + " is " + b2.intValueExact()); } catch (ArithmeticException e) { System.out.println("Arithmetic Exception caught"); } }}
Output by intValue() Function
The Integer Value of 3232435121868179 is -214774381
The Integer Value of 84561789104423214 is -920387282
Output by intValueExact() Function
Arithmetic Exception caught
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#intValueExact()
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Overriding in Java
Singleton Class in Java
Collections in Java
Multithreading in Java
Set in Java
LinkedList in Java
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 24486,
"s": 24458,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 24826,
"s": 24486,
"text": "The java.math.BigDecimal.intValueExact() is an inbuilt function which converts this BigDecimal to an integer value as well as checks for the lost information. This function throws an Arithmetic Exception if there is any fractional part of this BigDecimal or if the result of the conversion is too big to be represented as an integer value."
},
{
"code": null,
"e": 24834,
"s": 24826,
"text": "Syntax:"
},
{
"code": null,
"e": 24861,
"s": 24834,
"text": "public int intValueExact()"
},
{
"code": null,
"e": 24910,
"s": 24861,
"text": "Parameters: This function accepts no parameters."
},
{
"code": null,
"e": 24984,
"s": 24910,
"text": "Return Value: This function returns the integer value of this BigDecimal."
},
{
"code": null,
"e": 25153,
"s": 24984,
"text": "Exception: The function throws an ArithmeticException if there is a non-zero fractional part in this BigDecimal or its value is too big to be represented as an integer."
},
{
"code": null,
"e": 25163,
"s": 25153,
"text": "Examples:"
},
{
"code": null,
"e": 25235,
"s": 25163,
"text": "Input : \"19878124\"\nOutput : 19878124\n\nInput : \"721111\"\nOutput : 721111\n"
},
{
"code": null,
"e": 25327,
"s": 25235,
"text": "Below programs illustrate the use of java.math.BigDecimal.intValueExact() method:Program 1:"
},
{
"code": "// Java program to illustrate// intValueExact() methodimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal(\"19878124\"); b2 = new BigDecimal(\"721111\"); // Displaying their respective Integer Values System.out.println(\"Exact Integer Value of \" + b1 + \" is \" + b1.intValueExact()); System.out.println(\"Exact Integer Value of \" + b2 + \" is \" + b2.intValueExact()); }}",
"e": 25910,
"s": 25327,
"text": null
},
{
"code": null,
"e": 25995,
"s": 25910,
"text": "Exact Integer Value of 19878124 is 19878124\nExact Integer Value of 721111 is 721111\n"
},
{
"code": null,
"e": 26277,
"s": 25995,
"text": "Note: Unlike intValue() function which function discards any fractional part of this BigDecimal and returns only the lower-order 32 bits when result of the conversion is too big to be represented as a an integer value, this function throws Arithmetic Exception in such occurrences."
},
{
"code": null,
"e": 26354,
"s": 26277,
"text": "Program 2: This program will illustrate when this function throws Exception."
},
{
"code": "// Java program to illustrate// Arithmetic Exception occurrence// in intValueExact() methodimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal(\"3232435121868179\"); b2 = new BigDecimal(\"84561789104423214\"); // Displaying their respective Integer Values // using intValue() System.out.println(\"Output by intValue() Function\"); System.out.println(\"The Integer Value of \" + b1 + \" is \" + b1.intValue()); System.out.println(\"The Integer Value of \" + b2 + \" is \" + b2.intValue()); // Exception handling System.out.println(\"\\nOutput by intValueExact() Function\"); try { System.out.println(\"Exact Integer Value of \" + b1 + \" is \" + b1.intValueExact()); System.out.println(\"Exact Integer Value of \" + b2 + \" is \" + b2.intValueExact()); } catch (ArithmeticException e) { System.out.println(\"Arithmetic Exception caught\"); } }}",
"e": 27520,
"s": 26354,
"text": null
},
{
"code": null,
"e": 27720,
"s": 27520,
"text": "Output by intValue() Function\nThe Integer Value of 3232435121868179 is -214774381\nThe Integer Value of 84561789104423214 is -920387282\n\nOutput by intValueExact() Function\nArithmetic Exception caught\n"
},
{
"code": null,
"e": 27815,
"s": 27720,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#intValueExact()"
},
{
"code": null,
"e": 27831,
"s": 27815,
"text": "Java-BigDecimal"
},
{
"code": null,
"e": 27846,
"s": 27831,
"text": "Java-Functions"
},
{
"code": null,
"e": 27856,
"s": 27846,
"text": "java-math"
},
{
"code": null,
"e": 27874,
"s": 27856,
"text": "Java-math-package"
},
{
"code": null,
"e": 27879,
"s": 27874,
"text": "Java"
},
{
"code": null,
"e": 27884,
"s": 27879,
"text": "Java"
},
{
"code": null,
"e": 27982,
"s": 27884,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27991,
"s": 27982,
"text": "Comments"
},
{
"code": null,
"e": 28004,
"s": 27991,
"text": "Old Comments"
},
{
"code": null,
"e": 28023,
"s": 28004,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28041,
"s": 28023,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28073,
"s": 28041,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28092,
"s": 28073,
"text": "Overriding in Java"
},
{
"code": null,
"e": 28116,
"s": 28092,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 28136,
"s": 28116,
"text": "Collections in Java"
},
{
"code": null,
"e": 28159,
"s": 28136,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 28171,
"s": 28159,
"text": "Set in Java"
},
{
"code": null,
"e": 28190,
"s": 28171,
"text": "LinkedList in Java"
}
] |
Use Redis Queue for Asynchronous Tasks in a Flask App | by Edward Krueger | Towards Data Science
|
By: Content by Edward Krueger, Josh Farmer and Douglas Franklin.
When building an application that performs time-consuming, complex, or resource-intensive tasks, it can be frustrating to wait for these to complete within the front end application. Additionally, complex tasks in the front end can time-out. Redis Queue fixes this by pushing more sophisticated tasks to a worker for processing.
Using Redis with Redis Queue allows you to enter those complex tasks into a queue, so the Redis worker executes these tasks outside of your application’s HTTP server.
In this article, we will build an app that enqueues jobs with Redis queue, performs a function on those jobs and returns the result of the function.
Here is the link to the Github Repository with our code for this project.
Redis is an open-source, in-memory database, cache, and message broker. Messages handled by Redis are essentially JSONs. Redis is ideal for quickly and easily working with specific data types in a temporary database, and provides very rapid access and delivery of queries.
For us, Redis offers two benefits. First, it pushes complex tasks to another space to be processed. Second, it is easier for the developer to handle complex actions by splitting the task into separate functions, the main application and the queue.
For this application, we’ll be using Redis to hold our queue of JSON messages. Redis can be a stand-alone database, accessible by many computers or systems. In our example, we will be using it as a local memory store to support our application.
Redis Queue is a python library for queueing jobs for background processing. Since many hosting services will time out on long HTTP requests, it is best to design APIs to close requests as quickly as possible. Redis Queue allows us to do this by pushing tasks to a queue and then to a worker for processing.
Using Redis in conjunction with Redis Queue allows you to request input from the user, return a validation response to the user, and queue up processes in the background. All without the front end user having to wait for those processes to complete. Processes could be anything from Machine Learning models, to duplicating an image to complex simulations.
Anything that takes longer to complete than you would like to have taken place on the front end of your application belongs in the Redis Queue.
We will cover using Docker to run the Redis database and initialize the Redis Queue worker. The worker will allow us to process the jobs in our application’s queue.
We’ll go over each of these files in more detail in the following sections.
We’ll discuss the following constituent files of our app, main.py, functions.py, and redis_resc.py.
There are two ways to initiate the docker container. We will be covering the standard process one step at a time in this article. However, the docker container can be created using docker-compose, which we will cover in a separate article.
Docker is a containerization service. This means Docker runs code within a container that has within it the dependencies required for the application to run reliably from one system to another. It ensures our applications run consistently, from development to testing to production.
Follow this link to the Docker documentation for a comprehensive installation guide to help you select the correct version of Docker for your operating system.
Once you have Docker installed on your system, you will need to install Redis.
For Mac users, the home-brew command brew install redis will work. Windows requires a download from Github. With Linux, you can download the latest tarball directly from Redis.
To run our application, we must understand the instructions on the Readme file.
We will be using Pipenv to create a virtual environment and install the appropriate packages. Install the packages for this program with the command pipenv install -- dev. Adding the --dev flag installs development packages and production requirements. Before moving to the next step, activate the environment with the command pipenv shell.
We will have to start three services to have the app function correctly: Redis Database, a Redis Queue worker, and the Flask application. Two of these services will begin within the same terminal as the one we used to install our virtual environment and enter the shell.
First, run the command:
docker pull redis
This will pull the Redis image from Docker Hub.
Then, run the command:
docker run -d -p 6379:6379 redis
This command serves several purposes. First, it initializes the docker container. The -d flag runs the Redis container in the background, freeing up your terminal for the next step. The -p flag publishes your container’s port or ports to the host. Lastly, 6379:6379 binds port 6379 inside the docker container to port 6379 on the localhost. Without binding the port, you will run into issues when the local machine and processes within your docker container attempt to communicate with one another.
The final step before running our application is starting the Redis Queue worker. Since we are running the Redis image in detached mode, we can do this step within the same terminal.
Start the Redis worker with the command rq worker . The rq command is only available to the terminal if the Redis Queue package is installed, we installed the dependencies with Pipenv install, and entered the environment with pipenv shell. Running the rq command will allow Redis Queue to begin listening for jobs to enter into the queue and start processing these jobs.
We are now ready to initialize the flask app. On a development server, this is done with the command:
export FLASK_APP=app.main:app && flask run — reload
The command gunicorn app.main:app will run this on a production server. Gunicorn requires a Unix platform to run. Therefore, this command will work if you are using macOS or a Linux based system, but not for windows.
Now that the services are running, let’s move to the app files.
This file sets up the Redis connection and the Redis Queue.
The variable redis_conn defines the connection parameters for this connection, and redis_queue uses the Queue method. The Queue method initiates the queue, and any name can be given. Common naming patters are ‘low,’ ‘medium’ and ‘high.’ By providing the Queue method no args, we are instructing it to use the default queue. Aside from the name, we are simply passing our method the connection string to the Redis store.
Functions.py is where we define the functions to use in the Redis queue.
What some_long_function does is up to you. It can be anything you want with done with the data passed to the worker. This could be anything from machine learning, to image manipulation, to using the information to process queries in a connected database. Anything you want the backend to do so the front end doesn't wait would be placed within this function.
For our example, this function serves a couple of purposes. First, the job variable is created to retrieve the current job being worked. We use time.sleep(10) to demonstrate the different job status codes as the job is being processed. We will go into more detail on the job status codes later in the article. Finally, we return a JSON that contains information about the job and the results of processing the job.
Main.py is the primary flask app that drives the application. More details on setting up a flask app are outlined in this medium article.
towardsdatascience.com
The first route function, resource_not_found , is designed to handle any 404 errors that result from incorrect requests to the application. The route function defined as home is the default route that runs when you navigate to the home route. This route runs when you perform a GET request to http://127.0.0.1:8000 or the localhost URL. This route designed to let you know the flask app is running.
We can test it with Postman as seen below.
The remaining routes, specific for the Redis Queue, will be covered in more detail below.
The /enqueue route creates the task and enters the task into the queue. Redis Queue accepts things such as key-value pairs so that you can create a post request with a dictionary, for example:
{“hello”: “world”}
Submitting a JSON post request to the /enqueue route will tell the application to enqueue the JSON to the function some_long_function within the function.py file for processing.
The /enqueue route returns the job_id of the task created once it has done so. Take note of the job_id, as we will use it as part of the URL string for the application’s remaining routes.
This route takes the job_id and checks its status in the Redis Queue. The full URL of this route is http://127.0.0.1:8000?job_id=JobID. Where JobID is the job_id that was generated when the /enqueue route created the job.
The /check_status route will return a JSON that contains the job_id passed in the URL and the status of the job using the get_status method of rq.job. Remember within the some_long_function, the time.sleep at the start of the function. If you hit this route with a get request before the ten-second timer, the status will show ‘Queue.’ After some_long_function completes, the status will return as ‘finished.’
Once a job is shown as ‘finished’ by the /check_status route, get_result will return the results of the processed job. The results are determined by what you have set up within some_long_function. This URL follows the same structure as /check_status so it is:
http://127.0.0.1:8000?get_result=JobID
Our some_long_function returns data about the job, as seen in the image above.
In this article, we learned a little about building a queue of tasks with Redis Queue, and how to utilize a Redis database within a docker container. We covered how to build the application that makes it simple to enqueue time-consuming tasks without tying up or hindering our front end performance.
github.com
Here is the link to the Github Repository with our code for this project. Test it out for yourself and try queueing a few JSON tasks and viewing the results!
|
[
{
"code": null,
"e": 237,
"s": 172,
"text": "By: Content by Edward Krueger, Josh Farmer and Douglas Franklin."
},
{
"code": null,
"e": 566,
"s": 237,
"text": "When building an application that performs time-consuming, complex, or resource-intensive tasks, it can be frustrating to wait for these to complete within the front end application. Additionally, complex tasks in the front end can time-out. Redis Queue fixes this by pushing more sophisticated tasks to a worker for processing."
},
{
"code": null,
"e": 733,
"s": 566,
"text": "Using Redis with Redis Queue allows you to enter those complex tasks into a queue, so the Redis worker executes these tasks outside of your application’s HTTP server."
},
{
"code": null,
"e": 882,
"s": 733,
"text": "In this article, we will build an app that enqueues jobs with Redis queue, performs a function on those jobs and returns the result of the function."
},
{
"code": null,
"e": 956,
"s": 882,
"text": "Here is the link to the Github Repository with our code for this project."
},
{
"code": null,
"e": 1229,
"s": 956,
"text": "Redis is an open-source, in-memory database, cache, and message broker. Messages handled by Redis are essentially JSONs. Redis is ideal for quickly and easily working with specific data types in a temporary database, and provides very rapid access and delivery of queries."
},
{
"code": null,
"e": 1477,
"s": 1229,
"text": "For us, Redis offers two benefits. First, it pushes complex tasks to another space to be processed. Second, it is easier for the developer to handle complex actions by splitting the task into separate functions, the main application and the queue."
},
{
"code": null,
"e": 1722,
"s": 1477,
"text": "For this application, we’ll be using Redis to hold our queue of JSON messages. Redis can be a stand-alone database, accessible by many computers or systems. In our example, we will be using it as a local memory store to support our application."
},
{
"code": null,
"e": 2030,
"s": 1722,
"text": "Redis Queue is a python library for queueing jobs for background processing. Since many hosting services will time out on long HTTP requests, it is best to design APIs to close requests as quickly as possible. Redis Queue allows us to do this by pushing tasks to a queue and then to a worker for processing."
},
{
"code": null,
"e": 2386,
"s": 2030,
"text": "Using Redis in conjunction with Redis Queue allows you to request input from the user, return a validation response to the user, and queue up processes in the background. All without the front end user having to wait for those processes to complete. Processes could be anything from Machine Learning models, to duplicating an image to complex simulations."
},
{
"code": null,
"e": 2530,
"s": 2386,
"text": "Anything that takes longer to complete than you would like to have taken place on the front end of your application belongs in the Redis Queue."
},
{
"code": null,
"e": 2695,
"s": 2530,
"text": "We will cover using Docker to run the Redis database and initialize the Redis Queue worker. The worker will allow us to process the jobs in our application’s queue."
},
{
"code": null,
"e": 2771,
"s": 2695,
"text": "We’ll go over each of these files in more detail in the following sections."
},
{
"code": null,
"e": 2871,
"s": 2771,
"text": "We’ll discuss the following constituent files of our app, main.py, functions.py, and redis_resc.py."
},
{
"code": null,
"e": 3111,
"s": 2871,
"text": "There are two ways to initiate the docker container. We will be covering the standard process one step at a time in this article. However, the docker container can be created using docker-compose, which we will cover in a separate article."
},
{
"code": null,
"e": 3394,
"s": 3111,
"text": "Docker is a containerization service. This means Docker runs code within a container that has within it the dependencies required for the application to run reliably from one system to another. It ensures our applications run consistently, from development to testing to production."
},
{
"code": null,
"e": 3554,
"s": 3394,
"text": "Follow this link to the Docker documentation for a comprehensive installation guide to help you select the correct version of Docker for your operating system."
},
{
"code": null,
"e": 3633,
"s": 3554,
"text": "Once you have Docker installed on your system, you will need to install Redis."
},
{
"code": null,
"e": 3810,
"s": 3633,
"text": "For Mac users, the home-brew command brew install redis will work. Windows requires a download from Github. With Linux, you can download the latest tarball directly from Redis."
},
{
"code": null,
"e": 3890,
"s": 3810,
"text": "To run our application, we must understand the instructions on the Readme file."
},
{
"code": null,
"e": 4231,
"s": 3890,
"text": "We will be using Pipenv to create a virtual environment and install the appropriate packages. Install the packages for this program with the command pipenv install -- dev. Adding the --dev flag installs development packages and production requirements. Before moving to the next step, activate the environment with the command pipenv shell."
},
{
"code": null,
"e": 4502,
"s": 4231,
"text": "We will have to start three services to have the app function correctly: Redis Database, a Redis Queue worker, and the Flask application. Two of these services will begin within the same terminal as the one we used to install our virtual environment and enter the shell."
},
{
"code": null,
"e": 4526,
"s": 4502,
"text": "First, run the command:"
},
{
"code": null,
"e": 4544,
"s": 4526,
"text": "docker pull redis"
},
{
"code": null,
"e": 4592,
"s": 4544,
"text": "This will pull the Redis image from Docker Hub."
},
{
"code": null,
"e": 4615,
"s": 4592,
"text": "Then, run the command:"
},
{
"code": null,
"e": 4648,
"s": 4615,
"text": "docker run -d -p 6379:6379 redis"
},
{
"code": null,
"e": 5147,
"s": 4648,
"text": "This command serves several purposes. First, it initializes the docker container. The -d flag runs the Redis container in the background, freeing up your terminal for the next step. The -p flag publishes your container’s port or ports to the host. Lastly, 6379:6379 binds port 6379 inside the docker container to port 6379 on the localhost. Without binding the port, you will run into issues when the local machine and processes within your docker container attempt to communicate with one another."
},
{
"code": null,
"e": 5330,
"s": 5147,
"text": "The final step before running our application is starting the Redis Queue worker. Since we are running the Redis image in detached mode, we can do this step within the same terminal."
},
{
"code": null,
"e": 5701,
"s": 5330,
"text": "Start the Redis worker with the command rq worker . The rq command is only available to the terminal if the Redis Queue package is installed, we installed the dependencies with Pipenv install, and entered the environment with pipenv shell. Running the rq command will allow Redis Queue to begin listening for jobs to enter into the queue and start processing these jobs."
},
{
"code": null,
"e": 5803,
"s": 5701,
"text": "We are now ready to initialize the flask app. On a development server, this is done with the command:"
},
{
"code": null,
"e": 5855,
"s": 5803,
"text": "export FLASK_APP=app.main:app && flask run — reload"
},
{
"code": null,
"e": 6072,
"s": 5855,
"text": "The command gunicorn app.main:app will run this on a production server. Gunicorn requires a Unix platform to run. Therefore, this command will work if you are using macOS or a Linux based system, but not for windows."
},
{
"code": null,
"e": 6136,
"s": 6072,
"text": "Now that the services are running, let’s move to the app files."
},
{
"code": null,
"e": 6196,
"s": 6136,
"text": "This file sets up the Redis connection and the Redis Queue."
},
{
"code": null,
"e": 6616,
"s": 6196,
"text": "The variable redis_conn defines the connection parameters for this connection, and redis_queue uses the Queue method. The Queue method initiates the queue, and any name can be given. Common naming patters are ‘low,’ ‘medium’ and ‘high.’ By providing the Queue method no args, we are instructing it to use the default queue. Aside from the name, we are simply passing our method the connection string to the Redis store."
},
{
"code": null,
"e": 6689,
"s": 6616,
"text": "Functions.py is where we define the functions to use in the Redis queue."
},
{
"code": null,
"e": 7048,
"s": 6689,
"text": "What some_long_function does is up to you. It can be anything you want with done with the data passed to the worker. This could be anything from machine learning, to image manipulation, to using the information to process queries in a connected database. Anything you want the backend to do so the front end doesn't wait would be placed within this function."
},
{
"code": null,
"e": 7463,
"s": 7048,
"text": "For our example, this function serves a couple of purposes. First, the job variable is created to retrieve the current job being worked. We use time.sleep(10) to demonstrate the different job status codes as the job is being processed. We will go into more detail on the job status codes later in the article. Finally, we return a JSON that contains information about the job and the results of processing the job."
},
{
"code": null,
"e": 7601,
"s": 7463,
"text": "Main.py is the primary flask app that drives the application. More details on setting up a flask app are outlined in this medium article."
},
{
"code": null,
"e": 7624,
"s": 7601,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8023,
"s": 7624,
"text": "The first route function, resource_not_found , is designed to handle any 404 errors that result from incorrect requests to the application. The route function defined as home is the default route that runs when you navigate to the home route. This route runs when you perform a GET request to http://127.0.0.1:8000 or the localhost URL. This route designed to let you know the flask app is running."
},
{
"code": null,
"e": 8066,
"s": 8023,
"text": "We can test it with Postman as seen below."
},
{
"code": null,
"e": 8156,
"s": 8066,
"text": "The remaining routes, specific for the Redis Queue, will be covered in more detail below."
},
{
"code": null,
"e": 8349,
"s": 8156,
"text": "The /enqueue route creates the task and enters the task into the queue. Redis Queue accepts things such as key-value pairs so that you can create a post request with a dictionary, for example:"
},
{
"code": null,
"e": 8368,
"s": 8349,
"text": "{“hello”: “world”}"
},
{
"code": null,
"e": 8546,
"s": 8368,
"text": "Submitting a JSON post request to the /enqueue route will tell the application to enqueue the JSON to the function some_long_function within the function.py file for processing."
},
{
"code": null,
"e": 8734,
"s": 8546,
"text": "The /enqueue route returns the job_id of the task created once it has done so. Take note of the job_id, as we will use it as part of the URL string for the application’s remaining routes."
},
{
"code": null,
"e": 8956,
"s": 8734,
"text": "This route takes the job_id and checks its status in the Redis Queue. The full URL of this route is http://127.0.0.1:8000?job_id=JobID. Where JobID is the job_id that was generated when the /enqueue route created the job."
},
{
"code": null,
"e": 9366,
"s": 8956,
"text": "The /check_status route will return a JSON that contains the job_id passed in the URL and the status of the job using the get_status method of rq.job. Remember within the some_long_function, the time.sleep at the start of the function. If you hit this route with a get request before the ten-second timer, the status will show ‘Queue.’ After some_long_function completes, the status will return as ‘finished.’"
},
{
"code": null,
"e": 9626,
"s": 9366,
"text": "Once a job is shown as ‘finished’ by the /check_status route, get_result will return the results of the processed job. The results are determined by what you have set up within some_long_function. This URL follows the same structure as /check_status so it is:"
},
{
"code": null,
"e": 9665,
"s": 9626,
"text": "http://127.0.0.1:8000?get_result=JobID"
},
{
"code": null,
"e": 9744,
"s": 9665,
"text": "Our some_long_function returns data about the job, as seen in the image above."
},
{
"code": null,
"e": 10044,
"s": 9744,
"text": "In this article, we learned a little about building a queue of tasks with Redis Queue, and how to utilize a Redis database within a docker container. We covered how to build the application that makes it simple to enqueue time-consuming tasks without tying up or hindering our front end performance."
},
{
"code": null,
"e": 10055,
"s": 10044,
"text": "github.com"
}
] |
Default arguments in Python
|
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −
Live Demo
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35
|
[
{
"code": null,
"e": 1294,
"s": 1062,
"text": "A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −"
},
{
"code": null,
"e": 1305,
"s": 1294,
"text": " Live Demo"
},
{
"code": null,
"e": 1576,
"s": 1305,
"text": "#!/usr/bin/python\n# Function definition is here\ndef printinfo( name, age = 35 ):\n\"This prints a passed info into this function\"\nprint \"Name: \", name\nprint \"Age \", age\nreturn;\n# Now you can call printinfo function\nprintinfo( age=50, name=\"miki\" )\nprintinfo( name=\"miki\" )"
},
{
"code": null,
"e": 1644,
"s": 1576,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 1680,
"s": 1644,
"text": "Name: miki\nAge 50\nName: miki\nAge 35"
}
] |
How to call function from it name stored in a string using JavaScript?
|
21 Apr, 2019
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
Method 1: Using the window object: The window object in HTML 5 references the current window and all items contained in it. Hence we can use it to run a function in a string along with parameters to the function.
Syntax:
window[functionName](parameters)
Example:
<!DOCTYPE html><html> <head> <title> How to call function from string stored in a variable using JavaScript </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to call function from string stored in a variable using JavaScript </b> <p> Click on the button to call the function in the string </p> <p class="example"> GeeksforGeeks is a computer science portal. </p> <button onclick="evaluateFunction()"> Click here </button> <script type="text/javascript"> function changeColor(color) { document.querySelector('.example').style = `color: ${color}`; } function evaluateFunction() { stringFunction = "changeColor"; param = 'green'; window[stringFunction](param); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Using the eval() method: The other method that can be used is the eval() method. The string that may be passed on to the function may include a JavaScript expression, statement, or a sequence of statements. It can also have variables and properties of existing objects. The only problem with this method is that it is considered unsafe and may not be supported by newer browsers.
Syntax:
eval(stringFunction)
Example:
<!DOCTYPE html><html> <head> <title> How to call function from string stored in a variable using JavaScript </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to call function from string stored in a variable using JavaScript </b> <p> Click on the button to call the function in the string </p> <p class="example"> GeeksforGeeks is a computer science portal. </p> <button onclick="evaluateFunction()"> Click here </button> <script type="text/javascript"> function changeColor(color) { document.querySelector('.example').style = `color: ${color}`; } function evaluateFunction() { stringFunction = "changeColor('green')"; eval(stringFunction); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
javascript-functions
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
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": 52,
"s": 24,
"text": "\n21 Apr, 2019"
},
{
"code": null,
"e": 273,
"s": 52,
"text": "There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated."
},
{
"code": null,
"e": 486,
"s": 273,
"text": "Method 1: Using the window object: The window object in HTML 5 references the current window and all items contained in it. Hence we can use it to run a function in a string along with parameters to the function."
},
{
"code": null,
"e": 494,
"s": 486,
"text": "Syntax:"
},
{
"code": null,
"e": 527,
"s": 494,
"text": "window[functionName](parameters)"
},
{
"code": null,
"e": 536,
"s": 527,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to call function from string stored in a variable using JavaScript </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to call function from string stored in a variable using JavaScript </b> <p> Click on the button to call the function in the string </p> <p class=\"example\"> GeeksforGeeks is a computer science portal. </p> <button onclick=\"evaluateFunction()\"> Click here </button> <script type=\"text/javascript\"> function changeColor(color) { document.querySelector('.example').style = `color: ${color}`; } function evaluateFunction() { stringFunction = \"changeColor\"; param = 'green'; window[stringFunction](param); } </script></body> </html> ",
"e": 1509,
"s": 536,
"text": null
},
{
"code": null,
"e": 1517,
"s": 1509,
"text": "Output:"
},
{
"code": null,
"e": 1545,
"s": 1517,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1572,
"s": 1545,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1962,
"s": 1572,
"text": "Method 2: Using the eval() method: The other method that can be used is the eval() method. The string that may be passed on to the function may include a JavaScript expression, statement, or a sequence of statements. It can also have variables and properties of existing objects. The only problem with this method is that it is considered unsafe and may not be supported by newer browsers."
},
{
"code": null,
"e": 1970,
"s": 1962,
"text": "Syntax:"
},
{
"code": null,
"e": 1991,
"s": 1970,
"text": "eval(stringFunction)"
},
{
"code": null,
"e": 2000,
"s": 1991,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to call function from string stored in a variable using JavaScript </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to call function from string stored in a variable using JavaScript </b> <p> Click on the button to call the function in the string </p> <p class=\"example\"> GeeksforGeeks is a computer science portal. </p> <button onclick=\"evaluateFunction()\"> Click here </button> <script type=\"text/javascript\"> function changeColor(color) { document.querySelector('.example').style = `color: ${color}`; } function evaluateFunction() { stringFunction = \"changeColor('green')\"; eval(stringFunction); } </script></body> </html> ",
"e": 2953,
"s": 2000,
"text": null
},
{
"code": null,
"e": 2961,
"s": 2953,
"text": "Output:"
},
{
"code": null,
"e": 2989,
"s": 2961,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 3016,
"s": 2989,
"text": "After clicking the button:"
},
{
"code": null,
"e": 3037,
"s": 3016,
"text": "javascript-functions"
},
{
"code": null,
"e": 3044,
"s": 3037,
"text": "Picked"
},
{
"code": null,
"e": 3055,
"s": 3044,
"text": "JavaScript"
},
{
"code": null,
"e": 3072,
"s": 3055,
"text": "Web Technologies"
},
{
"code": null,
"e": 3170,
"s": 3072,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3231,
"s": 3170,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3303,
"s": 3231,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3343,
"s": 3303,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3384,
"s": 3343,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3436,
"s": 3384,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3469,
"s": 3436,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3531,
"s": 3469,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3592,
"s": 3531,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3642,
"s": 3592,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
SQL – SELECT LAST
|
16 Aug, 2021
SEQUEL widely known as SQL (Structured Query Language), is the most popular standard language to work on databases. It is a domain-specific language that is mostly used to perform tons of operations which include creating a database, storing data in the form of tables, modifying, extract and lot more. There are different versions of SQL like MYSQL, PostgreSQL, Oracle, SQL lite, etc.
SQL became the norm of American National Standards Institute (ANSI) in the year 1986 and the next year in 1987 it became the norm of the International Organization for Standardization (ISO). Today is the world of the Internet and technology. We are surrounded by tons of data. So to store this data securely and to manage them we need a proper database and to manage this database we need a language which is SQL.
In this article, we are going to look at how to get the last entry of any record in a Table. We are going to discuss four different ways to extract the last entry of any given table in a database.
Sample Input: Consider a Table “Student Information” which contains the data about the students enrolled in “GeekforGeeks DSA course“.
1. Creating a Database
CREATE DATABASE database_name;
2. Creating a Table
CREATE TABLE Table_name(
col_1 TYPE col_1_constraint,
col_2 TYPE col_2 constraint
.....
);
col: Column name
TYPE: Data type whether an integer, variable character, etc.
col_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc.
3. Inserting into a Table
INSERT INTO Table_name
VALUES(val_1, val_2, val_3, ..........);
val: Values in particular column.
4. View The Table
SELECT * FROM Table_name
We can use the command FIRST() to extract the first entry of a particular column and LAST() to extract the last entry of a particular column in a Table. For more information visit First() and Last()Function in MS Access.
Basic Syntax :
LAST(expression)
For example, say we want to extract the last student name from the table “Student Information”
SELECT LAST(Student_name) AS Stud_Name
FROM StudentInformation;
Output:
Last Student Name
As we can see, the last student name “Hina” is extracted using the above query. But it is to be noted that SELECT LAST or LAST(expression) is only supported in MS Access. This statement doesn’t support MYSQL, Oracle, PostgreSQL, etc. There are alternate ways as discussed below to perform the above operation in other versions of SQL like MYSQL, Oracle, PostgreSQL, etc.
We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table. And then we can select the entry which we want to retrieve.
MYSQL syntax :
SELECT col_name(s) FROM Table_Name
ORDER BY appr_col_name DESC
LIMIT 1;
col_name(s): The name of the column(s).
appr_col_name: Appropriate column name to perform ORDER BY.
Oracle syntax :
SELECT col_name(s) FROM Table_Name
ORDER BY appr_col_name DESC
WHERE ROWNUM <= 1;
col_name(s): The name of the column(s).
appr_col_name: Appropriate column name to perform ORDER BY.
Output :
Last Student Name
It is important to note that in order to perform sorting, the column needs to be chosen properly. For example, if we choose “ORDER BY Student_name DESC” then it will alphabetically sort the table on the basis of names. So, the row containing “Vishal” will come at the top, but the row having “Vishal” as entry is not the last row of the table. Also, we can’t use the column “Age” to perform ORDER BY as shown below:
Ram is not the Last Student Name
Vishal Is not the Last Student Name
Hence, it is mandatory to use the column ID or any column which is unique and sequentially increasing with every record in the table.
Subquery is nothing but a query inside another query that maintains a parent-child relationship. The inner query will execute first followed by the outer query. Here, in this method, the basic idea is to get the maximum ID using aggregate function MAX and then select the student name associated with that maximum ID. In this way, we can extract the last student’s name from the table.
SELECT col_name(s) FROM Table_Name
WHERE appr_col_name = (
SELECT MAX(appr_col_name)
FROM Table_Name
);
col_name(s): The name of the column(s).
appr_col_name: Appropriate column name. For example ID.
Output :
Last Student Name
In this method also, we are going to use a subquery. The basic idea is to filter out the rows and to check that no such row exists having higher ID values than the row we are going to extract. This will help in getting the row with maximum ID and hence we can retrieve the last information. It is a complex query and is an iterative approach in which we are going to use the NOT EXISTS statement. This method will take more time to execute if there are more records in the table.
SELECT col_name(s) FROM Table_Name t1
WHERE NOT EXISTS(
SELECT * FROM Table_Name t2
WHERE t2.appr_col_name > t1.appr_col_name
);
col_name(s): The name of the column(s).
appr_col_name: Appropriate column name. For example ID.
Output :
Last Student Name
sagar0719kumar
abhishek0719kadiyan
Picked
SQL-Functions
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 442,
"s": 54,
"text": "SEQUEL widely known as SQL (Structured Query Language), is the most popular standard language to work on databases. It is a domain-specific language that is mostly used to perform tons of operations which include creating a database, storing data in the form of tables, modifying, extract and lot more. There are different versions of SQL like MYSQL, PostgreSQL, Oracle, SQL lite, etc. "
},
{
"code": null,
"e": 857,
"s": 442,
"text": "SQL became the norm of American National Standards Institute (ANSI) in the year 1986 and the next year in 1987 it became the norm of the International Organization for Standardization (ISO). Today is the world of the Internet and technology. We are surrounded by tons of data. So to store this data securely and to manage them we need a proper database and to manage this database we need a language which is SQL. "
},
{
"code": null,
"e": 1054,
"s": 857,
"text": "In this article, we are going to look at how to get the last entry of any record in a Table. We are going to discuss four different ways to extract the last entry of any given table in a database."
},
{
"code": null,
"e": 1189,
"s": 1054,
"text": "Sample Input: Consider a Table “Student Information” which contains the data about the students enrolled in “GeekforGeeks DSA course“."
},
{
"code": null,
"e": 1212,
"s": 1189,
"text": "1. Creating a Database"
},
{
"code": null,
"e": 1243,
"s": 1212,
"text": "CREATE DATABASE database_name;"
},
{
"code": null,
"e": 1263,
"s": 1243,
"text": "2. Creating a Table"
},
{
"code": null,
"e": 1521,
"s": 1263,
"text": "CREATE TABLE Table_name(\ncol_1 TYPE col_1_constraint,\ncol_2 TYPE col_2 constraint\n.....\n);\n\ncol: Column name\nTYPE: Data type whether an integer, variable character, etc.\ncol_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc."
},
{
"code": null,
"e": 1547,
"s": 1521,
"text": "3. Inserting into a Table"
},
{
"code": null,
"e": 1646,
"s": 1547,
"text": "INSERT INTO Table_name\nVALUES(val_1, val_2, val_3, ..........);\n\nval: Values in particular column."
},
{
"code": null,
"e": 1664,
"s": 1646,
"text": "4. View The Table"
},
{
"code": null,
"e": 1689,
"s": 1664,
"text": "SELECT * FROM Table_name"
},
{
"code": null,
"e": 1910,
"s": 1689,
"text": "We can use the command FIRST() to extract the first entry of a particular column and LAST() to extract the last entry of a particular column in a Table. For more information visit First() and Last()Function in MS Access."
},
{
"code": null,
"e": 1925,
"s": 1910,
"text": "Basic Syntax :"
},
{
"code": null,
"e": 1942,
"s": 1925,
"text": "LAST(expression)"
},
{
"code": null,
"e": 2038,
"s": 1942,
"text": "For example, say we want to extract the last student name from the table “Student Information”"
},
{
"code": null,
"e": 2103,
"s": 2038,
"text": "SELECT LAST(Student_name) AS Stud_Name \nFROM StudentInformation;"
},
{
"code": null,
"e": 2111,
"s": 2103,
"text": "Output:"
},
{
"code": null,
"e": 2129,
"s": 2111,
"text": "Last Student Name"
},
{
"code": null,
"e": 2500,
"s": 2129,
"text": "As we can see, the last student name “Hina” is extracted using the above query. But it is to be noted that SELECT LAST or LAST(expression) is only supported in MS Access. This statement doesn’t support MYSQL, Oracle, PostgreSQL, etc. There are alternate ways as discussed below to perform the above operation in other versions of SQL like MYSQL, Oracle, PostgreSQL, etc."
},
{
"code": null,
"e": 2815,
"s": 2500,
"text": "We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table. And then we can select the entry which we want to retrieve."
},
{
"code": null,
"e": 2830,
"s": 2815,
"text": "MYSQL syntax :"
},
{
"code": null,
"e": 3003,
"s": 2830,
"text": "SELECT col_name(s) FROM Table_Name\nORDER BY appr_col_name DESC\nLIMIT 1;\n\ncol_name(s): The name of the column(s).\nappr_col_name: Appropriate column name to perform ORDER BY."
},
{
"code": null,
"e": 3019,
"s": 3003,
"text": "Oracle syntax :"
},
{
"code": null,
"e": 3202,
"s": 3019,
"text": "SELECT col_name(s) FROM Table_Name\nORDER BY appr_col_name DESC\nWHERE ROWNUM <= 1;\n\ncol_name(s): The name of the column(s).\nappr_col_name: Appropriate column name to perform ORDER BY."
},
{
"code": null,
"e": 3211,
"s": 3202,
"text": "Output :"
},
{
"code": null,
"e": 3230,
"s": 3211,
"text": " Last Student Name"
},
{
"code": null,
"e": 3648,
"s": 3230,
"text": "It is important to note that in order to perform sorting, the column needs to be chosen properly. For example, if we choose “ORDER BY Student_name DESC” then it will alphabetically sort the table on the basis of names. So, the row containing “Vishal” will come at the top, but the row having “Vishal” as entry is not the last row of the table. Also, we can’t use the column “Age” to perform ORDER BY as shown below:"
},
{
"code": null,
"e": 3681,
"s": 3648,
"text": "Ram is not the Last Student Name"
},
{
"code": null,
"e": 3717,
"s": 3681,
"text": "Vishal Is not the Last Student Name"
},
{
"code": null,
"e": 3851,
"s": 3717,
"text": "Hence, it is mandatory to use the column ID or any column which is unique and sequentially increasing with every record in the table."
},
{
"code": null,
"e": 4238,
"s": 3851,
"text": " Subquery is nothing but a query inside another query that maintains a parent-child relationship. The inner query will execute first followed by the outer query. Here, in this method, the basic idea is to get the maximum ID using aggregate function MAX and then select the student name associated with that maximum ID. In this way, we can extract the last student’s name from the table."
},
{
"code": null,
"e": 4455,
"s": 4238,
"text": "SELECT col_name(s) FROM Table_Name\nWHERE appr_col_name = (\n SELECT MAX(appr_col_name)\n FROM Table_Name\n);\n\ncol_name(s): The name of the column(s).\nappr_col_name: Appropriate column name. For example ID."
},
{
"code": null,
"e": 4464,
"s": 4455,
"text": "Output :"
},
{
"code": null,
"e": 4483,
"s": 4464,
"text": " Last Student Name"
},
{
"code": null,
"e": 4963,
"s": 4483,
"text": "In this method also, we are going to use a subquery. The basic idea is to filter out the rows and to check that no such row exists having higher ID values than the row we are going to extract. This will help in getting the row with maximum ID and hence we can retrieve the last information. It is a complex query and is an iterative approach in which we are going to use the NOT EXISTS statement. This method will take more time to execute if there are more records in the table."
},
{
"code": null,
"e": 5197,
"s": 4963,
"text": "SELECT col_name(s) FROM Table_Name t1\nWHERE NOT EXISTS(\n SELECT * FROM Table_Name t2\n WHERE t2.appr_col_name > t1.appr_col_name\n);\n\ncol_name(s): The name of the column(s).\nappr_col_name: Appropriate column name. For example ID."
},
{
"code": null,
"e": 5206,
"s": 5197,
"text": "Output :"
},
{
"code": null,
"e": 5225,
"s": 5206,
"text": " Last Student Name"
},
{
"code": null,
"e": 5240,
"s": 5225,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 5260,
"s": 5240,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 5267,
"s": 5260,
"text": "Picked"
},
{
"code": null,
"e": 5281,
"s": 5267,
"text": "SQL-Functions"
},
{
"code": null,
"e": 5285,
"s": 5281,
"text": "SQL"
},
{
"code": null,
"e": 5289,
"s": 5285,
"text": "SQL"
},
{
"code": null,
"e": 5387,
"s": 5289,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5453,
"s": 5387,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 5477,
"s": 5453,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 5509,
"s": 5477,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 5526,
"s": 5509,
"text": "SQL using Python"
},
{
"code": null,
"e": 5559,
"s": 5526,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 5637,
"s": 5559,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 5667,
"s": 5637,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 5703,
"s": 5667,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 5734,
"s": 5703,
"text": "SQL Query to Compare Two Dates"
}
] |
How to create Expanding Cards using HTML, CSS and Javascript ?
|
05 Mar, 2021
In this article, we will see how we can create an expanding card that displays an expanded view of the card on click. For creating this card we will use HTML, CSS, and JavaScript.
Approach: In this section, we will create the structure of our HTML card.
Create a div with the class container.
Create another div inside a container with the class section and active.
Style the div panel with a background image of your choice.
Make another four div with the same class section.
HTML:
HTML
<!-- Container --> <div class="container"> <!-- Div with section and active --> <div class="section one active"></div> <!-- All another div with section --> <div class="section two"></div> <div class="section three"></div> <div class="section four"></div> </div>
CSS: In this section, we will assign general properties to the element using CSS.
CSS
/* Setting container to flex and width to 80% of view port */.container{ display: flex; width: 80%;}/*Adding background image to each section*/.one{ background: url(img/one.jpg);}.two{ background: url(img/two.jpg);}.three{ background: url(img/three.jpg);}.four{ background: url(img/four.jpg);}/* Background properties and transition effect to section */.section{ background-size: cover; background-position: center; background-repeat: no-repeat; height: 80vh; cursor: pointer; flex: 0.2; margin:8px; position: relative; transition: all 0.7s ease-out;} /* section with active class will grow flex to 3 times */.section.active{ flex: 3;}
JavaScript: Add the click functionality to each card using JavaScript. The querySelectorAll() method is used to return a collection of child elements with the class section. The addEventListener() method is used to handle the click event for each card section.
Javascript
// Selecting all sections with class of section const sections = document.querySelectorAll('.section') // On click event for each section sections.forEach((section)=>{ section.addEventListener('click',()=>{ // remove active class from all another section // and add it to the selected section sections.forEach((section) => { section.classList.remove('active') }) section.classList.add('active') }) })
Complete Code:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> /* Setting container to flex and width to 80% of view port */ .container { display: flex; width: 80%; } /*Adding background image to each section*/ .one { background: url(https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210203171024/CSSTutorial.png); } .two { background: url(https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210203170945/HTML-Tutorials.png); } .three { background: url(https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210210175213/JavaScriptTutorial.png); } .four { background: url(https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210301162100/jquery.png); } /* Background properties and transition effect to section */ .section { background-size: cover; background-position: center; background-repeat: no-repeat; height: 80vh; cursor: pointer; flex: 0.2; margin: 8px; position: relative; transition: all 0.7s ease-out; } /* section with active class will grow flex to 3 times */ .section.active { flex: 3; } </style> <title>Expanding Cards</title> </head> <body> <!-- Container --> <div class="container"> <!-- Div with section and active --> <div class="section one active"></div> <!-- All another div with section --> <div class="section two"></div> <div class="section three"></div> <div class="section four"></div> </div> <script> // selecting all sections with class of section const sections = document.querySelectorAll(".section"); // Foreach section when clicked sections.forEach((section) => { section.addEventListener("click", () => { // remove active class from all another section and // add it to the selected section sections.forEach((section) => { section.classList.remove("active"); }); section.classList.add("active"); }); }); </script> </body></html>
Output:
CSS-Questions
HTML-Questions
JavaScript-Questions
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 208,
"s": 28,
"text": "In this article, we will see how we can create an expanding card that displays an expanded view of the card on click. For creating this card we will use HTML, CSS, and JavaScript."
},
{
"code": null,
"e": 282,
"s": 208,
"text": "Approach: In this section, we will create the structure of our HTML card."
},
{
"code": null,
"e": 321,
"s": 282,
"text": "Create a div with the class container."
},
{
"code": null,
"e": 394,
"s": 321,
"text": "Create another div inside a container with the class section and active."
},
{
"code": null,
"e": 454,
"s": 394,
"text": "Style the div panel with a background image of your choice."
},
{
"code": null,
"e": 505,
"s": 454,
"text": "Make another four div with the same class section."
},
{
"code": null,
"e": 511,
"s": 505,
"text": "HTML:"
},
{
"code": null,
"e": 516,
"s": 511,
"text": "HTML"
},
{
"code": "<!-- Container --> <div class=\"container\"> <!-- Div with section and active --> <div class=\"section one active\"></div> <!-- All another div with section --> <div class=\"section two\"></div> <div class=\"section three\"></div> <div class=\"section four\"></div> </div>",
"e": 821,
"s": 516,
"text": null
},
{
"code": null,
"e": 903,
"s": 821,
"text": "CSS: In this section, we will assign general properties to the element using CSS."
},
{
"code": null,
"e": 907,
"s": 903,
"text": "CSS"
},
{
"code": "/* Setting container to flex and width to 80% of view port */.container{ display: flex; width: 80%;}/*Adding background image to each section*/.one{ background: url(img/one.jpg);}.two{ background: url(img/two.jpg);}.three{ background: url(img/three.jpg);}.four{ background: url(img/four.jpg);}/* Background properties and transition effect to section */.section{ background-size: cover; background-position: center; background-repeat: no-repeat; height: 80vh; cursor: pointer; flex: 0.2; margin:8px; position: relative; transition: all 0.7s ease-out;} /* section with active class will grow flex to 3 times */.section.active{ flex: 3;}",
"e": 1595,
"s": 907,
"text": null
},
{
"code": null,
"e": 1856,
"s": 1595,
"text": "JavaScript: Add the click functionality to each card using JavaScript. The querySelectorAll() method is used to return a collection of child elements with the class section. The addEventListener() method is used to handle the click event for each card section."
},
{
"code": null,
"e": 1867,
"s": 1856,
"text": "Javascript"
},
{
"code": "// Selecting all sections with class of section const sections = document.querySelectorAll('.section') // On click event for each section sections.forEach((section)=>{ section.addEventListener('click',()=>{ // remove active class from all another section // and add it to the selected section sections.forEach((section) => { section.classList.remove('active') }) section.classList.add('active') }) })",
"e": 2380,
"s": 1867,
"text": null
},
{
"code": null,
"e": 2396,
"s": 2380,
"text": "Complete Code: "
},
{
"code": null,
"e": 2401,
"s": 2396,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <style> /* Setting container to flex and width to 80% of view port */ .container { display: flex; width: 80%; } /*Adding background image to each section*/ .one { background: url(https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210203171024/CSSTutorial.png); } .two { background: url(https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210203170945/HTML-Tutorials.png); } .three { background: url(https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210210175213/JavaScriptTutorial.png); } .four { background: url(https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210301162100/jquery.png); } /* Background properties and transition effect to section */ .section { background-size: cover; background-position: center; background-repeat: no-repeat; height: 80vh; cursor: pointer; flex: 0.2; margin: 8px; position: relative; transition: all 0.7s ease-out; } /* section with active class will grow flex to 3 times */ .section.active { flex: 3; } </style> <title>Expanding Cards</title> </head> <body> <!-- Container --> <div class=\"container\"> <!-- Div with section and active --> <div class=\"section one active\"></div> <!-- All another div with section --> <div class=\"section two\"></div> <div class=\"section three\"></div> <div class=\"section four\"></div> </div> <script> // selecting all sections with class of section const sections = document.querySelectorAll(\".section\"); // Foreach section when clicked sections.forEach((section) => { section.addEventListener(\"click\", () => { // remove active class from all another section and // add it to the selected section sections.forEach((section) => { section.classList.remove(\"active\"); }); section.classList.add(\"active\"); }); }); </script> </body></html>",
"e": 4726,
"s": 2401,
"text": null
},
{
"code": null,
"e": 4734,
"s": 4726,
"text": "Output:"
},
{
"code": null,
"e": 4748,
"s": 4734,
"text": "CSS-Questions"
},
{
"code": null,
"e": 4763,
"s": 4748,
"text": "HTML-Questions"
},
{
"code": null,
"e": 4784,
"s": 4763,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 4788,
"s": 4784,
"text": "CSS"
},
{
"code": null,
"e": 4793,
"s": 4788,
"text": "HTML"
},
{
"code": null,
"e": 4804,
"s": 4793,
"text": "JavaScript"
},
{
"code": null,
"e": 4821,
"s": 4804,
"text": "Web Technologies"
},
{
"code": null,
"e": 4826,
"s": 4821,
"text": "HTML"
}
] |
Python | Pandas dataframe.get_value()
|
19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.get_value() function is used to quickly retrieve single value in the data frame at passed column and index. The input to the function is the row label and the column label.
Syntax: DataFrame.get_value(index, col, takeable=False)
Parameters :index : row labelcol : column labeltakeable : interpret the index/col as indexers, default False
Returns : value : scalar value
For link to CSV file Used in Code, click here
Example #1: Use get_value() function to find the value of salary in the 10th row
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Print the dataframedf
# applying get_value() function df.get_value(10, 'Salary')
Output :
Example #2: Use get_value() function and pass the column index value rather than name.
Note : We can also use integer indexer value of columns by setting the takeable parameter=True.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # column index value of "Name" column is 0# We have set takeable = True# to interpret the index / col as indexerdf.get_value(4, 0, takeable = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 266,
"s": 52,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 456,
"s": 266,
"text": "Pandas dataframe.get_value() function is used to quickly retrieve single value in the data frame at passed column and index. The input to the function is the row label and the column label."
},
{
"code": null,
"e": 512,
"s": 456,
"text": "Syntax: DataFrame.get_value(index, col, takeable=False)"
},
{
"code": null,
"e": 621,
"s": 512,
"text": "Parameters :index : row labelcol : column labeltakeable : interpret the index/col as indexers, default False"
},
{
"code": null,
"e": 652,
"s": 621,
"text": "Returns : value : scalar value"
},
{
"code": null,
"e": 698,
"s": 652,
"text": "For link to CSV file Used in Code, click here"
},
{
"code": null,
"e": 779,
"s": 698,
"text": "Example #1: Use get_value() function to find the value of salary in the 10th row"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Print the dataframedf",
"e": 902,
"s": 779,
"text": null
},
{
"code": "# applying get_value() function df.get_value(10, 'Salary')",
"e": 961,
"s": 902,
"text": null
},
{
"code": null,
"e": 971,
"s": 961,
"text": "Output : "
},
{
"code": null,
"e": 1058,
"s": 971,
"text": "Example #2: Use get_value() function and pass the column index value rather than name."
},
{
"code": null,
"e": 1154,
"s": 1058,
"text": "Note : We can also use integer indexer value of columns by setting the takeable parameter=True."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # column index value of \"Name\" column is 0# We have set takeable = True# to interpret the index / col as indexerdf.get_value(4, 0, takeable = True)",
"e": 1401,
"s": 1154,
"text": null
},
{
"code": null,
"e": 1410,
"s": 1401,
"text": "Output :"
},
{
"code": null,
"e": 1434,
"s": 1410,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1466,
"s": 1434,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 1480,
"s": 1466,
"text": "Python-pandas"
},
{
"code": null,
"e": 1487,
"s": 1480,
"text": "Python"
},
{
"code": null,
"e": 1585,
"s": 1487,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1627,
"s": 1585,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1649,
"s": 1627,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1681,
"s": 1649,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1710,
"s": 1681,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1737,
"s": 1710,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1758,
"s": 1737,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1794,
"s": 1758,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1817,
"s": 1794,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1873,
"s": 1817,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Difference between Flutter and Angular
|
10 Aug, 2021
Flutter: Flutter is Google’s Mobile SDK to build native iOS and Android, Desktop (Windows, Linux, macOS), Web apps from a single codebase. It is an open-source framework created in May 2017. When building applications with Flutter everything towards Widgets – the blocks with which the flutter apps are built. They are structural elements that ship with a bunch of material design-specific functionalities and new widgets can be composed out of existing ones too. The process of composing widgets together is called composition. The User Interface of the app is composed of many simple widgets, each of them handling one particular job.
The Software Development Kit contains a number of tools that will help you work on your applications. Some of these tools enable you to compile your code into native machine code on both iOS and Android. It comprises of UI Library based on widgets ie., It consists of reusable user interface elements (buttons, text fields, sliders, etc.) that can be refactored or modified as per your requirements.
The programming language that is used to develop Flutter apps is Dart. Dart is a typed object programming language that is created by Google in October 2011 but has improved a lot in the past few years. It is used for developing mobile as well as web applications. The main focus of Dart is for front-end development.
Advantageous features of Flutter:
Flutter uses a single codebase, called, Dart for both platforms, Android and iOS which is a simple language ensuring type safety.
Flutter is not bound to the ROM w.r.t. the widget system. So, it enhances its portability over a wide ambit of Android versions and thus, lowering its dependencies on the host platform.
Both Flutter language and community are developing with great speed, releasing new features, widgets and add-ons.
Dart and Flutter unite closely to optimize dart Virtual Machine(VM) for those mobiles which are specifically needed by Flutter.
Let’s understand the concept through an example.
Example:
Dart
import 'package:flutter/material.dart'; void main() { runApp(GeeksForGeeks());} class GeeksForGeeks extends StatelessWidget { Widget build(BuildContext context) { // Material App return MaterialApp( // Scaffold Widget home: Scaffold( appBar: AppBar( // AppBar takes a Text Widget // in it's title parameter title: Text('GeeksforGeeks'), ), body: Center(child: Text( 'A Computer Science portal for geeks')), ) ); }}
Output:
For more information, please refer to Flutter Tutorial & to the official website flutter_docs
Angular: Angular is an open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a JavaScript framework that is written in TypeScript. As a framework, It provides developers with a standard structure that enables them to create large applications in an easily maintainable manner. It is a continuously growing and expanding framework which provides better ways for developing web applications. It changes the static HTML to dynamic HTML.
The name “Angular” simply refers to the various versions of the framework. Angular was developed in the year 2009.
Key features of Angular:
Model View Controller(MVC): An architecture is basically a software pattern used to develop an application. It consists of three components in general, they are:
Model: Used to manage the application data.
View: Responsible for displaying the application data.
Controller: The main job is to connect the model and the view component.
Normally when we talk about MVC architecture, we have to split our applications into these three components and then write the code to connect them. However, in AngularJs all we have to do is split the application into MVC and it does the rest by itself. It saves a lot of time and allows you to finish the job with less code.
Data Model Binding: Data Binding in AngularJS is a two-way process, i.e. the view layer of the MVC architecture is an exact copy of the model layer. You don’t need to write special code to bind data to the HTML controls. Normally in other MVC architectures, we have to continuously update the view layer and the model layer to remain in sync with one another. In AngularJs it can be said that the model layer and the view layer remain synchronized with each other. Like when the data in the model changes, then the view layer reflects the change and vice versa. It happens immediately and automatically which helps in making sure that the model and the view is updated at all times.
Some other features are:
Custom Components
Dependency Injection
Browser Compatibility
We will understand the concept through an example.
Example:
HTML
<html> <head> <title>AngularJS ng-app Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body style="text-align: center"> <h2 style="color: green">ng-app directive</h2> <div ng-app="" ng-init="name='GeeksforGeeks'"> <p>{{ name }} is the portal for geeks.</p> </div> </body></html>
Output:
Difference between Flutter and Angular:
Flutter is a Google UI toolkit for crafting beautiful, natively compiled applications for desktop, web and mobile from a single codebase.
Angular is a framework that is most suited to your application development. It is fully extensible and works well with other libraries.
It is written in Dart languages.
It is written and developed in Windows Typescript language
Flutter supports only mobile OS.
Angular supports both mobile and computer OS.
Offers faster apps.
Offers comparatively slower.
Comparatively lesser stability.
Offers a lot more stability.
It does not support the 32-bit version of any app in iOS.
It supports the 32-bit version.
Flutter works as SDK.
Angular works as a building block of the user interface.
It uses components like Flutter Engine, Foundation library and Dart platform.
It uses components like Type Components, Data Binding and Dependency Injection.
In flutter, operating systems design specific widgets to construct the applications.
In angular, service components are used to build the applications.
Companies using flutter are Alibaba, Hamilton Musical, Abbey Road Studios app, Reflecting etc.
Companies using angular are Microsoft Office, Upwork, General Motors, YouTube, HBO etc.
AngularJS-Basics
Flutter
AngularJS
Difference Between
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": "\n10 Aug, 2021"
},
{
"code": null,
"e": 666,
"s": 28,
"text": "Flutter: Flutter is Google’s Mobile SDK to build native iOS and Android, Desktop (Windows, Linux, macOS), Web apps from a single codebase. It is an open-source framework created in May 2017. When building applications with Flutter everything towards Widgets – the blocks with which the flutter apps are built. They are structural elements that ship with a bunch of material design-specific functionalities and new widgets can be composed out of existing ones too. The process of composing widgets together is called composition. The User Interface of the app is composed of many simple widgets, each of them handling one particular job. "
},
{
"code": null,
"e": 1066,
"s": 666,
"text": "The Software Development Kit contains a number of tools that will help you work on your applications. Some of these tools enable you to compile your code into native machine code on both iOS and Android. It comprises of UI Library based on widgets ie., It consists of reusable user interface elements (buttons, text fields, sliders, etc.) that can be refactored or modified as per your requirements."
},
{
"code": null,
"e": 1384,
"s": 1066,
"text": "The programming language that is used to develop Flutter apps is Dart. Dart is a typed object programming language that is created by Google in October 2011 but has improved a lot in the past few years. It is used for developing mobile as well as web applications. The main focus of Dart is for front-end development."
},
{
"code": null,
"e": 1418,
"s": 1384,
"text": "Advantageous features of Flutter:"
},
{
"code": null,
"e": 1548,
"s": 1418,
"text": "Flutter uses a single codebase, called, Dart for both platforms, Android and iOS which is a simple language ensuring type safety."
},
{
"code": null,
"e": 1734,
"s": 1548,
"text": "Flutter is not bound to the ROM w.r.t. the widget system. So, it enhances its portability over a wide ambit of Android versions and thus, lowering its dependencies on the host platform."
},
{
"code": null,
"e": 1848,
"s": 1734,
"text": "Both Flutter language and community are developing with great speed, releasing new features, widgets and add-ons."
},
{
"code": null,
"e": 1976,
"s": 1848,
"text": "Dart and Flutter unite closely to optimize dart Virtual Machine(VM) for those mobiles which are specifically needed by Flutter."
},
{
"code": null,
"e": 2027,
"s": 1978,
"text": "Let’s understand the concept through an example."
},
{
"code": null,
"e": 2037,
"s": 2027,
"text": "Example: "
},
{
"code": null,
"e": 2042,
"s": 2037,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(GeeksForGeeks());} class GeeksForGeeks extends StatelessWidget { Widget build(BuildContext context) { // Material App return MaterialApp( // Scaffold Widget home: Scaffold( appBar: AppBar( // AppBar takes a Text Widget // in it's title parameter title: Text('GeeksforGeeks'), ), body: Center(child: Text( 'A Computer Science portal for geeks')), ) ); }}",
"e": 2647,
"s": 2042,
"text": null
},
{
"code": null,
"e": 2655,
"s": 2647,
"text": "Output:"
},
{
"code": null,
"e": 2749,
"s": 2655,
"text": "For more information, please refer to Flutter Tutorial & to the official website flutter_docs"
},
{
"code": null,
"e": 3234,
"s": 2749,
"text": "Angular: Angular is an open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a JavaScript framework that is written in TypeScript. As a framework, It provides developers with a standard structure that enables them to create large applications in an easily maintainable manner. It is a continuously growing and expanding framework which provides better ways for developing web applications. It changes the static HTML to dynamic HTML."
},
{
"code": null,
"e": 3349,
"s": 3234,
"text": "The name “Angular” simply refers to the various versions of the framework. Angular was developed in the year 2009."
},
{
"code": null,
"e": 3374,
"s": 3349,
"text": "Key features of Angular:"
},
{
"code": null,
"e": 3538,
"s": 3374,
"text": "Model View Controller(MVC): An architecture is basically a software pattern used to develop an application. It consists of three components in general, they are: "
},
{
"code": null,
"e": 3582,
"s": 3538,
"text": "Model: Used to manage the application data."
},
{
"code": null,
"e": 3637,
"s": 3582,
"text": "View: Responsible for displaying the application data."
},
{
"code": null,
"e": 3710,
"s": 3637,
"text": "Controller: The main job is to connect the model and the view component."
},
{
"code": null,
"e": 4038,
"s": 3710,
"text": "Normally when we talk about MVC architecture, we have to split our applications into these three components and then write the code to connect them. However, in AngularJs all we have to do is split the application into MVC and it does the rest by itself. It saves a lot of time and allows you to finish the job with less code. "
},
{
"code": null,
"e": 4722,
"s": 4038,
"text": "Data Model Binding: Data Binding in AngularJS is a two-way process, i.e. the view layer of the MVC architecture is an exact copy of the model layer. You don’t need to write special code to bind data to the HTML controls. Normally in other MVC architectures, we have to continuously update the view layer and the model layer to remain in sync with one another. In AngularJs it can be said that the model layer and the view layer remain synchronized with each other. Like when the data in the model changes, then the view layer reflects the change and vice versa. It happens immediately and automatically which helps in making sure that the model and the view is updated at all times. "
},
{
"code": null,
"e": 4747,
"s": 4722,
"text": "Some other features are:"
},
{
"code": null,
"e": 4765,
"s": 4747,
"text": "Custom Components"
},
{
"code": null,
"e": 4786,
"s": 4765,
"text": "Dependency Injection"
},
{
"code": null,
"e": 4808,
"s": 4786,
"text": "Browser Compatibility"
},
{
"code": null,
"e": 4859,
"s": 4808,
"text": "We will understand the concept through an example."
},
{
"code": null,
"e": 4868,
"s": 4859,
"text": "Example:"
},
{
"code": null,
"e": 4873,
"s": 4868,
"text": "HTML"
},
{
"code": "<html> <head> <title>AngularJS ng-app Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> </head> <body style=\"text-align: center\"> <h2 style=\"color: green\">ng-app directive</h2> <div ng-app=\"\" ng-init=\"name='GeeksforGeeks'\"> <p>{{ name }} is the portal for geeks.</p> </div> </body></html>",
"e": 5259,
"s": 4873,
"text": null
},
{
"code": null,
"e": 5267,
"s": 5259,
"text": "Output:"
},
{
"code": null,
"e": 5307,
"s": 5267,
"text": "Difference between Flutter and Angular:"
},
{
"code": null,
"e": 5445,
"s": 5307,
"text": "Flutter is a Google UI toolkit for crafting beautiful, natively compiled applications for desktop, web and mobile from a single codebase."
},
{
"code": null,
"e": 5581,
"s": 5445,
"text": "Angular is a framework that is most suited to your application development. It is fully extensible and works well with other libraries."
},
{
"code": null,
"e": 5614,
"s": 5581,
"text": "It is written in Dart languages."
},
{
"code": null,
"e": 5673,
"s": 5614,
"text": "It is written and developed in Windows Typescript language"
},
{
"code": null,
"e": 5706,
"s": 5673,
"text": "Flutter supports only mobile OS."
},
{
"code": null,
"e": 5752,
"s": 5706,
"text": "Angular supports both mobile and computer OS."
},
{
"code": null,
"e": 5772,
"s": 5752,
"text": "Offers faster apps."
},
{
"code": null,
"e": 5801,
"s": 5772,
"text": "Offers comparatively slower."
},
{
"code": null,
"e": 5833,
"s": 5801,
"text": "Comparatively lesser stability."
},
{
"code": null,
"e": 5862,
"s": 5833,
"text": "Offers a lot more stability."
},
{
"code": null,
"e": 5920,
"s": 5862,
"text": "It does not support the 32-bit version of any app in iOS."
},
{
"code": null,
"e": 5952,
"s": 5920,
"text": "It supports the 32-bit version."
},
{
"code": null,
"e": 5974,
"s": 5952,
"text": "Flutter works as SDK."
},
{
"code": null,
"e": 6031,
"s": 5974,
"text": "Angular works as a building block of the user interface."
},
{
"code": null,
"e": 6109,
"s": 6031,
"text": "It uses components like Flutter Engine, Foundation library and Dart platform."
},
{
"code": null,
"e": 6189,
"s": 6109,
"text": "It uses components like Type Components, Data Binding and Dependency Injection."
},
{
"code": null,
"e": 6274,
"s": 6189,
"text": "In flutter, operating systems design specific widgets to construct the applications."
},
{
"code": null,
"e": 6341,
"s": 6274,
"text": "In angular, service components are used to build the applications."
},
{
"code": null,
"e": 6436,
"s": 6341,
"text": "Companies using flutter are Alibaba, Hamilton Musical, Abbey Road Studios app, Reflecting etc."
},
{
"code": null,
"e": 6524,
"s": 6436,
"text": "Companies using angular are Microsoft Office, Upwork, General Motors, YouTube, HBO etc."
},
{
"code": null,
"e": 6541,
"s": 6524,
"text": "AngularJS-Basics"
},
{
"code": null,
"e": 6549,
"s": 6541,
"text": "Flutter"
},
{
"code": null,
"e": 6559,
"s": 6549,
"text": "AngularJS"
},
{
"code": null,
"e": 6578,
"s": 6559,
"text": "Difference Between"
},
{
"code": null,
"e": 6595,
"s": 6578,
"text": "Web Technologies"
}
] |
How to avoid dropdown menu to close menu items on clicking inside ?
|
09 Jul, 2019
The default behavior of a dropdown menu is to close the menu list items when clicked inside. In this article, We will use stropPropagation method to prevent the dropdown menu from closing the menu list.
stopPropagation(): The stopPropagation() method is used to stop propagation of event calling i.e. the parent event is called we can stop the propagation of calling its children by using the stopProagration() method and vice-versa.
Syntax:
event.stopPropagation();
Example:
<!DOCTYPE html><html> <head> <title> How to avoid dropdown menu to close menu items on click inside ? </title> <style> .dropbutton { background-color: #4CAF50; color: white; padding: 14px; font-size: 14px; border: none; cursor: pointer; } .dropbutton:hover, .dropbutton:focus { background-color: #3e8e41; } .dropdownmenu { position: relative; display: inline-block; outline: none; } .dropdownmenu-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 140px; overflow: auto; box-shadow: 0px 8px 16px rgba(0,0,0,0.3); } .dropdownmenu-content a { color: black; padding: 12px 14px; text-decoration: none; display: block; } .dropdownmenu a:hover { background-color: #f1f1f1 } .show { display:block; } </style></head> <body style="text-align:center;"> <h1 style="color:green">GeeksforGeeks</h1> <p> Clicking outside will close the drop down menu. </p> <div class="dropdownmenu"> <button onclick="btnToggle()" class="dropbutton"> Dropdown </button> <div id="Dropdown" class="dropdownmenu-content" > <a href="#Java">Java</a> <a href="#HTML">HTML</a> <a href="#CSS">CSS</a> <a href="#JS">JavaScript</a> </div> </div> <script> // JavaScript code to avoid dropdown // menu close // Clicking dropdown button will toggle display function btnToggle() { document.getElementById("Dropdown").classList.toggle("show"); } // Prevents menu from closing when clicked inside document.getElementById("Dropdown").addEventListener('click', function (event) { alert("click outside"); event.stopPropagation(); }); // Closes the menu in the event of outside click window.onclick = function(event) { if (!event.target.matches('.dropbutton')) { var dropdowns = document.getElementsByClassName("dropdownmenu-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } </script> </body> </html>
Output:
Click Inside:
Click Outside:
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jul, 2019"
},
{
"code": null,
"e": 231,
"s": 28,
"text": "The default behavior of a dropdown menu is to close the menu list items when clicked inside. In this article, We will use stropPropagation method to prevent the dropdown menu from closing the menu list."
},
{
"code": null,
"e": 462,
"s": 231,
"text": "stopPropagation(): The stopPropagation() method is used to stop propagation of event calling i.e. the parent event is called we can stop the propagation of calling its children by using the stopProagration() method and vice-versa."
},
{
"code": null,
"e": 470,
"s": 462,
"text": "Syntax:"
},
{
"code": null,
"e": 495,
"s": 470,
"text": "event.stopPropagation();"
},
{
"code": null,
"e": 504,
"s": 495,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to avoid dropdown menu to close menu items on click inside ? </title> <style> .dropbutton { background-color: #4CAF50; color: white; padding: 14px; font-size: 14px; border: none; cursor: pointer; } .dropbutton:hover, .dropbutton:focus { background-color: #3e8e41; } .dropdownmenu { position: relative; display: inline-block; outline: none; } .dropdownmenu-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 140px; overflow: auto; box-shadow: 0px 8px 16px rgba(0,0,0,0.3); } .dropdownmenu-content a { color: black; padding: 12px 14px; text-decoration: none; display: block; } .dropdownmenu a:hover { background-color: #f1f1f1 } .show { display:block; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <p> Clicking outside will close the drop down menu. </p> <div class=\"dropdownmenu\"> <button onclick=\"btnToggle()\" class=\"dropbutton\"> Dropdown </button> <div id=\"Dropdown\" class=\"dropdownmenu-content\" > <a href=\"#Java\">Java</a> <a href=\"#HTML\">HTML</a> <a href=\"#CSS\">CSS</a> <a href=\"#JS\">JavaScript</a> </div> </div> <script> // JavaScript code to avoid dropdown // menu close // Clicking dropdown button will toggle display function btnToggle() { document.getElementById(\"Dropdown\").classList.toggle(\"show\"); } // Prevents menu from closing when clicked inside document.getElementById(\"Dropdown\").addEventListener('click', function (event) { alert(\"click outside\"); event.stopPropagation(); }); // Closes the menu in the event of outside click window.onclick = function(event) { if (!event.target.matches('.dropbutton')) { var dropdowns = document.getElementsByClassName(\"dropdownmenu-content\"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } </script> </body> </html> ",
"e": 3401,
"s": 504,
"text": null
},
{
"code": null,
"e": 3409,
"s": 3401,
"text": "Output:"
},
{
"code": null,
"e": 3423,
"s": 3409,
"text": "Click Inside:"
},
{
"code": null,
"e": 3438,
"s": 3423,
"text": "Click Outside:"
},
{
"code": null,
"e": 3445,
"s": 3438,
"text": "Picked"
},
{
"code": null,
"e": 3456,
"s": 3445,
"text": "JavaScript"
},
{
"code": null,
"e": 3473,
"s": 3456,
"text": "Web Technologies"
},
{
"code": null,
"e": 3500,
"s": 3473,
"text": "Web technologies Questions"
}
] |
How to store single cache data in ReactJS ?
|
21 Jan, 2022
We can use the following approach in ReactJS to store single data into cache in ReactJS. We can cache some data into the browser and use it in our application whenever needed. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested.
Approach: Follow these simple steps in order to store single data into cache in ReactJS. We have created our addDataIntoCache function which takes the user data and store into the browser cache. When we click on the button, the function is triggered and data gets stored into the cache, and we see an alert popup.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
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'; export default function App() { // Function to add our give data into cache const addDataIntoCache = (cacheName, url, response) => { // Converting our response into Actual Response form const data = new Response(JSON.stringify(response)); if ('caches' in window) { // Opening given cache and putting our data into it caches.open(cacheName).then((cache) => { cache.put(url, data); alert('Data Added into cache!') }); } }; return ( <div style={{ height: 500, width: '80%' }}> <h4>How to store data into cache in ReactJS?</h4> <button onClick={()=>addDataIntoCache('MyCache', 'https://localhost:300','SampleData')} > Add Data Into Cache</button> </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:
sooda367
simmytarika5
React-Questions
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": "\n21 Jan, 2022"
},
{
"code": null,
"e": 330,
"s": 28,
"text": "We can use the following approach in ReactJS to store single data into cache in ReactJS. We can cache some data into the browser and use it in our application whenever needed. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested."
},
{
"code": null,
"e": 644,
"s": 330,
"text": "Approach: Follow these simple steps in order to store single data into cache in ReactJS. We have created our addDataIntoCache function which takes the user data and store into the browser cache. When we click on the button, the function is triggered and data gets stored into the cache, and we see an alert popup."
},
{
"code": null,
"e": 672,
"s": 644,
"text": "Creating React Application:"
},
{
"code": null,
"e": 736,
"s": 672,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 768,
"s": 736,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 869,
"s": 768,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:"
},
{
"code": null,
"e": 883,
"s": 869,
"text": "cd foldername"
},
{
"code": null,
"e": 935,
"s": 883,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 953,
"s": 935,
"text": "Project Structure"
},
{
"code": null,
"e": 1083,
"s": 953,
"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": 1090,
"s": 1083,
"text": "App.js"
},
{
"code": "import * as React from 'react'; export default function App() { // Function to add our give data into cache const addDataIntoCache = (cacheName, url, response) => { // Converting our response into Actual Response form const data = new Response(JSON.stringify(response)); if ('caches' in window) { // Opening given cache and putting our data into it caches.open(cacheName).then((cache) => { cache.put(url, data); alert('Data Added into cache!') }); } }; return ( <div style={{ height: 500, width: '80%' }}> <h4>How to store data into cache in ReactJS?</h4> <button onClick={()=>addDataIntoCache('MyCache', 'https://localhost:300','SampleData')} > Add Data Into Cache</button> </div> );}",
"e": 1857,
"s": 1090,
"text": null
},
{
"code": null,
"e": 1973,
"s": 1860,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 1985,
"s": 1975,
"text": "npm start"
},
{
"code": null,
"e": 2084,
"s": 1985,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2095,
"s": 2086,
"text": "sooda367"
},
{
"code": null,
"e": 2108,
"s": 2095,
"text": "simmytarika5"
},
{
"code": null,
"e": 2124,
"s": 2108,
"text": "React-Questions"
},
{
"code": null,
"e": 2132,
"s": 2124,
"text": "ReactJS"
},
{
"code": null,
"e": 2149,
"s": 2132,
"text": "Web Technologies"
}
] |
Python | Working with PNG Images using Matplotlib
|
15 Apr, 2019
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc.
In this article, we will see how can we work with PNG images using Matplotlib.
Code #1: Read a PNG image using Matplotlib
# importing pyplot and image from matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as img # reading png image fileim = img.imread('imR.png') # show imageplt.imshow(im)
Output:
Code #2: Applying pseudocolor to image
Pseudocolor is useful for enhancing contrast of image.
# importing pyplot and image from matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as img # reading png imageim = img.imread('imR.png') # applying pseudocolor # default value of colormap is used.lum = im[:, :, 0] # show imageplt.imshow(lum)
Output:
Code #3: We can provide another value to colormap with colorbar.
# importing pyplot and image from matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as img # reading png imageim = img.imread('imR.png')lum = im[:, :, 0] # setting colormap as hotplt.imshow(lum, cmap ='hot')plt.colorbar()
Output:
Interpolation Schemes:Interpolation calculates what the color or value of a pixel “should” be and this needed when we resize the image but want the same information. There’s missing space when you resize image because pixels are discrete and interpolation is how you fill that space.
Code # 4: Interpolation
# importing PIL and matplotlibfrom PIL import Image import matplotlib.pyplot as plt # reading png image fileimg = Image.open('imR.png') # resizing the imageimg.thumbnail((50, 50), Image.ANTIALIAS)imgplot = plt.imshow(img)
Output:
Code #6: Here, ‘bicubic’ value is used for interpolation.
# importing pyplot from matplotlibimport matplotlib.pyplot as plt # importing image from PILfrom PIL import Image # reading imageimg = Image.open('imR.png') img.thumbnail((30, 30), Image.ANTIALIAS) # bicubic used for interpolationimgplot = plt.imshow(img, interpolation ='bicubic')
Output:
Code #7: ‘sinc’ value is used for interpolation.
# importing PIL and matplotlibfrom PIL import Image import matplotlib.pyplot as plt # reading imageimg = Image.open('imR.png') img.thumbnail((30, 30), Image.ANTIALIAS) # sinc used for interpolationimgplot = plt.imshow(img, interpolation ='sinc')
Output: Reference: https://matplotlib.org/gallery/images_contours_and_fields/interpolation_methods.html
Image-Processing
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Apr, 2019"
},
{
"code": null,
"e": 502,
"s": 28,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc."
},
{
"code": null,
"e": 581,
"s": 502,
"text": "In this article, we will see how can we work with PNG images using Matplotlib."
},
{
"code": null,
"e": 624,
"s": 581,
"text": "Code #1: Read a PNG image using Matplotlib"
},
{
"code": "# importing pyplot and image from matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as img # reading png image fileim = img.imread('imR.png') # show imageplt.imshow(im)",
"e": 810,
"s": 624,
"text": null
},
{
"code": null,
"e": 818,
"s": 810,
"text": "Output:"
},
{
"code": null,
"e": 857,
"s": 818,
"text": "Code #2: Applying pseudocolor to image"
},
{
"code": null,
"e": 912,
"s": 857,
"text": "Pseudocolor is useful for enhancing contrast of image."
},
{
"code": "# importing pyplot and image from matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as img # reading png imageim = img.imread('imR.png') # applying pseudocolor # default value of colormap is used.lum = im[:, :, 0] # show imageplt.imshow(lum)",
"e": 1172,
"s": 912,
"text": null
},
{
"code": null,
"e": 1180,
"s": 1172,
"text": "Output:"
},
{
"code": null,
"e": 1245,
"s": 1180,
"text": "Code #3: We can provide another value to colormap with colorbar."
},
{
"code": "# importing pyplot and image from matplotlibimport matplotlib.pyplot as pltimport matplotlib.image as img # reading png imageim = img.imread('imR.png')lum = im[:, :, 0] # setting colormap as hotplt.imshow(lum, cmap ='hot')plt.colorbar()",
"e": 1484,
"s": 1245,
"text": null
},
{
"code": null,
"e": 1492,
"s": 1484,
"text": "Output:"
},
{
"code": null,
"e": 1776,
"s": 1492,
"text": "Interpolation Schemes:Interpolation calculates what the color or value of a pixel “should” be and this needed when we resize the image but want the same information. There’s missing space when you resize image because pixels are discrete and interpolation is how you fill that space."
},
{
"code": null,
"e": 1800,
"s": 1776,
"text": "Code # 4: Interpolation"
},
{
"code": "# importing PIL and matplotlibfrom PIL import Image import matplotlib.pyplot as plt # reading png image fileimg = Image.open('imR.png') # resizing the imageimg.thumbnail((50, 50), Image.ANTIALIAS)imgplot = plt.imshow(img)",
"e": 2025,
"s": 1800,
"text": null
},
{
"code": null,
"e": 2033,
"s": 2025,
"text": "Output:"
},
{
"code": null,
"e": 2091,
"s": 2033,
"text": "Code #6: Here, ‘bicubic’ value is used for interpolation."
},
{
"code": "# importing pyplot from matplotlibimport matplotlib.pyplot as plt # importing image from PILfrom PIL import Image # reading imageimg = Image.open('imR.png') img.thumbnail((30, 30), Image.ANTIALIAS) # bicubic used for interpolationimgplot = plt.imshow(img, interpolation ='bicubic')",
"e": 2379,
"s": 2091,
"text": null
},
{
"code": null,
"e": 2387,
"s": 2379,
"text": "Output:"
},
{
"code": null,
"e": 2436,
"s": 2387,
"text": "Code #7: ‘sinc’ value is used for interpolation."
},
{
"code": "# importing PIL and matplotlibfrom PIL import Image import matplotlib.pyplot as plt # reading imageimg = Image.open('imR.png') img.thumbnail((30, 30), Image.ANTIALIAS) # sinc used for interpolationimgplot = plt.imshow(img, interpolation ='sinc')",
"e": 2685,
"s": 2436,
"text": null
},
{
"code": null,
"e": 2789,
"s": 2685,
"text": "Output: Reference: https://matplotlib.org/gallery/images_contours_and_fields/interpolation_methods.html"
},
{
"code": null,
"e": 2806,
"s": 2789,
"text": "Image-Processing"
},
{
"code": null,
"e": 2824,
"s": 2806,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2831,
"s": 2824,
"text": "Python"
}
] |
How to create a pop-up to print dialog box using JavaScript?
|
12 Sep, 2019
Given an HTML document and the task is to design a button that would pop-up a print dialog box. We are going to use JavaScript to do the assigned task:
Approach::Add a button which links to a JavaScript Function.Inside the JavaScript Function, use the JavaScript default function to call the print dialog boxSyntax:window.printExample:<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <script> function printPopUp() { alert("Pop-up dialog-box") window.print(); } </script> <button onclick="printPopUp()">Print</button> </center></body> </html>Output:Before:After:
Add a button which links to a JavaScript Function.
Inside the JavaScript Function, use the JavaScript default function to call the print dialog box
Syntax:
window.print
Example:
<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <script> function printPopUp() { alert("Pop-up dialog-box") window.print(); } </script> <button onclick="printPopUp()">Print</button> </center></body> </html>
Output:Before:After:
Approach::Use DOM onload Event in body tag.Use window alert method for pop-up dialog-box and window.print to print the document.Example:<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body onload="alert('Pop-up dialog-box');window.print();"> <center> <h1 style="color:green"> GeeksforGeeks </h1> create a pop-up to print dialog box using JavaScript </center></body> </html>Output:
Use DOM onload Event in body tag.
Use window alert method for pop-up dialog-box and window.print to print the document.
Example:
<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body onload="alert('Pop-up dialog-box');window.print();"> <center> <h1 style="color:green"> GeeksforGeeks </h1> create a pop-up to print dialog box using JavaScript </center></body> </html>
Output:
Approach::Use <a> href attribute to hyperlink text.Use window alert method for pop-up dialog-box and window.print to print the document.Example:<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <a href="javascript:alert('Pop-up dialog-box');window.print();"> Click Me </a> </center></body> </html>Output:Before:After:
Use <a> href attribute to hyperlink text.
Use window alert method for pop-up dialog-box and window.print to print the document.
Example:
<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <a href="javascript:alert('Pop-up dialog-box');window.print();"> Click Me </a> </center></body> </html>
Output:Before:
After:
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Sep, 2019"
},
{
"code": null,
"e": 180,
"s": 28,
"text": "Given an HTML document and the task is to design a button that would pop-up a print dialog box. We are going to use JavaScript to do the assigned task:"
},
{
"code": null,
"e": 805,
"s": 180,
"text": "Approach::Add a button which links to a JavaScript Function.Inside the JavaScript Function, use the JavaScript default function to call the print dialog boxSyntax:window.printExample:<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <script> function printPopUp() { alert(\"Pop-up dialog-box\") window.print(); } </script> <button onclick=\"printPopUp()\">Print</button> </center></body> </html>Output:Before:After:"
},
{
"code": null,
"e": 856,
"s": 805,
"text": "Add a button which links to a JavaScript Function."
},
{
"code": null,
"e": 953,
"s": 856,
"text": "Inside the JavaScript Function, use the JavaScript default function to call the print dialog box"
},
{
"code": null,
"e": 961,
"s": 953,
"text": "Syntax:"
},
{
"code": null,
"e": 974,
"s": 961,
"text": "window.print"
},
{
"code": null,
"e": 983,
"s": 974,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <script> function printPopUp() { alert(\"Pop-up dialog-box\") window.print(); } </script> <button onclick=\"printPopUp()\">Print</button> </center></body> </html>",
"e": 1405,
"s": 983,
"text": null
},
{
"code": null,
"e": 1426,
"s": 1405,
"text": "Output:Before:After:"
},
{
"code": null,
"e": 1906,
"s": 1426,
"text": "Approach::Use DOM onload Event in body tag.Use window alert method for pop-up dialog-box and window.print to print the document.Example:<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body onload=\"alert('Pop-up dialog-box');window.print();\"> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> create a pop-up to print dialog box using JavaScript </center></body> </html>Output:"
},
{
"code": null,
"e": 1940,
"s": 1906,
"text": "Use DOM onload Event in body tag."
},
{
"code": null,
"e": 2026,
"s": 1940,
"text": "Use window alert method for pop-up dialog-box and window.print to print the document."
},
{
"code": null,
"e": 2035,
"s": 2026,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body onload=\"alert('Pop-up dialog-box');window.print();\"> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> create a pop-up to print dialog box using JavaScript </center></body> </html>",
"e": 2372,
"s": 2035,
"text": null
},
{
"code": null,
"e": 2380,
"s": 2372,
"text": "Output:"
},
{
"code": null,
"e": 2871,
"s": 2380,
"text": "Approach::Use <a> href attribute to hyperlink text.Use window alert method for pop-up dialog-box and window.print to print the document.Example:<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <a href=\"javascript:alert('Pop-up dialog-box');window.print();\"> Click Me </a> </center></body> </html>Output:Before:After:"
},
{
"code": null,
"e": 2913,
"s": 2871,
"text": "Use <a> href attribute to hyperlink text."
},
{
"code": null,
"e": 2999,
"s": 2913,
"text": "Use window alert method for pop-up dialog-box and window.print to print the document."
},
{
"code": null,
"e": 3008,
"s": 2999,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>create a pop-up to print dialog box using JavaScript</title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <a href=\"javascript:alert('Pop-up dialog-box');window.print();\"> Click Me </a> </center></body> </html>",
"e": 3335,
"s": 3008,
"text": null
},
{
"code": null,
"e": 3350,
"s": 3335,
"text": "Output:Before:"
},
{
"code": null,
"e": 3357,
"s": 3350,
"text": "After:"
},
{
"code": null,
"e": 3364,
"s": 3357,
"text": "Picked"
},
{
"code": null,
"e": 3375,
"s": 3364,
"text": "JavaScript"
},
{
"code": null,
"e": 3392,
"s": 3375,
"text": "Web Technologies"
},
{
"code": null,
"e": 3419,
"s": 3392,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3517,
"s": 3419,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3578,
"s": 3517,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3650,
"s": 3578,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3690,
"s": 3650,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3732,
"s": 3690,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3773,
"s": 3732,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3806,
"s": 3773,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3868,
"s": 3806,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3929,
"s": 3868,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3979,
"s": 3929,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Dividing Sticks Problem
|
18 Aug, 2021
Given a list of integer each representing the length of each stick and an integer which tells how many times we can break a stick into half parts, we have to find maximum desired length sticks can be obtained from the group of sticks. Note 1: When we break a stick it gets converted into two half parts for example for a stick of length 10 two sticks can be obtained of both 5 in length and for a stick of length 5 two sticks will be obtained of length 2 and 3 respectively.Note 2: Discarded part can’t be used again for making sticks such that if a stick of length 11 is given we can break it into 5 and 6 of length pieces then we have to discard one of the pieces which can’t be used further.
Examples:
Input: list = [2, 3, 4, 11] n = 2 desired_length = 3 Output : Maximum sticks of desired length that can be obtained are : 3Explanation : We already have one stick of length 3 and two more sticks can be obtained by breaking stick of length 11 into [5, 3, 3] pieces therefore total sticks will be 3.
Input: list = [2, 1, 4, 5] n = 2 desired_length = 4 Output : Maximum sticks of desired length that can be obtained are : 1Explanation : We already have one stick of length 4 and no more sticks can be obtained by breaking any stick therefore total sticks will be 1
Approach:To solve the problem mentioned above we will first do a linear search operation to find all the sticks which have exact same length as of the desired stick length and count them. We will then store the count in the variable. Obviously, we have to discard all the sticks which have a length less than the desired length as with them we can’t make any desired length stick. Then pass the value of sticks that have a length more than the desired length to a function that calculates how many sticks can be obtained by breaking them. With the help of recursion find a number of ways in which sticks can be obtained.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; // Method to find number of sticks by breaking themint sticks_break(int stick_length,int n, int desired_length){ // If stick cant be break any more if (n < 1) return 0; // Check if stick length became // smaller than the desired length if (stick_length < desired_length) return 0; // Check if stick length is even number if (stick_length % 2 == 0) // Check if half of stick // length is equal to desired length if (stick_length / 2 == desired_length) return 2; // Check if half of stick length // is greater than the desired length else if (stick_length / 2 > desired_length) return (sticks_break(stick_length / 2, n - 1, desired_length)); // Check if stick length is odd number if (stick_length % 2 != 0) // For odd number two halves will be // generated checking if first half // is equal to desired length if (stick_length / 2 == desired_length) return 1; // Checking if second half // is equal to desired length if (stick_length / 2 + 1 == desired_length) return 1; // Check if half of stick length // is greater than the desired length if (stick_length/2 > desired_length) return (max (sticks_break( stick_length / 2, n - 1, desired_length), sticks_break( stick_length / 2 + 1, n - 1, desired_length))); return 0;} // Method to find number of sticks int numberOfSticks(vector<int>list_length, int n, int desired_length){ int count = 0; for(auto stick_lenght : list_length) { // Check if desired length is found if (desired_length == stick_lenght) // Incrementing the count count = count + 1; // Check if stick length is // greater than desired length else if (stick_lenght> desired_length) // Incrementing count // after break the sticks count = count + sticks_break( stick_lenght, n, desired_length); } // Return count return count;} // Driver codeint main(){ // List of integers vector<int>list_length = { 1, 2, 3, 21 }; // Number of ways stick can be break int n = 3; // Desired length int desired_length = 3; int count = numberOfSticks(list_length, n, desired_length); // Print result cout << count << endl;} // This code is contributed by Stream_Cipher
import java.util.*; class GFG{ // Method to find number of sticks by breaking themstatic int sticks_break(int stick_length, int n, int desired_length){ // If stick cant be break any more if (n < 1) return 0; // Check if stick length became // smaller than the desired length if (stick_length < desired_length) return 0; // Check if stick length is even number if (stick_length % 2 == 0) // Check if half of stick // length is equal to desired length if (stick_length / 2 == desired_length) return 2; // Check if half of stick length // is greater than the desired length else if (stick_length / 2 > desired_length) return (sticks_break(stick_length / 2, n - 1, desired_length)); // Check if stick length is odd number if (stick_length % 2 != 0) // For odd number two halves will be // generated checking if first half // is equal to desired length if (stick_length / 2 == desired_length) return 1; // Checking if second half // is equal to desired length if (stick_length / 2 + 1 == desired_length) return 1; // Check if half of stick length // is greater than the desired length if (stick_length/2 > desired_length) return (Math.max (sticks_break( stick_length / 2, n - 1, desired_length), sticks_break( stick_length / 2 + 1, n - 1, desired_length))); return 0;} // Method to find number of sticksstatic int numberOfSticks(int list_length[], int n, int desired_length){ int count = 0; for(int i = 0; i < list_length.length; i++) { // Check if desired length is found if (desired_length == list_length[i]) // Incrementing the count count = count + 1; // Check if stick length is // greater than desired length else if (list_length[i]> desired_length) // Incrementing count // after break the sticks count = count + sticks_break(list_length[i], n, desired_length); } // Return count return count;} // Driver codepublic static void main(String args[]){ // List of integers int[] list_length = new int[]{ 1, 2, 3, 21 }; // Number of ways stick can be break int n = 3; // Desired length int desired_length = 3; int count = numberOfSticks(list_length, n, desired_length); // Print result System.out.println(count);}} // This code is contributed by Stream_Cipher
# method to find number of sticks by breaking themdef sticks_break(stick_length, n, desired_length): # if stick cant be break any more if n < 1: return 0 # check if stick length became # smaller than the desired length if stick_length < desired_length: return 0 # check if stick length is even number if stick_length % 2 == 0: # check if half of stick # length is equal to desired length if stick_length / 2 == desired_length: return 2 # check if half of stick length # is greater than the desired length elif stick_length / 2 > desired_length: return sticks_break(stick_length / 2, n-1, desired_length) # check if stick length is odd number if stick_length % 2 != 0: # for odd number two halves will be generated # checking if first half is equal to desired length if stick_length // 2 == desired_length: return 1 # checking if second half # is equal to desired length if stick_length // 2 + 1 == desired_length: return 1 # check if half of stick length # is greater than the desired length if stick_length//2 > desired_length: return max (sticks_break(stick_length//2, n-1, desired_length), sticks_break(stick_length//2 + 1, n-1, desired_length)) return 0 # method to find number of sticksdef numberOfSticks(list_length, n, desired_length): count = 0 for stick_length in list_length: # check if desired length is found if desired_length == stick_length: # incrementing the count count = count + 1 # check if stick length is # greater than desired length elif stick_length > desired_length: # incrementing count # after break the sticks count = count + sticks_break(stick_length, n, desired_length) # return count return count # driver codeif __name__ == "__main__": # list of integers list_length =[1, 2, 3, 21] # number of ways stick can be break n = 3 # desired length desired_length = 3 count = numberOfSticks(list_length, n, desired_length) # print result print(str(count))
using System;class GFG{ // Method to find number of sticks by breaking themstatic int sticks_break(int stick_length, int n, int desired_length){ // If stick cant be break any more if (n < 1 ) return 0; // Check if stick length became // smaller than the desired length if (stick_length < desired_length) return 0; // Check if stick length is even number if (stick_length % 2 == 0) // Check if half of stick // length is equal to desired length if (stick_length / 2 == desired_length) return 2; // Check if half of stick length // is greater than the desired length else if (stick_length / 2 > desired_length) return (sticks_break(stick_length / 2, n - 1, desired_length)); // Check if stick length is odd number if (stick_length % 2 != 0) // For odd number two halves will be // generated checking if first half // is equal to desired length if (stick_length / 2 == desired_length) return 1; // Checking if second half // is equal to desired length if (stick_length / 2 + 1 == desired_length) return 1; // Check if half of stick length // is greater than the desired length if (stick_length/2 > desired_length) return (Math.Max(sticks_break( stick_length / 2, n - 1, desired_length), sticks_break( stick_length / 2 + 1, n - 1, desired_length))); return 0;} // Method to find number of sticksstatic int numberOfSticks(int []list_length, int n, int desired_length){ int count = 0; for(int i = 0; i < list_length.Length; i++) { // Check if desired length is found if (desired_length == list_length[i]) // Incrementing the count count = count + 1; // Check if stick length is // greater than desired length else if (list_length[i]> desired_length) // Incrementing count // after break the sticks count = count + sticks_break(list_length[i], n, desired_length); } // Return count return count;} // Driver codepublic static void Main(){ // list of integers int []list_length = { 1, 2, 3, 21 }; // Number of ways stick can be break int n = 3; // Desired length int desired_length = 3; int count = numberOfSticks(list_length, n, desired_length); // Print result Console.WriteLine(count);}} // This code is contributed by Stream_Cipher
<script> // Method to find number of sticks by breaking them function sticks_break(stick_length, n, desired_length) { // If stick cant be break any more if (n < 1) return 0; // Check if stick length became // smaller than the desired length if (stick_length < desired_length) return 0; // Check if stick length is even number if (stick_length % 2 == 0) // Check if half of stick // length is equal to desired length if (parseInt(stick_length / 2, 10) == desired_length) return 2; // Check if half of stick length // is greater than the desired length else if (parseInt(stick_length / 2, 10) > desired_length) return (sticks_break(parseInt(stick_length / 2, 10), n - 1, desired_length)); // Check if stick length is odd number if (stick_length % 2 != 0) // For odd number two halves will be // generated checking if first half // is equal to desired length if (parseInt(stick_length / 2, 10) == desired_length) return 1; // Checking if second half // is equal to desired length if (parseInt(stick_length / 2, 10) + 1 == desired_length) return 1; // Check if half of stick length // is greater than the desired length if (parseInt(stick_length/2, 10) > desired_length) return (Math.max(sticks_break( parseInt(stick_length / 2, 10), n - 1, desired_length), sticks_break( parseInt(stick_length / 2, 10) + 1, n - 1, desired_length))); return 0; } // Method to find number of sticks function numberOfSticks(list_length, n, desired_length) { let count = 0; for(let i = 0; i < list_length.length; i++) { // Check if desired length is found if (desired_length == list_length[i]) // Incrementing the count count = count + 1; // Check if stick length is // greater than desired length else if (list_length[i]> desired_length) // Incrementing count // after break the sticks count = count + sticks_break(list_length[i], n, desired_length); } // Return count return count; } // List of integers let list_length = [ 1, 2, 3, 21 ]; // Number of ways stick can be break let n = 3; // Desired length let desired_length = 3; let count = numberOfSticks(list_length, n, desired_length); // Print result document.write(count); </script>
3
Time Complexity: O(N^2)Auxiliary Space: O(N)
Stream_Cipher
decode2207
pankajsharmagfg
Algorithms
Competitive Programming
Python
Recursion
Recursion
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 747,
"s": 52,
"text": "Given a list of integer each representing the length of each stick and an integer which tells how many times we can break a stick into half parts, we have to find maximum desired length sticks can be obtained from the group of sticks. Note 1: When we break a stick it gets converted into two half parts for example for a stick of length 10 two sticks can be obtained of both 5 in length and for a stick of length 5 two sticks will be obtained of length 2 and 3 respectively.Note 2: Discarded part can’t be used again for making sticks such that if a stick of length 11 is given we can break it into 5 and 6 of length pieces then we have to discard one of the pieces which can’t be used further."
},
{
"code": null,
"e": 757,
"s": 747,
"text": "Examples:"
},
{
"code": null,
"e": 1055,
"s": 757,
"text": "Input: list = [2, 3, 4, 11] n = 2 desired_length = 3 Output : Maximum sticks of desired length that can be obtained are : 3Explanation : We already have one stick of length 3 and two more sticks can be obtained by breaking stick of length 11 into [5, 3, 3] pieces therefore total sticks will be 3."
},
{
"code": null,
"e": 1319,
"s": 1055,
"text": "Input: list = [2, 1, 4, 5] n = 2 desired_length = 4 Output : Maximum sticks of desired length that can be obtained are : 1Explanation : We already have one stick of length 4 and no more sticks can be obtained by breaking any stick therefore total sticks will be 1"
},
{
"code": null,
"e": 1990,
"s": 1319,
"text": "Approach:To solve the problem mentioned above we will first do a linear search operation to find all the sticks which have exact same length as of the desired stick length and count them. We will then store the count in the variable. Obviously, we have to discard all the sticks which have a length less than the desired length as with them we can’t make any desired length stick. Then pass the value of sticks that have a length more than the desired length to a function that calculates how many sticks can be obtained by breaking them. With the help of recursion find a number of ways in which sticks can be obtained.Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1994,
"s": 1990,
"text": "C++"
},
{
"code": null,
"e": 1999,
"s": 1994,
"text": "Java"
},
{
"code": null,
"e": 2007,
"s": 1999,
"text": "Python3"
},
{
"code": null,
"e": 2010,
"s": 2007,
"text": "C#"
},
{
"code": null,
"e": 2021,
"s": 2010,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; // Method to find number of sticks by breaking themint sticks_break(int stick_length,int n, int desired_length){ // If stick cant be break any more if (n < 1) return 0; // Check if stick length became // smaller than the desired length if (stick_length < desired_length) return 0; // Check if stick length is even number if (stick_length % 2 == 0) // Check if half of stick // length is equal to desired length if (stick_length / 2 == desired_length) return 2; // Check if half of stick length // is greater than the desired length else if (stick_length / 2 > desired_length) return (sticks_break(stick_length / 2, n - 1, desired_length)); // Check if stick length is odd number if (stick_length % 2 != 0) // For odd number two halves will be // generated checking if first half // is equal to desired length if (stick_length / 2 == desired_length) return 1; // Checking if second half // is equal to desired length if (stick_length / 2 + 1 == desired_length) return 1; // Check if half of stick length // is greater than the desired length if (stick_length/2 > desired_length) return (max (sticks_break( stick_length / 2, n - 1, desired_length), sticks_break( stick_length / 2 + 1, n - 1, desired_length))); return 0;} // Method to find number of sticks int numberOfSticks(vector<int>list_length, int n, int desired_length){ int count = 0; for(auto stick_lenght : list_length) { // Check if desired length is found if (desired_length == stick_lenght) // Incrementing the count count = count + 1; // Check if stick length is // greater than desired length else if (stick_lenght> desired_length) // Incrementing count // after break the sticks count = count + sticks_break( stick_lenght, n, desired_length); } // Return count return count;} // Driver codeint main(){ // List of integers vector<int>list_length = { 1, 2, 3, 21 }; // Number of ways stick can be break int n = 3; // Desired length int desired_length = 3; int count = numberOfSticks(list_length, n, desired_length); // Print result cout << count << endl;} // This code is contributed by Stream_Cipher",
"e": 4924,
"s": 2021,
"text": null
},
{
"code": "import java.util.*; class GFG{ // Method to find number of sticks by breaking themstatic int sticks_break(int stick_length, int n, int desired_length){ // If stick cant be break any more if (n < 1) return 0; // Check if stick length became // smaller than the desired length if (stick_length < desired_length) return 0; // Check if stick length is even number if (stick_length % 2 == 0) // Check if half of stick // length is equal to desired length if (stick_length / 2 == desired_length) return 2; // Check if half of stick length // is greater than the desired length else if (stick_length / 2 > desired_length) return (sticks_break(stick_length / 2, n - 1, desired_length)); // Check if stick length is odd number if (stick_length % 2 != 0) // For odd number two halves will be // generated checking if first half // is equal to desired length if (stick_length / 2 == desired_length) return 1; // Checking if second half // is equal to desired length if (stick_length / 2 + 1 == desired_length) return 1; // Check if half of stick length // is greater than the desired length if (stick_length/2 > desired_length) return (Math.max (sticks_break( stick_length / 2, n - 1, desired_length), sticks_break( stick_length / 2 + 1, n - 1, desired_length))); return 0;} // Method to find number of sticksstatic int numberOfSticks(int list_length[], int n, int desired_length){ int count = 0; for(int i = 0; i < list_length.length; i++) { // Check if desired length is found if (desired_length == list_length[i]) // Incrementing the count count = count + 1; // Check if stick length is // greater than desired length else if (list_length[i]> desired_length) // Incrementing count // after break the sticks count = count + sticks_break(list_length[i], n, desired_length); } // Return count return count;} // Driver codepublic static void main(String args[]){ // List of integers int[] list_length = new int[]{ 1, 2, 3, 21 }; // Number of ways stick can be break int n = 3; // Desired length int desired_length = 3; int count = numberOfSticks(list_length, n, desired_length); // Print result System.out.println(count);}} // This code is contributed by Stream_Cipher",
"e": 7898,
"s": 4924,
"text": null
},
{
"code": "# method to find number of sticks by breaking themdef sticks_break(stick_length, n, desired_length): # if stick cant be break any more if n < 1: return 0 # check if stick length became # smaller than the desired length if stick_length < desired_length: return 0 # check if stick length is even number if stick_length % 2 == 0: # check if half of stick # length is equal to desired length if stick_length / 2 == desired_length: return 2 # check if half of stick length # is greater than the desired length elif stick_length / 2 > desired_length: return sticks_break(stick_length / 2, n-1, desired_length) # check if stick length is odd number if stick_length % 2 != 0: # for odd number two halves will be generated # checking if first half is equal to desired length if stick_length // 2 == desired_length: return 1 # checking if second half # is equal to desired length if stick_length // 2 + 1 == desired_length: return 1 # check if half of stick length # is greater than the desired length if stick_length//2 > desired_length: return max (sticks_break(stick_length//2, n-1, desired_length), sticks_break(stick_length//2 + 1, n-1, desired_length)) return 0 # method to find number of sticksdef numberOfSticks(list_length, n, desired_length): count = 0 for stick_length in list_length: # check if desired length is found if desired_length == stick_length: # incrementing the count count = count + 1 # check if stick length is # greater than desired length elif stick_length > desired_length: # incrementing count # after break the sticks count = count + sticks_break(stick_length, n, desired_length) # return count return count # driver codeif __name__ == \"__main__\": # list of integers list_length =[1, 2, 3, 21] # number of ways stick can be break n = 3 # desired length desired_length = 3 count = numberOfSticks(list_length, n, desired_length) # print result print(str(count))",
"e": 10374,
"s": 7898,
"text": null
},
{
"code": "using System;class GFG{ // Method to find number of sticks by breaking themstatic int sticks_break(int stick_length, int n, int desired_length){ // If stick cant be break any more if (n < 1 ) return 0; // Check if stick length became // smaller than the desired length if (stick_length < desired_length) return 0; // Check if stick length is even number if (stick_length % 2 == 0) // Check if half of stick // length is equal to desired length if (stick_length / 2 == desired_length) return 2; // Check if half of stick length // is greater than the desired length else if (stick_length / 2 > desired_length) return (sticks_break(stick_length / 2, n - 1, desired_length)); // Check if stick length is odd number if (stick_length % 2 != 0) // For odd number two halves will be // generated checking if first half // is equal to desired length if (stick_length / 2 == desired_length) return 1; // Checking if second half // is equal to desired length if (stick_length / 2 + 1 == desired_length) return 1; // Check if half of stick length // is greater than the desired length if (stick_length/2 > desired_length) return (Math.Max(sticks_break( stick_length / 2, n - 1, desired_length), sticks_break( stick_length / 2 + 1, n - 1, desired_length))); return 0;} // Method to find number of sticksstatic int numberOfSticks(int []list_length, int n, int desired_length){ int count = 0; for(int i = 0; i < list_length.Length; i++) { // Check if desired length is found if (desired_length == list_length[i]) // Incrementing the count count = count + 1; // Check if stick length is // greater than desired length else if (list_length[i]> desired_length) // Incrementing count // after break the sticks count = count + sticks_break(list_length[i], n, desired_length); } // Return count return count;} // Driver codepublic static void Main(){ // list of integers int []list_length = { 1, 2, 3, 21 }; // Number of ways stick can be break int n = 3; // Desired length int desired_length = 3; int count = numberOfSticks(list_length, n, desired_length); // Print result Console.WriteLine(count);}} // This code is contributed by Stream_Cipher",
"e": 13292,
"s": 10374,
"text": null
},
{
"code": "<script> // Method to find number of sticks by breaking them function sticks_break(stick_length, n, desired_length) { // If stick cant be break any more if (n < 1) return 0; // Check if stick length became // smaller than the desired length if (stick_length < desired_length) return 0; // Check if stick length is even number if (stick_length % 2 == 0) // Check if half of stick // length is equal to desired length if (parseInt(stick_length / 2, 10) == desired_length) return 2; // Check if half of stick length // is greater than the desired length else if (parseInt(stick_length / 2, 10) > desired_length) return (sticks_break(parseInt(stick_length / 2, 10), n - 1, desired_length)); // Check if stick length is odd number if (stick_length % 2 != 0) // For odd number two halves will be // generated checking if first half // is equal to desired length if (parseInt(stick_length / 2, 10) == desired_length) return 1; // Checking if second half // is equal to desired length if (parseInt(stick_length / 2, 10) + 1 == desired_length) return 1; // Check if half of stick length // is greater than the desired length if (parseInt(stick_length/2, 10) > desired_length) return (Math.max(sticks_break( parseInt(stick_length / 2, 10), n - 1, desired_length), sticks_break( parseInt(stick_length / 2, 10) + 1, n - 1, desired_length))); return 0; } // Method to find number of sticks function numberOfSticks(list_length, n, desired_length) { let count = 0; for(let i = 0; i < list_length.length; i++) { // Check if desired length is found if (desired_length == list_length[i]) // Incrementing the count count = count + 1; // Check if stick length is // greater than desired length else if (list_length[i]> desired_length) // Incrementing count // after break the sticks count = count + sticks_break(list_length[i], n, desired_length); } // Return count return count; } // List of integers let list_length = [ 1, 2, 3, 21 ]; // Number of ways stick can be break let n = 3; // Desired length let desired_length = 3; let count = numberOfSticks(list_length, n, desired_length); // Print result document.write(count); </script>",
"e": 16314,
"s": 13292,
"text": null
},
{
"code": null,
"e": 16316,
"s": 16314,
"text": "3"
},
{
"code": null,
"e": 16361,
"s": 16316,
"text": "Time Complexity: O(N^2)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 16375,
"s": 16361,
"text": "Stream_Cipher"
},
{
"code": null,
"e": 16386,
"s": 16375,
"text": "decode2207"
},
{
"code": null,
"e": 16402,
"s": 16386,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 16413,
"s": 16402,
"text": "Algorithms"
},
{
"code": null,
"e": 16437,
"s": 16413,
"text": "Competitive Programming"
},
{
"code": null,
"e": 16444,
"s": 16437,
"text": "Python"
},
{
"code": null,
"e": 16454,
"s": 16444,
"text": "Recursion"
},
{
"code": null,
"e": 16464,
"s": 16454,
"text": "Recursion"
},
{
"code": null,
"e": 16475,
"s": 16464,
"text": "Algorithms"
}
] |
JavaScript | Promises
|
06 Dec, 2021
Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.
Prior to promises events and callback functions were used but they had limited functionalities and created unmanageable code. Multiple callback functions would create callback hell that leads to unmanageable code. Also it is not easy for any user to handle multiple callbacks at the same time.Events were not good at handling asynchronous operations.
Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events. In other words also, we may say that, promises are the ideal choice for handling multiple callbacks at the same time, thus avoiding the undesired callback hell situation. Promises do provide a better chance to a user to read the code in a more effective and efficient manner especially it that particular code is used for implementing multiple asynchronous operations.
Benefits of Promises Improves Code ReadabilityBetter handling of asynchronous operationsBetter flow of control definition in asynchronous logicBetter Error Handling
Improves Code ReadabilityBetter handling of asynchronous operationsBetter flow of control definition in asynchronous logicBetter Error Handling
Improves Code Readability
Better handling of asynchronous operations
Better flow of control definition in asynchronous logic
Better Error Handling
A Promise has four states: fulfilled: Action related to the promise succeededrejected: Action related to the promise failedpending: Promise is still pending i.e. not fulfilled or rejected yetsettled: Promise has fulfilled or rejected
fulfilled: Action related to the promise succeededrejected: Action related to the promise failedpending: Promise is still pending i.e. not fulfilled or rejected yetsettled: Promise has fulfilled or rejected
fulfilled: Action related to the promise succeeded
rejected: Action related to the promise failed
pending: Promise is still pending i.e. not fulfilled or rejected yet
settled: Promise has fulfilled or rejected
A promise can be created using Promise constructor.Syntax
var promise = new Promise(function(resolve, reject){
//do something
});
Parameters Promise constructor takes only one argument which is a callback function (and that callback function is also referred as anonymous function too).Callback function takes two arguments, resolve and rejectPerform operations inside the callback function and if everything went well then call resolve.If desired operations do not go well then call reject.
Promise constructor takes only one argument which is a callback function (and that callback function is also referred as anonymous function too).
Callback function takes two arguments, resolve and reject
Perform operations inside the callback function and if everything went well then call resolve.
If desired operations do not go well then call reject.
Example
Javascript
var promise = new Promise(function(resolve, reject) { const x = "geeksforgeeks"; const y = "geeksforgeeks" if(x === y) { resolve(); } else { reject(); }}); promise. then(function () { console.log('Success, You are a GEEK'); }). catch(function () { console.log('Some error has occurred'); });
Output:
Success, You are a GEEK
Promise ConsumersPromises can be consumed by registering functions using .then and .catch methods.
1. then() then() is invoked when a promise is either resolved or rejected. It may also be defined as a career which takes data from promise and further executes it successfully.
Parameters: then() method takes two functions as parameters.
First function is executed if promise is resolved and a result is received.Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method
First function is executed if promise is resolved and a result is received.
Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method
Syntax:
.then(function(result){
//handle success
}, function(error){
//handle error
})
Example: Promise Resolved
Javascript
var promise = new Promise(function(resolve, reject) { resolve('Geeks For Geeks');}) promise .then(function(successMessage) { //success handler function is invoked console.log(successMessage); }, function(errorMessage) { console.log(errorMessage); })
Output:
Geeks For Geeks
Examples: Promise Rejected
Javascript
var promise = new Promise(function(resolve, reject) { reject('Promise Rejected')}) promise .then(function(successMessage) { console.log(successMessage); }, function(errorMessage) { //error handler function is invoked console.log(errorMessage); })
Output:
Promise Rejected
2. catch()
catch() is invoked when a promise is either rejected or some error has occurred in execution. It is used as an Error Handler whenever at any step there is a chance of getting an error.
Parameters: catch() method takes one function as parameter.
Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )
Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )
Syntax:
.catch(function(error){
//handle error
})
Examples: Promise Rejected
Javascript
var promise = new Promise(function(resolve, reject) { reject('Promise Rejected')}) promise .then(function(successMessage) { console.log(successMessage); }) .catch(function(errorMessage) { //error handler function is invoked console.log(errorMessage); });
Output:
Promise Rejected
Examples: Promise Rejected
Javascript
var promise = new Promise(function(resolve, reject) { throw new Error('Some error has occurred')}) promise .then(function(successMessage) { console.log(successMessage); }) .catch(function(errorMessage) { //error handler function is invoked console.log(errorMessage); });
Output:
Error: Some error has occurred
Applications
Promises are used for asynchronous handling of events.Promises are used to handle asynchronous http requests.
Promises are used for asynchronous handling of events.
Promises are used to handle asynchronous http requests.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
sagar0719kumar
amansingla
javascript-basics
JavaScript
JS++
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 266,
"s": 52,
"text": "Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. "
},
{
"code": null,
"e": 617,
"s": 266,
"text": "Prior to promises events and callback functions were used but they had limited functionalities and created unmanageable code. Multiple callback functions would create callback hell that leads to unmanageable code. Also it is not easy for any user to handle multiple callbacks at the same time.Events were not good at handling asynchronous operations."
},
{
"code": null,
"e": 1195,
"s": 617,
"text": "Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events. In other words also, we may say that, promises are the ideal choice for handling multiple callbacks at the same time, thus avoiding the undesired callback hell situation. Promises do provide a better chance to a user to read the code in a more effective and efficient manner especially it that particular code is used for implementing multiple asynchronous operations. "
},
{
"code": null,
"e": 1360,
"s": 1195,
"text": "Benefits of Promises Improves Code ReadabilityBetter handling of asynchronous operationsBetter flow of control definition in asynchronous logicBetter Error Handling"
},
{
"code": null,
"e": 1504,
"s": 1360,
"text": "Improves Code ReadabilityBetter handling of asynchronous operationsBetter flow of control definition in asynchronous logicBetter Error Handling"
},
{
"code": null,
"e": 1530,
"s": 1504,
"text": "Improves Code Readability"
},
{
"code": null,
"e": 1573,
"s": 1530,
"text": "Better handling of asynchronous operations"
},
{
"code": null,
"e": 1629,
"s": 1573,
"text": "Better flow of control definition in asynchronous logic"
},
{
"code": null,
"e": 1651,
"s": 1629,
"text": "Better Error Handling"
},
{
"code": null,
"e": 1885,
"s": 1651,
"text": "A Promise has four states: fulfilled: Action related to the promise succeededrejected: Action related to the promise failedpending: Promise is still pending i.e. not fulfilled or rejected yetsettled: Promise has fulfilled or rejected"
},
{
"code": null,
"e": 2092,
"s": 1885,
"text": "fulfilled: Action related to the promise succeededrejected: Action related to the promise failedpending: Promise is still pending i.e. not fulfilled or rejected yetsettled: Promise has fulfilled or rejected"
},
{
"code": null,
"e": 2143,
"s": 2092,
"text": "fulfilled: Action related to the promise succeeded"
},
{
"code": null,
"e": 2190,
"s": 2143,
"text": "rejected: Action related to the promise failed"
},
{
"code": null,
"e": 2259,
"s": 2190,
"text": "pending: Promise is still pending i.e. not fulfilled or rejected yet"
},
{
"code": null,
"e": 2302,
"s": 2259,
"text": "settled: Promise has fulfilled or rejected"
},
{
"code": null,
"e": 2360,
"s": 2302,
"text": "A promise can be created using Promise constructor.Syntax"
},
{
"code": null,
"e": 2437,
"s": 2360,
"text": "var promise = new Promise(function(resolve, reject){\n //do something\n});"
},
{
"code": null,
"e": 2799,
"s": 2437,
"text": "Parameters Promise constructor takes only one argument which is a callback function (and that callback function is also referred as anonymous function too).Callback function takes two arguments, resolve and rejectPerform operations inside the callback function and if everything went well then call resolve.If desired operations do not go well then call reject."
},
{
"code": null,
"e": 2945,
"s": 2799,
"text": "Promise constructor takes only one argument which is a callback function (and that callback function is also referred as anonymous function too)."
},
{
"code": null,
"e": 3003,
"s": 2945,
"text": "Callback function takes two arguments, resolve and reject"
},
{
"code": null,
"e": 3098,
"s": 3003,
"text": "Perform operations inside the callback function and if everything went well then call resolve."
},
{
"code": null,
"e": 3153,
"s": 3098,
"text": "If desired operations do not go well then call reject."
},
{
"code": null,
"e": 3161,
"s": 3153,
"text": "Example"
},
{
"code": null,
"e": 3172,
"s": 3161,
"text": "Javascript"
},
{
"code": "var promise = new Promise(function(resolve, reject) { const x = \"geeksforgeeks\"; const y = \"geeksforgeeks\" if(x === y) { resolve(); } else { reject(); }}); promise. then(function () { console.log('Success, You are a GEEK'); }). catch(function () { console.log('Some error has occurred'); });",
"e": 3503,
"s": 3172,
"text": null
},
{
"code": null,
"e": 3511,
"s": 3503,
"text": "Output:"
},
{
"code": null,
"e": 3535,
"s": 3511,
"text": "Success, You are a GEEK"
},
{
"code": null,
"e": 3634,
"s": 3535,
"text": "Promise ConsumersPromises can be consumed by registering functions using .then and .catch methods."
},
{
"code": null,
"e": 3812,
"s": 3634,
"text": "1. then() then() is invoked when a promise is either resolved or rejected. It may also be defined as a career which takes data from promise and further executes it successfully."
},
{
"code": null,
"e": 3874,
"s": 3812,
"text": "Parameters: then() method takes two functions as parameters. "
},
{
"code": null,
"e": 4106,
"s": 3874,
"text": "First function is executed if promise is resolved and a result is received.Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method"
},
{
"code": null,
"e": 4182,
"s": 4106,
"text": "First function is executed if promise is resolved and a result is received."
},
{
"code": null,
"e": 4339,
"s": 4182,
"text": "Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method"
},
{
"code": null,
"e": 4347,
"s": 4339,
"text": "Syntax:"
},
{
"code": null,
"e": 4450,
"s": 4347,
"text": ".then(function(result){\n //handle success\n }, function(error){\n //handle error\n })"
},
{
"code": null,
"e": 4476,
"s": 4450,
"text": "Example: Promise Resolved"
},
{
"code": null,
"e": 4487,
"s": 4476,
"text": "Javascript"
},
{
"code": "var promise = new Promise(function(resolve, reject) { resolve('Geeks For Geeks');}) promise .then(function(successMessage) { //success handler function is invoked console.log(successMessage); }, function(errorMessage) { console.log(errorMessage); })",
"e": 4771,
"s": 4487,
"text": null
},
{
"code": null,
"e": 4779,
"s": 4771,
"text": "Output:"
},
{
"code": null,
"e": 4795,
"s": 4779,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 4822,
"s": 4795,
"text": "Examples: Promise Rejected"
},
{
"code": null,
"e": 4833,
"s": 4822,
"text": "Javascript"
},
{
"code": "var promise = new Promise(function(resolve, reject) { reject('Promise Rejected')}) promise .then(function(successMessage) { console.log(successMessage); }, function(errorMessage) { //error handler function is invoked console.log(errorMessage); })",
"e": 5114,
"s": 4833,
"text": null
},
{
"code": null,
"e": 5122,
"s": 5114,
"text": "Output:"
},
{
"code": null,
"e": 5139,
"s": 5122,
"text": "Promise Rejected"
},
{
"code": null,
"e": 5151,
"s": 5139,
"text": "2. catch() "
},
{
"code": null,
"e": 5336,
"s": 5151,
"text": "catch() is invoked when a promise is either rejected or some error has occurred in execution. It is used as an Error Handler whenever at any step there is a chance of getting an error."
},
{
"code": null,
"e": 5397,
"s": 5336,
"text": "Parameters: catch() method takes one function as parameter. "
},
{
"code": null,
"e": 5572,
"s": 5397,
"text": "Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )"
},
{
"code": null,
"e": 5747,
"s": 5572,
"text": "Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )"
},
{
"code": null,
"e": 5755,
"s": 5747,
"text": "Syntax:"
},
{
"code": null,
"e": 5809,
"s": 5755,
"text": ".catch(function(error){\n //handle error\n })"
},
{
"code": null,
"e": 5836,
"s": 5809,
"text": "Examples: Promise Rejected"
},
{
"code": null,
"e": 5847,
"s": 5836,
"text": "Javascript"
},
{
"code": "var promise = new Promise(function(resolve, reject) { reject('Promise Rejected')}) promise .then(function(successMessage) { console.log(successMessage); }) .catch(function(errorMessage) { //error handler function is invoked console.log(errorMessage); });",
"e": 6139,
"s": 5847,
"text": null
},
{
"code": null,
"e": 6147,
"s": 6139,
"text": "Output:"
},
{
"code": null,
"e": 6164,
"s": 6147,
"text": "Promise Rejected"
},
{
"code": null,
"e": 6191,
"s": 6164,
"text": "Examples: Promise Rejected"
},
{
"code": null,
"e": 6202,
"s": 6191,
"text": "Javascript"
},
{
"code": "var promise = new Promise(function(resolve, reject) { throw new Error('Some error has occurred')}) promise .then(function(successMessage) { console.log(successMessage); }) .catch(function(errorMessage) { //error handler function is invoked console.log(errorMessage); });",
"e": 6510,
"s": 6202,
"text": null
},
{
"code": null,
"e": 6518,
"s": 6510,
"text": "Output:"
},
{
"code": null,
"e": 6549,
"s": 6518,
"text": "Error: Some error has occurred"
},
{
"code": null,
"e": 6563,
"s": 6549,
"text": "Applications "
},
{
"code": null,
"e": 6673,
"s": 6563,
"text": "Promises are used for asynchronous handling of events.Promises are used to handle asynchronous http requests."
},
{
"code": null,
"e": 6728,
"s": 6673,
"text": "Promises are used for asynchronous handling of events."
},
{
"code": null,
"e": 6784,
"s": 6728,
"text": "Promises are used to handle asynchronous http requests."
},
{
"code": null,
"e": 6884,
"s": 6784,
"text": "Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"
},
{
"code": null,
"e": 7103,
"s": 6884,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 7118,
"s": 7103,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 7129,
"s": 7118,
"text": "amansingla"
},
{
"code": null,
"e": 7147,
"s": 7129,
"text": "javascript-basics"
},
{
"code": null,
"e": 7158,
"s": 7147,
"text": "JavaScript"
},
{
"code": null,
"e": 7163,
"s": 7158,
"text": "JS++"
},
{
"code": null,
"e": 7182,
"s": 7163,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7199,
"s": 7182,
"text": "Web Technologies"
}
] |
How to start nmap and run a simple scan ?
|
19 Jul, 2019
Nmap is a free and open-source utility which is used to scan networks and security auditing. Nmap can discover hosts and services on a computer network by sending packets and analyzing the responses. The utility is available on almost every os, it is available for windows, linux and mac.
Download Nmap –To download Nmap you can simply head towards the official website by clicking here. In case if kali Linux and parrot os, it is already available in there so you will not need to download the utility.
Please note that scanning websites from Nmap is not legal, in some cases if you are trying to too much in deep then you will need written permissions from the owner of the website and the IP holder.
In Windows hosts you can simply install nmap and run it from the desktop icon using administrator privileges . In linux hosts there are 2 ways of doing it, in case of kali linux and parrot os you can find the icon and click to start and later give it root privileges by entering your password .The other way is you can simply run
nmap --help
You can use it as a manual for using commands, just scroll down and head towards examples.
As already mentioned, scanning networks and websites using nmap can be illegal, you may need written permissions to so.So, to do scans be legal you can use scanme.org, they offer you to perform scans on their website without any issues, but please read their conditions so that you do not harm their website.Now lets see a simple example to do a scan.To do so simply use nslookup command following the website url or address. If you do not know the IP address of the website and using the command.
nslookup scanme.nmap.org
will give you its address. Now when you get the address you can use the same for scanning the network by
nslookup "address"
the address should be written as IP address which you found on the previous scan and without quotes.This is how you can do a simple network scan. Now you can also save your scans in a text file for simplicity by using the command
nslookup 45.33.32.156 >> result.txt
Please note that nmap is a very noisy scanning utility and you need to be anonymous and legal in some cases to do so. Please ensure that you use it for legal and educational purposes.
Cyber-security
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 341,
"s": 52,
"text": "Nmap is a free and open-source utility which is used to scan networks and security auditing. Nmap can discover hosts and services on a computer network by sending packets and analyzing the responses. The utility is available on almost every os, it is available for windows, linux and mac."
},
{
"code": null,
"e": 556,
"s": 341,
"text": "Download Nmap –To download Nmap you can simply head towards the official website by clicking here. In case if kali Linux and parrot os, it is already available in there so you will not need to download the utility."
},
{
"code": null,
"e": 755,
"s": 556,
"text": "Please note that scanning websites from Nmap is not legal, in some cases if you are trying to too much in deep then you will need written permissions from the owner of the website and the IP holder."
},
{
"code": null,
"e": 1085,
"s": 755,
"text": "In Windows hosts you can simply install nmap and run it from the desktop icon using administrator privileges . In linux hosts there are 2 ways of doing it, in case of kali linux and parrot os you can find the icon and click to start and later give it root privileges by entering your password .The other way is you can simply run"
},
{
"code": null,
"e": 1097,
"s": 1085,
"text": "nmap --help"
},
{
"code": null,
"e": 1188,
"s": 1097,
"text": "You can use it as a manual for using commands, just scroll down and head towards examples."
},
{
"code": null,
"e": 1686,
"s": 1188,
"text": "As already mentioned, scanning networks and websites using nmap can be illegal, you may need written permissions to so.So, to do scans be legal you can use scanme.org, they offer you to perform scans on their website without any issues, but please read their conditions so that you do not harm their website.Now lets see a simple example to do a scan.To do so simply use nslookup command following the website url or address. If you do not know the IP address of the website and using the command."
},
{
"code": null,
"e": 1711,
"s": 1686,
"text": "nslookup scanme.nmap.org"
},
{
"code": null,
"e": 1816,
"s": 1711,
"text": "will give you its address. Now when you get the address you can use the same for scanning the network by"
},
{
"code": null,
"e": 1835,
"s": 1816,
"text": "nslookup \"address\""
},
{
"code": null,
"e": 2065,
"s": 1835,
"text": "the address should be written as IP address which you found on the previous scan and without quotes.This is how you can do a simple network scan. Now you can also save your scans in a text file for simplicity by using the command"
},
{
"code": null,
"e": 2101,
"s": 2065,
"text": "nslookup 45.33.32.156 >> result.txt"
},
{
"code": null,
"e": 2285,
"s": 2101,
"text": "Please note that nmap is a very noisy scanning utility and you need to be anonymous and legal in some cases to do so. Please ensure that you use it for legal and educational purposes."
},
{
"code": null,
"e": 2300,
"s": 2285,
"text": "Cyber-security"
},
{
"code": null,
"e": 2311,
"s": 2300,
"text": "Linux-Unix"
}
] |
Overloading Varargs Methods in Java
|
A method with variable length arguments(Varargs) can have zero or multiple arguments. Also, Varargs methods can be overloaded if required.
A program that demonstrates this is given as follows:
Live Demo
public class Demo {
public static void Varargs(int... args) {
System.out.println("\nNumber of int arguments are: " + args.length);
System.out.println("The int argument values are: ");
for (int i : args)
System.out.println(i);
}
public static void Varargs(char... args) {
System.out.println("\nNumber of char arguments are: " + args.length);
System.out.println("The char argument values are: ");
for (char i : args)
System.out.println(i);
}
public static void Varargs(double... args) {
System.out.println("\nNumber of double arguments are: " + args.length);
System.out.println("The double argument values are: ");
for (double i : args)
System.out.println(i);
}
public static void main(String args[]) {
Varargs(4, 9, 1, 6, 3);
Varargs('A', 'B', 'C');
Varargs(5.9, 2.5);
}
}
Number of int arguments are: 5
The int argument values are:
4
9
1
6
3
Number of char arguments are: 3
The char argument values are:
A
B
C
Number of double arguments are: 2
The double argument values are:
5.9
2.5
|
[
{
"code": null,
"e": 1201,
"s": 1062,
"text": "A method with variable length arguments(Varargs) can have zero or multiple arguments. Also, Varargs methods can be overloaded if required."
},
{
"code": null,
"e": 1255,
"s": 1201,
"text": "A program that demonstrates this is given as follows:"
},
{
"code": null,
"e": 1266,
"s": 1255,
"text": " Live Demo"
},
{
"code": null,
"e": 2152,
"s": 1266,
"text": "public class Demo {\n public static void Varargs(int... args) {\n System.out.println(\"\\nNumber of int arguments are: \" + args.length);\n System.out.println(\"The int argument values are: \");\n for (int i : args)\n System.out.println(i);\n }\n public static void Varargs(char... args) {\n System.out.println(\"\\nNumber of char arguments are: \" + args.length);\n System.out.println(\"The char argument values are: \");\n for (char i : args)\n System.out.println(i);\n }\n public static void Varargs(double... args) {\n System.out.println(\"\\nNumber of double arguments are: \" + args.length);\n System.out.println(\"The double argument values are: \");\n for (double i : args)\n System.out.println(i);\n }\n public static void main(String args[]) {\n Varargs(4, 9, 1, 6, 3);\n Varargs('A', 'B', 'C');\n Varargs(5.9, 2.5);\n }\n}"
},
{
"code": null,
"e": 2364,
"s": 2152,
"text": "Number of int arguments are: 5\nThe int argument values are:\n4\n9\n1\n6\n3\nNumber of char arguments are: 3\nThe char argument values are:\nA\nB\nC\nNumber of double arguments are: 2\nThe double argument values are:\n5.9\n2.5"
}
] |
Introduction: Reinforcement Learning with OpenAI Gym | by ASHISH RANA | Towards Data Science
|
Understand the basic goto concepts to get a quick start on reinforcement learning and learn to test your algorithms with OpenAI gym to achieve research centric reproducible results.
This article first walks you through the basics of reinforcement learning, its current advancements and a somewhat detailed practical use-case of autonomous driving. After that we get dirty with code and learn about OpenAI Gym, a tool often used by researchers for standardization and benchmarking results. When the coding section comes please open your terminal and get ready for some hands on.A time saver tip: You can directly skip to ‘Conceptual Understanding’ section if you want to skip basics and only want try out Open AI gym directly.
Mainly three categories of learning are supervised, unsupervised and reinforcement. Let’s see the basic differences between them. In supervised learning we try to predict a target value or class where the input data for training is already having labels assigned to it. Whereas unsupervised learning uses unlabelled data for looking at patterns to make clusters, or doing PCA/anomaly detection. RL algorithms are like optimization procedures to find best methods to earn maximum reward i.e. give winning strategy to attain objective.
Within Reinforcement Learning, there are multiple paradigms that attain this winning strategy in their own way. In complex situations calculating exact winning strategy or exact reward-value function becomes really hard, especially where our agents start learning from interactions rather than prior-gained experience. For example, a dog finding its favorite toy hidden in a new house. The dog will search the house and get an approximate idea about house schematics based on its interactions. But, still there might be a very good chance that the dog will find it incredibly hard to find the hidden toy again if it’s located in a new unexplored location.
This interaction based learning is also popularly known as model-free learning where the agent doesn’t have exact knowledge of the environment i.e. agent doesn’t store the knowledge of state-action probability transition function. And it tries to approximate either winning strategy (i.e. policy) or reward-value gains (i.e. value function). The same dog searching for his hidden toy in his owner’s house would have previous experience i.e. prior environment knowledge and would be comfortable searching for the toy in any location within the house. And this type of learning for the hidden toy finding is known as model-based learning in RL.
By very definition in reinforcement learning an agent takes action in the given environment either in continuous or discrete manner to maximize some notion of reward that is coded into it. Sounds too profound, well it is with a research base dating way back to classical behaviorist psychology, game theory, optimization algorithms etc. But, good for us, a lot of ‘setting the stage’ work has already been done for us to kick-start us directly into the problem formulation world and discover new things.
Essentially, the most important of them all is that reinforcement learning scenarios for an agent in a completely known/observable deterministic environment can be formulated as a dynamic programming problem. Fundamentally meaning that the agent has to perform a series of steps in a systematic manner so that it can learn the ideal solution and it will receive guidance from reward values. The equation that expresses such a scenario in mathematical terms is known as the Bellman equation which we will see in action in some time.
Let’s first qualitatively define the concept of agent and environment formally before proceeding further for understanding technical details about RL. Environment is the universe of agents which changes the state of agent with given action performed on it. Agent is the system that perceives the environment via sensors and performs actions with actuators. In the below situations Homer(Left) and Bart(right) are our agents and World is their environment. They performs actions within it and improve their state of being by getting happiness or contentment as reward.
Starting with the most popular game series since IBM’s Deep Blue v/s Kasparov which created huge hype for AI. And the inhuman-like awareness for the deep reinforcement learning agent in AlpaGo v/s Lee Sedol in Go competition series. Mastering a game with more board configuration than atoms in the Universe against a den 9 master shows the power such smart systems hold. Also recent RL research breakthroughs and wins against World Pros with Dota bots from OpenAI is also commendable. With agents getting trained to handle such complex and dynamic environments, mastering these games are an example of testing the limits of AI agents for handling very complex hierarchical-like situations. Application wise, already complex applications like driverless cars, smart drones are operating in the real world.
Let’s understand some more fundamentals of reinforcement learning and then start with OpenAI gym to make our own agent. After that I’ll recommend you to move towards Deep RL and tackle more complex situations. Scope of all the RL applications is beyond imagination and can be applied to so many domains like time-series predictions, healthcare, supply-chain automation and so on. But, here we’ll discuss one of the most popular application use-case of self driving autonomous vehicles and navigation tasks in general.
The unique ability to run algorithms on the same state over and over which helps it to learn best action for that particular state to progress to the ideal next state, which essentially is equivalent to breaking the construct of time for humans to gain infinite learning experience at almost no time.
With RL as a framework agent acts with certain actions which transform the state of the agent, each action is associated with reward value. It also uses a policy to determine its next action, which is constituted of a sequence of steps that maps states-action pairs to calculated reward values. A policy can be qualitatively defined as an agent’s way of behaving at a given time. Now, policies can be deterministic and stochastic, finding an optimal policy is the key for solving a given task.
Also, Different actions in different states will have different associated reward values. Like the ‘Fire’ command in a game of Pocket Tanks can’t always have the same reward value associated with it, as sometimes it’s better to retain a position which is strategically good. To handle this complex dynamic problem with such huge combinations in a planned manner we need a Q-value( or action-value ) table which stores a map of state-action pairs to rewards.
Now, defining the environment in RL’s context as a functional component, it simply takes action at a given state as input and returns a new state and reward value associated with action-state pair.
Interestingly enough though, neural nets enter the picture with their ability to learn state-action pairs rewards with ease when the environment becomes highly complex to handle with computationally restrictive Iterative algorithms and this is known as Deep RL. Like playing those earlier games like Mario, Atari, PAC-MAN etc.
Here, we will limit to simple Q-Learning only i.e. w/o neural networks, where Q function maps state-action pairs to a maximum with combination of immediate reward plus future rewards i.e. for new states learned value is current reward plus future estimate of rewards. Quantifying it into an equation with different parameters like learning rate and discount factor to guide agent’s choice of action. We arrive at the following equation: Structurally, it holds much similarity to Bellman’s equation.
A 2016 Nature survey indicated that more than 70 percent of researchers have tried and failed to reproduce another scientist’s experiments, and more than half have failed to reproduce their own experiments.
OpenAI is created for removing this problem of lack of standardization in papers along with an aim to create better benchmarks by giving versatile numbers of environments with great ease of setting up. Aim of this tool is to increase reproducibility in the field of AI and provide tools with which everyone can learn about the basics of AI.
Open your terminal and get ready for some CTRL+C and CTRL+V work !! But, of course I’ll recommend against it.
What is OpenAI gym ? This python library gives us a huge number of test environments to work on our RL agent’s algorithms with shared interfaces for writing general algorithms and testing them. Let’s get started, just type pip install gym on the terminal for easy install, you’ll get some classic environment to start working on your agent. Copy the code below and run it, your environment will get loaded. You can check out other available environments like Algorithmic, Atari, Box2D and Robotics here and use the second listed code snippet component below for listing all the available environments.
# 1. It renders instances for 500 timesteps, performing random actions.import gymenv = gym.make('Acrobot-v1')env.reset()for _ in range(500): env.render() env.step(env.action_space.sample())# 2. To check all env available, uninstalled ones are also shown.from gym import envs print(envs.registry.all())
When object interacts with environment with an action then step() function returns observation which generally represents environments next state, reward a float of reward in previous action, done when it’s time to reset the environment or goal achieved and info a dict for debugging, it can be used for learning if it contains raw probabilities of environment’s last state. See how it works from the code snippet below. Also, observe how observation of type Space is different for different environments.
import gymenv = gym.make('MountainCarContinuous-v0') # try for different environmentsobservation = env.reset()for t in range(100): env.render() print observation action = env.action_space.sample() observation, reward, done, info = env.step(action) print observation, reward, done, info if done: print("Finished after {} timesteps".format(t+1)) break[Output For Mountain Car Cont Env:] [-0.56252328 0.00184034][-0.56081509 0.00170819] -0.00796802138459 False {}[Output For CartPole Env:][ 0.1895078 0.55386028 -0.19064739 -1.03988221][ 0.20058501 0.36171167 -0.21144503 -0.81259279] 1.0 True {}Finished after 52 timesteps
What is action_space in above code? action-space & observation-space describes what is the valid format of action & state parameters for that particular env to work on with. Just take a look at values returned.
import gymenv = gym.make('CartPole-v0')print(env.action_space) #[Output: ] Discrete(2)print(env.observation_space) # [Output: ] Box(4,)env = gym.make('MountainCarContinuous-v0')print(env.action_space) #[Output: ] Box(1,)print(env.observation_space) #[Output: ] Box(2,)
Discrete is non-negative possible values, above 0 or 1 are equivalent to left and right movement for CartPole balancing. Box represent n-dim array. These standard interfaces can help in writing general codes for different environments. As we can simply check the bounds env.observation_space.high/[low] and code them into our general algorithm.
Here, we are using Python3.x for the highlighted code sample of Q-Learning algorithm below.
sudo pip install 'gym[all]'
Let’s start building our Q-table algorithm, which will try to solve the FrozenLake navigation environment. In this environment the aim is to reach the goal, on a frozen lake that might have some holes in it. Here is how the surface is the depicted by this Toy-Text environment.
SFFF (S: starting point, safe)FHFH (F: frozen surface, safe)FFFH (H: hole, fall to your doom)HFFG (G: goal, where the frisbee is located)
Q-table contains state-action pairs mapping to reward. So, we will construct an array which maps different states and actions to reward values during execution of algorithm. Its dimension will clearly |states|x|actions|. Let’s write it in code for the Q-learning Algorithm.
import gymimport numpy as np # 1. Load Environment and Q-table structureenv = gym.make('FrozenLake8x8-v0')Q = np.zeros([env.observation_space.n,env.action_space.n])# env.observation.n, env.action_space.n gives number of states and action in env loaded# 2. Parameters of Q-learningeta = .628gma = .9epis = 5000rev_list = [] # rewards per episode calculate# 3. Q-learning Algorithmfor i in range(epis): # Reset environment s = env.reset() rAll = 0 d = False j = 0 #The Q-Table learning algorithm while j < 99: env.render() j+=1 # Choose action from Q table a = np.argmax(Q[s,:] + np.random.randn(1,env.action_space.n)*(1./(i+1))) #Get new state & reward from environment s1,r,d,_ = env.step(a) #Update Q-Table with new knowledge Q[s,a] = Q[s,a] + eta*(r + gma*np.max(Q[s1,:]) - Q[s,a]) rAll += r s = s1 if d == True: break rev_list.append(rAll) env.render()print("Reward Sum on all episodes " + str(sum(rev_list)/epis))print("Final Values Q-Table")print(Q)
If you are interested in working with other environments, you can opt to work along the lines of a cleaner code snippet highlighted below.
# Reset environments = env.reset()d = False# The Q-Table learning algorithmwhile d != True: env.render() # Choose action from Q table a = np.argmax(Q[s,:] + np.random.randn(1,env.action_space.n)*(1./(i+1))) #Get new state & reward from environment s1,r,d,_ = env.step(a) #Update Q-Table with new knowledge Q[s,a] = Q[s,a] + eta*(r + gma*np.max(Q[s1,:]) - Q[s,a]) s = s1# Code will stop at d == True, and render one state before it
But do remember even with a common interface the code complexity will be different for different environments. In the above environment we only had a simple 64 state environment with few actions only to handle. We were able to store them in a two dimensional array for reward mapping very easily. Now, Let’s consider more complicated environment cases like Atari envs and look at the approach that is needed.
env = gym.make("Breakout-v0")env.action_space.nOut[...]: 4env.env.get_action_meanings()Out[...]: ['NOOP', 'FIRE', 'RIGHT', 'LEFT']env.observation_spaceOut[...]: Box(210, 160, 3)
observation_space is needed to be represented by a 210x160x3 tensor which makes our Q-table even more complicated. Also, each action is repeatedly performed for a duration of k frames, where k is uniformly sampled from {2,3,4}. With 33,600 pixels in RGB channels with values ranging from 0–255 the environment clearly has become overly complicated. A simple Q-learning approach can’t be used here. Deep learning with its CNN architecture is the solution for this problem and a topic you should focus on for follow up of this introductory article.
Now, with the above tutorial you have the basic knowledge about the gym and all you need to get started with it. Gym is also TensorFlow & PyTorch compatible but I haven’t used them here to keep the tutorial simple. After trying out the gym package you must get started with stable-baselines3 for learning the good implementations of RL algorithms to compare your implementations. To see all the OpenAI tools check out their github page. RL is an expanding field with applications in a huge number of domains and it will play an important role in future AI breakthroughs. Hope you continue with your RL journey & thanks for reading!!
Yes, sharing with you shameful yet glorious starter project plugs, in case you are just getting started with reinforcement learning. The additional advantage of picking up these practical projects is getting complete mentor support & wonderful free reinforcement learning resources like books, videos and so on. Interestingly enough though, there are two liveProjects that I’ll recommend to you pursuing further:
In case you want a hands-on project for getting started with a complete spectrum of reinforcement learning concepts at beginner/intermediate level, you can opt for the below embedded liveProject. Here, in this liveProject I have discussed research principles required to achieve best performing driving autonomous vehicles.
www.manning.com
Additionally, the first milestone is free practice for this liveProject. Even if you don’t move forward with the liveProject, I promise that you’ll learn a great deal about the autonomous driving RL task just by practically following along the first milestone. Cheers!
Important Note: If you are here before July-26-2021 and are interested in carrying forward with the first liveProject. Please, use the code lprana and you’ll get 45% off on the project. Kudos!!
Second, If you specifically want to orient your focus & effort around the Deep Q-Learning concept of RL. Please, feel free to checkout the below liveProject as well. And again the first milestone is free to practice!
www.manning.com
Chao for now! In case you select the first project, be seeing you there...
|
[
{
"code": null,
"e": 354,
"s": 172,
"text": "Understand the basic goto concepts to get a quick start on reinforcement learning and learn to test your algorithms with OpenAI gym to achieve research centric reproducible results."
},
{
"code": null,
"e": 898,
"s": 354,
"text": "This article first walks you through the basics of reinforcement learning, its current advancements and a somewhat detailed practical use-case of autonomous driving. After that we get dirty with code and learn about OpenAI Gym, a tool often used by researchers for standardization and benchmarking results. When the coding section comes please open your terminal and get ready for some hands on.A time saver tip: You can directly skip to ‘Conceptual Understanding’ section if you want to skip basics and only want try out Open AI gym directly."
},
{
"code": null,
"e": 1432,
"s": 898,
"text": "Mainly three categories of learning are supervised, unsupervised and reinforcement. Let’s see the basic differences between them. In supervised learning we try to predict a target value or class where the input data for training is already having labels assigned to it. Whereas unsupervised learning uses unlabelled data for looking at patterns to make clusters, or doing PCA/anomaly detection. RL algorithms are like optimization procedures to find best methods to earn maximum reward i.e. give winning strategy to attain objective."
},
{
"code": null,
"e": 2088,
"s": 1432,
"text": "Within Reinforcement Learning, there are multiple paradigms that attain this winning strategy in their own way. In complex situations calculating exact winning strategy or exact reward-value function becomes really hard, especially where our agents start learning from interactions rather than prior-gained experience. For example, a dog finding its favorite toy hidden in a new house. The dog will search the house and get an approximate idea about house schematics based on its interactions. But, still there might be a very good chance that the dog will find it incredibly hard to find the hidden toy again if it’s located in a new unexplored location."
},
{
"code": null,
"e": 2731,
"s": 2088,
"text": "This interaction based learning is also popularly known as model-free learning where the agent doesn’t have exact knowledge of the environment i.e. agent doesn’t store the knowledge of state-action probability transition function. And it tries to approximate either winning strategy (i.e. policy) or reward-value gains (i.e. value function). The same dog searching for his hidden toy in his owner’s house would have previous experience i.e. prior environment knowledge and would be comfortable searching for the toy in any location within the house. And this type of learning for the hidden toy finding is known as model-based learning in RL."
},
{
"code": null,
"e": 3235,
"s": 2731,
"text": "By very definition in reinforcement learning an agent takes action in the given environment either in continuous or discrete manner to maximize some notion of reward that is coded into it. Sounds too profound, well it is with a research base dating way back to classical behaviorist psychology, game theory, optimization algorithms etc. But, good for us, a lot of ‘setting the stage’ work has already been done for us to kick-start us directly into the problem formulation world and discover new things."
},
{
"code": null,
"e": 3767,
"s": 3235,
"text": "Essentially, the most important of them all is that reinforcement learning scenarios for an agent in a completely known/observable deterministic environment can be formulated as a dynamic programming problem. Fundamentally meaning that the agent has to perform a series of steps in a systematic manner so that it can learn the ideal solution and it will receive guidance from reward values. The equation that expresses such a scenario in mathematical terms is known as the Bellman equation which we will see in action in some time."
},
{
"code": null,
"e": 4335,
"s": 3767,
"text": "Let’s first qualitatively define the concept of agent and environment formally before proceeding further for understanding technical details about RL. Environment is the universe of agents which changes the state of agent with given action performed on it. Agent is the system that perceives the environment via sensors and performs actions with actuators. In the below situations Homer(Left) and Bart(right) are our agents and World is their environment. They performs actions within it and improve their state of being by getting happiness or contentment as reward."
},
{
"code": null,
"e": 5140,
"s": 4335,
"text": "Starting with the most popular game series since IBM’s Deep Blue v/s Kasparov which created huge hype for AI. And the inhuman-like awareness for the deep reinforcement learning agent in AlpaGo v/s Lee Sedol in Go competition series. Mastering a game with more board configuration than atoms in the Universe against a den 9 master shows the power such smart systems hold. Also recent RL research breakthroughs and wins against World Pros with Dota bots from OpenAI is also commendable. With agents getting trained to handle such complex and dynamic environments, mastering these games are an example of testing the limits of AI agents for handling very complex hierarchical-like situations. Application wise, already complex applications like driverless cars, smart drones are operating in the real world."
},
{
"code": null,
"e": 5658,
"s": 5140,
"text": "Let’s understand some more fundamentals of reinforcement learning and then start with OpenAI gym to make our own agent. After that I’ll recommend you to move towards Deep RL and tackle more complex situations. Scope of all the RL applications is beyond imagination and can be applied to so many domains like time-series predictions, healthcare, supply-chain automation and so on. But, here we’ll discuss one of the most popular application use-case of self driving autonomous vehicles and navigation tasks in general."
},
{
"code": null,
"e": 5959,
"s": 5658,
"text": "The unique ability to run algorithms on the same state over and over which helps it to learn best action for that particular state to progress to the ideal next state, which essentially is equivalent to breaking the construct of time for humans to gain infinite learning experience at almost no time."
},
{
"code": null,
"e": 6453,
"s": 5959,
"text": "With RL as a framework agent acts with certain actions which transform the state of the agent, each action is associated with reward value. It also uses a policy to determine its next action, which is constituted of a sequence of steps that maps states-action pairs to calculated reward values. A policy can be qualitatively defined as an agent’s way of behaving at a given time. Now, policies can be deterministic and stochastic, finding an optimal policy is the key for solving a given task."
},
{
"code": null,
"e": 6911,
"s": 6453,
"text": "Also, Different actions in different states will have different associated reward values. Like the ‘Fire’ command in a game of Pocket Tanks can’t always have the same reward value associated with it, as sometimes it’s better to retain a position which is strategically good. To handle this complex dynamic problem with such huge combinations in a planned manner we need a Q-value( or action-value ) table which stores a map of state-action pairs to rewards."
},
{
"code": null,
"e": 7109,
"s": 6911,
"text": "Now, defining the environment in RL’s context as a functional component, it simply takes action at a given state as input and returns a new state and reward value associated with action-state pair."
},
{
"code": null,
"e": 7436,
"s": 7109,
"text": "Interestingly enough though, neural nets enter the picture with their ability to learn state-action pairs rewards with ease when the environment becomes highly complex to handle with computationally restrictive Iterative algorithms and this is known as Deep RL. Like playing those earlier games like Mario, Atari, PAC-MAN etc."
},
{
"code": null,
"e": 7935,
"s": 7436,
"text": "Here, we will limit to simple Q-Learning only i.e. w/o neural networks, where Q function maps state-action pairs to a maximum with combination of immediate reward plus future rewards i.e. for new states learned value is current reward plus future estimate of rewards. Quantifying it into an equation with different parameters like learning rate and discount factor to guide agent’s choice of action. We arrive at the following equation: Structurally, it holds much similarity to Bellman’s equation."
},
{
"code": null,
"e": 8142,
"s": 7935,
"text": "A 2016 Nature survey indicated that more than 70 percent of researchers have tried and failed to reproduce another scientist’s experiments, and more than half have failed to reproduce their own experiments."
},
{
"code": null,
"e": 8483,
"s": 8142,
"text": "OpenAI is created for removing this problem of lack of standardization in papers along with an aim to create better benchmarks by giving versatile numbers of environments with great ease of setting up. Aim of this tool is to increase reproducibility in the field of AI and provide tools with which everyone can learn about the basics of AI."
},
{
"code": null,
"e": 8593,
"s": 8483,
"text": "Open your terminal and get ready for some CTRL+C and CTRL+V work !! But, of course I’ll recommend against it."
},
{
"code": null,
"e": 9195,
"s": 8593,
"text": "What is OpenAI gym ? This python library gives us a huge number of test environments to work on our RL agent’s algorithms with shared interfaces for writing general algorithms and testing them. Let’s get started, just type pip install gym on the terminal for easy install, you’ll get some classic environment to start working on your agent. Copy the code below and run it, your environment will get loaded. You can check out other available environments like Algorithmic, Atari, Box2D and Robotics here and use the second listed code snippet component below for listing all the available environments."
},
{
"code": null,
"e": 9503,
"s": 9195,
"text": "# 1. It renders instances for 500 timesteps, performing random actions.import gymenv = gym.make('Acrobot-v1')env.reset()for _ in range(500): env.render() env.step(env.action_space.sample())# 2. To check all env available, uninstalled ones are also shown.from gym import envs print(envs.registry.all())"
},
{
"code": null,
"e": 10009,
"s": 9503,
"text": "When object interacts with environment with an action then step() function returns observation which generally represents environments next state, reward a float of reward in previous action, done when it’s time to reset the environment or goal achieved and info a dict for debugging, it can be used for learning if it contains raw probabilities of environment’s last state. See how it works from the code snippet below. Also, observe how observation of type Space is different for different environments."
},
{
"code": null,
"e": 10699,
"s": 10009,
"text": "import gymenv = gym.make('MountainCarContinuous-v0') # try for different environmentsobservation = env.reset()for t in range(100): env.render() print observation action = env.action_space.sample() observation, reward, done, info = env.step(action) print observation, reward, done, info if done: print(\"Finished after {} timesteps\".format(t+1)) break[Output For Mountain Car Cont Env:] [-0.56252328 0.00184034][-0.56081509 0.00170819] -0.00796802138459 False {}[Output For CartPole Env:][ 0.1895078 0.55386028 -0.19064739 -1.03988221][ 0.20058501 0.36171167 -0.21144503 -0.81259279] 1.0 True {}Finished after 52 timesteps"
},
{
"code": null,
"e": 10910,
"s": 10699,
"text": "What is action_space in above code? action-space & observation-space describes what is the valid format of action & state parameters for that particular env to work on with. Just take a look at values returned."
},
{
"code": null,
"e": 11179,
"s": 10910,
"text": "import gymenv = gym.make('CartPole-v0')print(env.action_space) #[Output: ] Discrete(2)print(env.observation_space) # [Output: ] Box(4,)env = gym.make('MountainCarContinuous-v0')print(env.action_space) #[Output: ] Box(1,)print(env.observation_space) #[Output: ] Box(2,)"
},
{
"code": null,
"e": 11524,
"s": 11179,
"text": "Discrete is non-negative possible values, above 0 or 1 are equivalent to left and right movement for CartPole balancing. Box represent n-dim array. These standard interfaces can help in writing general codes for different environments. As we can simply check the bounds env.observation_space.high/[low] and code them into our general algorithm."
},
{
"code": null,
"e": 11616,
"s": 11524,
"text": "Here, we are using Python3.x for the highlighted code sample of Q-Learning algorithm below."
},
{
"code": null,
"e": 11645,
"s": 11616,
"text": "sudo pip install 'gym[all]' "
},
{
"code": null,
"e": 11923,
"s": 11645,
"text": "Let’s start building our Q-table algorithm, which will try to solve the FrozenLake navigation environment. In this environment the aim is to reach the goal, on a frozen lake that might have some holes in it. Here is how the surface is the depicted by this Toy-Text environment."
},
{
"code": null,
"e": 12085,
"s": 11923,
"text": "SFFF (S: starting point, safe)FHFH (F: frozen surface, safe)FFFH (H: hole, fall to your doom)HFFG (G: goal, where the frisbee is located)"
},
{
"code": null,
"e": 12359,
"s": 12085,
"text": "Q-table contains state-action pairs mapping to reward. So, we will construct an array which maps different states and actions to reward values during execution of algorithm. Its dimension will clearly |states|x|actions|. Let’s write it in code for the Q-learning Algorithm."
},
{
"code": null,
"e": 13429,
"s": 12359,
"text": "import gymimport numpy as np # 1. Load Environment and Q-table structureenv = gym.make('FrozenLake8x8-v0')Q = np.zeros([env.observation_space.n,env.action_space.n])# env.observation.n, env.action_space.n gives number of states and action in env loaded# 2. Parameters of Q-learningeta = .628gma = .9epis = 5000rev_list = [] # rewards per episode calculate# 3. Q-learning Algorithmfor i in range(epis): # Reset environment s = env.reset() rAll = 0 d = False j = 0 #The Q-Table learning algorithm while j < 99: env.render() j+=1 # Choose action from Q table a = np.argmax(Q[s,:] + np.random.randn(1,env.action_space.n)*(1./(i+1))) #Get new state & reward from environment s1,r,d,_ = env.step(a) #Update Q-Table with new knowledge Q[s,a] = Q[s,a] + eta*(r + gma*np.max(Q[s1,:]) - Q[s,a]) rAll += r s = s1 if d == True: break rev_list.append(rAll) env.render()print(\"Reward Sum on all episodes \" + str(sum(rev_list)/epis))print(\"Final Values Q-Table\")print(Q)"
},
{
"code": null,
"e": 13568,
"s": 13429,
"text": "If you are interested in working with other environments, you can opt to work along the lines of a cleaner code snippet highlighted below."
},
{
"code": null,
"e": 14023,
"s": 13568,
"text": "# Reset environments = env.reset()d = False# The Q-Table learning algorithmwhile d != True: env.render() # Choose action from Q table a = np.argmax(Q[s,:] + np.random.randn(1,env.action_space.n)*(1./(i+1))) #Get new state & reward from environment s1,r,d,_ = env.step(a) #Update Q-Table with new knowledge Q[s,a] = Q[s,a] + eta*(r + gma*np.max(Q[s1,:]) - Q[s,a]) s = s1# Code will stop at d == True, and render one state before it"
},
{
"code": null,
"e": 14432,
"s": 14023,
"text": "But do remember even with a common interface the code complexity will be different for different environments. In the above environment we only had a simple 64 state environment with few actions only to handle. We were able to store them in a two dimensional array for reward mapping very easily. Now, Let’s consider more complicated environment cases like Atari envs and look at the approach that is needed."
},
{
"code": null,
"e": 14610,
"s": 14432,
"text": "env = gym.make(\"Breakout-v0\")env.action_space.nOut[...]: 4env.env.get_action_meanings()Out[...]: ['NOOP', 'FIRE', 'RIGHT', 'LEFT']env.observation_spaceOut[...]: Box(210, 160, 3)"
},
{
"code": null,
"e": 15157,
"s": 14610,
"text": "observation_space is needed to be represented by a 210x160x3 tensor which makes our Q-table even more complicated. Also, each action is repeatedly performed for a duration of k frames, where k is uniformly sampled from {2,3,4}. With 33,600 pixels in RGB channels with values ranging from 0–255 the environment clearly has become overly complicated. A simple Q-learning approach can’t be used here. Deep learning with its CNN architecture is the solution for this problem and a topic you should focus on for follow up of this introductory article."
},
{
"code": null,
"e": 15790,
"s": 15157,
"text": "Now, with the above tutorial you have the basic knowledge about the gym and all you need to get started with it. Gym is also TensorFlow & PyTorch compatible but I haven’t used them here to keep the tutorial simple. After trying out the gym package you must get started with stable-baselines3 for learning the good implementations of RL algorithms to compare your implementations. To see all the OpenAI tools check out their github page. RL is an expanding field with applications in a huge number of domains and it will play an important role in future AI breakthroughs. Hope you continue with your RL journey & thanks for reading!!"
},
{
"code": null,
"e": 16203,
"s": 15790,
"text": "Yes, sharing with you shameful yet glorious starter project plugs, in case you are just getting started with reinforcement learning. The additional advantage of picking up these practical projects is getting complete mentor support & wonderful free reinforcement learning resources like books, videos and so on. Interestingly enough though, there are two liveProjects that I’ll recommend to you pursuing further:"
},
{
"code": null,
"e": 16527,
"s": 16203,
"text": "In case you want a hands-on project for getting started with a complete spectrum of reinforcement learning concepts at beginner/intermediate level, you can opt for the below embedded liveProject. Here, in this liveProject I have discussed research principles required to achieve best performing driving autonomous vehicles."
},
{
"code": null,
"e": 16543,
"s": 16527,
"text": "www.manning.com"
},
{
"code": null,
"e": 16812,
"s": 16543,
"text": "Additionally, the first milestone is free practice for this liveProject. Even if you don’t move forward with the liveProject, I promise that you’ll learn a great deal about the autonomous driving RL task just by practically following along the first milestone. Cheers!"
},
{
"code": null,
"e": 17006,
"s": 16812,
"text": "Important Note: If you are here before July-26-2021 and are interested in carrying forward with the first liveProject. Please, use the code lprana and you’ll get 45% off on the project. Kudos!!"
},
{
"code": null,
"e": 17223,
"s": 17006,
"text": "Second, If you specifically want to orient your focus & effort around the Deep Q-Learning concept of RL. Please, feel free to checkout the below liveProject as well. And again the first milestone is free to practice!"
},
{
"code": null,
"e": 17239,
"s": 17223,
"text": "www.manning.com"
}
] |
SAP Hybris - Modelling
|
One of the main features in Hybris is the flexibility to add new objects to the global Hybris Commerce Data model. Hybris data modeling helps an organization in maintaining their database and help to manage database connections and queries. Hybris Type system is used to design data modeling in Hybris.
A Hybris type system has the following types supported for data modeling −
Items.xml − This file is used for data modeling in a Hybris Commerce data model.
Items.xml − This file is used for data modeling in a Hybris Commerce data model.
Item types − This is used to create tables.
Item types − This is used to create tables.
Relation types − This is used to create relation between tables.
Relation types − This is used to create relation between tables.
Atomic types − Used to create various Atomic types.
Atomic types − Used to create various Atomic types.
Collection types − Used to create Collections.
Collection types − Used to create Collections.
Map Types − To define maps.
Map Types − To define maps.
Enum types − To define Enums.
Enum types − To define Enums.
Let us now discuss all of these in detail.
These are defined as basic types in Hybris, which include Java number and string objects – java.lang.integer, java.lang.boolean or java.lang.string.
<atomictypes>
<atomictype class = "java.lang.Object" autocreate = "true" generate = "false" />
<atomictype class = "java.lang.Boolean" extends = "java.lang.Object" autocreate = "true" generate = "false" />
<atomictype class = "java.lang.Double" extends = "java.lang.Number" autocreate = "true" generate = "false" />
<atomictype class = "java.lang.String" extends = "java.lang.Object" autocreate = "true" generate = "false" />
</atomictypes>
Item types are used to create new tables or to update existing tables. This is considered as a base for a Hybris type system. All new table structures are configured over this type using different attributes as shown below −
<itemtype code = "Customer" extends = "User"
jaloclass = "de.hybris/platform.jalo.user.Customer" autocreate = "true" generate = "true">
<attributes>
<attribute autocreate = "true" qualifier = "customerID" type = "java.lang.String">
<modifiers read = "true" write = "true" search = "true" optional = "true"/>
<persistence type = "property"/>
</attribute>
</attributes>
</itemtype>
This type is used to create a link between tables. For example – You can link a country and region.
<relation code = "Country2RegionRelation" generate = "true" localized = "false"
autocreate = "true">
<sourceElement type = "Country" qualifier = "country" cardinality = "one">
<modifiers read = "true" write = "true" search = "true" optional = "false" unique = "true"/>
</sourceElement>
<targetElement type = "Region" qualifier = "regions" cardinality = "many">
<modifiers read = "true" write = "true" search = "true" partof = "true"/>
</targetElement>
</relation>
These are used to build enumeration in Java for preparing a particular set of values. For example – Months in a year.
<enumtype code = "CreditCardType" autocreate = "true" generate = "true">
<value code = "amex"/>
<value code = "visa"/>
<value code = "master"/>
<value code = "diners"/>
</enumtype>
These are used to build collection/group of element types – group of products, etc.
<collectiontype code = "ProductCollection" elementtype = "Product" autocreate = "true" generate = "true"/>
<collectiontype code = "LanguageList" elementtype = "Langauage" autocreate = "true" generate = "true"/>
<collectiontype code = "LanguageSet" elementtype = "Langauage" autocreate = "true" generate = "true"/>
Map types are used to store key values pairs in Hybris data modeling. Each key represents its own code.
<maptype code = "localized:java.lang.String" argumenttype = "Language"
returntype = "java.lang.String" autocreate = "true" generate = "false"/>
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2766,
"s": 2463,
"text": "One of the main features in Hybris is the flexibility to add new objects to the global Hybris Commerce Data model. Hybris data modeling helps an organization in maintaining their database and help to manage database connections and queries. Hybris Type system is used to design data modeling in Hybris."
},
{
"code": null,
"e": 2841,
"s": 2766,
"text": "A Hybris type system has the following types supported for data modeling −"
},
{
"code": null,
"e": 2922,
"s": 2841,
"text": "Items.xml − This file is used for data modeling in a Hybris Commerce data model."
},
{
"code": null,
"e": 3003,
"s": 2922,
"text": "Items.xml − This file is used for data modeling in a Hybris Commerce data model."
},
{
"code": null,
"e": 3047,
"s": 3003,
"text": "Item types − This is used to create tables."
},
{
"code": null,
"e": 3091,
"s": 3047,
"text": "Item types − This is used to create tables."
},
{
"code": null,
"e": 3156,
"s": 3091,
"text": "Relation types − This is used to create relation between tables."
},
{
"code": null,
"e": 3221,
"s": 3156,
"text": "Relation types − This is used to create relation between tables."
},
{
"code": null,
"e": 3273,
"s": 3221,
"text": "Atomic types − Used to create various Atomic types."
},
{
"code": null,
"e": 3325,
"s": 3273,
"text": "Atomic types − Used to create various Atomic types."
},
{
"code": null,
"e": 3372,
"s": 3325,
"text": "Collection types − Used to create Collections."
},
{
"code": null,
"e": 3419,
"s": 3372,
"text": "Collection types − Used to create Collections."
},
{
"code": null,
"e": 3447,
"s": 3419,
"text": "Map Types − To define maps."
},
{
"code": null,
"e": 3475,
"s": 3447,
"text": "Map Types − To define maps."
},
{
"code": null,
"e": 3505,
"s": 3475,
"text": "Enum types − To define Enums."
},
{
"code": null,
"e": 3535,
"s": 3505,
"text": "Enum types − To define Enums."
},
{
"code": null,
"e": 3578,
"s": 3535,
"text": "Let us now discuss all of these in detail."
},
{
"code": null,
"e": 3727,
"s": 3578,
"text": "These are defined as basic types in Hybris, which include Java number and string objects – java.lang.integer, java.lang.boolean or java.lang.string."
},
{
"code": null,
"e": 4180,
"s": 3727,
"text": "<atomictypes>\n <atomictype class = \"java.lang.Object\" autocreate = \"true\" generate = \"false\" />\n <atomictype class = \"java.lang.Boolean\" extends = \"java.lang.Object\" autocreate = \"true\" generate = \"false\" />\n <atomictype class = \"java.lang.Double\" extends = \"java.lang.Number\" autocreate = \"true\" generate = \"false\" />\n <atomictype class = \"java.lang.String\" extends = \"java.lang.Object\" autocreate = \"true\" generate = \"false\" />\n</atomictypes>"
},
{
"code": null,
"e": 4405,
"s": 4180,
"text": "Item types are used to create new tables or to update existing tables. This is considered as a base for a Hybris type system. All new table structures are configured over this type using different attributes as shown below −"
},
{
"code": null,
"e": 4828,
"s": 4405,
"text": "<itemtype code = \"Customer\" extends = \"User\" \n jaloclass = \"de.hybris/platform.jalo.user.Customer\" autocreate = \"true\" generate = \"true\">\n <attributes>\n <attribute autocreate = \"true\" qualifier = \"customerID\" type = \"java.lang.String\">\n <modifiers read = \"true\" write = \"true\" search = \"true\" optional = \"true\"/>\n <persistence type = \"property\"/>\n </attribute> \n </attributes>\n</itemtype>"
},
{
"code": null,
"e": 4928,
"s": 4828,
"text": "This type is used to create a link between tables. For example – You can link a country and region."
},
{
"code": null,
"e": 5428,
"s": 4928,
"text": "<relation code = \"Country2RegionRelation\" generate = \"true\" localized = \"false\" \n autocreate = \"true\">\n \n <sourceElement type = \"Country\" qualifier = \"country\" cardinality = \"one\">\n <modifiers read = \"true\" write = \"true\" search = \"true\" optional = \"false\" unique = \"true\"/>\n </sourceElement>\n \n <targetElement type = \"Region\" qualifier = \"regions\" cardinality = \"many\">\n <modifiers read = \"true\" write = \"true\" search = \"true\" partof = \"true\"/>\n </targetElement>\n</relation>"
},
{
"code": null,
"e": 5546,
"s": 5428,
"text": "These are used to build enumeration in Java for preparing a particular set of values. For example – Months in a year."
},
{
"code": null,
"e": 5739,
"s": 5546,
"text": "<enumtype code = \"CreditCardType\" autocreate = \"true\" generate = \"true\">\n <value code = \"amex\"/>\n <value code = \"visa\"/>\n <value code = \"master\"/>\n <value code = \"diners\"/>\n</enumtype>"
},
{
"code": null,
"e": 5823,
"s": 5739,
"text": "These are used to build collection/group of element types – group of products, etc."
},
{
"code": null,
"e": 6137,
"s": 5823,
"text": "<collectiontype code = \"ProductCollection\" elementtype = \"Product\" autocreate = \"true\" generate = \"true\"/>\n<collectiontype code = \"LanguageList\" elementtype = \"Langauage\" autocreate = \"true\" generate = \"true\"/>\n<collectiontype code = \"LanguageSet\" elementtype = \"Langauage\" autocreate = \"true\" generate = \"true\"/>"
},
{
"code": null,
"e": 6241,
"s": 6137,
"text": "Map types are used to store key values pairs in Hybris data modeling. Each key represents its own code."
},
{
"code": null,
"e": 6390,
"s": 6241,
"text": "<maptype code = \"localized:java.lang.String\" argumenttype = \"Language\" \n returntype = \"java.lang.String\" autocreate = \"true\" generate = \"false\"/>\n"
},
{
"code": null,
"e": 6423,
"s": 6390,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6437,
"s": 6423,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 6470,
"s": 6437,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6482,
"s": 6470,
"text": " Neha Gupta"
},
{
"code": null,
"e": 6517,
"s": 6482,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6532,
"s": 6517,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 6565,
"s": 6532,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6580,
"s": 6565,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 6615,
"s": 6580,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6627,
"s": 6615,
"text": " Neha Malik"
},
{
"code": null,
"e": 6662,
"s": 6627,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6674,
"s": 6662,
"text": " Neha Malik"
},
{
"code": null,
"e": 6681,
"s": 6674,
"text": " Print"
},
{
"code": null,
"e": 6692,
"s": 6681,
"text": " Add Notes"
}
] |
How to Keep the Device Screen On in Android? - GeeksforGeeks
|
14 Sep, 2020
In Android it’s seen that screen timeout will be set for 30 seconds or it is set by the user manually in system settings, to avoid the battery drain. But there are cases where applications like stopwatch, document reader applications, games, etc, need the screen to be always awake. In this article its been demonstrated, how to keep the device screen awake.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Change the color combination of the base theme of the application
To change the base application theme colors Goto app -> res -> values -> colors.xml, and invoke the following color combination.
XML
<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0f9d58</color> <color name="colorPrimaryDark">#006d2d</color> <color name="colorAccent">#55cf86</color></resources>
Refer the following image if one has not got the colors.xml file:
Step 3: Working with the activity_main.xml file
In the activity_main.xml file add TextViews to make an app like the document reading application.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--This layout contains some simple text views--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="64dp" android:fontFamily="sans-serif" android:gravity="center" android:text="GeeksforGeeks" android:textColor="@color/colorPrimary" android:textSize="32sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:fontFamily="sans-serif" android:gravity="center" android:text="A Computer Science portal for geeks" android:textColor="@color/colorPrimary" android:textSize="16sp" /> <View android:layout_width="300dp" android:layout_height="1dp" android:layout_gravity="center" android:layout_marginTop="8dp" android:background="@android:color/darker_gray" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:text="About GeeksforGeeks" android:textColor="@android:color/black" android:textSize="16sp" android:textStyle="bold" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions." android:textColor="@android:color/black" android:textSize="16sp" /> </LinearLayout>
The following output UI is produced:
Step 4: Working on keep the device screen awake
There are two methods to implement the screen always awake.
Method 1: Invoking the “keepScreenOn” as true
One can keep the device screen awake by invoking the following attribute in the root view of the application.
android:keepScreenOn = “true”
You can have a look at the following activity_main.xml code:
XML
<?xml version="1.0" encoding="utf-8"?> <!--one needs to focus on the keepScreenOn in the root view of the application--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:keepScreenOn="true" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--This layout contains some simple text views--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="64dp" android:fontFamily="sans-serif" android:gravity="center" android:text="GeeksforGeeks" android:textColor="@color/colorPrimary" android:textSize="32sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:fontFamily="sans-serif" android:gravity="center" android:text="A Computer Science portal for geeks" android:textColor="@color/colorPrimary" android:textSize="16sp" /> <View android:layout_width="300dp" android:layout_height="1dp" android:layout_gravity="center" android:layout_marginTop="8dp" android:background="@android:color/darker_gray" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:text="About GeeksforGeeks" android:textColor="@android:color/black" android:textSize="16sp" android:textStyle="bold" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions." android:textColor="@android:color/black" android:textSize="16sp" /> </LinearLayout>
Method 2: Keep screen on programmatically
Now you can remove the attribute android:keepScreenOn=”true” from the activity_main.xml file and rest all code remains the same and invoke the following code in MainActivity.java file.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
The complete code is given below.
Java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.WindowManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // setting up the flag programmatically so that the // device screen should be always on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); }}
The output is produced as the following image (it is recommended to test this application in a physical android device so that you can see the result whether the app screen is awake or not) and both method’s output will remain the same:
Both the methods are the same and one can use whichever it feels better, but implementing this programmatically is recommended because in complex android applications, developers set the many flags in a particular activity and it becomes easy to get those all flags and manually disable and manage them.
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Services in Android with Example
How to Create and Add Data to SQLite Database in Android?
Content Providers in Android with Example
Android RecyclerView in Kotlin
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 25044,
"s": 25016,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 25403,
"s": 25044,
"text": "In Android it’s seen that screen timeout will be set for 30 seconds or it is set by the user manually in system settings, to avoid the battery drain. But there are cases where applications like stopwatch, document reader applications, games, etc, need the screen to be always awake. In this article its been demonstrated, how to keep the device screen awake."
},
{
"code": null,
"e": 25432,
"s": 25403,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25594,
"s": 25432,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 25668,
"s": 25594,
"text": "Step 2: Change the color combination of the base theme of the application"
},
{
"code": null,
"e": 25797,
"s": 25668,
"text": "To change the base application theme colors Goto app -> res -> values -> colors.xml, and invoke the following color combination."
},
{
"code": null,
"e": 25801,
"s": 25797,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#0f9d58</color> <color name=\"colorPrimaryDark\">#006d2d</color> <color name=\"colorAccent\">#55cf86</color></resources>",
"e": 26004,
"s": 25801,
"text": null
},
{
"code": null,
"e": 26070,
"s": 26004,
"text": "Refer the following image if one has not got the colors.xml file:"
},
{
"code": null,
"e": 26118,
"s": 26070,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26216,
"s": 26118,
"text": "In the activity_main.xml file add TextViews to make an app like the document reading application."
},
{
"code": null,
"e": 26220,
"s": 26216,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--This layout contains some simple text views--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"64dp\" android:fontFamily=\"sans-serif\" android:gravity=\"center\" android:text=\"GeeksforGeeks\" android:textColor=\"@color/colorPrimary\" android:textSize=\"32sp\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"8dp\" android:fontFamily=\"sans-serif\" android:gravity=\"center\" android:text=\"A Computer Science portal for geeks\" android:textColor=\"@color/colorPrimary\" android:textSize=\"16sp\" /> <View android:layout_width=\"300dp\" android:layout_height=\"1dp\" android:layout_gravity=\"center\" android:layout_marginTop=\"8dp\" android:background=\"@android:color/darker_gray\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:text=\"About GeeksforGeeks\" android:textColor=\"@android:color/black\" android:textSize=\"16sp\" android:textStyle=\"bold\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"16dp\" android:text=\"How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions.\" android:textColor=\"@android:color/black\" android:textSize=\"16sp\" /> </LinearLayout>",
"e": 28474,
"s": 26220,
"text": null
},
{
"code": null,
"e": 28511,
"s": 28474,
"text": "The following output UI is produced:"
},
{
"code": null,
"e": 28559,
"s": 28511,
"text": "Step 4: Working on keep the device screen awake"
},
{
"code": null,
"e": 28619,
"s": 28559,
"text": "There are two methods to implement the screen always awake."
},
{
"code": null,
"e": 28666,
"s": 28619,
"text": "Method 1: Invoking the “keepScreenOn” as true "
},
{
"code": null,
"e": 28776,
"s": 28666,
"text": "One can keep the device screen awake by invoking the following attribute in the root view of the application."
},
{
"code": null,
"e": 28807,
"s": 28776,
"text": "android:keepScreenOn = “true” "
},
{
"code": null,
"e": 28868,
"s": 28807,
"text": "You can have a look at the following activity_main.xml code:"
},
{
"code": null,
"e": 28872,
"s": 28868,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--one needs to focus on the keepScreenOn in the root view of the application--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:keepScreenOn=\"true\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--This layout contains some simple text views--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"64dp\" android:fontFamily=\"sans-serif\" android:gravity=\"center\" android:text=\"GeeksforGeeks\" android:textColor=\"@color/colorPrimary\" android:textSize=\"32sp\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"8dp\" android:fontFamily=\"sans-serif\" android:gravity=\"center\" android:text=\"A Computer Science portal for geeks\" android:textColor=\"@color/colorPrimary\" android:textSize=\"16sp\" /> <View android:layout_width=\"300dp\" android:layout_height=\"1dp\" android:layout_gravity=\"center\" android:layout_marginTop=\"8dp\" android:background=\"@android:color/darker_gray\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:text=\"About GeeksforGeeks\" android:textColor=\"@android:color/black\" android:textSize=\"16sp\" android:textStyle=\"bold\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"16dp\" android:text=\"How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions.\" android:textColor=\"@android:color/black\" android:textSize=\"16sp\" /> </LinearLayout>",
"e": 31275,
"s": 28872,
"text": null
},
{
"code": null,
"e": 31317,
"s": 31275,
"text": "Method 2: Keep screen on programmatically"
},
{
"code": null,
"e": 31502,
"s": 31317,
"text": "Now you can remove the attribute android:keepScreenOn=”true” from the activity_main.xml file and rest all code remains the same and invoke the following code in MainActivity.java file."
},
{
"code": null,
"e": 31572,
"s": 31502,
"text": "getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);"
},
{
"code": null,
"e": 31606,
"s": 31572,
"text": "The complete code is given below."
},
{
"code": null,
"e": 31611,
"s": 31606,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.WindowManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // setting up the flag programmatically so that the // device screen should be always on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); }}",
"e": 32126,
"s": 31611,
"text": null
},
{
"code": null,
"e": 32363,
"s": 32126,
"text": "The output is produced as the following image (it is recommended to test this application in a physical android device so that you can see the result whether the app screen is awake or not) and both method’s output will remain the same:"
},
{
"code": null,
"e": 32667,
"s": 32363,
"text": "Both the methods are the same and one can use whichever it feels better, but implementing this programmatically is recommended because in complex android applications, developers set the many flags in a particular activity and it becomes easy to get those all flags and manually disable and manage them."
},
{
"code": null,
"e": 32675,
"s": 32667,
"text": "android"
},
{
"code": null,
"e": 32683,
"s": 32675,
"text": "Android"
},
{
"code": null,
"e": 32688,
"s": 32683,
"text": "Java"
},
{
"code": null,
"e": 32693,
"s": 32688,
"text": "Java"
},
{
"code": null,
"e": 32701,
"s": 32693,
"text": "Android"
},
{
"code": null,
"e": 32799,
"s": 32701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32842,
"s": 32799,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 32875,
"s": 32842,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 32933,
"s": 32875,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 32975,
"s": 32933,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 33006,
"s": 32975,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 33021,
"s": 33006,
"text": "Arrays in Java"
},
{
"code": null,
"e": 33065,
"s": 33021,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 33087,
"s": 33065,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 33123,
"s": 33087,
"text": "Arrays.sort() in Java with examples"
}
] |
Feature Variation Explanation. Employing PCA in Scikit-Learn | by Maryam Kargar | Towards Data Science
|
As a multivariate ordination technique, principal component analysis (PCA) can be carried out on dependent variables in a multivariate dataset to explore relationships between them. This results in displaying the relative positions of data points in fewer dimensions while retaining as much information as possible [2].
In this article, I will apply PCA on the auto-mpg dataset (derived from GitHub) using Scikit-learn library. The article is divided into three sections of data preprocessing, PCA and principal component visualization.
We first need to import the required libraries for the dataset preprocessing:
import tensorflow as tffrom tensorflow import kerasimport numpy as npimport pandas as pdimport seaborn as sns!pip install -q git+https://github.com/tensorflow/docsimport tensorflow_docs as tfdocsimport tensorflow_docs.plotsimport tensorflow_docs.modeling
We can then import the data:
datapath = keras.utils.get_file(“auto-mpg.data”, “http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data")datapath
and change the title of the columns:
columnTitles = [‘MPG’,’Cylinders’,’Displacement’,’Horsepower’,’Weight’, ‘Acceleration’, ‘Model Year’, ‘Origin’]rawData = pd.read_csv(dataPath, names=columnTitles, na_values = “?”, comment=’\t’, sep=” “, skipinitialspace=True)
Here is how the data looks:
data = rawData.copy()data.head()
We then need to clean the data:
data.isna().sum()
data = data.dropna()
The next step will be defining the features, separating them out from the response variable and standardizing them as the input for PCA:
from sklearn.preprocessing import StandardScalerdf = pd.DataFrame(data)features = [‘Cylinders’, ‘Displacement’, ‘Horsepower’, ‘Weight’, ‘Acceleration’]X = df.loc[:, features].valuesy = df.loc[:,[‘MPG’]].valuesX = StandardScaler().fit_transform(X)
In PCA, we first need to know how many components are required to explain at least 90% of our feature variation:
from sklearn.decomposition import PCApca = PCA().fit(X)plt.plot(np.cumsum(pca.explained_variance_ratio_))plt.xlabel(‘number of components’)plt.ylabel(‘cumulative explained variance’)
In this case study, two components were chosen as the optimum number of components. We can then start to conduct PCA:
from sklearn.decomposition import PCApca = PCA(n_components=2)principalComponents = pca.fit_transform(X)
As indicated below, in total, the two components explained around 95% of the feature variation of the dataset:
pca.explained_variance_ratio_array([0.81437196, 0.13877225])
Given the response variable value (MPG in the current dataset), the two principal components can be visualized as below :
plt.scatter(principalComponents[:, 0], principalComponents[:, 1],c=data.MPG, edgecolor=’none’, alpha=0.5,cmap=plt.cm.get_cmap(‘Spectral’, 10))plt.xlabel(‘Principal component 1’)plt.ylabel(‘Pricipal component 2’)plt.colorbar()
Principal component analysis (PCA) reduces the dimensionality of large datasets, increases the data interpretability while minimizes the information loss. It does so by creating new uncorrelated components that successively maximize variance [3].
[1]https://commons.wikimedia.org/wiki/File:PCA_vs_Linear_Autoencoder.png
[2] C. Syms. Principal Components Analysis. (2008), Encyclopedia Of Ecology, 2940–2949. doi: 10.1016/b978–008045405–4.00538–3.
[3] T. I. Jolliffe, and J. Cadima. “Principal Component Analysis: a Review and Recent Developments.” (2016), Philosophical Transactions of the Royal Society A: Mathematical, Physical and Engineering Sciences, vol. 374, no. 2065, p. 2015–2020, doi:10.1098/rsta.2015.0202.
|
[
{
"code": null,
"e": 492,
"s": 172,
"text": "As a multivariate ordination technique, principal component analysis (PCA) can be carried out on dependent variables in a multivariate dataset to explore relationships between them. This results in displaying the relative positions of data points in fewer dimensions while retaining as much information as possible [2]."
},
{
"code": null,
"e": 709,
"s": 492,
"text": "In this article, I will apply PCA on the auto-mpg dataset (derived from GitHub) using Scikit-learn library. The article is divided into three sections of data preprocessing, PCA and principal component visualization."
},
{
"code": null,
"e": 787,
"s": 709,
"text": "We first need to import the required libraries for the dataset preprocessing:"
},
{
"code": null,
"e": 1042,
"s": 787,
"text": "import tensorflow as tffrom tensorflow import kerasimport numpy as npimport pandas as pdimport seaborn as sns!pip install -q git+https://github.com/tensorflow/docsimport tensorflow_docs as tfdocsimport tensorflow_docs.plotsimport tensorflow_docs.modeling"
},
{
"code": null,
"e": 1071,
"s": 1042,
"text": "We can then import the data:"
},
{
"code": null,
"e": 1211,
"s": 1071,
"text": "datapath = keras.utils.get_file(“auto-mpg.data”, “http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data\")datapath"
},
{
"code": null,
"e": 1248,
"s": 1211,
"text": "and change the title of the columns:"
},
{
"code": null,
"e": 1474,
"s": 1248,
"text": "columnTitles = [‘MPG’,’Cylinders’,’Displacement’,’Horsepower’,’Weight’, ‘Acceleration’, ‘Model Year’, ‘Origin’]rawData = pd.read_csv(dataPath, names=columnTitles, na_values = “?”, comment=’\\t’, sep=” “, skipinitialspace=True)"
},
{
"code": null,
"e": 1502,
"s": 1474,
"text": "Here is how the data looks:"
},
{
"code": null,
"e": 1535,
"s": 1502,
"text": "data = rawData.copy()data.head()"
},
{
"code": null,
"e": 1567,
"s": 1535,
"text": "We then need to clean the data:"
},
{
"code": null,
"e": 1585,
"s": 1567,
"text": "data.isna().sum()"
},
{
"code": null,
"e": 1606,
"s": 1585,
"text": "data = data.dropna()"
},
{
"code": null,
"e": 1743,
"s": 1606,
"text": "The next step will be defining the features, separating them out from the response variable and standardizing them as the input for PCA:"
},
{
"code": null,
"e": 1990,
"s": 1743,
"text": "from sklearn.preprocessing import StandardScalerdf = pd.DataFrame(data)features = [‘Cylinders’, ‘Displacement’, ‘Horsepower’, ‘Weight’, ‘Acceleration’]X = df.loc[:, features].valuesy = df.loc[:,[‘MPG’]].valuesX = StandardScaler().fit_transform(X)"
},
{
"code": null,
"e": 2103,
"s": 1990,
"text": "In PCA, we first need to know how many components are required to explain at least 90% of our feature variation:"
},
{
"code": null,
"e": 2286,
"s": 2103,
"text": "from sklearn.decomposition import PCApca = PCA().fit(X)plt.plot(np.cumsum(pca.explained_variance_ratio_))plt.xlabel(‘number of components’)plt.ylabel(‘cumulative explained variance’)"
},
{
"code": null,
"e": 2404,
"s": 2286,
"text": "In this case study, two components were chosen as the optimum number of components. We can then start to conduct PCA:"
},
{
"code": null,
"e": 2509,
"s": 2404,
"text": "from sklearn.decomposition import PCApca = PCA(n_components=2)principalComponents = pca.fit_transform(X)"
},
{
"code": null,
"e": 2620,
"s": 2509,
"text": "As indicated below, in total, the two components explained around 95% of the feature variation of the dataset:"
},
{
"code": null,
"e": 2681,
"s": 2620,
"text": "pca.explained_variance_ratio_array([0.81437196, 0.13877225])"
},
{
"code": null,
"e": 2803,
"s": 2681,
"text": "Given the response variable value (MPG in the current dataset), the two principal components can be visualized as below :"
},
{
"code": null,
"e": 3029,
"s": 2803,
"text": "plt.scatter(principalComponents[:, 0], principalComponents[:, 1],c=data.MPG, edgecolor=’none’, alpha=0.5,cmap=plt.cm.get_cmap(‘Spectral’, 10))plt.xlabel(‘Principal component 1’)plt.ylabel(‘Pricipal component 2’)plt.colorbar()"
},
{
"code": null,
"e": 3276,
"s": 3029,
"text": "Principal component analysis (PCA) reduces the dimensionality of large datasets, increases the data interpretability while minimizes the information loss. It does so by creating new uncorrelated components that successively maximize variance [3]."
},
{
"code": null,
"e": 3349,
"s": 3276,
"text": "[1]https://commons.wikimedia.org/wiki/File:PCA_vs_Linear_Autoencoder.png"
},
{
"code": null,
"e": 3476,
"s": 3349,
"text": "[2] C. Syms. Principal Components Analysis. (2008), Encyclopedia Of Ecology, 2940–2949. doi: 10.1016/b978–008045405–4.00538–3."
}
] |
HBase - Security
|
We can grant and revoke permissions to users in HBase. There are three commands for security purpose: grant, revoke, and user_permission.
The grant command grants specific rights such as read, write, execute, and admin on a table to a certain user. The syntax of grant command is as follows:
hbase> grant <user> <permissions> [<table> [<column family> [<column; qualifier>]]
We can grant zero or more privileges to a user from the set of RWXCA, where
R - represents read privilege.
W - represents write privilege.
X - represents execute privilege.
C - represents create privilege.
A - represents admin privilege.
Given below is an example that grants all privileges to a user named ‘Tutorialspoint’.
hbase(main):018:0> grant 'Tutorialspoint', 'RWXCA'
The revoke command is used to revoke a user's access rights of a table. Its syntax is as follows:
hbase> revoke <user>
The following code revokes all the permissions from the user named ‘Tutorialspoint’.
hbase(main):006:0> revoke 'Tutorialspoint'
This command is used to list all the permissions for a particular table. The
syntax of user_permission is as follows:
hbase>user_permission ‘tablename’
The following code lists all the user permissions of ‘emp’ table.
hbase(main):013:0> user_permission 'emp'
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2175,
"s": 2037,
"text": "We can grant and revoke permissions to users in HBase. There are three commands for security purpose: grant, revoke, and user_permission."
},
{
"code": null,
"e": 2329,
"s": 2175,
"text": "The grant command grants specific rights such as read, write, execute, and admin on a table to a certain user. The syntax of grant command is as follows:"
},
{
"code": null,
"e": 2413,
"s": 2329,
"text": "hbase> grant <user> <permissions> [<table> [<column family> [<column; qualifier>]]\n"
},
{
"code": null,
"e": 2489,
"s": 2413,
"text": "We can grant zero or more privileges to a user from the set of RWXCA, where"
},
{
"code": null,
"e": 2520,
"s": 2489,
"text": "R - represents read privilege."
},
{
"code": null,
"e": 2552,
"s": 2520,
"text": "W - represents write privilege."
},
{
"code": null,
"e": 2586,
"s": 2552,
"text": "X - represents execute privilege."
},
{
"code": null,
"e": 2619,
"s": 2586,
"text": "C - represents create privilege."
},
{
"code": null,
"e": 2651,
"s": 2619,
"text": "A - represents admin privilege."
},
{
"code": null,
"e": 2738,
"s": 2651,
"text": "Given below is an example that grants all privileges to a user named ‘Tutorialspoint’."
},
{
"code": null,
"e": 2790,
"s": 2738,
"text": "hbase(main):018:0> grant 'Tutorialspoint', 'RWXCA'\n"
},
{
"code": null,
"e": 2888,
"s": 2790,
"text": "The revoke command is used to revoke a user's access rights of a table. Its syntax is as follows:"
},
{
"code": null,
"e": 2910,
"s": 2888,
"text": "hbase> revoke <user>\n"
},
{
"code": null,
"e": 2995,
"s": 2910,
"text": "The following code revokes all the permissions from the user named ‘Tutorialspoint’."
},
{
"code": null,
"e": 3039,
"s": 2995,
"text": "hbase(main):006:0> revoke 'Tutorialspoint'\n"
},
{
"code": null,
"e": 3157,
"s": 3039,
"text": "This command is used to list all the permissions for a particular table. The\nsyntax of user_permission is as follows:"
},
{
"code": null,
"e": 3192,
"s": 3157,
"text": "hbase>user_permission ‘tablename’\n"
},
{
"code": null,
"e": 3258,
"s": 3192,
"text": "The following code lists all the user permissions of ‘emp’ table."
},
{
"code": null,
"e": 3300,
"s": 3258,
"text": "hbase(main):013:0> user_permission 'emp'\n"
},
{
"code": null,
"e": 3307,
"s": 3300,
"text": " Print"
},
{
"code": null,
"e": 3318,
"s": 3307,
"text": " Add Notes"
}
] |
SWING - JSpinner Class
|
The class JSpinner is a component which lets the user select a number or an object value from an ordered sequence using an input field.
Following is the declaration for javax.swing.JSpinner class −
public class JSpinner
extends JComponent
implements Accessible
JSpinner()
Constructs a spinner with an Integer SpinnerNumberModel with initial value 0 and no minimum or maximum limits.
JSpinner(SpinnerModel model)
Constructs a complete spinner with pair of next/previous buttons and an editor for the SpinnerModel.
void addChangeListener(ChangeListener listener)
Adds a listener to the list who that is notified each time a change to the model occurs.
void commitEdit()
Commits the currently edited value to the SpinnerModel.
protected JComponent createEditor(SpinnerModel model)
This method is called by the constructors to create the JComponent that displays the current value of the sequence.
protected void fireStateChanged()
Sends a ChangeEvent, whose source is this JSpinner, to each ChangeListener.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext for the JSpinner.
ChangeListener[] getChangeListeners()
Returns an array of all the ChangeListeners added to this JSpinner with addChangeListener().
JComponent getEditor()
Returns the component that displays and potentially changes the model's value.
SpinnerModel getModel()
Returns the SpinnerModel that defines this spinners sequence of values.
Object getNextValue()
Returns the object in the sequence that comes after the object returned by getValue().
Object getPreviousValue()
Returns the object in the sequence that comes before the object returned by getValue().
SpinnerUI getUI()
Returns the look and feel (L&F) object that renders this component.
String getUIClassID()
Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component.
Object getValue()
Returns the current value of the model, typically this value is displayed by the editor.
void removeChangeListener(ChangeListener listener)
Removes a ChangeListener from this spinner.
void setEditor(JComponent editor)
Changes the JComponent that displays the current value of the SpinnerModel.
void setModel(SpinnerModel model)
Changes the model that represents the value of this spinner.
void setUI(SpinnerUI ui)
Sets the look and feel (L&F) object that renders this component.
void setValue(Object value)
Changes the current value of the model, typically this value is displayed by the editor.
void updateUI()
Resets the UI property with the value from the current look and feel.
This class inherits methods from the following classes −
javax.swing.JComponent
java.awt.Container
java.awt.Component
java.lang.Object
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showSpinnerDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showSpinnerDemo(){
headerLabel.setText("Control in action: JSpinner");
SpinnerModel spinnerModel = new SpinnerNumberModel(10, //initial value
0, //min
100, //max
1);//step
JSpinner spinner = new JSpinner(spinnerModel);
spinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
statusLabel.setText("Value : " + ((JSpinner)e.getSource()).getValue());
}
});
controlPanel.add(spinner);
mainFrame.setVisible(true);
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingControlDemo
Verify the following output.
30 Lectures
3.5 hours
Pranjal Srivastava
13 Lectures
1 hours
Pranjal Srivastava
25 Lectures
4.5 hours
Emenwa Global, Ejike IfeanyiChukwu
14 Lectures
1.5 hours
Travis Rose
14 Lectures
1 hours
Travis Rose
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1899,
"s": 1763,
"text": "The class JSpinner is a component which lets the user select a number or an object value from an ordered sequence using an input field."
},
{
"code": null,
"e": 1961,
"s": 1899,
"text": "Following is the declaration for javax.swing.JSpinner class −"
},
{
"code": null,
"e": 2034,
"s": 1961,
"text": "public class JSpinner\n extends JComponent\n implements Accessible\n"
},
{
"code": null,
"e": 2045,
"s": 2034,
"text": "JSpinner()"
},
{
"code": null,
"e": 2156,
"s": 2045,
"text": "Constructs a spinner with an Integer SpinnerNumberModel with initial value 0 and no minimum or maximum limits."
},
{
"code": null,
"e": 2185,
"s": 2156,
"text": "JSpinner(SpinnerModel model)"
},
{
"code": null,
"e": 2286,
"s": 2185,
"text": "Constructs a complete spinner with pair of next/previous buttons and an editor for the SpinnerModel."
},
{
"code": null,
"e": 2334,
"s": 2286,
"text": "void addChangeListener(ChangeListener listener)"
},
{
"code": null,
"e": 2423,
"s": 2334,
"text": "Adds a listener to the list who that is notified each time a change to the model occurs."
},
{
"code": null,
"e": 2441,
"s": 2423,
"text": "void commitEdit()"
},
{
"code": null,
"e": 2497,
"s": 2441,
"text": "Commits the currently edited value to the SpinnerModel."
},
{
"code": null,
"e": 2551,
"s": 2497,
"text": "protected JComponent createEditor(SpinnerModel model)"
},
{
"code": null,
"e": 2667,
"s": 2551,
"text": "This method is called by the constructors to create the JComponent that displays the current value of the sequence."
},
{
"code": null,
"e": 2701,
"s": 2667,
"text": "protected void fireStateChanged()"
},
{
"code": null,
"e": 2777,
"s": 2701,
"text": "Sends a ChangeEvent, whose source is this JSpinner, to each ChangeListener."
},
{
"code": null,
"e": 2818,
"s": 2777,
"text": "AccessibleContext getAccessibleContext()"
},
{
"code": null,
"e": 2863,
"s": 2818,
"text": "Gets the AccessibleContext for the JSpinner."
},
{
"code": null,
"e": 2901,
"s": 2863,
"text": "ChangeListener[] getChangeListeners()"
},
{
"code": null,
"e": 2994,
"s": 2901,
"text": "Returns an array of all the ChangeListeners added to this JSpinner with addChangeListener()."
},
{
"code": null,
"e": 3017,
"s": 2994,
"text": "JComponent getEditor()"
},
{
"code": null,
"e": 3096,
"s": 3017,
"text": "Returns the component that displays and potentially changes the model's value."
},
{
"code": null,
"e": 3120,
"s": 3096,
"text": "SpinnerModel getModel()"
},
{
"code": null,
"e": 3192,
"s": 3120,
"text": "Returns the SpinnerModel that defines this spinners sequence of values."
},
{
"code": null,
"e": 3214,
"s": 3192,
"text": "Object getNextValue()"
},
{
"code": null,
"e": 3301,
"s": 3214,
"text": "Returns the object in the sequence that comes after the object returned by getValue()."
},
{
"code": null,
"e": 3327,
"s": 3301,
"text": "Object getPreviousValue()"
},
{
"code": null,
"e": 3415,
"s": 3327,
"text": "Returns the object in the sequence that comes before the object returned by getValue()."
},
{
"code": null,
"e": 3433,
"s": 3415,
"text": "SpinnerUI getUI()"
},
{
"code": null,
"e": 3501,
"s": 3433,
"text": "Returns the look and feel (L&F) object that renders this component."
},
{
"code": null,
"e": 3523,
"s": 3501,
"text": "String getUIClassID()"
},
{
"code": null,
"e": 3633,
"s": 3523,
"text": "Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component."
},
{
"code": null,
"e": 3651,
"s": 3633,
"text": "Object getValue()"
},
{
"code": null,
"e": 3740,
"s": 3651,
"text": "Returns the current value of the model, typically this value is displayed by the editor."
},
{
"code": null,
"e": 3791,
"s": 3740,
"text": "void removeChangeListener(ChangeListener listener)"
},
{
"code": null,
"e": 3835,
"s": 3791,
"text": "Removes a ChangeListener from this spinner."
},
{
"code": null,
"e": 3869,
"s": 3835,
"text": "void setEditor(JComponent editor)"
},
{
"code": null,
"e": 3945,
"s": 3869,
"text": "Changes the JComponent that displays the current value of the SpinnerModel."
},
{
"code": null,
"e": 3979,
"s": 3945,
"text": "void setModel(SpinnerModel model)"
},
{
"code": null,
"e": 4040,
"s": 3979,
"text": "Changes the model that represents the value of this spinner."
},
{
"code": null,
"e": 4065,
"s": 4040,
"text": "void setUI(SpinnerUI ui)"
},
{
"code": null,
"e": 4130,
"s": 4065,
"text": "Sets the look and feel (L&F) object that renders this component."
},
{
"code": null,
"e": 4158,
"s": 4130,
"text": "void setValue(Object value)"
},
{
"code": null,
"e": 4247,
"s": 4158,
"text": "Changes the current value of the model, typically this value is displayed by the editor."
},
{
"code": null,
"e": 4263,
"s": 4247,
"text": "void updateUI()"
},
{
"code": null,
"e": 4333,
"s": 4263,
"text": "Resets the UI property with the value from the current look and feel."
},
{
"code": null,
"e": 4390,
"s": 4333,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 4413,
"s": 4390,
"text": "javax.swing.JComponent"
},
{
"code": null,
"e": 4432,
"s": 4413,
"text": "java.awt.Container"
},
{
"code": null,
"e": 4451,
"s": 4432,
"text": "java.awt.Component"
},
{
"code": null,
"e": 4468,
"s": 4451,
"text": "java.lang.Object"
},
{
"code": null,
"e": 4584,
"s": 4468,
"text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 4606,
"s": 4584,
"text": "SwingControlDemo.java"
},
{
"code": null,
"e": 6408,
"s": 4606,
"text": "package com.tutorialspoint.gui;\n \nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.event.*;\n \npublic class SwingControlDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n\n public SwingControlDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingControlDemo swingControlDemo = new SwingControlDemo(); \n swingControlDemo.showSpinnerDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java Swing Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new JLabel(\"\", JLabel.CENTER); \n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n\n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showSpinnerDemo(){\n headerLabel.setText(\"Control in action: JSpinner\"); \n SpinnerModel spinnerModel = new SpinnerNumberModel(10, //initial value\n 0, //min\n 100, //max\n 1);//step\n JSpinner spinner = new JSpinner(spinnerModel);\n spinner.addChangeListener(new ChangeListener() {\n public void stateChanged(ChangeEvent e) {\n statusLabel.setText(\"Value : \" + ((JSpinner)e.getSource()).getValue());\n }\n });\n controlPanel.add(spinner);\n mainFrame.setVisible(true); \n } \n}"
},
{
"code": null,
"e": 6504,
"s": 6408,
"text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command."
},
{
"code": null,
"e": 6565,
"s": 6504,
"text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingControlDemo.java\n"
},
{
"code": null,
"e": 6670,
"s": 6565,
"text": "If no error occurs, it means the compilation is successful. Run the program using the following command."
},
{
"code": null,
"e": 6725,
"s": 6670,
"text": "D:\\SWING>java com.tutorialspoint.gui.SwingControlDemo\n"
},
{
"code": null,
"e": 6754,
"s": 6725,
"text": "Verify the following output."
},
{
"code": null,
"e": 6789,
"s": 6754,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6809,
"s": 6789,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6842,
"s": 6809,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6862,
"s": 6842,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6897,
"s": 6862,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6933,
"s": 6897,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 6968,
"s": 6933,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6981,
"s": 6968,
"text": " Travis Rose"
},
{
"code": null,
"e": 7014,
"s": 6981,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7027,
"s": 7014,
"text": " Travis Rose"
},
{
"code": null,
"e": 7034,
"s": 7027,
"text": " Print"
},
{
"code": null,
"e": 7045,
"s": 7034,
"text": " Add Notes"
}
] |
Angular CLI - Environment Setup
|
To work with Angular CLI, we need to have Node installed on our system. Let us understand about the environment setup required for Angular CLI in detail.
Download latest version of Node.js installable archive file from Node.js Downloads, which is available at https://nodejs.org/download/. At the time of writing this tutorial, the versions available on different OS are listed below −
Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into /tmp, and then, finally move extracted files into/usr/local/nodejs directory.
For example −
$ cd /tmp
$ wgethttp://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz
$ tar xvfz node-v6.3.1-linux-x64.tar.gz
$ mkdir -p /usr/local/nodejs
$ mv node-v6.3.1-linux-x64/*/usr/local/nodejs
Add /usr/local/nodejs/bin to the PATH environment variable.
Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:\Program Files\nodejs.
The installer should set the C:\ProgramFiles\nodejs\bin directory in windows PATH environment variable.Restart any open command prompts for the change to take effect.
Create a js file named main.json your machine (Windows or Linux) having the following code −
/* Hello, World! program in node.js */
console.log("Hello, World!")
The link for live demo is https://www.tutorialspoint.com/execute_nodejs_online.php.
Now, execute main.js file using Node.js interpreter to see the result −
$ node main.js
If everything is fine with your installation, this should produce the following result −
Hello, World!
Now, the Node is installed. You can run the following command to install Angular CLI.
npm install -g @angular/cli
Now, run the following command to seethe result −
$ ng --version
If everything is fine with yourinstallation, this should produce the following result −
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 9.1.0
Node: 12.16.1
OS: win32 x64
Angular:
...
Ivy Workspace:
Package Version
------------------------------------------------------
@angular-devkit/architect 0.901.0
@angular-devkit/core 9.1.0
@angular-devkit/schematics 9.1.0
@schematics/angular 9.1.0
@schematics/update 0.901.0
rxjs 6.5.4
On Windows, in case of ng being not recognised as internal or external command, update
the system path variable to include the following path.
C:\Users\<User Directory>\AppData\Roaming\npm
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": 2229,
"s": 2075,
"text": "To work with Angular CLI, we need to have Node installed on our system. Let us understand about the environment setup required for Angular CLI in detail."
},
{
"code": null,
"e": 2461,
"s": 2229,
"text": "Download latest version of Node.js installable archive file from Node.js Downloads, which is available at https://nodejs.org/download/. At the time of writing this tutorial, the versions available on different OS are listed below −"
},
{
"code": null,
"e": 2634,
"s": 2461,
"text": "Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into /tmp, and then, finally move extracted files into/usr/local/nodejs directory."
},
{
"code": null,
"e": 2648,
"s": 2634,
"text": "For example −"
},
{
"code": null,
"e": 2843,
"s": 2648,
"text": "$ cd /tmp\n\n$ wgethttp://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz\n\n$ tar xvfz node-v6.3.1-linux-x64.tar.gz\n\n$ mkdir -p /usr/local/nodejs\n\n$ mv node-v6.3.1-linux-x64/*/usr/local/nodejs\n"
},
{
"code": null,
"e": 2903,
"s": 2843,
"text": "Add /usr/local/nodejs/bin to the PATH environment variable."
},
{
"code": null,
"e": 3051,
"s": 2903,
"text": "Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:\\Program Files\\nodejs."
},
{
"code": null,
"e": 3218,
"s": 3051,
"text": "The installer should set the C:\\ProgramFiles\\nodejs\\bin directory in windows PATH environment variable.Restart any open command prompts for the change to take effect."
},
{
"code": null,
"e": 3311,
"s": 3218,
"text": "Create a js file named main.json your machine (Windows or Linux) having the following code −"
},
{
"code": null,
"e": 3380,
"s": 3311,
"text": "/* Hello, World! program in node.js */\nconsole.log(\"Hello, World!\")\n"
},
{
"code": null,
"e": 3464,
"s": 3380,
"text": "The link for live demo is https://www.tutorialspoint.com/execute_nodejs_online.php."
},
{
"code": null,
"e": 3536,
"s": 3464,
"text": "Now, execute main.js file using Node.js interpreter to see the result −"
},
{
"code": null,
"e": 3552,
"s": 3536,
"text": "$ node main.js\n"
},
{
"code": null,
"e": 3641,
"s": 3552,
"text": "If everything is fine with your installation, this should produce the following result −"
},
{
"code": null,
"e": 3656,
"s": 3641,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 3742,
"s": 3656,
"text": "Now, the Node is installed. You can run the following command to install Angular CLI."
},
{
"code": null,
"e": 3771,
"s": 3742,
"text": "npm install -g @angular/cli\n"
},
{
"code": null,
"e": 3821,
"s": 3771,
"text": "Now, run the following command to seethe result −"
},
{
"code": null,
"e": 3837,
"s": 3821,
"text": "$ ng --version\n"
},
{
"code": null,
"e": 3925,
"s": 3837,
"text": "If everything is fine with yourinstallation, this should produce the following result −"
},
{
"code": null,
"e": 4641,
"s": 3925,
"text": "\n _ _ ____ _ ___\n / \\ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|\n / ? \\ | '_ \\ / _` | | | | |/ _` | '__| | | | | | |\n / ___ \\| | | | (_| | |_| | | (_| | | | |___| |___ | |\n /_/ \\_\\_| |_|\\__, |\\__,_|_|\\__,_|_| \\____|_____|___|\n |___/\n\n\nAngular CLI: 9.1.0\nNode: 12.16.1\nOS: win32 x64\n\nAngular:\n...\nIvy Workspace:\n\nPackage Version\n------------------------------------------------------\n@angular-devkit/architect 0.901.0\n@angular-devkit/core 9.1.0\n@angular-devkit/schematics 9.1.0\n@schematics/angular 9.1.0\n@schematics/update 0.901.0\nrxjs 6.5.4\n"
},
{
"code": null,
"e": 4784,
"s": 4641,
"text": "On Windows, in case of ng being not recognised as internal or external command, update\nthe system path variable to include the following path."
},
{
"code": null,
"e": 4831,
"s": 4784,
"text": "C:\\Users\\<User Directory>\\AppData\\Roaming\\npm\n"
},
{
"code": null,
"e": 4866,
"s": 4831,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4880,
"s": 4866,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4915,
"s": 4880,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4929,
"s": 4915,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4964,
"s": 4929,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4984,
"s": 4964,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5019,
"s": 4984,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5036,
"s": 5019,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5069,
"s": 5036,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5081,
"s": 5069,
"text": " Senol Atac"
},
{
"code": null,
"e": 5116,
"s": 5081,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5128,
"s": 5116,
"text": " Senol Atac"
},
{
"code": null,
"e": 5135,
"s": 5128,
"text": " Print"
},
{
"code": null,
"e": 5146,
"s": 5135,
"text": " Add Notes"
}
] |
Which MySQL data type is used for long decimal?
|
For this, use DECIMAL(21,20). Let us first create a table −
mysql> create table DemoTable1493
-> (
-> LongValue DECIMAL(21,20)
-> );
Query OK, 0 rows affected (0.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1493 values(1.0047464644664677373);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1493 values(5.999999484757773);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1493 values(0.009994995885885);
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1493;
This will produce the following output −
+------------------------+
| LongValue |
+------------------------+
| 1.00474646446646773730 |
| 5.99999948475777300000 |
| 0.00999499588588500000 |
+------------------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1122,
"s": 1062,
"text": "For this, use DECIMAL(21,20). Let us first create a table −"
},
{
"code": null,
"e": 1241,
"s": 1122,
"text": "mysql> create table DemoTable1493\n -> (\n -> LongValue DECIMAL(21,20)\n -> );\nQuery OK, 0 rows affected (0.48 sec)"
},
{
"code": null,
"e": 1297,
"s": 1241,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1589,
"s": 1297,
"text": "mysql> insert into DemoTable1493 values(1.0047464644664677373);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1493 values(5.999999484757773);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1493 values(0.009994995885885);\nQuery OK, 1 row affected (0.21 sec)"
},
{
"code": null,
"e": 1649,
"s": 1589,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1685,
"s": 1649,
"text": "mysql> select * from DemoTable1493;"
},
{
"code": null,
"e": 1726,
"s": 1685,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1940,
"s": 1726,
"text": "+------------------------+\n| LongValue |\n+------------------------+\n| 1.00474646446646773730 |\n| 5.99999948475777300000 |\n| 0.00999499588588500000 |\n+------------------------+\n3 rows in set (0.00 sec)"
}
] |
Feature Engineering. Improving a Linear Regression through... | by Andrew Cole | Towards Data Science
|
Last week, I published a blog which walked through all steps of the linear regression modeling process. In this post, we will manipulate the data slightly in order to decrease our model result metrics. We will then walk through the most critical step in any linear regression: Feature Engineering. All code can be found in this notebook. This blog begins halfway through the notebook at the “Feature Engineering” heading.
Feature Engineering is the process of taking certain variables (features) from our dataset and transforming them in a predictive model. Essentially, we will be trying to manipulate single variables and combinations of variables in order to engineer new features. By creating these new features, we are increasing the likelihood that one of the new variables has more predictive power over our outcome variable than the original, un-transformed variables.
To recap, we set out with the goal of trying to predict carseat sales given generated data with several features. We pre-processed our data to account for nominal and categorical data, scaled and normalized our data, removed outliers, built our model, and verified our linear regression assumptions. Our features looked as such:
Sales (target): unit sales at each location
CompPrice: price charged by the nearest competitor at each location
Income: community income level
Advertising: local advertising budget for the company at each location
Population: population size in the region (in thousands)
Price: price charged for a car seat at each site
ShelveLoc: quality of shelving location at site (Good | Bad | Medium)
Age: average age of the local population
Education: education level at each location
Urban: whether the store is in an urban or rural location
USA: whether the store is in the US or not
The approach that we took allowed for us to piece together a well-performing model that returned an r-squared metric of 0.88 with a 0.96 root mean squared error. Both of these metrics indicate a very strong model, but we must keep in mind that this data was generated solely for the purpose of the exercise, and is not real world data. It would be nice, and save a ton of headaches, but very rarely will real-world data result in such a strong result after the first iteration through the model.
Before we get into our feature engineering, let’s first take a look at our previous regression data. Because we had such a strong performing regression, for the sake of this blog’s purpose, we want to remove the strongest impacting variable on our target variable. Covariance measures how two variables will vary in respect to each other (scale = [0, 1]). If the covariance between variable X and variable Y is high, that means that the two variables have a strong impact on each other. The code block below will show us how to see the covariance among all variables in our model training set:
X_train_prep.cov()
This simple method will output the above DataFrame, which is extremely informative but also a lot to digest. We read the variables on the y-axis and find it’s corresponding covariance scores underneath each of the x-axis variables. What we are trying to identify is which variable has the highest impact on the other variables, so that we might remove them from this model. To reiterate, we are only identifying and removing significant variables to reduce our model performance for the sake of feature engineering. In a real-world model, this would be absolutely ridiculous to do without justification from domain knowledge.
We can make the covariance output a bit more digestible by visualizing it in a seaborn heatmap.
sns.heatmap(X_train_prep.cov())
The heatmap just shows our covariance degrees via color intensity. The lighter the color, the higher the covariance of the two variables (per the scale on the right hand side of the map). We see that ‘CompPrice’ has a strong impact on itself and on ‘Price’. This inherently makes sense that the change in a competitor’s price would influence the change in the original business changing its price to reflect. Again, this is where domain knowledge is so important. Because we have two very similar predicting variables in ‘CompPrice’ and ‘Price’, and ‘CompPrice’ is a variable not native to the business selling the car seats, we will remove ‘CompPrice’ to worsen our model.
X_train_prep.drop('CompPrice', axis = 1, inplace = True)lr2 = LinearRegression()lr2.fit(X_train_prep, y_train)y_hat_train = lr2.predict(X_train_prep)r2_score(y_train, y_hat_train)
R-Squared Score = 0.7343
We see that simply removing one strong predictor decreases our R-Squared value to a significantly worse value of 0.73. In the real-world, this would actually be a somewhat promising score after an initial iteration of the model. However, we would not be satisfied with it, and would then move to feature engineering to try and improve our model.
Now that we have dropped ‘CompPrice’ from our DataFrame, it looks like this (data is already scaled and normalized):
During feature engineering, we want to try to create a wide variety of interactions between multiple variables in order to create new variables. For example, multiplying price by income, or advertising by urban-specific populations. By manipulating them together, we create opportunities to have new and impactful features which could potentially impact our target variable, thus engineering our features. For this argument, we will create as many bivariate combinations of our predicting variables using the ‘combinations’ method from itertools library.
from itertools import combinationscolumns_list = X_train_prep.columnsinteractions = list(combinations(column_list, 2))
We only need to manipulate the column titles to generate all the possible combinations, for now. Our result is a list of 45 possible bivariate combinations of our features.
While we have our combinations, it would be incredibly tedious and time consuming to test individually every single combination in a regression. Instead, we will add each combination to a dictionary, and then index the respective dictionary items as arguments in an iterative linear regression:
interaction_dict = {}for interaction in interactions: X_train_int = X_train_prep X_train_int['int'] = X_train_int[interaction[0]] * X_train_int[interaction[1]] lr3 = LinearRegression() lr3.fit(X_train_int, y_train) interaction_dict[lr3.score(X_train_int, y_train)] = interaction
In the above code block we set the X_train to a new copy variable, establish a new feature, ‘int’, by multiplying the two features together, and then use that new DataFrame containing the new combination feature as the only arguments for our new LinearRegression (so excluding the original features which are already in our DataFrame).
We now actually have all of our new regressions completed, thanks to the iteration, but we can’t see them because they are all stored in the ‘interaction_dict’. Let’s sort the dictionary to return the five best performing (r-squared score) combinations.
top_5 = sorted(interaction_dict.keys(), reverse = True)[:5]for interaction in top_5: print(interaction_dict[interaction])
Our top performing combinations are:
Advertising x Education
Advertising x US
US x Advertising
Price x Age
Good x Age
At this point, domain knowledge kicks it into an even higher gear. The variables returned here should start to move some cranks and gears in your brain as to why certain variables are more impactful. Get creative with it, we are engineering after all. For the sake of this blog, let’s say that our domain knowledge already assumes any categorical variable to be irrelevant because location doesn’t matter. We will only be looking at ‘Advertising x Education’ and ‘Price x Age’. Let’s run a new regression including both these combinations. First, we add the features to our original DataFrame that contained the univariate data.
X_train_int = X_train_prepX_train_int['ad_ed'] = X_train_int['Advertising'] * X_train_int['Age']
Now we run another regression with our new features in the DataFrame.
lr4 = LinearRegression()lr4.fit(X_train_int, y_train)lr4.score(X_train_int, y_train)
R-Squared Score = .74
We can see that our linear regression score increased from .73 to .74. This is obviously a minimal increase, and one that is not super significant, but nonetheless we can see how creating new bivariate feature terms can play a significant role in improving our model.
Again, there are no clear-cut guidelines to test all possible variable manipulations. We have just seen how to make two variables interact together, but what is another way we can engineer new features? Polynomials! A very strong (usually) option for new features is increasing the power of a single variable. For our purposes, we will try and see if all the existing variables, including our bivariate combinations, can improve our regression by being increased in power.
To do so, we will use the ‘PolynomialFeatures’ object from the sklearn.preprocessing library. We create a new, empty dictionary for storage of our new feature possibilities (same as bivariates). We will then iterate through our X_train_int feature set and create a new feature for each respective feature to be squared thru fifth-power. We will then fit a linear regression with each of the new individual features and choose the best performing feature for use in our final regression.
from sklearn.preprocessing import PolynomialFeaturespoly_dict = {}for feature in X_train_int.columns: for p in range(2, 5): X_train_poly = X_train_int X_train_poly['sq'] = X_train_poly[feature] ** p lr = LinearRegression() lr.fit(X_train_poly, y_train) poly_dict[lr.score(X_train_poly, y_train) = [feature, p]poly_dict[max(poly_dict.keys())]
R-Squared Score = 0.743
Once again, we see a tiny yet still positive increase in our R-squared metric. There are numerous methods for engineering new possibilities and improving your regression, but these are a great starting point for any new data scientist!
|
[
{
"code": null,
"e": 593,
"s": 171,
"text": "Last week, I published a blog which walked through all steps of the linear regression modeling process. In this post, we will manipulate the data slightly in order to decrease our model result metrics. We will then walk through the most critical step in any linear regression: Feature Engineering. All code can be found in this notebook. This blog begins halfway through the notebook at the “Feature Engineering” heading."
},
{
"code": null,
"e": 1048,
"s": 593,
"text": "Feature Engineering is the process of taking certain variables (features) from our dataset and transforming them in a predictive model. Essentially, we will be trying to manipulate single variables and combinations of variables in order to engineer new features. By creating these new features, we are increasing the likelihood that one of the new variables has more predictive power over our outcome variable than the original, un-transformed variables."
},
{
"code": null,
"e": 1377,
"s": 1048,
"text": "To recap, we set out with the goal of trying to predict carseat sales given generated data with several features. We pre-processed our data to account for nominal and categorical data, scaled and normalized our data, removed outliers, built our model, and verified our linear regression assumptions. Our features looked as such:"
},
{
"code": null,
"e": 1421,
"s": 1377,
"text": "Sales (target): unit sales at each location"
},
{
"code": null,
"e": 1489,
"s": 1421,
"text": "CompPrice: price charged by the nearest competitor at each location"
},
{
"code": null,
"e": 1520,
"s": 1489,
"text": "Income: community income level"
},
{
"code": null,
"e": 1591,
"s": 1520,
"text": "Advertising: local advertising budget for the company at each location"
},
{
"code": null,
"e": 1648,
"s": 1591,
"text": "Population: population size in the region (in thousands)"
},
{
"code": null,
"e": 1697,
"s": 1648,
"text": "Price: price charged for a car seat at each site"
},
{
"code": null,
"e": 1767,
"s": 1697,
"text": "ShelveLoc: quality of shelving location at site (Good | Bad | Medium)"
},
{
"code": null,
"e": 1808,
"s": 1767,
"text": "Age: average age of the local population"
},
{
"code": null,
"e": 1852,
"s": 1808,
"text": "Education: education level at each location"
},
{
"code": null,
"e": 1910,
"s": 1852,
"text": "Urban: whether the store is in an urban or rural location"
},
{
"code": null,
"e": 1953,
"s": 1910,
"text": "USA: whether the store is in the US or not"
},
{
"code": null,
"e": 2449,
"s": 1953,
"text": "The approach that we took allowed for us to piece together a well-performing model that returned an r-squared metric of 0.88 with a 0.96 root mean squared error. Both of these metrics indicate a very strong model, but we must keep in mind that this data was generated solely for the purpose of the exercise, and is not real world data. It would be nice, and save a ton of headaches, but very rarely will real-world data result in such a strong result after the first iteration through the model."
},
{
"code": null,
"e": 3043,
"s": 2449,
"text": "Before we get into our feature engineering, let’s first take a look at our previous regression data. Because we had such a strong performing regression, for the sake of this blog’s purpose, we want to remove the strongest impacting variable on our target variable. Covariance measures how two variables will vary in respect to each other (scale = [0, 1]). If the covariance between variable X and variable Y is high, that means that the two variables have a strong impact on each other. The code block below will show us how to see the covariance among all variables in our model training set:"
},
{
"code": null,
"e": 3062,
"s": 3043,
"text": "X_train_prep.cov()"
},
{
"code": null,
"e": 3688,
"s": 3062,
"text": "This simple method will output the above DataFrame, which is extremely informative but also a lot to digest. We read the variables on the y-axis and find it’s corresponding covariance scores underneath each of the x-axis variables. What we are trying to identify is which variable has the highest impact on the other variables, so that we might remove them from this model. To reiterate, we are only identifying and removing significant variables to reduce our model performance for the sake of feature engineering. In a real-world model, this would be absolutely ridiculous to do without justification from domain knowledge."
},
{
"code": null,
"e": 3784,
"s": 3688,
"text": "We can make the covariance output a bit more digestible by visualizing it in a seaborn heatmap."
},
{
"code": null,
"e": 3816,
"s": 3784,
"text": "sns.heatmap(X_train_prep.cov())"
},
{
"code": null,
"e": 4490,
"s": 3816,
"text": "The heatmap just shows our covariance degrees via color intensity. The lighter the color, the higher the covariance of the two variables (per the scale on the right hand side of the map). We see that ‘CompPrice’ has a strong impact on itself and on ‘Price’. This inherently makes sense that the change in a competitor’s price would influence the change in the original business changing its price to reflect. Again, this is where domain knowledge is so important. Because we have two very similar predicting variables in ‘CompPrice’ and ‘Price’, and ‘CompPrice’ is a variable not native to the business selling the car seats, we will remove ‘CompPrice’ to worsen our model."
},
{
"code": null,
"e": 4670,
"s": 4490,
"text": "X_train_prep.drop('CompPrice', axis = 1, inplace = True)lr2 = LinearRegression()lr2.fit(X_train_prep, y_train)y_hat_train = lr2.predict(X_train_prep)r2_score(y_train, y_hat_train)"
},
{
"code": null,
"e": 4695,
"s": 4670,
"text": "R-Squared Score = 0.7343"
},
{
"code": null,
"e": 5041,
"s": 4695,
"text": "We see that simply removing one strong predictor decreases our R-Squared value to a significantly worse value of 0.73. In the real-world, this would actually be a somewhat promising score after an initial iteration of the model. However, we would not be satisfied with it, and would then move to feature engineering to try and improve our model."
},
{
"code": null,
"e": 5158,
"s": 5041,
"text": "Now that we have dropped ‘CompPrice’ from our DataFrame, it looks like this (data is already scaled and normalized):"
},
{
"code": null,
"e": 5713,
"s": 5158,
"text": "During feature engineering, we want to try to create a wide variety of interactions between multiple variables in order to create new variables. For example, multiplying price by income, or advertising by urban-specific populations. By manipulating them together, we create opportunities to have new and impactful features which could potentially impact our target variable, thus engineering our features. For this argument, we will create as many bivariate combinations of our predicting variables using the ‘combinations’ method from itertools library."
},
{
"code": null,
"e": 5832,
"s": 5713,
"text": "from itertools import combinationscolumns_list = X_train_prep.columnsinteractions = list(combinations(column_list, 2))"
},
{
"code": null,
"e": 6005,
"s": 5832,
"text": "We only need to manipulate the column titles to generate all the possible combinations, for now. Our result is a list of 45 possible bivariate combinations of our features."
},
{
"code": null,
"e": 6300,
"s": 6005,
"text": "While we have our combinations, it would be incredibly tedious and time consuming to test individually every single combination in a regression. Instead, we will add each combination to a dictionary, and then index the respective dictionary items as arguments in an iterative linear regression:"
},
{
"code": null,
"e": 6589,
"s": 6300,
"text": "interaction_dict = {}for interaction in interactions: X_train_int = X_train_prep X_train_int['int'] = X_train_int[interaction[0]] * X_train_int[interaction[1]] lr3 = LinearRegression() lr3.fit(X_train_int, y_train) interaction_dict[lr3.score(X_train_int, y_train)] = interaction"
},
{
"code": null,
"e": 6925,
"s": 6589,
"text": "In the above code block we set the X_train to a new copy variable, establish a new feature, ‘int’, by multiplying the two features together, and then use that new DataFrame containing the new combination feature as the only arguments for our new LinearRegression (so excluding the original features which are already in our DataFrame)."
},
{
"code": null,
"e": 7179,
"s": 6925,
"text": "We now actually have all of our new regressions completed, thanks to the iteration, but we can’t see them because they are all stored in the ‘interaction_dict’. Let’s sort the dictionary to return the five best performing (r-squared score) combinations."
},
{
"code": null,
"e": 7303,
"s": 7179,
"text": "top_5 = sorted(interaction_dict.keys(), reverse = True)[:5]for interaction in top_5: print(interaction_dict[interaction])"
},
{
"code": null,
"e": 7340,
"s": 7303,
"text": "Our top performing combinations are:"
},
{
"code": null,
"e": 7364,
"s": 7340,
"text": "Advertising x Education"
},
{
"code": null,
"e": 7381,
"s": 7364,
"text": "Advertising x US"
},
{
"code": null,
"e": 7398,
"s": 7381,
"text": "US x Advertising"
},
{
"code": null,
"e": 7410,
"s": 7398,
"text": "Price x Age"
},
{
"code": null,
"e": 7421,
"s": 7410,
"text": "Good x Age"
},
{
"code": null,
"e": 8050,
"s": 7421,
"text": "At this point, domain knowledge kicks it into an even higher gear. The variables returned here should start to move some cranks and gears in your brain as to why certain variables are more impactful. Get creative with it, we are engineering after all. For the sake of this blog, let’s say that our domain knowledge already assumes any categorical variable to be irrelevant because location doesn’t matter. We will only be looking at ‘Advertising x Education’ and ‘Price x Age’. Let’s run a new regression including both these combinations. First, we add the features to our original DataFrame that contained the univariate data."
},
{
"code": null,
"e": 8147,
"s": 8050,
"text": "X_train_int = X_train_prepX_train_int['ad_ed'] = X_train_int['Advertising'] * X_train_int['Age']"
},
{
"code": null,
"e": 8217,
"s": 8147,
"text": "Now we run another regression with our new features in the DataFrame."
},
{
"code": null,
"e": 8302,
"s": 8217,
"text": "lr4 = LinearRegression()lr4.fit(X_train_int, y_train)lr4.score(X_train_int, y_train)"
},
{
"code": null,
"e": 8324,
"s": 8302,
"text": "R-Squared Score = .74"
},
{
"code": null,
"e": 8592,
"s": 8324,
"text": "We can see that our linear regression score increased from .73 to .74. This is obviously a minimal increase, and one that is not super significant, but nonetheless we can see how creating new bivariate feature terms can play a significant role in improving our model."
},
{
"code": null,
"e": 9065,
"s": 8592,
"text": "Again, there are no clear-cut guidelines to test all possible variable manipulations. We have just seen how to make two variables interact together, but what is another way we can engineer new features? Polynomials! A very strong (usually) option for new features is increasing the power of a single variable. For our purposes, we will try and see if all the existing variables, including our bivariate combinations, can improve our regression by being increased in power."
},
{
"code": null,
"e": 9552,
"s": 9065,
"text": "To do so, we will use the ‘PolynomialFeatures’ object from the sklearn.preprocessing library. We create a new, empty dictionary for storage of our new feature possibilities (same as bivariates). We will then iterate through our X_train_int feature set and create a new feature for each respective feature to be squared thru fifth-power. We will then fit a linear regression with each of the new individual features and choose the best performing feature for use in our final regression."
},
{
"code": null,
"e": 9921,
"s": 9552,
"text": "from sklearn.preprocessing import PolynomialFeaturespoly_dict = {}for feature in X_train_int.columns: for p in range(2, 5): X_train_poly = X_train_int X_train_poly['sq'] = X_train_poly[feature] ** p lr = LinearRegression() lr.fit(X_train_poly, y_train) poly_dict[lr.score(X_train_poly, y_train) = [feature, p]poly_dict[max(poly_dict.keys())]"
},
{
"code": null,
"e": 9945,
"s": 9921,
"text": "R-Squared Score = 0.743"
}
] |
C++ program to get the Sum of series: 1 – x^2/2! + x^4/4! -.... upto nth term
|
In this tutorial, we will be discussing a program to get the sum of series 1 – x^2/2! + x^4/4! ... upto nth term.
For this we will be given with the values of x and n. Our task will be to calculate the sum of the given series upto the given n terms. This can be easily done by computing the factorial and using the standard power function to calculate powers.
#include <math.h>
#include <stdio.h>
//calculating the sum of series
double calc_sum(double x, int n){
double sum = 1, term = 1, fct, j, y = 2, m;
int i;
for (i = 1; i < n; i++) {
fct = 1;
for (j = 1; j <= y; j++) {
fct = fct * j;
}
term = term * (-1);
m = term * pow(x, y) / fct;
sum = sum + m;
y += 2;
}
return sum;
}
int main(){
double x = 5;
int n = 7;
printf("%.4f", calc_sum(x, n));
return 0;
}
0.3469
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to get the sum of series 1 – x^2/2! + x^4/4! ... upto nth term."
},
{
"code": null,
"e": 1422,
"s": 1176,
"text": "For this we will be given with the values of x and n. Our task will be to calculate the sum of the given series upto the given n terms. This can be easily done by computing the factorial and using the standard power function to calculate powers."
},
{
"code": null,
"e": 1901,
"s": 1422,
"text": "#include <math.h>\n#include <stdio.h>\n//calculating the sum of series\ndouble calc_sum(double x, int n){\n double sum = 1, term = 1, fct, j, y = 2, m;\n int i;\n for (i = 1; i < n; i++) {\n fct = 1;\n for (j = 1; j <= y; j++) {\n fct = fct * j;\n }\n term = term * (-1);\n m = term * pow(x, y) / fct;\n sum = sum + m;\n y += 2;\n }\n return sum;\n}\nint main(){\n double x = 5;\n int n = 7;\n printf(\"%.4f\", calc_sum(x, n));\n return 0;\n}"
},
{
"code": null,
"e": 1908,
"s": 1901,
"text": "0.3469"
}
] |
log4j - Configuration
|
The previous chapter explained the core components of log4j. This chapter explains how you can configure the core components using a configuration file. Configuring log4j involves assigning the Level, defining Appender, and specifying Layout objects in a configuration file.
The log4j.properties file is a log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.properties in the CLASSPATH.
The level of the root logger is defined as DEBUG. The DEBUG attaches the appender named X to it.
The level of the root logger is defined as DEBUG. The DEBUG attaches the appender named X to it.
Set the appender named X to be a valid appender.
Set the appender named X to be a valid appender.
Set the layout for the appender X.
Set the layout for the appender X.
Following is the syntax of log4j.properties file for an appender X:
# Define the root logger with appender X
log4j.rootLogger = DEBUG, X
# Set the appender named X to be a File appender
log4j.appender.X=org.apache.log4j.FileAppender
# Define the layout for X appender
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.conversionPattern=%m%n
Using the above syntax, we define the following in log4j.properties file:
The level of the root logger is defined as DEBUG, The DEBUG appender named FILE to it.
The level of the root logger is defined as DEBUG, The DEBUG appender named FILE to it.
The appender FILE is defined as org.apache.log4j.FileAppender. It writes to a file named log.out located in the log directory.
The appender FILE is defined as org.apache.log4j.FileAppender. It writes to a file named log.out located in the log directory.
The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.
The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
It is important to note that log4j supports UNIX-style variable substitution such as ${variableName}.
We have used DEBUG with both the appenders. All the possible options are:
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
ALL
These levels are explained later in this tutorial.
Apache log4j provides Appender objects which are primarily responsible for printing logging messages to different destinations such as consoles, files, sockets, NT event logs, etc.
Each Appender object has different properties associated with it, and these properties indicate the behavior of that object.
We can add an Appender object to a Logger by including the following setting in the configuration file with the following method:
log4j.logger.[logger-name]=level, appender1,appender..n
You can write same configuration in XML format as follows:
<logger name="com.apress.logging.log4j" additivity="false">
<appender-ref ref="appender1"/>
<appender-ref ref="appender2"/>
</logger>
If you are willing to add Appender object inside your program then you can use following method:
public void addAppender(Appender appender);
The addAppender() method adds an Appender to the Logger object. As the example configuration demonstrates, it is possible to add many Appender objects to a logger in a comma-separated list, each printing logging information to separate destinations.
We have used only one appender FileAppender in our example above. All the possible appender options are:
AppenderSkeleton
AsyncAppender
ConsoleAppender
DailyRollingFileAppender
ExternallyRolledFileAppender
FileAppender
JDBCAppender
JMSAppender
LF5Appender
NTEventLogAppender
NullAppender
RollingFileAppender
SMTPAppender
SocketAppender
SocketHubAppender
SyslogAppender
TelnetAppender
WriterAppender
We would cover FileAppender in Logging in Files and JDBC Appender would be covered in Logging in Database.
We have used PatternLayout with our appender. All the possible options are:
DateLayout
HTMLLayout
PatternLayout
SimpleLayout
XMLLayout
Using HTMLLayout and XMLLayout, you can generate log in HTML and in XML format as well.
You would learn how to format a log message in chapter: Log Formatting.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2101,
"s": 1826,
"text": "The previous chapter explained the core components of log4j. This chapter explains how you can configure the core components using a configuration file. Configuring log4j involves assigning the Level, defining Appender, and specifying Layout objects in a configuration file."
},
{
"code": null,
"e": 2285,
"s": 2101,
"text": "The log4j.properties file is a log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.properties in the CLASSPATH."
},
{
"code": null,
"e": 2382,
"s": 2285,
"text": "The level of the root logger is defined as DEBUG. The DEBUG attaches the appender named X to it."
},
{
"code": null,
"e": 2479,
"s": 2382,
"text": "The level of the root logger is defined as DEBUG. The DEBUG attaches the appender named X to it."
},
{
"code": null,
"e": 2528,
"s": 2479,
"text": "Set the appender named X to be a valid appender."
},
{
"code": null,
"e": 2577,
"s": 2528,
"text": "Set the appender named X to be a valid appender."
},
{
"code": null,
"e": 2612,
"s": 2577,
"text": "Set the layout for the appender X."
},
{
"code": null,
"e": 2647,
"s": 2612,
"text": "Set the layout for the appender X."
},
{
"code": null,
"e": 2715,
"s": 2647,
"text": "Following is the syntax of log4j.properties file for an appender X:"
},
{
"code": null,
"e": 3020,
"s": 2715,
"text": "# Define the root logger with appender X\nlog4j.rootLogger = DEBUG, X\n\n# Set the appender named X to be a File appender\nlog4j.appender.X=org.apache.log4j.FileAppender\n\n# Define the layout for X appender\nlog4j.appender.X.layout=org.apache.log4j.PatternLayout\nlog4j.appender.X.layout.conversionPattern=%m%n\n"
},
{
"code": null,
"e": 3094,
"s": 3020,
"text": "Using the above syntax, we define the following in log4j.properties file:"
},
{
"code": null,
"e": 3181,
"s": 3094,
"text": "The level of the root logger is defined as DEBUG, The DEBUG appender named FILE to it."
},
{
"code": null,
"e": 3268,
"s": 3181,
"text": "The level of the root logger is defined as DEBUG, The DEBUG appender named FILE to it."
},
{
"code": null,
"e": 3395,
"s": 3268,
"text": "The appender FILE is defined as org.apache.log4j.FileAppender. It writes to a file named log.out located in the log directory."
},
{
"code": null,
"e": 3522,
"s": 3395,
"text": "The appender FILE is defined as org.apache.log4j.FileAppender. It writes to a file named log.out located in the log directory."
},
{
"code": null,
"e": 3639,
"s": 3522,
"text": "The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character."
},
{
"code": null,
"e": 3756,
"s": 3639,
"text": "The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character."
},
{
"code": null,
"e": 4097,
"s": 3756,
"text": "# Define the root logger with appender file\nlog4j.rootLogger = DEBUG, FILE\n\n# Define the file appender\nlog4j.appender.FILE=org.apache.log4j.FileAppender\nlog4j.appender.FILE.File=${log}/log.out\n\n# Define the layout for file appender\nlog4j.appender.FILE.layout=org.apache.log4j.PatternLayout\nlog4j.appender.FILE.layout.conversionPattern=%m%n\n"
},
{
"code": null,
"e": 4199,
"s": 4097,
"text": "It is important to note that log4j supports UNIX-style variable substitution such as ${variableName}."
},
{
"code": null,
"e": 4273,
"s": 4199,
"text": "We have used DEBUG with both the appenders. All the possible options are:"
},
{
"code": null,
"e": 4279,
"s": 4273,
"text": "TRACE"
},
{
"code": null,
"e": 4285,
"s": 4279,
"text": "DEBUG"
},
{
"code": null,
"e": 4290,
"s": 4285,
"text": "INFO"
},
{
"code": null,
"e": 4295,
"s": 4290,
"text": "WARN"
},
{
"code": null,
"e": 4301,
"s": 4295,
"text": "ERROR"
},
{
"code": null,
"e": 4307,
"s": 4301,
"text": "FATAL"
},
{
"code": null,
"e": 4311,
"s": 4307,
"text": "ALL"
},
{
"code": null,
"e": 4362,
"s": 4311,
"text": "These levels are explained later in this tutorial."
},
{
"code": null,
"e": 4543,
"s": 4362,
"text": "Apache log4j provides Appender objects which are primarily responsible for printing logging messages to different destinations such as consoles, files, sockets, NT event logs, etc."
},
{
"code": null,
"e": 4668,
"s": 4543,
"text": "Each Appender object has different properties associated with it, and these properties indicate the behavior of that object."
},
{
"code": null,
"e": 4798,
"s": 4668,
"text": "We can add an Appender object to a Logger by including the following setting in the configuration file with the following method:"
},
{
"code": null,
"e": 4855,
"s": 4798,
"text": "log4j.logger.[logger-name]=level, appender1,appender..n\n"
},
{
"code": null,
"e": 4914,
"s": 4855,
"text": "You can write same configuration in XML format as follows:"
},
{
"code": null,
"e": 5054,
"s": 4914,
"text": "<logger name=\"com.apress.logging.log4j\" additivity=\"false\">\n <appender-ref ref=\"appender1\"/>\n <appender-ref ref=\"appender2\"/>\n</logger>"
},
{
"code": null,
"e": 5151,
"s": 5054,
"text": "If you are willing to add Appender object inside your program then you can use following method:"
},
{
"code": null,
"e": 5195,
"s": 5151,
"text": "public void addAppender(Appender appender);"
},
{
"code": null,
"e": 5445,
"s": 5195,
"text": "The addAppender() method adds an Appender to the Logger object. As the example configuration demonstrates, it is possible to add many Appender objects to a logger in a comma-separated list, each printing logging information to separate destinations."
},
{
"code": null,
"e": 5550,
"s": 5445,
"text": "We have used only one appender FileAppender in our example above. All the possible appender options are:"
},
{
"code": null,
"e": 5567,
"s": 5550,
"text": "AppenderSkeleton"
},
{
"code": null,
"e": 5581,
"s": 5567,
"text": "AsyncAppender"
},
{
"code": null,
"e": 5597,
"s": 5581,
"text": "ConsoleAppender"
},
{
"code": null,
"e": 5622,
"s": 5597,
"text": "DailyRollingFileAppender"
},
{
"code": null,
"e": 5651,
"s": 5622,
"text": "ExternallyRolledFileAppender"
},
{
"code": null,
"e": 5664,
"s": 5651,
"text": "FileAppender"
},
{
"code": null,
"e": 5677,
"s": 5664,
"text": "JDBCAppender"
},
{
"code": null,
"e": 5689,
"s": 5677,
"text": "JMSAppender"
},
{
"code": null,
"e": 5701,
"s": 5689,
"text": "LF5Appender"
},
{
"code": null,
"e": 5720,
"s": 5701,
"text": "NTEventLogAppender"
},
{
"code": null,
"e": 5733,
"s": 5720,
"text": "NullAppender"
},
{
"code": null,
"e": 5753,
"s": 5733,
"text": "RollingFileAppender"
},
{
"code": null,
"e": 5766,
"s": 5753,
"text": "SMTPAppender"
},
{
"code": null,
"e": 5781,
"s": 5766,
"text": "SocketAppender"
},
{
"code": null,
"e": 5799,
"s": 5781,
"text": "SocketHubAppender"
},
{
"code": null,
"e": 5814,
"s": 5799,
"text": "SyslogAppender"
},
{
"code": null,
"e": 5829,
"s": 5814,
"text": "TelnetAppender"
},
{
"code": null,
"e": 5844,
"s": 5829,
"text": "WriterAppender"
},
{
"code": null,
"e": 5951,
"s": 5844,
"text": "We would cover FileAppender in Logging in Files and JDBC Appender would be covered in Logging in Database."
},
{
"code": null,
"e": 6027,
"s": 5951,
"text": "We have used PatternLayout with our appender. All the possible options are:"
},
{
"code": null,
"e": 6038,
"s": 6027,
"text": "DateLayout"
},
{
"code": null,
"e": 6049,
"s": 6038,
"text": "HTMLLayout"
},
{
"code": null,
"e": 6063,
"s": 6049,
"text": "PatternLayout"
},
{
"code": null,
"e": 6076,
"s": 6063,
"text": "SimpleLayout"
},
{
"code": null,
"e": 6086,
"s": 6076,
"text": "XMLLayout"
},
{
"code": null,
"e": 6174,
"s": 6086,
"text": "Using HTMLLayout and XMLLayout, you can generate log in HTML and in XML format as well."
},
{
"code": null,
"e": 6246,
"s": 6174,
"text": "You would learn how to format a log message in chapter: Log Formatting."
},
{
"code": null,
"e": 6253,
"s": 6246,
"text": " Print"
},
{
"code": null,
"e": 6264,
"s": 6253,
"text": " Add Notes"
}
] |
Gensim - Creating LDA Mallet Model
|
This chapter will explain what is a Latent Dirichlet Allocation (LDA) Mallet Model and how to create the same in Gensim.
In the previous section we have implemented LDA model and get the topics from documents of 20Newsgroup dataset. That was Gensim’s inbuilt version of the LDA algorithm. There is a Mallet version of Gensim also, which provides better quality of topics. Here, we are going to apply Mallet’s LDA on the previous example we have already implemented.
Mallet, an open source toolkit, was written by Andrew McCullum. It is basically a Java based package which is used for NLP, document classification, clustering, topic modeling, and many other machine learning applications to text. It provides us the Mallet Topic Modeling toolkit which contains efficient, sampling-based implementations of LDA as well as Hierarchical LDA.
Mallet2.0 is the current release from MALLET, the java topic modeling toolkit. Before we start using it with Gensim for LDA, we must download the mallet-2.0.8.zip package on our system and unzip it. Once installed and unzipped, set the environment variable %MALLET_HOME% to the point to the MALLET directory either manually or by the code we will be providing, while implementing the LDA with Mallet next.
Python provides Gensim wrapper for Latent Dirichlet Allocation (LDA). The syntax of that wrapper is gensim.models.wrappers.LdaMallet. This module, collapsed gibbs sampling from MALLET, allows LDA model estimation from a training corpus and inference of topic distribution on new, unseen documents as well.
We will be using LDA Mallet on previously built LDA model and will check the difference in performance by calculating Coherence score.
Before applying Mallet LDA model on our corpus built in previous example, we must have to update the environment variables and provide the path the Mallet file as well. It can be done with the help of following code −
import os
from gensim.models.wrappers import LdaMallet
os.environ.update({'MALLET_HOME':r'C:/mallet-2.0.8/'})
#You should update this path as per the path of Mallet directory on your system.
mallet_path = r'C:/mallet-2.0.8/bin/mallet'
#You should update this path as per the path of Mallet directory on your system.
Once we provided the path to Mallet file, we can now use it on the corpus. It can be done with the help of ldamallet.show_topics() function as follows −
ldamallet = gensim.models.wrappers.LdaMallet(
mallet_path, corpus=corpus, num_topics=20, id2word=id2word
)
pprint(ldamallet.show_topics(formatted=False))
[
(4,
[('gun', 0.024546225966016102),
('law', 0.02181426826996709),
('state', 0.017633545129043606),
('people', 0.017612848479831116),
('case', 0.011341763768445888),
('crime', 0.010596684396796159),
('weapon', 0.00985160502514643),
('person', 0.008671896020034356),
('firearm', 0.00838214293105946),
('police', 0.008257963035784506)]),
(9,
[('make', 0.02147966482730431),
('people', 0.021377478029838543),
('work', 0.018557122419783363),
('money', 0.016676885346413244),
('year', 0.015982015123646026),
('job', 0.012221540976905783),
('pay', 0.010239117106069897),
('time', 0.008910688739014919),
('school', 0.0079092581238504),
('support', 0.007357449417535254)]),
(14,
[('power', 0.018428398507941996),
('line', 0.013784244460364121),
('high', 0.01183271164249895),
('work', 0.011560979224821522),
('ground', 0.010770484918850819),
('current', 0.010745781971789235),
('wire', 0.008399002000938712),
('low', 0.008053160742076529),
('water', 0.006966231071366814),
('run', 0.006892122230182061)]),
(0,
[('people', 0.025218349201353372),
('kill', 0.01500904870564167),
('child', 0.013612400660948935),
('armenian', 0.010307655991816822),
('woman', 0.010287984892595798),
('start', 0.01003226060272248),
('day', 0.00967818081674404),
('happen', 0.009383114328428673),
('leave', 0.009383114328428673),
('fire', 0.009009363443229208)]),
(1,
[('file', 0.030686386604212003),
('program', 0.02227713642901929),
('window', 0.01945561169918489),
('set', 0.015914874783314277),
('line', 0.013831003577619592),
('display', 0.013794120901412606),
('application', 0.012576992586582082),
('entry', 0.009275993066056873),
('change', 0.00872275292295209),
('color', 0.008612104894331132)]),
(12,
[('line', 0.07153810971508515),
('buy', 0.02975597944523662),
('organization', 0.026877236406682988),
('host', 0.025451316957679788),
('price', 0.025182275552207485),
('sell', 0.02461728860071565),
('mail', 0.02192687454599263),
('good', 0.018967419085797303),
('sale', 0.017998870026097017),
('send', 0.013694207538540181)]),
(11,
[('thing', 0.04901329901329901),
('good', 0.0376018876018876),
('make', 0.03393393393393394),
('time', 0.03326898326898327),
('bad', 0.02664092664092664),
('happen', 0.017696267696267698),
('hear', 0.015615615615615615),
('problem', 0.015465465465465466),
('back', 0.015143715143715144),
('lot', 0.01495066495066495)]),
(18,
[('space', 0.020626317374284855),
('launch', 0.00965716006366413),
('system', 0.008560244332602057),
('project', 0.008173097603991913),
('time', 0.008108573149223556),
('cost', 0.007764442723792318),
('year', 0.0076784101174345075),
('earth', 0.007484836753129436),
('base', 0.0067535595990880545),
('large', 0.006689035144319697)]),
(5,
[('government', 0.01918437232469453),
('people', 0.01461203206475212),
('state', 0.011207097828624796),
('country', 0.010214802708381975),
('israeli', 0.010039691804809714),
('war', 0.009436532025838587),
('force', 0.00858043427504086),
('attack', 0.008424780138532182),
('land', 0.0076659662230523775),
('world', 0.0075103120865437)]),
(2,
[('car', 0.041091194044470564),
('bike', 0.015598981291017729),
('ride', 0.011019688510138114),
('drive', 0.010627877363110981),
('engine', 0.009403467528651191),
('speed', 0.008081104907434616),
('turn', 0.007738270153785875),
('back', 0.007738270153785875),
('front', 0.007468899990204721),
('big', 0.007370947203447938)])
]
Now we can also evaluate its performance by calculating the coherence score as follows −
ldamallet = gensim.models.wrappers.LdaMallet(
mallet_path, corpus=corpus, num_topics=20, id2word=id2word
)
pprint(ldamallet.show_topics(formatted=False))
Coherence Score: 0.5842762900901401
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2173,
"s": 2052,
"text": "This chapter will explain what is a Latent Dirichlet Allocation (LDA) Mallet Model and how to create the same in Gensim."
},
{
"code": null,
"e": 2518,
"s": 2173,
"text": "In the previous section we have implemented LDA model and get the topics from documents of 20Newsgroup dataset. That was Gensim’s inbuilt version of the LDA algorithm. There is a Mallet version of Gensim also, which provides better quality of topics. Here, we are going to apply Mallet’s LDA on the previous example we have already implemented."
},
{
"code": null,
"e": 2891,
"s": 2518,
"text": "Mallet, an open source toolkit, was written by Andrew McCullum. It is basically a Java based package which is used for NLP, document classification, clustering, topic modeling, and many other machine learning applications to text. It provides us the Mallet Topic Modeling toolkit which contains efficient, sampling-based implementations of LDA as well as Hierarchical LDA."
},
{
"code": null,
"e": 3297,
"s": 2891,
"text": "Mallet2.0 is the current release from MALLET, the java topic modeling toolkit. Before we start using it with Gensim for LDA, we must download the mallet-2.0.8.zip package on our system and unzip it. Once installed and unzipped, set the environment variable %MALLET_HOME% to the point to the MALLET directory either manually or by the code we will be providing, while implementing the LDA with Mallet next."
},
{
"code": null,
"e": 3603,
"s": 3297,
"text": "Python provides Gensim wrapper for Latent Dirichlet Allocation (LDA). The syntax of that wrapper is gensim.models.wrappers.LdaMallet. This module, collapsed gibbs sampling from MALLET, allows LDA model estimation from a training corpus and inference of topic distribution on new, unseen documents as well."
},
{
"code": null,
"e": 3738,
"s": 3603,
"text": "We will be using LDA Mallet on previously built LDA model and will check the difference in performance by calculating Coherence score."
},
{
"code": null,
"e": 3956,
"s": 3738,
"text": "Before applying Mallet LDA model on our corpus built in previous example, we must have to update the environment variables and provide the path the Mallet file as well. It can be done with the help of following code −"
},
{
"code": null,
"e": 4274,
"s": 3956,
"text": "import os\nfrom gensim.models.wrappers import LdaMallet\nos.environ.update({'MALLET_HOME':r'C:/mallet-2.0.8/'}) \n#You should update this path as per the path of Mallet directory on your system.\nmallet_path = r'C:/mallet-2.0.8/bin/mallet' \n#You should update this path as per the path of Mallet directory on your system."
},
{
"code": null,
"e": 4427,
"s": 4274,
"text": "Once we provided the path to Mallet file, we can now use it on the corpus. It can be done with the help of ldamallet.show_topics() function as follows −"
},
{
"code": null,
"e": 4584,
"s": 4427,
"text": "ldamallet = gensim.models.wrappers.LdaMallet(\n mallet_path, corpus=corpus, num_topics=20, id2word=id2word\n)\npprint(ldamallet.show_topics(formatted=False))"
},
{
"code": null,
"e": 8259,
"s": 4584,
"text": "[\n (4,\n [('gun', 0.024546225966016102),\n ('law', 0.02181426826996709),\n ('state', 0.017633545129043606),\n ('people', 0.017612848479831116),\n ('case', 0.011341763768445888),\n ('crime', 0.010596684396796159),\n ('weapon', 0.00985160502514643),\n ('person', 0.008671896020034356),\n ('firearm', 0.00838214293105946),\n ('police', 0.008257963035784506)]),\n (9,\n [('make', 0.02147966482730431),\n ('people', 0.021377478029838543),\n ('work', 0.018557122419783363),\n ('money', 0.016676885346413244),\n ('year', 0.015982015123646026),\n ('job', 0.012221540976905783),\n ('pay', 0.010239117106069897),\n ('time', 0.008910688739014919),\n ('school', 0.0079092581238504),\n ('support', 0.007357449417535254)]),\n (14,\n [('power', 0.018428398507941996),\n ('line', 0.013784244460364121),\n ('high', 0.01183271164249895),\n ('work', 0.011560979224821522),\n ('ground', 0.010770484918850819),\n ('current', 0.010745781971789235),\n ('wire', 0.008399002000938712),\n ('low', 0.008053160742076529),\n ('water', 0.006966231071366814),\n ('run', 0.006892122230182061)]),\n (0,\n [('people', 0.025218349201353372),\n ('kill', 0.01500904870564167),\n ('child', 0.013612400660948935),\n ('armenian', 0.010307655991816822),\n ('woman', 0.010287984892595798),\n ('start', 0.01003226060272248),\n ('day', 0.00967818081674404),\n ('happen', 0.009383114328428673),\n ('leave', 0.009383114328428673),\n ('fire', 0.009009363443229208)]),\n (1,\n [('file', 0.030686386604212003),\n ('program', 0.02227713642901929),\n ('window', 0.01945561169918489),\n ('set', 0.015914874783314277),\n ('line', 0.013831003577619592),\n ('display', 0.013794120901412606),\n ('application', 0.012576992586582082),\n ('entry', 0.009275993066056873),\n ('change', 0.00872275292295209),\n ('color', 0.008612104894331132)]),\n (12,\n [('line', 0.07153810971508515),\n ('buy', 0.02975597944523662),\n ('organization', 0.026877236406682988),\n ('host', 0.025451316957679788),\n ('price', 0.025182275552207485),\n ('sell', 0.02461728860071565),\n ('mail', 0.02192687454599263),\n ('good', 0.018967419085797303),\n ('sale', 0.017998870026097017),\n ('send', 0.013694207538540181)]),\n (11,\n [('thing', 0.04901329901329901),\n ('good', 0.0376018876018876),\n ('make', 0.03393393393393394),\n ('time', 0.03326898326898327),\n ('bad', 0.02664092664092664),\n ('happen', 0.017696267696267698),\n ('hear', 0.015615615615615615),\n ('problem', 0.015465465465465466),\n ('back', 0.015143715143715144),\n ('lot', 0.01495066495066495)]),\n (18,\n [('space', 0.020626317374284855),\n ('launch', 0.00965716006366413),\n ('system', 0.008560244332602057),\n ('project', 0.008173097603991913),\n ('time', 0.008108573149223556),\n ('cost', 0.007764442723792318),\n ('year', 0.0076784101174345075),\n ('earth', 0.007484836753129436),\n ('base', 0.0067535595990880545),\n ('large', 0.006689035144319697)]),\n (5,\n [('government', 0.01918437232469453),\n ('people', 0.01461203206475212),\n ('state', 0.011207097828624796),\n ('country', 0.010214802708381975),\n ('israeli', 0.010039691804809714),\n ('war', 0.009436532025838587),\n ('force', 0.00858043427504086),\n ('attack', 0.008424780138532182),\n ('land', 0.0076659662230523775),\n ('world', 0.0075103120865437)]),\n (2,\n [('car', 0.041091194044470564),\n ('bike', 0.015598981291017729),\n ('ride', 0.011019688510138114),\n ('drive', 0.010627877363110981),\n ('engine', 0.009403467528651191),\n ('speed', 0.008081104907434616),\n ('turn', 0.007738270153785875),\n ('back', 0.007738270153785875),\n ('front', 0.007468899990204721),\n ('big', 0.007370947203447938)])\n]\n"
},
{
"code": null,
"e": 8348,
"s": 8259,
"text": "Now we can also evaluate its performance by calculating the coherence score as follows −"
},
{
"code": null,
"e": 8505,
"s": 8348,
"text": "ldamallet = gensim.models.wrappers.LdaMallet(\n mallet_path, corpus=corpus, num_topics=20, id2word=id2word\n)\npprint(ldamallet.show_topics(formatted=False))"
},
{
"code": null,
"e": 8542,
"s": 8505,
"text": "Coherence Score: 0.5842762900901401\n"
},
{
"code": null,
"e": 8549,
"s": 8542,
"text": " Print"
},
{
"code": null,
"e": 8560,
"s": 8549,
"text": " Add Notes"
}
] |
How to Extract filename from a given path in C# - GeeksforGeeks
|
04 Apr, 2019
While developing an application that can be desktop or web in C#, such kind of requirement to extract the filename from a given path (where the path can be taken while selecting a file using File Open dialog box or any other sources) can arise. A path may contain the drive name, directory name(s) and the filename. To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.
Syntax: public static string GetFileName (string path);Here, path is the string from which we have to obtain the file name and extension.
Return Value: This method will return the characters after the last directory separator character in path. If the last character of the path is a directory or volume separator character, this method returns Empty. If the path is null, this method returns null.
Exception: This method will give ArgumentException if the path contains one or more of the invalid characters defined in GetInvalidPathChars().
Examples:
Input :
string strPath = "c://myfiles//ref//file1.txt";
//function call to get the filename
filename = Path.GetFileName(strPath);
Output :
file1.txt
// C# program to extract the // filename from a given pathusing System;using System.IO;using System.Text; namespace Geeks { class GFG { // Main Method static void Main(string[] args) { // taking full path of a file string strPath = "C:// myfiles//ref//file1.txt"; // initialize the value of filename string filename = null; // using the method filename = Path.GetFileName(strPath); Console.WriteLine("Filename = " + filename); Console.ReadLine(); }}}
Filename = file1.txt
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=netframework-4.7.2
CSharp-method
CSharp-Path-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Delegates
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
|
[
{
"code": null,
"e": 24528,
"s": 24500,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 25064,
"s": 24528,
"text": "While developing an application that can be desktop or web in C#, such kind of requirement to extract the filename from a given path (where the path can be taken while selecting a file using File Open dialog box or any other sources) can arise. A path may contain the drive name, directory name(s) and the filename. To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null."
},
{
"code": null,
"e": 25202,
"s": 25064,
"text": "Syntax: public static string GetFileName (string path);Here, path is the string from which we have to obtain the file name and extension."
},
{
"code": null,
"e": 25463,
"s": 25202,
"text": "Return Value: This method will return the characters after the last directory separator character in path. If the last character of the path is a directory or volume separator character, this method returns Empty. If the path is null, this method returns null."
},
{
"code": null,
"e": 25607,
"s": 25463,
"text": "Exception: This method will give ArgumentException if the path contains one or more of the invalid characters defined in GetInvalidPathChars()."
},
{
"code": null,
"e": 25617,
"s": 25607,
"text": "Examples:"
},
{
"code": null,
"e": 25772,
"s": 25617,
"text": "Input : \n\nstring strPath = \"c://myfiles//ref//file1.txt\";\n\n//function call to get the filename\nfilename = Path.GetFileName(strPath);\n\nOutput :\n\nfile1.txt\n"
},
{
"code": "// C# program to extract the // filename from a given pathusing System;using System.IO;using System.Text; namespace Geeks { class GFG { // Main Method static void Main(string[] args) { // taking full path of a file string strPath = \"C:// myfiles//ref//file1.txt\"; // initialize the value of filename string filename = null; // using the method filename = Path.GetFileName(strPath); Console.WriteLine(\"Filename = \" + filename); Console.ReadLine(); }}}",
"e": 26303,
"s": 25772,
"text": null
},
{
"code": null,
"e": 26325,
"s": 26303,
"text": "Filename = file1.txt\n"
},
{
"code": null,
"e": 26336,
"s": 26325,
"text": "Reference:"
},
{
"code": null,
"e": 26431,
"s": 26336,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=netframework-4.7.2"
},
{
"code": null,
"e": 26445,
"s": 26431,
"text": "CSharp-method"
},
{
"code": null,
"e": 26463,
"s": 26445,
"text": "CSharp-Path-Class"
},
{
"code": null,
"e": 26466,
"s": 26463,
"text": "C#"
},
{
"code": null,
"e": 26564,
"s": 26466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26573,
"s": 26564,
"text": "Comments"
},
{
"code": null,
"e": 26586,
"s": 26573,
"text": "Old Comments"
},
{
"code": null,
"e": 26608,
"s": 26586,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 26654,
"s": 26608,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26672,
"s": 26654,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26703,
"s": 26672,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 26726,
"s": 26703,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26741,
"s": 26726,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26763,
"s": 26741,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 26779,
"s": 26763,
"text": "C# | Data Types"
},
{
"code": null,
"e": 26807,
"s": 26779,
"text": "HashSet in C# with Examples"
}
] |
Addition of two numbers without propagating Carry - GeeksforGeeks
|
25 Mar, 2021
Given 2 numbers a and b of same length. The task is to calculate their sum in such a way that when adding two corresponding positions the carry has to be kept with them only instead of propagating to the left.See the below image for reference:
Examples:
Input: a = 7752 , b = 8834
Output: 151586
Input: a = 123 , b = 456
Output: 579
Approach: First of all, reverse both of the numbers a and b. Now, to generate the resulting sum:
Extract digits from both a and b.
Calculate sum of digits.
If sum of digits is a single digit number, append it directly to the resultant sum.
Otherwise, reverse the current calculated digit sum and extract digits from it one by one and append to the resultant sum.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; // Function to print sum of 2 numbers// without propagating carryint printSum(int a, int b){ int res = 0; int temp1 = 0, temp2 = 0; // Reverse a while(a) { temp1 = temp1*10 + (a%10); a /= 10; } a = temp1; // Reverse b while(b) { temp2 = temp2*10 + (b%10); b /= 10; } b = temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while(a) { // Extract digits from a and b and add int sum = (a%10 + b%10); // If sum is single digit if(sum/10 == 0) res = res*10 + sum; else { // If sum is not single digit // reverse sum temp1 = 0; while(sum) { temp1 = temp1*10 + (sum%10); sum /= 10; } sum = temp1; // Extract digits from sum and append // to result while(sum) { res = res*10 + (sum%10); sum /=10; } } a/=10; b/=10; } return res;} // Driver codeint main(){ int a = 7752, b = 8834; cout<<printSum(a, b); return 0;}
// Java implementation of the approachclass GFG{ // Function to print sum of 2 numbers // without propagating carry static int printSum(int a, int b) { int res = 0; int temp1 = 0, temp2 = 0; // Reverse a while (a != 0) { temp1 = temp1 * 10 + (a % 10); a /= 10; } a = temp1; // Reverse b while (b != 0) { temp2 = temp2 * 10 + (b % 10); b /= 10; } b = temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while (a != 0) { // Extract digits from a and b and add int sum = (a % 10 + b % 10); // If sum is single digit if (sum / 10 == 0) { res = res * 10 + sum; } else { // If sum is not single digit // reverse sum temp1 = 0; while (sum != 0) { temp1 = temp1 * 10 + (sum % 10); sum /= 10; } sum = temp1; // Extract digits from sum and append // to result while (sum != 0) { res = res * 10 + (sum % 10); sum /= 10; } } a /= 10; b /= 10; } return res; } // Driver code public static void main(String[] args) { int a = 7752, b = 8834; System.out.println(printSum(a, b)); }} // This code contributed by Rajput-Ji
# Python3 implementation of the approach # Function to prsum of 2 numbers# without propagating carrydef printSum(a, b): res, temp1, temp2 = 0, 0, 0 # Reverse a while a > 0: temp1 = temp1 * 10 + (a % 10) a //= 10 a = temp1 # Reverse b while b > 0: temp2 = temp2 * 10 + (b % 10) b //= 10 b = temp2 # Generate sum # Since length of both a and b are same, # take any one of them. while a: # Extract digits from a and b and add Sum = a % 10 + b % 10 # If sum is single digit if Sum // 10 == 0: res = res * 10 + Sum else: # If sum is not single digit # reverse sum temp1 = 0 while Sum > 0: temp1 = temp1 * 10 + (Sum % 10) Sum //= 10 Sum = temp1 # Extract digits from sum and # append to result while Sum > 0: res = res * 10 + (Sum % 10) Sum //= 10 a //= 10 b //= 10 return res # Driver codeif __name__ == "__main__": a, b = 7752, 8834 print(printSum(a, b)) # This code is contributed# by Rituraj Jain
// C# implementation of the above approachusing System; class GFG{ // Function to print sum of 2 numbers// without propagating carrystatic int printSum(int a, int b){ int res = 0; int temp1 = 0, temp2 = 0; // Reverse a while(a != 0) { temp1 = temp1 * 10 + (a % 10); a /= 10; } a = temp1; // Reverse b while(b != 0) { temp2 = temp2 * 10 + (b % 10); b /= 10; } b = temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while(a != 0) { // Extract digits from a and b and add int sum = (a % 10 + b % 10); // If sum is single digit if(sum / 10 == 0) res = res * 10 + sum; else { // If sum is not single digit // reverse sum temp1 = 0; while(sum != 0) { temp1 = temp1 * 10 + (sum % 10); sum /= 10; } sum = temp1; // Extract digits from sum and append // to result while(sum != 0) { res = res * 10 + (sum % 10); sum /=10; } } a /= 10; b /= 10; } return res;} // Driver codepublic static void Main(){ int a = 7752, b = 8834; Console.Write(printSum(a, b)); }} // This code is contributed// by Akanksha Rai
<?php// PHP implementation of the approach // Function to print sum of 2 numbers// without propagating carryfunction printSum($a, $b){ $res = 0; $temp1 = 0; $temp2 = 0; // Reverse a while ($a != 0) { $temp1 = $temp1 * 10 + ($a % 10); $a = (int)($a / 10); } $a = $temp1; // Reverse b while ($b != 0) { $temp2 = $temp2 * 10 + ($b % 10); $b = (int)($b / 10); } $b = $temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while ($a != 0) { // Extract digits from a and b and add $sum = ($a % 10 + $b % 10); // If sum is single digit if ((int)($sum / 10) == 0) { $res = $res * 10 + $sum; } else { // If sum is not single digit // reverse sum $temp1 = 0; while ($sum != 0) { $temp1 = $temp1 * 10 + ($sum % 10); $sum = (int)($sum / 10); } $sum = $temp1; // Extract digits from sum and append // to result while ($sum != 0) { $res = $res * 10 + ($sum % 10); $sum = (int)($sum / 10); } } $a = (int)($a / 10); $b = (int)($b / 10); } return $res;} // Driver code$a = 7752; $b = 8834;echo(printSum($a, $b)); // This code contributed by Code_Mech.?>
<script> // Javascript implementation of the above approach // Function to print sum of 2 numbers // without propagating carry function printSum(a, b) { var res = 0; var temp1 = 0, temp2 = 0; // Reverse a while (a) { temp1 = temp1 * 10 + (a % 10); a = parseInt(a / 10); } a = temp1; // Reverse b while (b) { temp2 = temp2 * 10 + (b % 10); b = parseInt(b / 10); } b = temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while (a) { // Extract digits from a and b and add var sum = (a % 10 + b % 10); // If sum is single digit if (parseInt(sum / 10) == 0) res = res * 10 + sum; else { // If sum is not single digit // reverse sum temp1 = 0; while (sum) { temp1 = temp1 * 10 + (sum % 10); sum = parseInt(sum / 10); } sum = temp1; // Extract digits from sum and append // to result while (sum) { res = res * 10 + (sum % 10); sum = parseInt(sum / 10); } } a = parseInt(a / 10); b = parseInt(b / 10); } return res; } // Driver code var a = 7752, b = 8834; document.write(printSum(a, b)); // This code is contributed by rrrtnx. </script>
151586
Time Complexity: O(N).
rituraj_jain
Akanksha_Rai
Rajput-Ji
Code_Mech
rrrtnx
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Generate all permutation of a set in Python
Check if a number is Palindrome
Program to multiply two matrices
Segment Tree | Set 1 (Sum of given range)
How to check if a given point lies inside or outside a polygon?
Merge two sorted arrays with O(1) extra space
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 25961,
"s": 25933,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 26207,
"s": 25961,
"text": "Given 2 numbers a and b of same length. The task is to calculate their sum in such a way that when adding two corresponding positions the carry has to be kept with them only instead of propagating to the left.See the below image for reference: "
},
{
"code": null,
"e": 26219,
"s": 26207,
"text": "Examples: "
},
{
"code": null,
"e": 26299,
"s": 26219,
"text": "Input: a = 7752 , b = 8834\nOutput: 151586\n\nInput: a = 123 , b = 456\nOutput: 579"
},
{
"code": null,
"e": 26400,
"s": 26301,
"text": "Approach: First of all, reverse both of the numbers a and b. Now, to generate the resulting sum: "
},
{
"code": null,
"e": 26434,
"s": 26400,
"text": "Extract digits from both a and b."
},
{
"code": null,
"e": 26459,
"s": 26434,
"text": "Calculate sum of digits."
},
{
"code": null,
"e": 26543,
"s": 26459,
"text": "If sum of digits is a single digit number, append it directly to the resultant sum."
},
{
"code": null,
"e": 26666,
"s": 26543,
"text": "Otherwise, reverse the current calculated digit sum and extract digits from it one by one and append to the resultant sum."
},
{
"code": null,
"e": 26718,
"s": 26666,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26722,
"s": 26718,
"text": "C++"
},
{
"code": null,
"e": 26727,
"s": 26722,
"text": "Java"
},
{
"code": null,
"e": 26735,
"s": 26727,
"text": "Python3"
},
{
"code": null,
"e": 26738,
"s": 26735,
"text": "C#"
},
{
"code": null,
"e": 26742,
"s": 26738,
"text": "PHP"
},
{
"code": null,
"e": 26753,
"s": 26742,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; // Function to print sum of 2 numbers// without propagating carryint printSum(int a, int b){ int res = 0; int temp1 = 0, temp2 = 0; // Reverse a while(a) { temp1 = temp1*10 + (a%10); a /= 10; } a = temp1; // Reverse b while(b) { temp2 = temp2*10 + (b%10); b /= 10; } b = temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while(a) { // Extract digits from a and b and add int sum = (a%10 + b%10); // If sum is single digit if(sum/10 == 0) res = res*10 + sum; else { // If sum is not single digit // reverse sum temp1 = 0; while(sum) { temp1 = temp1*10 + (sum%10); sum /= 10; } sum = temp1; // Extract digits from sum and append // to result while(sum) { res = res*10 + (sum%10); sum /=10; } } a/=10; b/=10; } return res;} // Driver codeint main(){ int a = 7752, b = 8834; cout<<printSum(a, b); return 0;}",
"e": 28106,
"s": 26753,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to print sum of 2 numbers // without propagating carry static int printSum(int a, int b) { int res = 0; int temp1 = 0, temp2 = 0; // Reverse a while (a != 0) { temp1 = temp1 * 10 + (a % 10); a /= 10; } a = temp1; // Reverse b while (b != 0) { temp2 = temp2 * 10 + (b % 10); b /= 10; } b = temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while (a != 0) { // Extract digits from a and b and add int sum = (a % 10 + b % 10); // If sum is single digit if (sum / 10 == 0) { res = res * 10 + sum; } else { // If sum is not single digit // reverse sum temp1 = 0; while (sum != 0) { temp1 = temp1 * 10 + (sum % 10); sum /= 10; } sum = temp1; // Extract digits from sum and append // to result while (sum != 0) { res = res * 10 + (sum % 10); sum /= 10; } } a /= 10; b /= 10; } return res; } // Driver code public static void main(String[] args) { int a = 7752, b = 8834; System.out.println(printSum(a, b)); }} // This code contributed by Rajput-Ji",
"e": 29769,
"s": 28106,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to prsum of 2 numbers# without propagating carrydef printSum(a, b): res, temp1, temp2 = 0, 0, 0 # Reverse a while a > 0: temp1 = temp1 * 10 + (a % 10) a //= 10 a = temp1 # Reverse b while b > 0: temp2 = temp2 * 10 + (b % 10) b //= 10 b = temp2 # Generate sum # Since length of both a and b are same, # take any one of them. while a: # Extract digits from a and b and add Sum = a % 10 + b % 10 # If sum is single digit if Sum // 10 == 0: res = res * 10 + Sum else: # If sum is not single digit # reverse sum temp1 = 0 while Sum > 0: temp1 = temp1 * 10 + (Sum % 10) Sum //= 10 Sum = temp1 # Extract digits from sum and # append to result while Sum > 0: res = res * 10 + (Sum % 10) Sum //= 10 a //= 10 b //= 10 return res # Driver codeif __name__ == \"__main__\": a, b = 7752, 8834 print(printSum(a, b)) # This code is contributed# by Rituraj Jain",
"e": 31085,
"s": 29769,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to print sum of 2 numbers// without propagating carrystatic int printSum(int a, int b){ int res = 0; int temp1 = 0, temp2 = 0; // Reverse a while(a != 0) { temp1 = temp1 * 10 + (a % 10); a /= 10; } a = temp1; // Reverse b while(b != 0) { temp2 = temp2 * 10 + (b % 10); b /= 10; } b = temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while(a != 0) { // Extract digits from a and b and add int sum = (a % 10 + b % 10); // If sum is single digit if(sum / 10 == 0) res = res * 10 + sum; else { // If sum is not single digit // reverse sum temp1 = 0; while(sum != 0) { temp1 = temp1 * 10 + (sum % 10); sum /= 10; } sum = temp1; // Extract digits from sum and append // to result while(sum != 0) { res = res * 10 + (sum % 10); sum /=10; } } a /= 10; b /= 10; } return res;} // Driver codepublic static void Main(){ int a = 7752, b = 8834; Console.Write(printSum(a, b)); }} // This code is contributed// by Akanksha Rai",
"e": 32535,
"s": 31085,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to print sum of 2 numbers// without propagating carryfunction printSum($a, $b){ $res = 0; $temp1 = 0; $temp2 = 0; // Reverse a while ($a != 0) { $temp1 = $temp1 * 10 + ($a % 10); $a = (int)($a / 10); } $a = $temp1; // Reverse b while ($b != 0) { $temp2 = $temp2 * 10 + ($b % 10); $b = (int)($b / 10); } $b = $temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while ($a != 0) { // Extract digits from a and b and add $sum = ($a % 10 + $b % 10); // If sum is single digit if ((int)($sum / 10) == 0) { $res = $res * 10 + $sum; } else { // If sum is not single digit // reverse sum $temp1 = 0; while ($sum != 0) { $temp1 = $temp1 * 10 + ($sum % 10); $sum = (int)($sum / 10); } $sum = $temp1; // Extract digits from sum and append // to result while ($sum != 0) { $res = $res * 10 + ($sum % 10); $sum = (int)($sum / 10); } } $a = (int)($a / 10); $b = (int)($b / 10); } return $res;} // Driver code$a = 7752; $b = 8834;echo(printSum($a, $b)); // This code contributed by Code_Mech.?>",
"e": 33999,
"s": 32535,
"text": null
},
{
"code": " <script> // Javascript implementation of the above approach // Function to print sum of 2 numbers // without propagating carry function printSum(a, b) { var res = 0; var temp1 = 0, temp2 = 0; // Reverse a while (a) { temp1 = temp1 * 10 + (a % 10); a = parseInt(a / 10); } a = temp1; // Reverse b while (b) { temp2 = temp2 * 10 + (b % 10); b = parseInt(b / 10); } b = temp2; // Generate sum // Since length of both a and b are same, // take any one of them. while (a) { // Extract digits from a and b and add var sum = (a % 10 + b % 10); // If sum is single digit if (parseInt(sum / 10) == 0) res = res * 10 + sum; else { // If sum is not single digit // reverse sum temp1 = 0; while (sum) { temp1 = temp1 * 10 + (sum % 10); sum = parseInt(sum / 10); } sum = temp1; // Extract digits from sum and append // to result while (sum) { res = res * 10 + (sum % 10); sum = parseInt(sum / 10); } } a = parseInt(a / 10); b = parseInt(b / 10); } return res; } // Driver code var a = 7752, b = 8834; document.write(printSum(a, b)); // This code is contributed by rrrtnx. </script>",
"e": 35442,
"s": 33999,
"text": null
},
{
"code": null,
"e": 35449,
"s": 35442,
"text": "151586"
},
{
"code": null,
"e": 35475,
"s": 35451,
"text": "Time Complexity: O(N). "
},
{
"code": null,
"e": 35488,
"s": 35475,
"text": "rituraj_jain"
},
{
"code": null,
"e": 35501,
"s": 35488,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35511,
"s": 35501,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 35521,
"s": 35511,
"text": "Code_Mech"
},
{
"code": null,
"e": 35528,
"s": 35521,
"text": "rrrtnx"
},
{
"code": null,
"e": 35542,
"s": 35528,
"text": "number-theory"
},
{
"code": null,
"e": 35555,
"s": 35542,
"text": "Mathematical"
},
{
"code": null,
"e": 35569,
"s": 35555,
"text": "number-theory"
},
{
"code": null,
"e": 35582,
"s": 35569,
"text": "Mathematical"
},
{
"code": null,
"e": 35680,
"s": 35582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35724,
"s": 35680,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 35755,
"s": 35724,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 35780,
"s": 35755,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 35824,
"s": 35780,
"text": "Generate all permutation of a set in Python"
},
{
"code": null,
"e": 35856,
"s": 35824,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 35889,
"s": 35856,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 35931,
"s": 35889,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 35995,
"s": 35931,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 36041,
"s": 35995,
"text": "Merge two sorted arrays with O(1) extra space"
}
] |
Why do we use internal keyword in C#?
|
Internal keyword allows you to set internal access specifier.
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly.
Any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
using System;
namespace RectangleApplication {
class Rectangle {
internal double length;
internal double width;
double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class Demo {
static void Main(string[] args) {
Rectangle rc = new Rectangle();
rc.length = 10.35;
rc.width = 8.3;
rc.Display();
Console.ReadLine();
}
}
}
|
[
{
"code": null,
"e": 1124,
"s": 1062,
"text": "Internal keyword allows you to set internal access specifier."
},
{
"code": null,
"e": 1273,
"s": 1124,
"text": "Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly."
},
{
"code": null,
"e": 1419,
"s": 1273,
"text": "Any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined."
},
{
"code": null,
"e": 2028,
"s": 1419,
"text": "using System;\n\nnamespace RectangleApplication {\n class Rectangle {\n\n internal double length;\n internal double width;\n\n double GetArea() {\n return length * width;\n }\n\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }\n\n class Demo {\n static void Main(string[] args) {\n Rectangle rc = new Rectangle();\n rc.length = 10.35;\n rc.width = 8.3;\n rc.Display();\n Console.ReadLine();\n }\n }\n}"
}
] |
Caffe2 - Quick Guide
|
Last couple of years, Deep Learning has become a big trend in Machine Learning. It has been successfully applied to solve previously unsolvable problems in Vision, Speech Recognition and Natural Language Processing (NLP). There are many more domains in which Deep Learning is being applied and has shown its usefulness.
Caffe (Convolutional Architecture for Fast Feature Embedding) is a deep learning framework developed at Berkeley Vision and Learning Center (BVLC). The Caffe project was created by Yangqing Jia during his Ph.D. at University of California - Berkeley. Caffe provides an easy way to experiment with deep learning. It is written in C++ and provides bindings for Python and Matlab.
It supports many different types of deep learning architectures such as CNN (Convolutional Neural Network), LSTM (Long Short Term Memory) and FC (Fully Connected). It supports GPU and is thus, ideally suited for production environments involving deep neural networks. It also supports CPU-based kernel libraries such as NVIDIA, CUDA Deep Neural Network library (cuDNN) and Intel Math Kernel Library (Intel MKL).
In April 2017, U.S. based social networking service company Facebook announced Caffe2, which now includes RNN (Recurrent Neural Networks) and in March 2018, Caffe2 was merged into PyTorch. Caffe2 creators and community members have created models for solving various problems. These models are available to the public as pre-trained models. Caffe2 helps the creators in using these models and creating one’s own network for making predictions on the dataset.
Before we go into the details of Caffe2, let us understand the difference between machine learning and deep learning. This is necessary to understand how models are created and used in Caffe2.
In any machine learning algorithm, be it a traditional one or a deep learning one, the selection of features in the dataset plays an extremely important role in getting the desired prediction accuracy. In traditional machine learning techniques, the feature selection is done mostly by human inspection, judgement and deep domain knowledge. Sometimes, you may seek help from a few tested algorithms for feature selection.
The traditional machine learning flow is depicted in the figure below −
In deep learning, the feature selection is automatic and is a part of deep learning algorithm itself. This is shown in the figure below −
In deep learning algorithms, feature engineering is done automatically. Generally, feature engineering is time-consuming and requires a good expertise in domain. To implement the automatic feature extraction, the deep learning algorithms typically ask for huge amount of data, so if you have only thousands and tens of thousands of data points, the deep learning technique may fail to give you satisfactory results.
With larger data, the deep learning algorithms produce better results compared to traditional ML algorithms with an added advantage of less or no feature engineering.
Now, as you have got some insights into deep learning, let us get an overview of what is Caffe.
Let us learn the process for training a CNN for classifying images. The process consists of the following steps −
Data Preparation − In this step, we center-crop the images and resize them so that all images for training and testing would be of the same size. This is usually done by running a small Python script on the image data.
Data Preparation − In this step, we center-crop the images and resize them so that all images for training and testing would be of the same size. This is usually done by running a small Python script on the image data.
Model Definition − In this step, we define a CNN architecture. The configuration is stored in .pb (protobuf) file. A typical CNN architecture is shown in figure below.
Model Definition − In this step, we define a CNN architecture. The configuration is stored in .pb (protobuf) file. A typical CNN architecture is shown in figure below.
Solver Definition − We define the solver configuration file. Solver does the model optimization.
Solver Definition − We define the solver configuration file. Solver does the model optimization.
Model Training − We use the built-in Caffe utility to train the model. The training may take a considerable amount of time and CPU usage. After the training is completed, Caffe stores the model in a file, which can later on be used on test data and final deployment for predictions.
Model Training − We use the built-in Caffe utility to train the model. The training may take a considerable amount of time and CPU usage. After the training is completed, Caffe stores the model in a file, which can later on be used on test data and final deployment for predictions.
In Caffe2, you would find many ready-to-use pre-trained models and also leverage the community contributions of new models and algorithms quite frequently. The models that you create can scale up easily using the GPU power in the cloud and also can be brought down to the use of masses on mobile with its cross-platform libraries.
The improvements made in Caffe2 over Caffe may be summarized as follows −
Mobile deployment
New hardware support
Support for large-scale distributed training
Quantized computation
Stress tested on Facebook
The Berkeley Vision and Learning Center (BVLC) site provides demos of their pre- trained networks. One such network for image classification is available on the link stated herewith https://caffe2.ai/docs/learn-more#null__caffe-neural-network-for-image-classification and is depicted in the screenshot below.
In the screenshot, the image of a dog is classified and labelled with its prediction accuracy. It also says that it took just 0.068 seconds to classify the image. You may try an image of your own choice by specifying the image URL or uploading the image itself in the options given at the bottom of the screen.
Now, that you have got enough insights on the capabilities of Caffe2, it is time to experiment Caffe2 on your own. To use the pre-trained models or to develop your models in your own Python code, you must first install Caffe2 on your machine.
On the installation page of Caffe2 site which is available at the link https://caffe2.ai/docs/getting-started.html you would see the following to select your platform and install type.
As you can see in the above screenshot, Caffe2 supports several popular platforms including the mobile ones.
Now, we shall understand the steps for MacOS installation on which all the projects in this tutorial are tested.
The installation can be of four types as given below −
Pre-Built Binaries
Build From Source
Docker Images
Cloud
Depending upon your preference, select any of the above as your installation type. The instructions given here are as per the Caffe2 installation site for pre-built binaries. It uses Anaconda for Jupyter environment. Execute the following command on your console prompt
pip install torch_nightly -f
https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html
In addition to the above, you will need a few third-party libraries, which are installed using the following commands −
conda install -c anaconda setuptools
conda install -c conda-forge graphviz
conda install -c conda-forge hypothesis
conda install -c conda-forge ipython
conda install -c conda-forge jupyter
conda install -c conda-forge matplotlib
conda install -c anaconda notebook
conda install -c anaconda pydot
conda install -c conda-forge python-nvd3
conda install -c anaconda pyyaml
conda install -c anaconda requests
conda install -c anaconda scikit-image
conda install -c anaconda scipy
Some of the tutorials in the Caffe2 website also require the installation of zeromq, which is installed using the following command −
conda install -c anaconda zeromq
Execute the following command on your console prompt −
conda install -c pytorch pytorch-nightly-cpu
As you must have noticed, you would need Anaconda to use the above installation. You will need to install the additional packages as specified in the MacOS installation.
To test your installation, a small Python script is given below, which you can cut and paste in your Juypter project and execute.
from caffe2.python import workspace
import numpy as np
print ("Creating random data")
data = np.random.rand(3, 2)
print(data)
print ("Adding data to workspace ...")
workspace.FeedBlob("mydata", data)
print ("Retrieving data from workspace")
mydata = workspace.FetchBlob("mydata")
print(mydata)
When you execute the above code, you should see the following output −
Creating random data
[[0.06152718 0.86448082]
[0.36409966 0.52786113]
[0.65780886 0.67101053]]
Adding data to workspace ...
Retrieving data from workspace
[[0.06152718 0.86448082]
[0.36409966 0.52786113]
[0.65780886 0.67101053]]
The screenshot of the installation test page is shown here for your quick reference −
Now, that you have installed Caffe2 on your machine, proceed to install the tutorial applications.
Download the tutorials source using the following command on your console −
git clone --recursive https://github.com/caffe2/tutorials caffe2_tutorials
After the download is completed, you will find several Python projects in the caffe2_tutorials folder in your installation directory. The screenshot of this folder is given for your quick perusal.
/Users/yourusername/caffe2_tutorials
You can open some of these tutorials to see what the Caffe2 code looks like. The next two projects described in this tutorial are largely based on the samples shown above.
It is now time to do some Python coding of our own. Let us understand, how to use a pre-trained model from Caffe2. Later, you will learn to create your own trivial neural network for training on your own dataset.
Before you learn to use a pre-trained model in your Python application, let us first verify that the models are installed on your machine and are accessible through the Python code.
When you install Caffe2, the pre-trained models are copied in the installation folder. On the machine with Anaconda installation, these models are available in the following folder.
anaconda3/lib/python3.7/site-packages/caffe2/python/models
Check out the installation folder on your machine for the presence of these models. You can try loading these models from the installation folder with the following short Python script −
CAFFE_MODELS = os.path.expanduser("/anaconda3/lib/python3.7/site-packages/caffe2/python/models")
INIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')
PREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')
print(INIT_NET)
print(PREDICT_NET)
When the script runs successfully, you will see the following output −
/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/init_net.pb
/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/predict_net.pb
This confirms that the squeezenet module is installed on your machine and is accessible to your code.
Now, you are ready to write your own Python code for image classification using Caffe2 squeezenet pre-trained module.
In this lesson, you will learn to use a pre-trained model to detect objects in a given image. You will use squeezenet pre-trained module that detects and classifies the objects in a given image with a great accuracy.
Open a new Juypter notebook and follow the steps to develop this image classification application.
First, we import the required packages using the below code −
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace, models
import numpy as np
import skimage.io
import skimage.transform
from matplotlib import pyplot
import os
import urllib.request as urllib2
import operator
Next, we set up a few variables −
INPUT_IMAGE_SIZE = 227
mean = 128
The images used for training will obviously be of varied sizes. All these images must be converted into a fixed size for accurate training. Likewise, the test images and the image which you want to predict in the production environment must also be converted to the size, the same as the one used during training. Thus, we create a variable above called INPUT_IMAGE_SIZE having value 227. Hence, we will convert all our images to the size 227x227 before using it in our classifier.
We also declare a variable called mean having value 128, which is used later for improving the classification results.
Next, we will develop two functions for processing the image.
The image processing consists of two steps. First one is to resize the image, and the second one is to centrally crop the image. For these two steps, we will write two functions for resizing and cropping.
First, we will write a function for resizing the image. As said earlier, we will resize the image to 227x227. So let us define the function resize as follows −
def resize(img, input_height, input_width):
We obtain the aspect ratio of the image by dividing the width by the height.
original_aspect = img.shape[1]/float(img.shape[0])
If the aspect ratio is greater than 1, it indicates that the image is wide, that to say it is in the landscape mode. We now adjust the image height and return the resized image using the following code −
if(original_aspect>1):
new_height = int(original_aspect * input_height)
return skimage.transform.resize(img, (input_width,
new_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
If the aspect ratio is less than 1, it indicates the portrait mode. We now adjust the width using the following code −
if(original_aspect<1):
new_width = int(input_width/original_aspect)
return skimage.transform.resize(img, (new_width,
input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
If the aspect ratio equals 1, we do not make any height/width adjustments.
if(original_aspect == 1):
return skimage.transform.resize(img, (input_width,
input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
The full function code is given below for your quick reference −
def resize(img, input_height, input_width):
original_aspect = img.shape[1]/float(img.shape[0])
if(original_aspect>1):
new_height = int(original_aspect * input_height)
return skimage.transform.resize(img, (input_width,
new_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
if(original_aspect<1):
new_width = int(input_width/original_aspect)
return skimage.transform.resize(img, (new_width,
input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
if(original_aspect == 1):
return skimage.transform.resize(img, (input_width,
input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
We will now write a function for cropping the image around its center.
We declare the crop_image function as follows −
def crop_image(img,cropx,cropy):
We extract the dimensions of the image using the following statement −
y,x,c = img.shape
We create a new starting point for the image using the following two lines of code −
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
Finally, we return the cropped image by creating an image object with the new dimensions −
return img[starty:starty+cropy,startx:startx+cropx]
The entire function code is given below for your quick reference −
def crop_image(img,cropx,cropy):
y,x,c = img.shape
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return img[starty:starty+cropy,startx:startx+cropx]
Now, we will write code to test these functions.
Firstly, copy an image file into images subfolder within your project directory. tree.jpg file is copied in the project. The following Python code loads the image and displays it on the console −
img = skimage.img_as_float(skimage.io.imread("images/tree.jpg")).astype(np.float32)
print("Original Image Shape: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Original image')
The output is as follows −
Note that size of the original image is 600 x 960. We need to resize this to our specification of 227 x 227. Calling our earlier-defined resizefunction does this job.
img = resize(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)
print("Image Shape after resizing: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Resized image')
The output is as given below −
Note that now the image size is 227 x 363. We need to crop this to 227 x 227 for the final feed to our algorithm. We call the previously-defined crop function for this purpose.
img = crop_image(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)
print("Image Shape after cropping: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Center Cropped')
Below mentioned is the output of the code −
At this point, the image is of size 227 x 227 and is ready for further processing. We now swap the image axes to extract the three colours into three different zones.
img = img.swapaxes(1, 2).swapaxes(0, 1)
print("CHW Image Shape: " , img.shape)
Given below is the output −
CHW Image Shape: (3, 227, 227)
Note that the last axis has now become the first dimension in the array. We will now plot the three channels using the following code −
pyplot.figure()
for i in range(3):
pyplot.subplot(1, 3, i+1)
pyplot.imshow(img[i])
pyplot.axis('off')
pyplot.title('RGB channel %d' % (i+1))
The output is stated below −
Finally, we do some additional processing on the image such as converting Red Green Blue to Blue Green Red (RGB to BGR), removing mean for better results and adding batch size axis using the following three lines of code −
# convert RGB --> BGR
img = img[(2, 1, 0), :, :]
# remove mean
img = img * 255 - mean
# add batch size axis
img = img[np.newaxis, :, :, :].astype(np.float32)
At this point, your image is in NCHW format and is ready for feeding into our network. Next, we will load our pre-trained model files and feed the above image into it for prediction.
We first setup the paths for the init and predict networks defined in the pre-trained models of Caffe.
Remember from our earlier discussion, all the pre-trained models are installed in the models folder. We set up the path to this folder as follows −
CAFFE_MODELS = os.path.expanduser("/anaconda3/lib/python3.7/site-packages/caffe2/python/models")
We set up the path to the init_net protobuf file of the squeezenet model as follows −
INIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')
Likewise, we set up the path to the predict_net protobuf as follows −
PREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')
We print the two paths for diagnosis purpose −
print(INIT_NET)
print(PREDICT_NET)
The above code along with the output is given here for your quick reference −
CAFFE_MODELS = os.path.expanduser("/anaconda3/lib/python3.7/site-packages/caffe2/python/models")
INIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')
PREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')
print(INIT_NET)
print(PREDICT_NET)
The output is mentioned below −
/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/init_net.pb
/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/predict_net.pb
Next, we will create a predictor.
We read the model files using the following two statements −
with open(INIT_NET, "rb") as f:
init_net = f.read()
with open(PREDICT_NET, "rb") as f:
predict_net = f.read()
The predictor is created by passing pointers to the two files as parameters to the Predictor function.
p = workspace.Predictor(init_net, predict_net)
The p object is the predictor, which is used for predicting the objects in any given image. Note that each input image must be in NCHW format as what we have done earlier to our tree.jpg file.
To predict the objects in a given image is trivial - just executing a single line of command. We call run method on the predictor object for an object detection in a given image.
results = p.run({'data': img})
The prediction results are now available in the results object, which we convert to an array for our readability.
results = np.asarray(results)
Print the dimensions of the array for your understanding using the following statement −
print("results shape: ", results.shape)
The output is as shown below −
results shape: (1, 1, 1000, 1, 1)
We will now remove the unnecessary axis −
preds = np.squeeze(results)
The topmost predication can now be retrieved by taking the max value in the preds array.
curr_pred, curr_conf = max(enumerate(preds), key=operator.itemgetter(1))
print("Prediction: ", curr_pred)
print("Confidence: ", curr_conf)
The output is as follows −
Prediction: 984
Confidence: 0.89235985
As you see the model has predicted an object with an index value 984 with 89% confidence. The index of 984 does not make much sense to us in understanding what kind of object is detected. We need to get the stringified name for the object using its index value. The kind of objects that the model recognizes along with their corresponding index values are available on a github repository.
Now, we will see how to retrieve the name for our object having index value of 984.
We create a URL object to the github repository as follows −
codes = "https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac0
71eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes"
We read the contents of the URL −
response = urllib2.urlopen(codes)
The response will contain a list of all codes and its descriptions. Few lines of the response are shown below for your understanding of what it contains −
5: 'electric ray, crampfish, numbfish, torpedo',
6: 'stingray',
7: 'cock',
8: 'hen',
9: 'ostrich, Struthio camelus',
10: 'brambling, Fringilla montifringilla',
We now iterate the entire array to locate our desired code of 984 using a for loop as follows −
for line in response:
mystring = line.decode('ascii')
code, result = mystring.partition(":")[::2]
code = code.strip()
result = result.replace("'", "")
if (code == str(curr_pred)):
name = result.split(",")[0][1:]
print("Model predicts", name, "with", curr_conf, "confidence")
When you run the code, you will see the following output −
Model predicts rapeseed with 0.89235985 confidence
You may now try the model on another image.
To predict another image, simply copy the image file into the images folder of your project directory. This is the directory in which our earlier tree.jpg file is stored. Change the name of the image file in the code. Only one change is required as shown below
img = skimage.img_as_float(skimage.io.imread("images/pretzel.jpg")).astype(np.float32)
The original picture and the prediction result are shown below −
The output is mentioned below −
Model predicts pretzel with 0.99999976 confidence
As you see the pre-trained model is able to detect objects in a given image with a great amount of accuracy.
The full source for the above code that uses a pre-trained model for object detection in a given image is mentioned here for your quick reference −
def crop_image(img,cropx,cropy):
y,x,c = img.shape
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return img[starty:starty+cropy,startx:startx+cropx]
img = skimage.img_as_float(skimage.io.imread("images/pretzel.jpg")).astype(np.float32)
print("Original Image Shape: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Original image')
img = resize(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)
print("Image Shape after resizing: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Resized image')
img = crop_image(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)
print("Image Shape after cropping: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Center Cropped')
img = img.swapaxes(1, 2).swapaxes(0, 1)
print("CHW Image Shape: " , img.shape)
pyplot.figure()
for i in range(3):
pyplot.subplot(1, 3, i+1)
pyplot.imshow(img[i])
pyplot.axis('off')
pyplot.title('RGB channel %d' % (i+1))
# convert RGB --> BGR
img = img[(2, 1, 0), :, :]
# remove mean
img = img * 255 - mean
# add batch size axis
img = img[np.newaxis, :, :, :].astype(np.float32)
CAFFE_MODELS = os.path.expanduser("/anaconda3/lib/python3.7/site-packages/caffe2/python/models")
INIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')
PREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')
print(INIT_NET)
print(PREDICT_NET)
with open(INIT_NET, "rb") as f:
init_net = f.read()
with open(PREDICT_NET, "rb") as f:
predict_net = f.read()
p = workspace.Predictor(init_net, predict_net)
results = p.run({'data': img})
results = np.asarray(results)
print("results shape: ", results.shape)
preds = np.squeeze(results)
curr_pred, curr_conf = max(enumerate(preds), key=operator.itemgetter(1))
print("Prediction: ", curr_pred)
print("Confidence: ", curr_conf)
codes = "https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac071eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes"
response = urllib2.urlopen(codes)
for line in response:
mystring = line.decode('ascii')
code, result = mystring.partition(":")[::2]
code = code.strip()
result = result.replace("'", "")
if (code == str(curr_pred)):
name = result.split(",")[0][1:]
print("Model predicts", name, "with", curr_conf, "confidence")
By this time, you know how to use a pre-trained model for doing the predictions on your dataset.
What’s next is to learn how to define your neural network (NN) architectures in Caffe2 and train them on your dataset. We will now learn how to create a trivial single layer NN.
In this lesson, you will learn to define a single layer neural network (NN) in Caffe2 and run it on a randomly generated dataset. We will write code to graphically depict the network architecture, print input, output, weights, and bias values. To understand this lesson, you must be familiar with neural network architectures, its terms and mathematics used in them.
Let us consider that we want to build a single layer NN as shown in the figure below −
Mathematically, this network is represented by the following Python code −
Y = X * W^T + b
Where X, W, b are tensors and Y is the output. We will fill all three tensors with some random data, run the network and examine the Y output. To define the network and tensors, Caffe2 provides several Operator functions.
In Caffe2, Operator is the basic unit of computation. The Caffe2 Operator is represented as follows.
Caffe2 provides an exhaustive list of operators. For the network that we are designing currently, we will use the operator called FC, which computes the result of passing an input vector X into a fully connected network with a two-dimensional weight matrix W and a single-dimensional bias vector b. In other words, it computes the following mathematical equation
Y = X * W^T + b
Where X has dimensions (M x k), W has dimensions (n x k) and b is (1 x n). The output Y will be of dimension (M x n), where M is the batch size.
For the vectors X and W, we will use the GaussianFill operator to create some random data. For generating bias values b, we will use ConstantFill operator.
We will now proceed to define our network.
First of all, import the required packages −
from caffe2.python import core, workspace
Next, define the network by calling core.Net as follows −
net = core.Net("SingleLayerFC")
The name of the network is specified as SingleLayerFC. At this point, the network object called net is created. It does not contain any layers so far.
We will now create the three vectors required by our network. First, we will create X tensor by calling GaussianFill operator as follows −
X = net.GaussianFill([], ["X"], mean=0.0, std=1.0, shape=[2, 3], run_once=0)
The X vector has dimensions 2 x 3 with the mean data value of 0,0 and standard deviation of 1.0.
Likewise, we create W tensor as follows −
W = net.GaussianFill([], ["W"], mean=0.0, std=1.0, shape=[5, 3], run_once=0)
The W vector is of size 5 x 3.
Finally, we create bias b matrix of size 5.
b = net.ConstantFill([], ["b"], shape=[5,], value=1.0, run_once=0)
Now, comes the most important part of the code and that is defining the network itself.
We define the network in the following Python statement −
Y = X.FC([W, b], ["Y"])
We call FC operator on the input data X. The weights are specified in W and bias in b. The output is Y. Alternatively, you may create the network using the following Python statement, which is more verbose.
Y = net.FC([X, W, b], ["Y"])
At this point, the network is simply created. Until we run the network at least once, it will not contain any data. Before running the network, we will examine its architecture.
Caffe2 defines the network architecture in a JSON file, which can be examined by calling the Proto method on the created net object.
print (net.Proto())
This produces the following output −
name: "SingleLayerFC"
op {
output: "X"
name: ""
type: "GaussianFill"
arg {
name: "mean"
f: 0.0
}
arg {
name: "std"
f: 1.0
}
arg {
name: "shape"
ints: 2
ints: 3
}
arg {
name: "run_once"
i: 0
}
}
op {
output: "W"
name: ""
type: "GaussianFill"
arg {
name: "mean"
f: 0.0
}
arg {
name: "std"
f: 1.0
}
arg {
name: "shape"
ints: 5
ints: 3
}
arg {
name: "run_once"
i: 0
}
}
op {
output: "b"
name: ""
type: "ConstantFill"
arg {
name: "shape"
ints: 5
}
arg {
name: "value"
f: 1.0
}
arg {
name: "run_once"
i: 0
}
}
op {
input: "X"
input: "W"
input: "b"
output: "Y"
name: ""
type: "FC"
}
As you can see in the above listing, it first defines the operators X, W and b. Let us examine the definition of W as an example. The type of W is specified as GausianFill. The mean is defined as float 0.0, the standard deviation is defined as float 1.0, and the shape is 5 x 3.
op {
output: "W"
name: "" type: "GaussianFill"
arg {
name: "mean"
f: 0.0
}
arg {
name: "std"
f: 1.0
}
arg {
name: "shape"
ints: 5
ints: 3
}
...
}
Examine the definitions of X and b for your own understanding. Finally, let us look at the definition of our single layer network, which is reproduced here
op {
input: "X"
input: "W"
input: "b"
output: "Y"
name: ""
type: "FC"
}
Here, the network type is FC (Fully Connected) with X, W, b as inputs and Y is the output. This network definition is too verbose and for large networks, it will become tedious to examine its contents. Fortunately, Caffe2 provides a graphical representation for the created networks.
To get the graphical representation of the network, run the following code snippet, which is essentially only two lines of Python code.
from caffe2.python import net_drawer
from IPython import display
graph = net_drawer.GetPydotGraph(net, rankdir="LR")
display.Image(graph.create_png(), width=800)
When you run the code, you will see the following output −
For large networks, the graphical representation becomes extremely useful in visualizing and debugging network definition errors.
Finally, it is now time to run the network.
You run the network by calling the RunNetOnce method on the workspace object −
workspace.RunNetOnce(net)
After the network is run once, all our data that is generated at random would be created, fed into the network and the output will be created. The tensors which are created after running the network are called blobs in Caffe2. The workspace consists of the blobs you create and store in memory. This is quite similar to Matlab.
After running the network, you can examine the blobs that the workspace contains using the following print command
print("Blobs in the workspace: {}".format(workspace.Blobs()))
You will see the following output −
Blobs in the workspace: ['W', 'X', 'Y', 'b']
Note that the workspace consists of three input blobs − X, W and b. It also contains the output blob called Y. Let us now examine the contents of these blobs.
for name in workspace.Blobs():
print("{}:\n{}".format(name, workspace.FetchBlob(name)))
You will see the following output −
W:
[[ 1.0426593 0.15479846 0.25635982]
[-2.2461145 1.4581774 0.16827184]
[-0.12009818 0.30771437 0.00791338]
[ 1.2274994 -0.903331 -0.68799865]
[ 0.30834186 -0.53060573 0.88776857]]
X:
[[ 1.6588869e+00 1.5279824e+00 1.1889904e+00]
[ 6.7048723e-01 -9.7490678e-04 2.5114202e-01]]
Y:
[[ 3.2709925 -0.297907 1.2803618 0.837985 1.7562964]
[ 1.7633215 -0.4651525 0.9211631 1.6511179 1.4302125]]
b:
[1. 1. 1. 1. 1.]
Note that the data on your machine or as a matter of fact on every run of the network would be different as all inputs are created at random. You have now successfully defined a network and run it on your computer.
In the previous lesson, you learned to create a trivial network and learned how to execute it and examine its output. The process for creating complex networks is similar to the process described above. Caffe2 provides a huge set of operators for creating complex architectures. You are encouraged to examine the Caffe2 documentation for a list of operators. After studying the purpose of various operators, you would be in a position to create complex networks and train them. For training the network, Caffe2 provides several predefined computation units - that is the operators. You will need to select the appropriate operators for training your network for the kind of problem that you are trying to solve.
Once a network is trained to your satisfaction, you can store it in a model file similar to the pre-trained model files you used earlier. These trained models may be contributed to Caffe2 repository for the benefits of other users. Or you may simply put the trained model for your own private production use.
Caffe2, which is a deep learning framework allows you to experiment with several kinds of neural networks for predicting your data. Caffe2 site provides many pre-trained models. You learned to use one of the pre-trained models for classifying objects in a given image. You also learned to define a neural network architecture of your choice. Such custom networks can be trained using many predefined operators in Caffe. A trained model is stored in a file which can be taken into a production environment.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2112,
"s": 1791,
"text": "Last couple of years, Deep Learning has become a big trend in Machine Learning. It has been successfully applied to solve previously unsolvable problems in Vision, Speech Recognition and Natural Language Processing (NLP). There are many more domains in which Deep Learning is being applied and has shown its usefulness."
},
{
"code": null,
"e": 2490,
"s": 2112,
"text": "Caffe (Convolutional Architecture for Fast Feature Embedding) is a deep learning framework developed at Berkeley Vision and Learning Center (BVLC). The Caffe project was created by Yangqing Jia during his Ph.D. at University of California - Berkeley. Caffe provides an easy way to experiment with deep learning. It is written in C++ and provides bindings for Python and Matlab."
},
{
"code": null,
"e": 2902,
"s": 2490,
"text": "It supports many different types of deep learning architectures such as CNN (Convolutional Neural Network), LSTM (Long Short Term Memory) and FC (Fully Connected). It supports GPU and is thus, ideally suited for production environments involving deep neural networks. It also supports CPU-based kernel libraries such as NVIDIA, CUDA Deep Neural Network library (cuDNN) and Intel Math Kernel Library (Intel MKL)."
},
{
"code": null,
"e": 3361,
"s": 2902,
"text": "In April 2017, U.S. based social networking service company Facebook announced Caffe2, which now includes RNN (Recurrent Neural Networks) and in March 2018, Caffe2 was merged into PyTorch. Caffe2 creators and community members have created models for solving various problems. These models are available to the public as pre-trained models. Caffe2 helps the creators in using these models and creating one’s own network for making predictions on the dataset."
},
{
"code": null,
"e": 3554,
"s": 3361,
"text": "Before we go into the details of Caffe2, let us understand the difference between machine learning and deep learning. This is necessary to understand how models are created and used in Caffe2."
},
{
"code": null,
"e": 3976,
"s": 3554,
"text": "In any machine learning algorithm, be it a traditional one or a deep learning one, the selection of features in the dataset plays an extremely important role in getting the desired prediction accuracy. In traditional machine learning techniques, the feature selection is done mostly by human inspection, judgement and deep domain knowledge. Sometimes, you may seek help from a few tested algorithms for feature selection."
},
{
"code": null,
"e": 4048,
"s": 3976,
"text": "The traditional machine learning flow is depicted in the figure below −"
},
{
"code": null,
"e": 4186,
"s": 4048,
"text": "In deep learning, the feature selection is automatic and is a part of deep learning algorithm itself. This is shown in the figure below −"
},
{
"code": null,
"e": 4602,
"s": 4186,
"text": "In deep learning algorithms, feature engineering is done automatically. Generally, feature engineering is time-consuming and requires a good expertise in domain. To implement the automatic feature extraction, the deep learning algorithms typically ask for huge amount of data, so if you have only thousands and tens of thousands of data points, the deep learning technique may fail to give you satisfactory results."
},
{
"code": null,
"e": 4769,
"s": 4602,
"text": "With larger data, the deep learning algorithms produce better results compared to traditional ML algorithms with an added advantage of less or no feature engineering."
},
{
"code": null,
"e": 4865,
"s": 4769,
"text": "Now, as you have got some insights into deep learning, let us get an overview of what is Caffe."
},
{
"code": null,
"e": 4979,
"s": 4865,
"text": "Let us learn the process for training a CNN for classifying images. The process consists of the following steps −"
},
{
"code": null,
"e": 5198,
"s": 4979,
"text": "Data Preparation − In this step, we center-crop the images and resize them so that all images for training and testing would be of the same size. This is usually done by running a small Python script on the image data."
},
{
"code": null,
"e": 5417,
"s": 5198,
"text": "Data Preparation − In this step, we center-crop the images and resize them so that all images for training and testing would be of the same size. This is usually done by running a small Python script on the image data."
},
{
"code": null,
"e": 5585,
"s": 5417,
"text": "Model Definition − In this step, we define a CNN architecture. The configuration is stored in .pb (protobuf) file. A typical CNN architecture is shown in figure below."
},
{
"code": null,
"e": 5753,
"s": 5585,
"text": "Model Definition − In this step, we define a CNN architecture. The configuration is stored in .pb (protobuf) file. A typical CNN architecture is shown in figure below."
},
{
"code": null,
"e": 5850,
"s": 5753,
"text": "Solver Definition − We define the solver configuration file. Solver does the model optimization."
},
{
"code": null,
"e": 5947,
"s": 5850,
"text": "Solver Definition − We define the solver configuration file. Solver does the model optimization."
},
{
"code": null,
"e": 6230,
"s": 5947,
"text": "Model Training − We use the built-in Caffe utility to train the model. The training may take a considerable amount of time and CPU usage. After the training is completed, Caffe stores the model in a file, which can later on be used on test data and final deployment for predictions."
},
{
"code": null,
"e": 6513,
"s": 6230,
"text": "Model Training − We use the built-in Caffe utility to train the model. The training may take a considerable amount of time and CPU usage. After the training is completed, Caffe stores the model in a file, which can later on be used on test data and final deployment for predictions."
},
{
"code": null,
"e": 6844,
"s": 6513,
"text": "In Caffe2, you would find many ready-to-use pre-trained models and also leverage the community contributions of new models and algorithms quite frequently. The models that you create can scale up easily using the GPU power in the cloud and also can be brought down to the use of masses on mobile with its cross-platform libraries."
},
{
"code": null,
"e": 6918,
"s": 6844,
"text": "The improvements made in Caffe2 over Caffe may be summarized as follows −"
},
{
"code": null,
"e": 6936,
"s": 6918,
"text": "Mobile deployment"
},
{
"code": null,
"e": 6957,
"s": 6936,
"text": "New hardware support"
},
{
"code": null,
"e": 7002,
"s": 6957,
"text": "Support for large-scale distributed training"
},
{
"code": null,
"e": 7024,
"s": 7002,
"text": "Quantized computation"
},
{
"code": null,
"e": 7050,
"s": 7024,
"text": "Stress tested on Facebook"
},
{
"code": null,
"e": 7360,
"s": 7050,
"text": "The Berkeley Vision and Learning Center (BVLC) site provides demos of their pre- trained networks. One such network for image classification is available on the link stated herewith https://caffe2.ai/docs/learn-more#null__caffe-neural-network-for-image-classification and is depicted in the screenshot below."
},
{
"code": null,
"e": 7671,
"s": 7360,
"text": "In the screenshot, the image of a dog is classified and labelled with its prediction accuracy. It also says that it took just 0.068 seconds to classify the image. You may try an image of your own choice by specifying the image URL or uploading the image itself in the options given at the bottom of the screen."
},
{
"code": null,
"e": 7914,
"s": 7671,
"text": "Now, that you have got enough insights on the capabilities of Caffe2, it is time to experiment Caffe2 on your own. To use the pre-trained models or to develop your models in your own Python code, you must first install Caffe2 on your machine."
},
{
"code": null,
"e": 8100,
"s": 7914,
"text": "On the installation page of Caffe2 site which is available at the link https://caffe2.ai/docs/getting-started.html you would see the following to select your platform and install type."
},
{
"code": null,
"e": 8209,
"s": 8100,
"text": "As you can see in the above screenshot, Caffe2 supports several popular platforms including the mobile ones."
},
{
"code": null,
"e": 8322,
"s": 8209,
"text": "Now, we shall understand the steps for MacOS installation on which all the projects in this tutorial are tested."
},
{
"code": null,
"e": 8377,
"s": 8322,
"text": "The installation can be of four types as given below −"
},
{
"code": null,
"e": 8396,
"s": 8377,
"text": "Pre-Built Binaries"
},
{
"code": null,
"e": 8414,
"s": 8396,
"text": "Build From Source"
},
{
"code": null,
"e": 8428,
"s": 8414,
"text": "Docker Images"
},
{
"code": null,
"e": 8434,
"s": 8428,
"text": "Cloud"
},
{
"code": null,
"e": 8704,
"s": 8434,
"text": "Depending upon your preference, select any of the above as your installation type. The instructions given here are as per the Caffe2 installation site for pre-built binaries. It uses Anaconda for Jupyter environment. Execute the following command on your console prompt"
},
{
"code": null,
"e": 8799,
"s": 8704,
"text": "pip install torch_nightly -f \nhttps://download.pytorch.org/whl/nightly/cpu/torch_nightly.html\n"
},
{
"code": null,
"e": 8919,
"s": 8799,
"text": "In addition to the above, you will need a few third-party libraries, which are installed using the following commands −"
},
{
"code": null,
"e": 9398,
"s": 8919,
"text": "conda install -c anaconda setuptools\nconda install -c conda-forge graphviz \nconda install -c conda-forge hypothesis\nconda install -c conda-forge ipython\nconda install -c conda-forge jupyter\nconda install -c conda-forge matplotlib\nconda install -c anaconda notebook\nconda install -c anaconda pydot\nconda install -c conda-forge python-nvd3\nconda install -c anaconda pyyaml\nconda install -c anaconda requests\nconda install -c anaconda scikit-image\nconda install -c anaconda scipy\n"
},
{
"code": null,
"e": 9532,
"s": 9398,
"text": "Some of the tutorials in the Caffe2 website also require the installation of zeromq, which is installed using the following command −"
},
{
"code": null,
"e": 9566,
"s": 9532,
"text": "conda install -c anaconda zeromq\n"
},
{
"code": null,
"e": 9621,
"s": 9566,
"text": "Execute the following command on your console prompt −"
},
{
"code": null,
"e": 9667,
"s": 9621,
"text": "conda install -c pytorch pytorch-nightly-cpu\n"
},
{
"code": null,
"e": 9837,
"s": 9667,
"text": "As you must have noticed, you would need Anaconda to use the above installation. You will need to install the additional packages as specified in the MacOS installation."
},
{
"code": null,
"e": 9967,
"s": 9837,
"text": "To test your installation, a small Python script is given below, which you can cut and paste in your Juypter project and execute."
},
{
"code": null,
"e": 10262,
"s": 9967,
"text": "from caffe2.python import workspace\nimport numpy as np\nprint (\"Creating random data\")\ndata = np.random.rand(3, 2)\nprint(data)\nprint (\"Adding data to workspace ...\")\nworkspace.FeedBlob(\"mydata\", data)\nprint (\"Retrieving data from workspace\")\nmydata = workspace.FetchBlob(\"mydata\")\nprint(mydata)\n"
},
{
"code": null,
"e": 10333,
"s": 10262,
"text": "When you execute the above code, you should see the following output −"
},
{
"code": null,
"e": 10563,
"s": 10333,
"text": "Creating random data\n[[0.06152718 0.86448082]\n[0.36409966 0.52786113]\n[0.65780886 0.67101053]]\nAdding data to workspace ...\nRetrieving data from workspace\n[[0.06152718 0.86448082]\n[0.36409966 0.52786113]\n[0.65780886 0.67101053]]\n"
},
{
"code": null,
"e": 10649,
"s": 10563,
"text": "The screenshot of the installation test page is shown here for your quick reference −"
},
{
"code": null,
"e": 10748,
"s": 10649,
"text": "Now, that you have installed Caffe2 on your machine, proceed to install the tutorial applications."
},
{
"code": null,
"e": 10824,
"s": 10748,
"text": "Download the tutorials source using the following command on your console −"
},
{
"code": null,
"e": 10900,
"s": 10824,
"text": "git clone --recursive https://github.com/caffe2/tutorials caffe2_tutorials\n"
},
{
"code": null,
"e": 11097,
"s": 10900,
"text": "After the download is completed, you will find several Python projects in the caffe2_tutorials folder in your installation directory. The screenshot of this folder is given for your quick perusal."
},
{
"code": null,
"e": 11135,
"s": 11097,
"text": "/Users/yourusername/caffe2_tutorials\n"
},
{
"code": null,
"e": 11307,
"s": 11135,
"text": "You can open some of these tutorials to see what the Caffe2 code looks like. The next two projects described in this tutorial are largely based on the samples shown above."
},
{
"code": null,
"e": 11520,
"s": 11307,
"text": "It is now time to do some Python coding of our own. Let us understand, how to use a pre-trained model from Caffe2. Later, you will learn to create your own trivial neural network for training on your own dataset."
},
{
"code": null,
"e": 11702,
"s": 11520,
"text": "Before you learn to use a pre-trained model in your Python application, let us first verify that the models are installed on your machine and are accessible through the Python code."
},
{
"code": null,
"e": 11884,
"s": 11702,
"text": "When you install Caffe2, the pre-trained models are copied in the installation folder. On the machine with Anaconda installation, these models are available in the following folder."
},
{
"code": null,
"e": 11944,
"s": 11884,
"text": "anaconda3/lib/python3.7/site-packages/caffe2/python/models\n"
},
{
"code": null,
"e": 12131,
"s": 11944,
"text": "Check out the installation folder on your machine for the presence of these models. You can try loading these models from the installation folder with the following short Python script −"
},
{
"code": null,
"e": 12404,
"s": 12131,
"text": "CAFFE_MODELS = os.path.expanduser(\"/anaconda3/lib/python3.7/site-packages/caffe2/python/models\")\nINIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')\nPREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')\nprint(INIT_NET)\nprint(PREDICT_NET)\n"
},
{
"code": null,
"e": 12475,
"s": 12404,
"text": "When the script runs successfully, you will see the following output −"
},
{
"code": null,
"e": 12645,
"s": 12475,
"text": "/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/init_net.pb\n/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/predict_net.pb\n"
},
{
"code": null,
"e": 12747,
"s": 12645,
"text": "This confirms that the squeezenet module is installed on your machine and is accessible to your code."
},
{
"code": null,
"e": 12865,
"s": 12747,
"text": "Now, you are ready to write your own Python code for image classification using Caffe2 squeezenet pre-trained module."
},
{
"code": null,
"e": 13082,
"s": 12865,
"text": "In this lesson, you will learn to use a pre-trained model to detect objects in a given image. You will use squeezenet pre-trained module that detects and classifies the objects in a given image with a great accuracy."
},
{
"code": null,
"e": 13181,
"s": 13082,
"text": "Open a new Juypter notebook and follow the steps to develop this image classification application."
},
{
"code": null,
"e": 13243,
"s": 13181,
"text": "First, we import the required packages using the below code −"
},
{
"code": null,
"e": 13481,
"s": 13243,
"text": "from caffe2.proto import caffe2_pb2\nfrom caffe2.python import core, workspace, models\nimport numpy as np\nimport skimage.io\nimport skimage.transform\nfrom matplotlib import pyplot\nimport os\nimport urllib.request as urllib2\nimport operator\n"
},
{
"code": null,
"e": 13515,
"s": 13481,
"text": "Next, we set up a few variables −"
},
{
"code": null,
"e": 13550,
"s": 13515,
"text": "INPUT_IMAGE_SIZE = 227\nmean = 128\n"
},
{
"code": null,
"e": 14032,
"s": 13550,
"text": "The images used for training will obviously be of varied sizes. All these images must be converted into a fixed size for accurate training. Likewise, the test images and the image which you want to predict in the production environment must also be converted to the size, the same as the one used during training. Thus, we create a variable above called INPUT_IMAGE_SIZE having value 227. Hence, we will convert all our images to the size 227x227 before using it in our classifier."
},
{
"code": null,
"e": 14151,
"s": 14032,
"text": "We also declare a variable called mean having value 128, which is used later for improving the classification results."
},
{
"code": null,
"e": 14213,
"s": 14151,
"text": "Next, we will develop two functions for processing the image."
},
{
"code": null,
"e": 14418,
"s": 14213,
"text": "The image processing consists of two steps. First one is to resize the image, and the second one is to centrally crop the image. For these two steps, we will write two functions for resizing and cropping."
},
{
"code": null,
"e": 14578,
"s": 14418,
"text": "First, we will write a function for resizing the image. As said earlier, we will resize the image to 227x227. So let us define the function resize as follows −"
},
{
"code": null,
"e": 14623,
"s": 14578,
"text": "def resize(img, input_height, input_width):\n"
},
{
"code": null,
"e": 14700,
"s": 14623,
"text": "We obtain the aspect ratio of the image by dividing the width by the height."
},
{
"code": null,
"e": 14752,
"s": 14700,
"text": "original_aspect = img.shape[1]/float(img.shape[0])\n"
},
{
"code": null,
"e": 14956,
"s": 14752,
"text": "If the aspect ratio is greater than 1, it indicates that the image is wide, that to say it is in the landscape mode. We now adjust the image height and return the resized image using the following code −"
},
{
"code": null,
"e": 15165,
"s": 14956,
"text": "if(original_aspect>1):\n new_height = int(original_aspect * input_height)\n return skimage.transform.resize(img, (input_width,\n new_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n"
},
{
"code": null,
"e": 15284,
"s": 15165,
"text": "If the aspect ratio is less than 1, it indicates the portrait mode. We now adjust the width using the following code −"
},
{
"code": null,
"e": 15489,
"s": 15284,
"text": "if(original_aspect<1):\n new_width = int(input_width/original_aspect)\n return skimage.transform.resize(img, (new_width,\n input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n"
},
{
"code": null,
"e": 15564,
"s": 15489,
"text": "If the aspect ratio equals 1, we do not make any height/width adjustments."
},
{
"code": null,
"e": 15726,
"s": 15564,
"text": "if(original_aspect == 1):\n return skimage.transform.resize(img, (input_width,\n input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n"
},
{
"code": null,
"e": 15791,
"s": 15726,
"text": "The full function code is given below for your quick reference −"
},
{
"code": null,
"e": 16509,
"s": 15791,
"text": "def resize(img, input_height, input_width):\n original_aspect = img.shape[1]/float(img.shape[0])\n if(original_aspect>1):\n new_height = int(original_aspect * input_height)\n return skimage.transform.resize(img, (input_width,\n\t new_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n if(original_aspect<1):\n new_width = int(input_width/original_aspect)\n return skimage.transform.resize(img, (new_width,\n input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n if(original_aspect == 1):\n return skimage.transform.resize(img, (input_width,\n input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n"
},
{
"code": null,
"e": 16580,
"s": 16509,
"text": "We will now write a function for cropping the image around its center."
},
{
"code": null,
"e": 16628,
"s": 16580,
"text": "We declare the crop_image function as follows −"
},
{
"code": null,
"e": 16662,
"s": 16628,
"text": "def crop_image(img,cropx,cropy):\n"
},
{
"code": null,
"e": 16733,
"s": 16662,
"text": "We extract the dimensions of the image using the following statement −"
},
{
"code": null,
"e": 16752,
"s": 16733,
"text": "y,x,c = img.shape\n"
},
{
"code": null,
"e": 16837,
"s": 16752,
"text": "We create a new starting point for the image using the following two lines of code −"
},
{
"code": null,
"e": 16888,
"s": 16837,
"text": "startx = x//2-(cropx//2)\nstarty = y//2-(cropy//2)\n"
},
{
"code": null,
"e": 16979,
"s": 16888,
"text": "Finally, we return the cropped image by creating an image object with the new dimensions −"
},
{
"code": null,
"e": 17032,
"s": 16979,
"text": "return img[starty:starty+cropy,startx:startx+cropx]\n"
},
{
"code": null,
"e": 17099,
"s": 17032,
"text": "The entire function code is given below for your quick reference −"
},
{
"code": null,
"e": 17265,
"s": 17099,
"text": "def crop_image(img,cropx,cropy):\n y,x,c = img.shape\n startx = x//2-(cropx//2)\n starty = y//2-(cropy//2)\n return img[starty:starty+cropy,startx:startx+cropx]\n"
},
{
"code": null,
"e": 17314,
"s": 17265,
"text": "Now, we will write code to test these functions."
},
{
"code": null,
"e": 17510,
"s": 17314,
"text": "Firstly, copy an image file into images subfolder within your project directory. tree.jpg file is copied in the project. The following Python code loads the image and displays it on the console −"
},
{
"code": null,
"e": 17705,
"s": 17510,
"text": "img = skimage.img_as_float(skimage.io.imread(\"images/tree.jpg\")).astype(np.float32)\nprint(\"Original Image Shape: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Original image')\n"
},
{
"code": null,
"e": 17732,
"s": 17705,
"text": "The output is as follows −"
},
{
"code": null,
"e": 17899,
"s": 17732,
"text": "Note that size of the original image is 600 x 960. We need to resize this to our specification of 227 x 227. Calling our earlier-defined resizefunction does this job."
},
{
"code": null,
"e": 18069,
"s": 17899,
"text": "img = resize(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)\nprint(\"Image Shape after resizing: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Resized image')\n"
},
{
"code": null,
"e": 18100,
"s": 18069,
"text": "The output is as given below −"
},
{
"code": null,
"e": 18277,
"s": 18100,
"text": "Note that now the image size is 227 x 363. We need to crop this to 227 x 227 for the final feed to our algorithm. We call the previously-defined crop function for this purpose."
},
{
"code": null,
"e": 18452,
"s": 18277,
"text": "img = crop_image(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)\nprint(\"Image Shape after cropping: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Center Cropped')\n"
},
{
"code": null,
"e": 18496,
"s": 18452,
"text": "Below mentioned is the output of the code −"
},
{
"code": null,
"e": 18663,
"s": 18496,
"text": "At this point, the image is of size 227 x 227 and is ready for further processing. We now swap the image axes to extract the three colours into three different zones."
},
{
"code": null,
"e": 18743,
"s": 18663,
"text": "img = img.swapaxes(1, 2).swapaxes(0, 1)\nprint(\"CHW Image Shape: \" , img.shape)\n"
},
{
"code": null,
"e": 18771,
"s": 18743,
"text": "Given below is the output −"
},
{
"code": null,
"e": 18803,
"s": 18771,
"text": "CHW Image Shape: (3, 227, 227)\n"
},
{
"code": null,
"e": 18939,
"s": 18803,
"text": "Note that the last axis has now become the first dimension in the array. We will now plot the three channels using the following code −"
},
{
"code": null,
"e": 19093,
"s": 18939,
"text": "pyplot.figure()\nfor i in range(3):\n pyplot.subplot(1, 3, i+1)\n pyplot.imshow(img[i])\n pyplot.axis('off')\n pyplot.title('RGB channel %d' % (i+1))\n"
},
{
"code": null,
"e": 19122,
"s": 19093,
"text": "The output is stated below −"
},
{
"code": null,
"e": 19345,
"s": 19122,
"text": "Finally, we do some additional processing on the image such as converting Red Green Blue to Blue Green Red (RGB to BGR), removing mean for better results and adding batch size axis using the following three lines of code −"
},
{
"code": null,
"e": 19504,
"s": 19345,
"text": "# convert RGB --> BGR\nimg = img[(2, 1, 0), :, :]\n# remove mean\nimg = img * 255 - mean\n# add batch size axis\nimg = img[np.newaxis, :, :, :].astype(np.float32)\n"
},
{
"code": null,
"e": 19687,
"s": 19504,
"text": "At this point, your image is in NCHW format and is ready for feeding into our network. Next, we will load our pre-trained model files and feed the above image into it for prediction."
},
{
"code": null,
"e": 19790,
"s": 19687,
"text": "We first setup the paths for the init and predict networks defined in the pre-trained models of Caffe."
},
{
"code": null,
"e": 19938,
"s": 19790,
"text": "Remember from our earlier discussion, all the pre-trained models are installed in the models folder. We set up the path to this folder as follows −"
},
{
"code": null,
"e": 20036,
"s": 19938,
"text": "CAFFE_MODELS = os.path.expanduser(\"/anaconda3/lib/python3.7/site-packages/caffe2/python/models\")\n"
},
{
"code": null,
"e": 20122,
"s": 20036,
"text": "We set up the path to the init_net protobuf file of the squeezenet model as follows −"
},
{
"code": null,
"e": 20190,
"s": 20122,
"text": "INIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')\n"
},
{
"code": null,
"e": 20260,
"s": 20190,
"text": "Likewise, we set up the path to the predict_net protobuf as follows −"
},
{
"code": null,
"e": 20334,
"s": 20260,
"text": "PREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')\n"
},
{
"code": null,
"e": 20381,
"s": 20334,
"text": "We print the two paths for diagnosis purpose −"
},
{
"code": null,
"e": 20417,
"s": 20381,
"text": "print(INIT_NET)\nprint(PREDICT_NET)\n"
},
{
"code": null,
"e": 20495,
"s": 20417,
"text": "The above code along with the output is given here for your quick reference −"
},
{
"code": null,
"e": 20768,
"s": 20495,
"text": "CAFFE_MODELS = os.path.expanduser(\"/anaconda3/lib/python3.7/site-packages/caffe2/python/models\")\nINIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')\nPREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')\nprint(INIT_NET)\nprint(PREDICT_NET)\n"
},
{
"code": null,
"e": 20800,
"s": 20768,
"text": "The output is mentioned below −"
},
{
"code": null,
"e": 20970,
"s": 20800,
"text": "/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/init_net.pb\n/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/predict_net.pb\n"
},
{
"code": null,
"e": 21004,
"s": 20970,
"text": "Next, we will create a predictor."
},
{
"code": null,
"e": 21065,
"s": 21004,
"text": "We read the model files using the following two statements −"
},
{
"code": null,
"e": 21182,
"s": 21065,
"text": "with open(INIT_NET, \"rb\") as f:\n init_net = f.read()\nwith open(PREDICT_NET, \"rb\") as f:\n predict_net = f.read()\n"
},
{
"code": null,
"e": 21285,
"s": 21182,
"text": "The predictor is created by passing pointers to the two files as parameters to the Predictor function."
},
{
"code": null,
"e": 21333,
"s": 21285,
"text": "p = workspace.Predictor(init_net, predict_net)\n"
},
{
"code": null,
"e": 21526,
"s": 21333,
"text": "The p object is the predictor, which is used for predicting the objects in any given image. Note that each input image must be in NCHW format as what we have done earlier to our tree.jpg file."
},
{
"code": null,
"e": 21705,
"s": 21526,
"text": "To predict the objects in a given image is trivial - just executing a single line of command. We call run method on the predictor object for an object detection in a given image."
},
{
"code": null,
"e": 21737,
"s": 21705,
"text": "results = p.run({'data': img})\n"
},
{
"code": null,
"e": 21851,
"s": 21737,
"text": "The prediction results are now available in the results object, which we convert to an array for our readability."
},
{
"code": null,
"e": 21882,
"s": 21851,
"text": "results = np.asarray(results)\n"
},
{
"code": null,
"e": 21971,
"s": 21882,
"text": "Print the dimensions of the array for your understanding using the following statement −"
},
{
"code": null,
"e": 22012,
"s": 21971,
"text": "print(\"results shape: \", results.shape)\n"
},
{
"code": null,
"e": 22043,
"s": 22012,
"text": "The output is as shown below −"
},
{
"code": null,
"e": 22078,
"s": 22043,
"text": "results shape: (1, 1, 1000, 1, 1)\n"
},
{
"code": null,
"e": 22120,
"s": 22078,
"text": "We will now remove the unnecessary axis −"
},
{
"code": null,
"e": 22149,
"s": 22120,
"text": "preds = np.squeeze(results)\n"
},
{
"code": null,
"e": 22238,
"s": 22149,
"text": "The topmost predication can now be retrieved by taking the max value in the preds array."
},
{
"code": null,
"e": 22378,
"s": 22238,
"text": "curr_pred, curr_conf = max(enumerate(preds), key=operator.itemgetter(1))\nprint(\"Prediction: \", curr_pred)\nprint(\"Confidence: \", curr_conf)\n"
},
{
"code": null,
"e": 22405,
"s": 22378,
"text": "The output is as follows −"
},
{
"code": null,
"e": 22445,
"s": 22405,
"text": "Prediction: 984\nConfidence: 0.89235985\n"
},
{
"code": null,
"e": 22835,
"s": 22445,
"text": "As you see the model has predicted an object with an index value 984 with 89% confidence. The index of 984 does not make much sense to us in understanding what kind of object is detected. We need to get the stringified name for the object using its index value. The kind of objects that the model recognizes along with their corresponding index values are available on a github repository."
},
{
"code": null,
"e": 22919,
"s": 22835,
"text": "Now, we will see how to retrieve the name for our object having index value of 984."
},
{
"code": null,
"e": 22980,
"s": 22919,
"text": "We create a URL object to the github repository as follows −"
},
{
"code": null,
"e": 23132,
"s": 22980,
"text": "codes = \"https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac0\n71eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes\"\n"
},
{
"code": null,
"e": 23166,
"s": 23132,
"text": "We read the contents of the URL −"
},
{
"code": null,
"e": 23201,
"s": 23166,
"text": "response = urllib2.urlopen(codes)\n"
},
{
"code": null,
"e": 23356,
"s": 23201,
"text": "The response will contain a list of all codes and its descriptions. Few lines of the response are shown below for your understanding of what it contains −"
},
{
"code": null,
"e": 23517,
"s": 23356,
"text": "5: 'electric ray, crampfish, numbfish, torpedo',\n6: 'stingray',\n7: 'cock',\n8: 'hen',\n9: 'ostrich, Struthio camelus',\n10: 'brambling, Fringilla montifringilla',\n"
},
{
"code": null,
"e": 23613,
"s": 23517,
"text": "We now iterate the entire array to locate our desired code of 984 using a for loop as follows −"
},
{
"code": null,
"e": 23916,
"s": 23613,
"text": "for line in response:\n mystring = line.decode('ascii')\n code, result = mystring.partition(\":\")[::2]\n code = code.strip()\n result = result.replace(\"'\", \"\")\n if (code == str(curr_pred)):\n name = result.split(\",\")[0][1:]\n print(\"Model predicts\", name, \"with\", curr_conf, \"confidence\")\n"
},
{
"code": null,
"e": 23975,
"s": 23916,
"text": "When you run the code, you will see the following output −"
},
{
"code": null,
"e": 24027,
"s": 23975,
"text": "Model predicts rapeseed with 0.89235985 confidence\n"
},
{
"code": null,
"e": 24071,
"s": 24027,
"text": "You may now try the model on another image."
},
{
"code": null,
"e": 24332,
"s": 24071,
"text": "To predict another image, simply copy the image file into the images folder of your project directory. This is the directory in which our earlier tree.jpg file is stored. Change the name of the image file in the code. Only one change is required as shown below"
},
{
"code": null,
"e": 24420,
"s": 24332,
"text": "img = skimage.img_as_float(skimage.io.imread(\"images/pretzel.jpg\")).astype(np.float32)\n"
},
{
"code": null,
"e": 24485,
"s": 24420,
"text": "The original picture and the prediction result are shown below −"
},
{
"code": null,
"e": 24517,
"s": 24485,
"text": "The output is mentioned below −"
},
{
"code": null,
"e": 24568,
"s": 24517,
"text": "Model predicts pretzel with 0.99999976 confidence\n"
},
{
"code": null,
"e": 24677,
"s": 24568,
"text": "As you see the pre-trained model is able to detect objects in a given image with a great amount of accuracy."
},
{
"code": null,
"e": 24825,
"s": 24677,
"text": "The full source for the above code that uses a pre-trained model for object detection in a given image is mentioned here for your quick reference −"
},
{
"code": null,
"e": 27098,
"s": 24825,
"text": "def crop_image(img,cropx,cropy):\n y,x,c = img.shape\n startx = x//2-(cropx//2)\n starty = y//2-(cropy//2)\n return img[starty:starty+cropy,startx:startx+cropx]\nimg = skimage.img_as_float(skimage.io.imread(\"images/pretzel.jpg\")).astype(np.float32)\nprint(\"Original Image Shape: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Original image')\nimg = resize(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)\nprint(\"Image Shape after resizing: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Resized image')\nimg = crop_image(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)\nprint(\"Image Shape after cropping: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Center Cropped')\nimg = img.swapaxes(1, 2).swapaxes(0, 1)\nprint(\"CHW Image Shape: \" , img.shape)\npyplot.figure()\nfor i in range(3):\npyplot.subplot(1, 3, i+1)\npyplot.imshow(img[i])\npyplot.axis('off')\npyplot.title('RGB channel %d' % (i+1))\n# convert RGB --> BGR\nimg = img[(2, 1, 0), :, :]\n# remove mean\nimg = img * 255 - mean\n# add batch size axis\nimg = img[np.newaxis, :, :, :].astype(np.float32)\nCAFFE_MODELS = os.path.expanduser(\"/anaconda3/lib/python3.7/site-packages/caffe2/python/models\")\nINIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')\nPREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')\nprint(INIT_NET)\nprint(PREDICT_NET)\nwith open(INIT_NET, \"rb\") as f:\n init_net = f.read()\nwith open(PREDICT_NET, \"rb\") as f:\n predict_net = f.read()\np = workspace.Predictor(init_net, predict_net)\nresults = p.run({'data': img})\nresults = np.asarray(results)\nprint(\"results shape: \", results.shape)\npreds = np.squeeze(results)\ncurr_pred, curr_conf = max(enumerate(preds), key=operator.itemgetter(1))\nprint(\"Prediction: \", curr_pred)\nprint(\"Confidence: \", curr_conf)\ncodes = \"https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac071eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes\"\nresponse = urllib2.urlopen(codes)\nfor line in response:\n mystring = line.decode('ascii')\n code, result = mystring.partition(\":\")[::2]\n code = code.strip()\n result = result.replace(\"'\", \"\")\n if (code == str(curr_pred)):\n name = result.split(\",\")[0][1:]\n print(\"Model predicts\", name, \"with\", curr_conf, \"confidence\")\n"
},
{
"code": null,
"e": 27195,
"s": 27098,
"text": "By this time, you know how to use a pre-trained model for doing the predictions on your dataset."
},
{
"code": null,
"e": 27373,
"s": 27195,
"text": "What’s next is to learn how to define your neural network (NN) architectures in Caffe2 and train them on your dataset. We will now learn how to create a trivial single layer NN."
},
{
"code": null,
"e": 27740,
"s": 27373,
"text": "In this lesson, you will learn to define a single layer neural network (NN) in Caffe2 and run it on a randomly generated dataset. We will write code to graphically depict the network architecture, print input, output, weights, and bias values. To understand this lesson, you must be familiar with neural network architectures, its terms and mathematics used in them."
},
{
"code": null,
"e": 27827,
"s": 27740,
"text": "Let us consider that we want to build a single layer NN as shown in the figure below −"
},
{
"code": null,
"e": 27902,
"s": 27827,
"text": "Mathematically, this network is represented by the following Python code −"
},
{
"code": null,
"e": 27919,
"s": 27902,
"text": "Y = X * W^T + b\n"
},
{
"code": null,
"e": 28141,
"s": 27919,
"text": "Where X, W, b are tensors and Y is the output. We will fill all three tensors with some random data, run the network and examine the Y output. To define the network and tensors, Caffe2 provides several Operator functions."
},
{
"code": null,
"e": 28242,
"s": 28141,
"text": "In Caffe2, Operator is the basic unit of computation. The Caffe2 Operator is represented as follows."
},
{
"code": null,
"e": 28605,
"s": 28242,
"text": "Caffe2 provides an exhaustive list of operators. For the network that we are designing currently, we will use the operator called FC, which computes the result of passing an input vector X into a fully connected network with a two-dimensional weight matrix W and a single-dimensional bias vector b. In other words, it computes the following mathematical equation"
},
{
"code": null,
"e": 28622,
"s": 28605,
"text": "Y = X * W^T + b\n"
},
{
"code": null,
"e": 28767,
"s": 28622,
"text": "Where X has dimensions (M x k), W has dimensions (n x k) and b is (1 x n). The output Y will be of dimension (M x n), where M is the batch size."
},
{
"code": null,
"e": 28923,
"s": 28767,
"text": "For the vectors X and W, we will use the GaussianFill operator to create some random data. For generating bias values b, we will use ConstantFill operator."
},
{
"code": null,
"e": 28966,
"s": 28923,
"text": "We will now proceed to define our network."
},
{
"code": null,
"e": 29011,
"s": 28966,
"text": "First of all, import the required packages −"
},
{
"code": null,
"e": 29054,
"s": 29011,
"text": "from caffe2.python import core, workspace\n"
},
{
"code": null,
"e": 29112,
"s": 29054,
"text": "Next, define the network by calling core.Net as follows −"
},
{
"code": null,
"e": 29145,
"s": 29112,
"text": "net = core.Net(\"SingleLayerFC\")\n"
},
{
"code": null,
"e": 29296,
"s": 29145,
"text": "The name of the network is specified as SingleLayerFC. At this point, the network object called net is created. It does not contain any layers so far."
},
{
"code": null,
"e": 29435,
"s": 29296,
"text": "We will now create the three vectors required by our network. First, we will create X tensor by calling GaussianFill operator as follows −"
},
{
"code": null,
"e": 29513,
"s": 29435,
"text": "X = net.GaussianFill([], [\"X\"], mean=0.0, std=1.0, shape=[2, 3], run_once=0)\n"
},
{
"code": null,
"e": 29610,
"s": 29513,
"text": "The X vector has dimensions 2 x 3 with the mean data value of 0,0 and standard deviation of 1.0."
},
{
"code": null,
"e": 29652,
"s": 29610,
"text": "Likewise, we create W tensor as follows −"
},
{
"code": null,
"e": 29730,
"s": 29652,
"text": "W = net.GaussianFill([], [\"W\"], mean=0.0, std=1.0, shape=[5, 3], run_once=0)\n"
},
{
"code": null,
"e": 29761,
"s": 29730,
"text": "The W vector is of size 5 x 3."
},
{
"code": null,
"e": 29805,
"s": 29761,
"text": "Finally, we create bias b matrix of size 5."
},
{
"code": null,
"e": 29873,
"s": 29805,
"text": "b = net.ConstantFill([], [\"b\"], shape=[5,], value=1.0, run_once=0)\n"
},
{
"code": null,
"e": 29961,
"s": 29873,
"text": "Now, comes the most important part of the code and that is defining the network itself."
},
{
"code": null,
"e": 30019,
"s": 29961,
"text": "We define the network in the following Python statement −"
},
{
"code": null,
"e": 30044,
"s": 30019,
"text": "Y = X.FC([W, b], [\"Y\"])\n"
},
{
"code": null,
"e": 30251,
"s": 30044,
"text": "We call FC operator on the input data X. The weights are specified in W and bias in b. The output is Y. Alternatively, you may create the network using the following Python statement, which is more verbose."
},
{
"code": null,
"e": 30281,
"s": 30251,
"text": "Y = net.FC([X, W, b], [\"Y\"])\n"
},
{
"code": null,
"e": 30459,
"s": 30281,
"text": "At this point, the network is simply created. Until we run the network at least once, it will not contain any data. Before running the network, we will examine its architecture."
},
{
"code": null,
"e": 30592,
"s": 30459,
"text": "Caffe2 defines the network architecture in a JSON file, which can be examined by calling the Proto method on the created net object."
},
{
"code": null,
"e": 30613,
"s": 30592,
"text": "print (net.Proto())\n"
},
{
"code": null,
"e": 30650,
"s": 30613,
"text": "This produces the following output −"
},
{
"code": null,
"e": 31482,
"s": 30650,
"text": "name: \"SingleLayerFC\"\nop {\n output: \"X\"\n name: \"\"\n type: \"GaussianFill\"\n arg {\n name: \"mean\"\n f: 0.0\n }\n arg {\n name: \"std\"\n f: 1.0\n }\n arg {\n name: \"shape\"\n ints: 2\n ints: 3\n }\n arg {\n name: \"run_once\"\n i: 0\n }\n}\nop {\n output: \"W\"\n name: \"\"\n type: \"GaussianFill\"\n arg {\n name: \"mean\"\n f: 0.0\n }\n arg {\n name: \"std\"\n f: 1.0\n }\n arg {\n name: \"shape\"\n ints: 5\n ints: 3\n }\n arg {\n name: \"run_once\"\n i: 0\n }\n}\nop {\n output: \"b\"\n name: \"\"\n type: \"ConstantFill\"\n arg {\n name: \"shape\"\n ints: 5\n }\n arg {\n name: \"value\"\n f: 1.0\n }\n arg {\n name: \"run_once\"\n i: 0\n }\n}\nop {\n input: \"X\"\n input: \"W\"\n input: \"b\"\n output: \"Y\"\n name: \"\"\n type: \"FC\"\n}\n"
},
{
"code": null,
"e": 31761,
"s": 31482,
"text": "As you can see in the above listing, it first defines the operators X, W and b. Let us examine the definition of W as an example. The type of W is specified as GausianFill. The mean is defined as float 0.0, the standard deviation is defined as float 1.0, and the shape is 5 x 3."
},
{
"code": null,
"e": 31981,
"s": 31761,
"text": "op {\n output: \"W\"\n name: \"\" type: \"GaussianFill\"\n arg {\n name: \"mean\" \n\t f: 0.0\n }\n arg { \n name: \"std\" \n f: 1.0\n }\n arg { \n name: \"shape\" \n ints: 5 \n ints: 3\n }\n ...\n}\n"
},
{
"code": null,
"e": 32137,
"s": 31981,
"text": "Examine the definitions of X and b for your own understanding. Finally, let us look at the definition of our single layer network, which is reproduced here"
},
{
"code": null,
"e": 32228,
"s": 32137,
"text": "op {\n input: \"X\"\n input: \"W\"\n input: \"b\"\n output: \"Y\"\n name: \"\"\n type: \"FC\"\n}\n"
},
{
"code": null,
"e": 32512,
"s": 32228,
"text": "Here, the network type is FC (Fully Connected) with X, W, b as inputs and Y is the output. This network definition is too verbose and for large networks, it will become tedious to examine its contents. Fortunately, Caffe2 provides a graphical representation for the created networks."
},
{
"code": null,
"e": 32648,
"s": 32512,
"text": "To get the graphical representation of the network, run the following code snippet, which is essentially only two lines of Python code."
},
{
"code": null,
"e": 32811,
"s": 32648,
"text": "from caffe2.python import net_drawer\nfrom IPython import display\ngraph = net_drawer.GetPydotGraph(net, rankdir=\"LR\")\ndisplay.Image(graph.create_png(), width=800)\n"
},
{
"code": null,
"e": 32870,
"s": 32811,
"text": "When you run the code, you will see the following output −"
},
{
"code": null,
"e": 33000,
"s": 32870,
"text": "For large networks, the graphical representation becomes extremely useful in visualizing and debugging network definition errors."
},
{
"code": null,
"e": 33044,
"s": 33000,
"text": "Finally, it is now time to run the network."
},
{
"code": null,
"e": 33123,
"s": 33044,
"text": "You run the network by calling the RunNetOnce method on the workspace object −"
},
{
"code": null,
"e": 33150,
"s": 33123,
"text": "workspace.RunNetOnce(net)\n"
},
{
"code": null,
"e": 33478,
"s": 33150,
"text": "After the network is run once, all our data that is generated at random would be created, fed into the network and the output will be created. The tensors which are created after running the network are called blobs in Caffe2. The workspace consists of the blobs you create and store in memory. This is quite similar to Matlab."
},
{
"code": null,
"e": 33593,
"s": 33478,
"text": "After running the network, you can examine the blobs that the workspace contains using the following print command"
},
{
"code": null,
"e": 33656,
"s": 33593,
"text": "print(\"Blobs in the workspace: {}\".format(workspace.Blobs()))\n"
},
{
"code": null,
"e": 33692,
"s": 33656,
"text": "You will see the following output −"
},
{
"code": null,
"e": 33738,
"s": 33692,
"text": "Blobs in the workspace: ['W', 'X', 'Y', 'b']\n"
},
{
"code": null,
"e": 33897,
"s": 33738,
"text": "Note that the workspace consists of three input blobs − X, W and b. It also contains the output blob called Y. Let us now examine the contents of these blobs."
},
{
"code": null,
"e": 33989,
"s": 33897,
"text": "for name in workspace.Blobs():\n print(\"{}:\\n{}\".format(name, workspace.FetchBlob(name)))\n"
},
{
"code": null,
"e": 34025,
"s": 33989,
"text": "You will see the following output −"
},
{
"code": null,
"e": 34435,
"s": 34025,
"text": "W:\n[[ 1.0426593 0.15479846 0.25635982]\n[-2.2461145 1.4581774 0.16827184]\n[-0.12009818 0.30771437 0.00791338]\n[ 1.2274994 -0.903331 -0.68799865]\n[ 0.30834186 -0.53060573 0.88776857]]\nX:\n[[ 1.6588869e+00 1.5279824e+00 1.1889904e+00]\n[ 6.7048723e-01 -9.7490678e-04 2.5114202e-01]]\nY:\n[[ 3.2709925 -0.297907 1.2803618 0.837985 1.7562964]\n[ 1.7633215 -0.4651525 0.9211631 1.6511179 1.4302125]]\nb:\n[1. 1. 1. 1. 1.]\n"
},
{
"code": null,
"e": 34650,
"s": 34435,
"text": "Note that the data on your machine or as a matter of fact on every run of the network would be different as all inputs are created at random. You have now successfully defined a network and run it on your computer."
},
{
"code": null,
"e": 35362,
"s": 34650,
"text": "In the previous lesson, you learned to create a trivial network and learned how to execute it and examine its output. The process for creating complex networks is similar to the process described above. Caffe2 provides a huge set of operators for creating complex architectures. You are encouraged to examine the Caffe2 documentation for a list of operators. After studying the purpose of various operators, you would be in a position to create complex networks and train them. For training the network, Caffe2 provides several predefined computation units - that is the operators. You will need to select the appropriate operators for training your network for the kind of problem that you are trying to solve."
},
{
"code": null,
"e": 35671,
"s": 35362,
"text": "Once a network is trained to your satisfaction, you can store it in a model file similar to the pre-trained model files you used earlier. These trained models may be contributed to Caffe2 repository for the benefits of other users. Or you may simply put the trained model for your own private production use."
},
{
"code": null,
"e": 36177,
"s": 35671,
"text": "Caffe2, which is a deep learning framework allows you to experiment with several kinds of neural networks for predicting your data. Caffe2 site provides many pre-trained models. You learned to use one of the pre-trained models for classifying objects in a given image. You also learned to define a neural network architecture of your choice. Such custom networks can be trained using many predefined operators in Caffe. A trained model is stored in a file which can be taken into a production environment."
},
{
"code": null,
"e": 36184,
"s": 36177,
"text": " Print"
},
{
"code": null,
"e": 36195,
"s": 36184,
"text": " Add Notes"
}
] |
Overlapping rectangles | Practice | GeeksforGeeks
|
Given two rectangles, find if the given two rectangles overlap or not. A rectangle is denoted by providing the x and y coordinates of two points: the left top corner and the right bottom corner of the rectangle. Two rectangles sharing a side are considered overlapping. (L1 and R1 are the extreme points of the first rectangle and L2 and R2 are the extreme points of the second rectangle).
Note: It may be assumed that the rectangles are parallel to the coordinate axis.
Example 1:
Input:
L1=(0,10)
R1=(10,0)
L2=(5,5)
R2=(15,0)
Output:
1
Explanation:
The rectangles overlap.
Example 2:
Input:
L1=(0,2)
R1=(1,1)
L2=(-2,0)
R2=(0,-3)
Output:
0
Explanation:
The rectangles do not overlap.
Your Task:
You don't need to read input or print anything. Your task is to complete the function doOverlap() which takes the points L1, R1, L2, and R2 as input parameters and returns 1 if the rectangles overlap. Otherwise, it returns 0.
Expected Time Complexity:O(1)
Expected Auxillary Space:O(1)
Constraints:
-109<=x-coordinate,y-coordinate<=109
0
billi1 week ago
int doOverlap(int l1[], int r1[], int l2[], int r2[]) {
int a1=l1[0];
int b1=l1[1];
int a2=r1[0];
int b2=r1[1];
int x1=l2[0];
int y1=l2[1];
int x2=r2[0];
int y2=r2[1];
//// there four posssible cndition in which 2 rectange does not overlap ...
//// 1st one when lower index y of 2nd rectangle(y2)> upper index y of 1st
//->y2>b1;
///if this the case then it must have its vice versa where ....
////b2>y1
/// nxt we do the comparison of x coordinate.....
/// if a1>x2 then not valid
/// and similar fashion if x1>a2 then not valid....
/// and in rest cases rectangle will overlapp....
if(b1<y2||a2<x1||x2<a1||y1<b2)return 0;
return 1;
}
+2
sandeepkmrnayak2 weeks ago
Simple C++ Solution:
int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // code here if(L1[1] < R2[1] || R1[0] < L2[0] || L1[0] > R2[0] || R1[1] > L2[1]){ return 0; } return 1; }
0
tharabhai4 months ago
C++ inplementation:
int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // Calculate midpoints of both rectangles then check the distance between them.
float mid1[2],mid2[2]; mid1[0] = (R1[0]-L1[0])/2.0; mid1[1] = (L1[1]-R1[1])/2.0; mid2[0] = (R2[0]-L2[0])/2.0; mid2[1] = (L2[1]-R2[1])/2.0; float max_x = mid1[0] + mid2[0]; float max_y = mid1[1] + mid2[1]; mid1[0] = L1[0] + ((R1[0]-L1[0])/2.0); mid1[1] = R1[1] + ((L1[1]-R1[1])/2.0); mid2[0] = L2[0] + ((R2[0]-L2[0])/2.0); mid2[1] = R2[1] + ((L2[1]-R2[1])/2.0); if(abs(mid2[0]-mid1[0])>max_x || abs(mid2[1]-mid1[1])>max_y){ return 0; } return 1; }
0
chechipresh4 months ago
What about a case like
L1(1,6) R1(2,4) L2(2,4) R2(5,2) (one of thecorner points of two rectangles coinciding)
Should it be considered overlapping or non overlapping?
0
noviicee6 months ago
I don't know why, but checking if the rectangle is actually is a line, leads to failure of some test-cases ?
+6
jainisha5306 months ago
class Solution { public: int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // code here if(L2[0]>R1[0]||L1[0]>R2[0]||L1[1]<R2[1]||L2[1]<R1[1]) return 0; return 1; }};
0
shahsourabh116 months ago
//c++ //
class Solution { public: int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // code here return min(R1[0],R2[0])>=max(L1[0],L2[0]) && min(L1[1],L2[1])>=max(R1[1],R2[1]); }};
+7
riyajha23056 months ago
//C++ solution
class Solution { public: int doOverlap(int l1[], int r1[], int l2[], int r2[]) { // If one rectangle is on left side of other if (l1[0] > r2[0] || l2[0] > r1[0]) return false; // If one rectangle is above other if (r1[1] > l2[1] || r2[1] > l1[1]) return false; return true; }};
+3
dishasarna20016 months ago
Expected Time Complexity:O(1)Expected Auxillary Space:O(1)
//C++ Solution
class Solution { public: int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // code here //If one rectangle is on left side of the left edge of the other rectangle if(L1[0]>R2[0] || L2[0]>R1[0]) return false; //If one rectangle is above the other if(L1[1]<R2[1] || L2[1]<R1[1]) return false; return true; }};
+2
mridulkapoor1234566 months ago
Expected Time Complexity:O(1)Expected Auxillary Space:O(1)
class Solution {
public:
int doOverlap(int L1[], int R1[], int L2[], int R2[]) {
// code here
//If one rectangle is on left side of other
if(L1[0]>R2[0] || L2[0]>R1[0])
return false;
//If one rectangle is above the other
if(L1[1]<R2[1] || L2[1]<R1[1])
return false;
return true;
}
};
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": 628,
"s": 238,
"text": "Given two rectangles, find if the given two rectangles overlap or not. A rectangle is denoted by providing the x and y coordinates of two points: the left top corner and the right bottom corner of the rectangle. Two rectangles sharing a side are considered overlapping. (L1 and R1 are the extreme points of the first rectangle and L2 and R2 are the extreme points of the second rectangle)."
},
{
"code": null,
"e": 709,
"s": 628,
"text": "Note: It may be assumed that the rectangles are parallel to the coordinate axis."
},
{
"code": null,
"e": 720,
"s": 709,
"text": "Example 1:"
},
{
"code": null,
"e": 813,
"s": 720,
"text": "Input:\nL1=(0,10)\nR1=(10,0)\nL2=(5,5)\nR2=(15,0)\nOutput:\n1\nExplanation:\nThe rectangles overlap."
},
{
"code": null,
"e": 824,
"s": 813,
"text": "Example 2:"
},
{
"code": null,
"e": 923,
"s": 824,
"text": "Input:\nL1=(0,2)\nR1=(1,1)\nL2=(-2,0)\nR2=(0,-3)\nOutput:\n0\nExplanation:\nThe rectangles do not overlap."
},
{
"code": null,
"e": 1161,
"s": 923,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function doOverlap() which takes the points L1, R1, L2, and R2 as input parameters and returns 1 if the rectangles overlap. Otherwise, it returns 0."
},
{
"code": null,
"e": 1222,
"s": 1161,
"text": "\nExpected Time Complexity:O(1)\nExpected Auxillary Space:O(1)"
},
{
"code": null,
"e": 1273,
"s": 1222,
"text": "\nConstraints:\n-109<=x-coordinate,y-coordinate<=109"
},
{
"code": null,
"e": 1275,
"s": 1273,
"text": "0"
},
{
"code": null,
"e": 1291,
"s": 1275,
"text": "billi1 week ago"
},
{
"code": null,
"e": 2130,
"s": 1291,
"text": " int doOverlap(int l1[], int r1[], int l2[], int r2[]) {\n int a1=l1[0];\n int b1=l1[1];\n int a2=r1[0];\n int b2=r1[1];\n \n int x1=l2[0];\n int y1=l2[1];\n int x2=r2[0];\n int y2=r2[1];\n //// there four posssible cndition in which 2 rectange does not overlap ...\n //// 1st one when lower index y of 2nd rectangle(y2)> upper index y of 1st\n //->y2>b1;\n ///if this the case then it must have its vice versa where ....\n ////b2>y1\n \n /// nxt we do the comparison of x coordinate.....\n /// if a1>x2 then not valid \n /// and similar fashion if x1>a2 then not valid....\n \n /// and in rest cases rectangle will overlapp....\n \n \n if(b1<y2||a2<x1||x2<a1||y1<b2)return 0;\n return 1;\n }"
},
{
"code": null,
"e": 2133,
"s": 2130,
"text": "+2"
},
{
"code": null,
"e": 2160,
"s": 2133,
"text": "sandeepkmrnayak2 weeks ago"
},
{
"code": null,
"e": 2181,
"s": 2160,
"text": "Simple C++ Solution:"
},
{
"code": null,
"e": 2380,
"s": 2181,
"text": "int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // code here if(L1[1] < R2[1] || R1[0] < L2[0] || L1[0] > R2[0] || R1[1] > L2[1]){ return 0; } return 1; }"
},
{
"code": null,
"e": 2382,
"s": 2380,
"text": "0"
},
{
"code": null,
"e": 2404,
"s": 2382,
"text": "tharabhai4 months ago"
},
{
"code": null,
"e": 2424,
"s": 2404,
"text": "C++ inplementation:"
},
{
"code": null,
"e": 2568,
"s": 2426,
"text": "int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // Calculate midpoints of both rectangles then check the distance between them."
},
{
"code": null,
"e": 3158,
"s": 2568,
"text": " float mid1[2],mid2[2]; mid1[0] = (R1[0]-L1[0])/2.0; mid1[1] = (L1[1]-R1[1])/2.0; mid2[0] = (R2[0]-L2[0])/2.0; mid2[1] = (L2[1]-R2[1])/2.0; float max_x = mid1[0] + mid2[0]; float max_y = mid1[1] + mid2[1]; mid1[0] = L1[0] + ((R1[0]-L1[0])/2.0); mid1[1] = R1[1] + ((L1[1]-R1[1])/2.0); mid2[0] = L2[0] + ((R2[0]-L2[0])/2.0); mid2[1] = R2[1] + ((L2[1]-R2[1])/2.0); if(abs(mid2[0]-mid1[0])>max_x || abs(mid2[1]-mid1[1])>max_y){ return 0; } return 1; }"
},
{
"code": null,
"e": 3160,
"s": 3158,
"text": "0"
},
{
"code": null,
"e": 3184,
"s": 3160,
"text": "chechipresh4 months ago"
},
{
"code": null,
"e": 3208,
"s": 3184,
"text": "What about a case like "
},
{
"code": null,
"e": 3297,
"s": 3208,
"text": "L1(1,6) R1(2,4) L2(2,4) R2(5,2) (one of thecorner points of two rectangles coinciding)"
},
{
"code": null,
"e": 3353,
"s": 3297,
"text": "Should it be considered overlapping or non overlapping?"
},
{
"code": null,
"e": 3355,
"s": 3353,
"text": "0"
},
{
"code": null,
"e": 3376,
"s": 3355,
"text": "noviicee6 months ago"
},
{
"code": null,
"e": 3485,
"s": 3376,
"text": "I don't know why, but checking if the rectangle is actually is a line, leads to failure of some test-cases ?"
},
{
"code": null,
"e": 3488,
"s": 3485,
"text": "+6"
},
{
"code": null,
"e": 3512,
"s": 3488,
"text": "jainisha5306 months ago"
},
{
"code": null,
"e": 3713,
"s": 3512,
"text": "class Solution { public: int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // code here if(L2[0]>R1[0]||L1[0]>R2[0]||L1[1]<R2[1]||L2[1]<R1[1]) return 0; return 1; }};"
},
{
"code": null,
"e": 3715,
"s": 3713,
"text": "0"
},
{
"code": null,
"e": 3741,
"s": 3715,
"text": "shahsourabh116 months ago"
},
{
"code": null,
"e": 3750,
"s": 3741,
"text": "//c++ //"
},
{
"code": null,
"e": 3946,
"s": 3750,
"text": "class Solution { public: int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // code here return min(R1[0],R2[0])>=max(L1[0],L2[0]) && min(L1[1],L2[1])>=max(R1[1],R2[1]); }}; "
},
{
"code": null,
"e": 3949,
"s": 3946,
"text": "+7"
},
{
"code": null,
"e": 3973,
"s": 3949,
"text": "riyajha23056 months ago"
},
{
"code": null,
"e": 3988,
"s": 3973,
"text": "//C++ solution"
},
{
"code": null,
"e": 4325,
"s": 3990,
"text": "class Solution { public: int doOverlap(int l1[], int r1[], int l2[], int r2[]) { // If one rectangle is on left side of other if (l1[0] > r2[0] || l2[0] > r1[0]) return false; // If one rectangle is above other if (r1[1] > l2[1] || r2[1] > l1[1]) return false; return true; }};"
},
{
"code": null,
"e": 4328,
"s": 4325,
"text": "+3"
},
{
"code": null,
"e": 4355,
"s": 4328,
"text": "dishasarna20016 months ago"
},
{
"code": null,
"e": 4414,
"s": 4355,
"text": "Expected Time Complexity:O(1)Expected Auxillary Space:O(1)"
},
{
"code": null,
"e": 4429,
"s": 4414,
"text": "//C++ Solution"
},
{
"code": null,
"e": 4803,
"s": 4429,
"text": "class Solution { public: int doOverlap(int L1[], int R1[], int L2[], int R2[]) { // code here //If one rectangle is on left side of the left edge of the other rectangle if(L1[0]>R2[0] || L2[0]>R1[0]) return false; //If one rectangle is above the other if(L1[1]<R2[1] || L2[1]<R1[1]) return false; return true; }};"
},
{
"code": null,
"e": 4810,
"s": 4807,
"text": "+2"
},
{
"code": null,
"e": 4841,
"s": 4810,
"text": "mridulkapoor1234566 months ago"
},
{
"code": null,
"e": 4900,
"s": 4841,
"text": "Expected Time Complexity:O(1)Expected Auxillary Space:O(1)"
},
{
"code": null,
"e": 5266,
"s": 4900,
"text": "class Solution {\n public:\n int doOverlap(int L1[], int R1[], int L2[], int R2[]) {\n // code here\n //If one rectangle is on left side of other\n if(L1[0]>R2[0] || L2[0]>R1[0])\n return false;\n //If one rectangle is above the other\n if(L1[1]<R2[1] || L2[1]<R1[1])\n return false;\n return true;\n }\n};"
},
{
"code": null,
"e": 5412,
"s": 5266,
"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": 5448,
"s": 5412,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5458,
"s": 5448,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5468,
"s": 5458,
"text": "\nContest\n"
},
{
"code": null,
"e": 5531,
"s": 5468,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5716,
"s": 5531,
"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": 6000,
"s": 5716,
"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": 6146,
"s": 6000,
"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": 6223,
"s": 6146,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6264,
"s": 6223,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6292,
"s": 6264,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6363,
"s": 6292,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 6550,
"s": 6363,
"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."
}
] |
TypeScript | Array concat() Method
|
18 Jun, 2020
The Array.concat() is an inbuilt TypeScript function which is used to merge two or more arrays together. Syntax:
array.concat(value1, value2, ..., valueN)
Parameter: This method accepts a single parameter multiple time as mentioned above and described below:
valueN : These parameters are arrays and/or values to concatenate.
Return Value: This method returns the new array. Below examples illustrate the Array concat() method in TypeScriptExample 1:
JavaScript
<script> // Driver code var num1 = [11, 12, 13]; var num2 = [14, 15, 16]; var num3 = [17, 18, 19]; // use of String concat() Method console.log(num1.concat(num2, num3)); </script>
Output:
[ 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
Example 2:
JavaScript
<script> // Driver code var num1 = ['a', 'b', 'c']; // use of String concat() Method console.log(num1.concat(1, [2, 3])); </script>
Output:
[ 'a', 'b', 'c', '1,2,3' ]
TypeScript
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
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": 53,
"s": 25,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 166,
"s": 53,
"text": "The Array.concat() is an inbuilt TypeScript function which is used to merge two or more arrays together. Syntax:"
},
{
"code": null,
"e": 208,
"s": 166,
"text": "array.concat(value1, value2, ..., valueN)"
},
{
"code": null,
"e": 313,
"s": 208,
"text": "Parameter: This method accepts a single parameter multiple time as mentioned above and described below: "
},
{
"code": null,
"e": 380,
"s": 313,
"text": "valueN : These parameters are arrays and/or values to concatenate."
},
{
"code": null,
"e": 506,
"s": 380,
"text": "Return Value: This method returns the new array. Below examples illustrate the Array concat() method in TypeScriptExample 1: "
},
{
"code": null,
"e": 517,
"s": 506,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var num1 = [11, 12, 13]; var num2 = [14, 15, 16]; var num3 = [17, 18, 19]; // use of String concat() Method console.log(num1.concat(num2, num3)); </script>",
"e": 718,
"s": 517,
"text": null
},
{
"code": null,
"e": 727,
"s": 718,
"text": "Output: "
},
{
"code": null,
"e": 767,
"s": 727,
"text": "[ 11, 12, 13, 14, 15, 16, 17, 18, 19 ]\n"
},
{
"code": null,
"e": 779,
"s": 767,
"text": "Example 2: "
},
{
"code": null,
"e": 790,
"s": 779,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var num1 = ['a', 'b', 'c']; // use of String concat() Method console.log(num1.concat(1, [2, 3])); </script>",
"e": 936,
"s": 790,
"text": null
},
{
"code": null,
"e": 945,
"s": 936,
"text": "Output: "
},
{
"code": null,
"e": 973,
"s": 945,
"text": "[ 'a', 'b', 'c', '1,2,3' ]\n"
},
{
"code": null,
"e": 984,
"s": 973,
"text": "TypeScript"
},
{
"code": null,
"e": 995,
"s": 984,
"text": "JavaScript"
},
{
"code": null,
"e": 1012,
"s": 995,
"text": "Web Technologies"
},
{
"code": null,
"e": 1110,
"s": 1012,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1171,
"s": 1110,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1243,
"s": 1171,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1283,
"s": 1243,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1335,
"s": 1283,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 1376,
"s": 1335,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1438,
"s": 1376,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1471,
"s": 1438,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1532,
"s": 1471,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1582,
"s": 1532,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python – Maximum in Row Range
|
12 Nov, 2020
Given a range and a Matrix, extract the maximum element out of that range of rows.
Input : test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]], i, j = 2, 5 Output : 12 Explanation : Checks for rows 2, 3 and 4, maximum element is 12.
Input : test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]], i, j = 1, 4 Output : 10 Explanation : Checks for rows 1, 2 and 3, maximum element is 10.
Method #1 : Using max() + slicing
In this, we perform the task of slicing the rows in which maximum has to be found, then the maximum is found for each row using max(), another max() is applied to get maximum upon extracted elements.
Python3
# Python3 code to demonstrate working of# Maximum in Rows Range# Using max() + slicing # initializing listtest_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]] # printing original listprint("The original list is : " + str(test_list)) # initializing rangei, j = 2, 4 res = 0for idx in range(i, j): # getting max in range res = max(max(test_list[idx]), res) # printing resultprint("The maximum element in row range ? : " + str(res))
Output:
The original list is : [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]]The maximum element in row range ? : 10
Method #2 : Using max() + slicing + list comprehension
In this, we perform the similar task as above using list comprehension to offer one liner to this operation.
Python3
# Python3 code to demonstrate working of# Maximum in Rows Range# Using max() + slicing + list comprehension # initializing listtest_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]] # printing original listprint("The original list is : " + str(test_list)) # initializing rangei, j = 2, 4 # getting max of maximum of sub listsres = max([max(test_list[idx]) for idx in range(i, j)]) # printing resultprint("The maximum element in row range ? : " + str(res))
Output:
The original list is : [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]]The maximum element in row range ? : 10
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 111,
"s": 28,
"text": "Given a range and a Matrix, extract the maximum element out of that range of rows."
},
{
"code": null,
"e": 291,
"s": 111,
"text": "Input : test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]], i, j = 2, 5 Output : 12 Explanation : Checks for rows 2, 3 and 4, maximum element is 12."
},
{
"code": null,
"e": 472,
"s": 291,
"text": "Input : test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]], i, j = 1, 4 Output : 10 Explanation : Checks for rows 1, 2 and 3, maximum element is 10. "
},
{
"code": null,
"e": 508,
"s": 472,
"text": "Method #1 : Using max() + slicing "
},
{
"code": null,
"e": 708,
"s": 508,
"text": "In this, we perform the task of slicing the rows in which maximum has to be found, then the maximum is found for each row using max(), another max() is applied to get maximum upon extracted elements."
},
{
"code": null,
"e": 716,
"s": 708,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Maximum in Rows Range# Using max() + slicing # initializing listtest_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing rangei, j = 2, 4 res = 0for idx in range(i, j): # getting max in range res = max(max(test_list[idx]), res) # printing resultprint(\"The maximum element in row range ? : \" + str(res))",
"e": 1200,
"s": 716,
"text": null
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Output:"
},
{
"code": null,
"e": 1340,
"s": 1208,
"text": "The original list is : [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]]The maximum element in row range ? : 10"
},
{
"code": null,
"e": 1395,
"s": 1340,
"text": "Method #2 : Using max() + slicing + list comprehension"
},
{
"code": null,
"e": 1504,
"s": 1395,
"text": "In this, we perform the similar task as above using list comprehension to offer one liner to this operation."
},
{
"code": null,
"e": 1512,
"s": 1504,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Maximum in Rows Range# Using max() + slicing + list comprehension # initializing listtest_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing rangei, j = 2, 4 # getting max of maximum of sub listsres = max([max(test_list[idx]) for idx in range(i, j)]) # printing resultprint(\"The maximum element in row range ? : \" + str(res))",
"e": 2012,
"s": 1512,
"text": null
},
{
"code": null,
"e": 2020,
"s": 2012,
"text": "Output:"
},
{
"code": null,
"e": 2152,
"s": 2020,
"text": "The original list is : [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]]The maximum element in row range ? : 10"
},
{
"code": null,
"e": 2173,
"s": 2152,
"text": "Python list-programs"
},
{
"code": null,
"e": 2180,
"s": 2173,
"text": "Python"
},
{
"code": null,
"e": 2196,
"s": 2180,
"text": "Python Programs"
}
] |
How to Restrict Dynamic Allocation of Objects in C++?
|
21 Jun, 2022
C++ programming language allows both auto(or stack-allocated) and dynamically allocated objects. In Java & C#, all objects must be dynamically allocated using new. C++ supports stack-allocated objects for the reason of runtime efficiency. Stack-based objects are implicitly managed by the C++ compiler. They are destroyed when they go out of scope and dynamically allocated objects must be manually released, using the delete operator otherwise, a memory leak occurs. C++ doesn’t support the automatic garbage collection approach used by languages such as Java & C#. How do we achieve the following behavior from a class ‘Test’ in C++?
Test* t = new Test; // should produce compile time error
Test t; // OK
The idea is to keep the new operator function private so that new cannot be called. See the following program. Objects of the ‘Test’ class cannot be created using new as new operator function is private in ‘Test’. If we uncomment the 2nd line of main(), the program would produce a compile-time error.
CPP
// CPP Program to restrict dynamic// allocation of objects in C++#include <iostream>using namespace std; // Objects of Test can not be// dynamically allocatedclass Test { // new operator function is private void* operator new(size_t size); int x; public: Test() { x = 9; cout << "Constructor is called\n"; } void display() { cout << "x = " << x << "\n"; } ~Test() { cout << "Destructor is executed\n"; }}; // Driver Codeint main(){ // Test* obj=new Test(); -> Uncommenting this line would // cause a compile time error. Test t; // Ok, object is allocated at compile time t.display(); // object goes out of scope, destructor will be called return 0;}
Constructor is called
x = 9
Destructor is executed
Also, it is a general query if we can allocate memory for the objects dynamically in C++?
Yes, we can dynamically allocate objects also.
Whenever a new object is created, constructor, a member function of a class is called.
Whenever the object goes out of scope, destructor, a class member function is called.
Time complexity : O(1) Auxiliary Space : O(1)
This article is contributed by Pravasi Meet. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
mahendrabagul569
cpp-pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 689,
"s": 52,
"text": "C++ programming language allows both auto(or stack-allocated) and dynamically allocated objects. In Java & C#, all objects must be dynamically allocated using new. C++ supports stack-allocated objects for the reason of runtime efficiency. Stack-based objects are implicitly managed by the C++ compiler. They are destroyed when they go out of scope and dynamically allocated objects must be manually released, using the delete operator otherwise, a memory leak occurs. C++ doesn’t support the automatic garbage collection approach used by languages such as Java & C#. How do we achieve the following behavior from a class ‘Test’ in C++? "
},
{
"code": null,
"e": 764,
"s": 689,
"text": "Test* t = new Test; // should produce compile time error\nTest t; // OK "
},
{
"code": null,
"e": 1067,
"s": 764,
"text": "The idea is to keep the new operator function private so that new cannot be called. See the following program. Objects of the ‘Test’ class cannot be created using new as new operator function is private in ‘Test’. If we uncomment the 2nd line of main(), the program would produce a compile-time error. "
},
{
"code": null,
"e": 1071,
"s": 1067,
"text": "CPP"
},
{
"code": "// CPP Program to restrict dynamic// allocation of objects in C++#include <iostream>using namespace std; // Objects of Test can not be// dynamically allocatedclass Test { // new operator function is private void* operator new(size_t size); int x; public: Test() { x = 9; cout << \"Constructor is called\\n\"; } void display() { cout << \"x = \" << x << \"\\n\"; } ~Test() { cout << \"Destructor is executed\\n\"; }}; // Driver Codeint main(){ // Test* obj=new Test(); -> Uncommenting this line would // cause a compile time error. Test t; // Ok, object is allocated at compile time t.display(); // object goes out of scope, destructor will be called return 0;}",
"e": 1778,
"s": 1071,
"text": null
},
{
"code": null,
"e": 1829,
"s": 1778,
"text": "Constructor is called\nx = 9\nDestructor is executed"
},
{
"code": null,
"e": 1920,
"s": 1829,
"text": "Also, it is a general query if we can allocate memory for the objects dynamically in C++? "
},
{
"code": null,
"e": 1968,
"s": 1920,
"text": "Yes, we can dynamically allocate objects also. "
},
{
"code": null,
"e": 2055,
"s": 1968,
"text": "Whenever a new object is created, constructor, a member function of a class is called."
},
{
"code": null,
"e": 2141,
"s": 2055,
"text": "Whenever the object goes out of scope, destructor, a class member function is called."
},
{
"code": null,
"e": 2187,
"s": 2141,
"text": "Time complexity : O(1) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 2357,
"s": 2187,
"text": "This article is contributed by Pravasi Meet. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2371,
"s": 2357,
"text": "anshikajain26"
},
{
"code": null,
"e": 2388,
"s": 2371,
"text": "mahendrabagul569"
},
{
"code": null,
"e": 2400,
"s": 2388,
"text": "cpp-pointer"
},
{
"code": null,
"e": 2411,
"s": 2400,
"text": "C Language"
},
{
"code": null,
"e": 2415,
"s": 2411,
"text": "C++"
},
{
"code": null,
"e": 2419,
"s": 2415,
"text": "CPP"
}
] |
How to detect “shift+enter” and generate a new line in Textarea?
|
31 Oct, 2019
The text area tag defines a multi-line text input control. The size of a text area can be specified by the cols and rows attributes. By default, whenever we press “enter” or “shift+enter” it creates a new line in the text area. So, to only detect “shift+enter” and generate a new line from it we need to block “enter” from generating a new line and to redirect it to do something else like submitting.
Example 1: Check out the following Example for “enter” and “shift+enter” mechanism. So, here in the below code both “enter” and “shift+enter” do the same. So, all that has to be done is to either block the “enter” mechanism or redirecting it to do something else.
<!DOCTYPE html><html><body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <script> function geeks(event) { // 13 is the keycode for "enter" if (event.keyCode == 13 && event.shiftKey) { document.getElementById("d").innerHTML = "Triggered enter+shift"; } if (event.keyCode == 13 && !event.shiftKey) { document.getElementById("d").innerHTML = "Triggered enter"; } } </script> <h4>Press "enter" or "shift+enter" in the textarea, both does the same.</h4> <textarea rows="8" cols="50" onkeypress="geeks(event)">GeeksforGeeks A Computer science portal for geeks. </textarea> <p id="d" style="color:red"></p> </center></body> </html>
Output:
Example 2: In the below code, we created a function(submitForm()) to submit the form which just contains a line, because placing this document.geek.submit() under event.preventDefault(), document.geek.submit() will overrides the event.preventDefault() and never blocks the “enter” from creating a line.
<!DOCTYPE html><html> <head> <script> function press(event) { if (event.keyCode == 13 && !event.shiftKey) { //Stops enter from creating a new line event.preventDefault(); submitForm(); return true; } function submitForm() { document.geek.submit(); //submits the form. } } </script></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h4> Press "enter" to submit and "shift+enter" to generate a new line. </h4> <form action="submit.html" name="geek"> <textarea rows="7" cols="30" onkeypress="press(event)"></textarea> </form> </center></body> </html>
HTML in submit.html:
<!DOCTYPE html><html> <body> <h2 style="color:red">List Submitted.</h2> </body></html>
Output:
JavaScript-Misc
Picked
JavaScript
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 430,
"s": 28,
"text": "The text area tag defines a multi-line text input control. The size of a text area can be specified by the cols and rows attributes. By default, whenever we press “enter” or “shift+enter” it creates a new line in the text area. So, to only detect “shift+enter” and generate a new line from it we need to block “enter” from generating a new line and to redirect it to do something else like submitting."
},
{
"code": null,
"e": 694,
"s": 430,
"text": "Example 1: Check out the following Example for “enter” and “shift+enter” mechanism. So, here in the below code both “enter” and “shift+enter” do the same. So, all that has to be done is to either block the “enter” mechanism or redirecting it to do something else."
},
{
"code": "<!DOCTYPE html><html><body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <script> function geeks(event) { // 13 is the keycode for \"enter\" if (event.keyCode == 13 && event.shiftKey) { document.getElementById(\"d\").innerHTML = \"Triggered enter+shift\"; } if (event.keyCode == 13 && !event.shiftKey) { document.getElementById(\"d\").innerHTML = \"Triggered enter\"; } } </script> <h4>Press \"enter\" or \"shift+enter\" in the textarea, both does the same.</h4> <textarea rows=\"8\" cols=\"50\" onkeypress=\"geeks(event)\">GeeksforGeeks A Computer science portal for geeks. </textarea> <p id=\"d\" style=\"color:red\"></p> </center></body> </html>",
"e": 1518,
"s": 694,
"text": null
},
{
"code": null,
"e": 1526,
"s": 1518,
"text": "Output:"
},
{
"code": null,
"e": 1829,
"s": 1526,
"text": "Example 2: In the below code, we created a function(submitForm()) to submit the form which just contains a line, because placing this document.geek.submit() under event.preventDefault(), document.geek.submit() will overrides the event.preventDefault() and never blocks the “enter” from creating a line."
},
{
"code": "<!DOCTYPE html><html> <head> <script> function press(event) { if (event.keyCode == 13 && !event.shiftKey) { //Stops enter from creating a new line event.preventDefault(); submitForm(); return true; } function submitForm() { document.geek.submit(); //submits the form. } } </script></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h4> Press \"enter\" to submit and \"shift+enter\" to generate a new line. </h4> <form action=\"submit.html\" name=\"geek\"> <textarea rows=\"7\" cols=\"30\" onkeypress=\"press(event)\"></textarea> </form> </center></body> </html>",
"e": 2614,
"s": 1829,
"text": null
},
{
"code": null,
"e": 2635,
"s": 2614,
"text": "HTML in submit.html:"
},
{
"code": "<!DOCTYPE html><html> <body> <h2 style=\"color:red\">List Submitted.</h2> </body></html> ",
"e": 2732,
"s": 2635,
"text": null
},
{
"code": null,
"e": 2740,
"s": 2732,
"text": "Output:"
},
{
"code": null,
"e": 2756,
"s": 2740,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2763,
"s": 2756,
"text": "Picked"
},
{
"code": null,
"e": 2774,
"s": 2763,
"text": "JavaScript"
},
{
"code": null,
"e": 2801,
"s": 2774,
"text": "Web technologies Questions"
}
] |
How to make HTML table expand on click using JavaScript ?
|
11 Jun, 2020
The expandable table can be achieved by using JavaScript with HTML. By Clicking on a row of the table, it expands and a sub-table pops up. When the user again clicks on that row the content will hide. This can be very useful when the data is complex but it is inter-related.
Example 1: The following example is implemented using HTML, CSS, and JQuery. It shows data of multiple people working in an organization about their age, salary, and job. By clicking on the row, the table expands and the description about that particular employee is displayed.
html
<!DOCTYPE html><html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"> </script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"> <script type="text/javascript"> function showHideRow(row) { $("#" + row).toggle(); } </script> <style> body { margin: 0 auto; padding: 0px; text-align: center; width: 100%; font-family: "Myriad Pro", "Helvetica Neue", Helvetica, Arial, Sans-Serif; } #wrapper { margin: 0 auto; padding: 0px; text-align: center; width: 995px; } #wrapper h1 { margin-top: 50px; font-size: 45px; color: #585858; } #wrapper h1 p { font-size: 20px; } #table_detail { width: 500px; text-align: left; border-collapse: collapse; color: #2E2E2E; border: #A4A4A4; } #table_detail tr:hover { background-color: #F2F2F2; } #table_detail .hidden_row { display: none; } </style></head> <body> <div id="wrapper"> <table border=1 id="table_detail" align=center cellpadding=10> <tr> <th>Name</th> <th>Age</th> <th>Salary</th> <th>Job</th> </tr> <tr onclick="showHideRow('hidden_row1');"> <td>Person-1</td> <td>24</td> <td>60000</td> <td>Computer Programmer</td> </tr> <tr id="hidden_row1" class="hidden_row"> <td colspan=4> Person-1 is 24 years old and he is a computer programmer he earns 60000 per month </td> </tr> <tr onclick="showHideRow('hidden_row2');"> <td>Person-2</td> <td>25</td> <td>100000</td> <td>Web Designer</td> </tr> <tr id="hidden_row2" class="hidden_row"> <td colspan=4> Person-2 is 25 years old and she is a web designer she earns 100000 per month </td> </tr> <tr onclick="showHideRow('hidden_row3');"> <td>Person-3</td> <td>35</td> <td>90000</td> <td>Cyber Security Expert</td> </tr> <tr id="hidden_row3" class="hidden_row"> <td colspan=4> Person is 35 years old and he is a cyber security expert he earns 90000 per month </td> </tr> <tr onclick="showHideRow('hidden_row4');"> <td>Person-4</td> <td>52</td> <td>200000</td> <td>Content Writer</td> </tr> <tr id="hidden_row4" class="hidden_row"> <td colspan=4> Person-4 is 52 years old and he is a content writer he earns 200000 per month </td> </tr> <tr onclick="showHideRow('hidden_row5');"> <td>Person-5</td> <td>38</td> <td>400000</td> <td>Chief Executive</td> </tr> <tr id="hidden_row5" class="hidden_row"> <td colspan=4> Person-5 is 38 years old and he is chief executive he earns 400000 per month </td> </tr> </table> </div></body> </html>
Output:
Example 2: The following example is implemented using HTML, CSS, and JQuery. In this table, profit and loss are displayed for multiple hotels. By clicking on any of the plus signs, a sub-table is displayed which informs about the hotel’s revenue in three different cities.
html
<!DOCTYPE html><html> <head> <title>Expandable Table</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"> <div align="center" class= "table table-responsive"> <table id="ExpenseTable" class="table table-responsive table-hover table-bordered"> </table> </div> <style> .add-btn { color: green; cursor: pointer; margin-right: 6px; } </style></head> <body> <script> class CellEntry { constructor() { this.sum = 0; this.percentage = 0; } } class OutletBasedRowEntry { constructor() { this.cells = { Total: new CellEntry() }; this.childRows = {}; } add(entry) { this.cells.Total.sum += entry.netamount; this.getOrCreateCellById( entry.outlet).sum += entry.netamount; } getOrCreateChildRowById(id) { if (!this.childRows[id]) this.childRows[id] = new OutletBasedRowEntry(); return this.childRows[id]; } getOrCreateCellById(id) { if (!this.cells[id]) this.cells[id] = new CellEntry(); return this.cells[id]; } } function tabulizeData(data) { let TotalRowEntry = new OutletBasedRowEntry(); data.forEach(entry => { TotalRowEntry.add(entry); TotalRowEntry.getOrCreateChildRowById( entry.brandname).add(entry); TotalRowEntry.getOrCreateChildRowById( entry.brandname). getOrCreateChildRowById( entry.itemname).add(entry); }); renderTable(TotalRowEntry); } function renderTable(TotalRowEntry) { let $table = $('#ExpenseTable'); let $thead = $('<thead><tr><th>Brand Name</th></tr><tr><th></th></tr><tr><th>Total</th></tr><thead>'), $tbody = $('<tbody>'); let $headingRows = $thead.find('tr'); function addCellEntriesToRow( rowEntry, $row) { for (let cellName in TotalRowEntry.cells) { let cellEntry = rowEntry .getOrCreateCellById(cellName); $('<td>').html(cellEntry.sum) .appendTo($row); $('<td>').html(cellEntry.percentage) .appendTo($row); } } $.each(TotalRowEntry.cells, function (cellName, cellEntry) { $('<th colspan=2>').html(cellName) .appendTo($headingRows.eq(0)); $('<th>PROFIT</th>') .appendTo($headingRows.eq(1)); $('<th>LOSS</th>').appendTo( $headingRows.eq(1)); $('<th>').html(cellEntry.sum) .appendTo($headingRows.eq(2)); $('<th>').html(cellEntry.percentage) .appendTo($headingRows.eq(2)); }); $.each(TotalRowEntry.childRows, function (brandName, rowEntry) { let $row = $('<tr>').appendTo($tbody); let rowId = 'row' + $row.index(); let firstCell = $('<td><i class="fas fa-plus add-btn" data-toggle="collapse" data-target=".' + rowId + '"></i>' + brandName + '</td>').appendTo($row); addCellEntriesToRow(rowEntry, $row); $.each(rowEntry.childRows, function ( itemName, rowEntry) { $row = $('<tr>').addClass('collapse ' + rowId).appendTo($tbody); $('<td>').html(itemName).appendTo($row); addCellEntriesToRow(rowEntry, $row); }); }); $thead.appendTo($table); $tbody.appendTo($table); } tabulizeData([{ "outlet": "MUMBAI", "brandname": "HOTEL-1", "itemname": "Restaurant", "transactionType": "TransferIn", "netamount": 980 }, { "outlet": "MUMBAI", "brandname": "HOTEL-1", "itemname": "Hall", "transactionType": "TransferIn", "netamount": 130 }, { "outlet": "MUMBAI", "brandname": "HOTEL-1", "itemname": "Bakery", "transactionType": "TransferIn", "netamount": 500 }, { "outlet": "MUMBAI", "brandname": "HOTEL-2", "itemname": "Restaurant", "transactionType": "TransferIn", "netamount": 110 }, { "outlet": "MUMBAI", "brandname": "HOTEL-2", "itemname": "Party", "transactionType": "TransferIn", "netamount": 720 }, { "outlet": "MUMBAI", "brandname": "HOTEL-2", "itemname": "Pool", "transactionType": "TransferIn", "netamount": 40000 }, { "outlet": "MUMBAI", "brandname": "HOTEL-2", "itemname": "Bakery", "transactionType": "TransferIn", "netamount": 14000 }, { "outlet": "MUMBAI", "brandname": "HOTEL-2", "itemname": "Marriage", "transactionType": "TransferIn", "netamount": 500 }, { "outlet": "MUMBAI", "brandname": "HOTEL-2", "itemname": "Car Valet", "transactionType": "TransferIn", "netamount": 5500 }, { "outlet": "MUMBAI", "brandname": "HOTEL-2", "itemname": "Expense", "transactionType": "TransferIn", "netamount": 1000 }, { "outlet": "MUMBAI", "brandname": "HOTEL-3", "itemname": "Restaurant", "transactionType": "TransferIn", "netamount": 324 }, { "outlet": "MUMBAI", "brandname": "HOTEL-4", "itemname": "Party", "transactionType": "LOSS", "netamount": 476426 }, { "outlet": "JAIPUR", "brandname": "HOTEL-4", "itemname": "Party", "transactionType": "LOSS", "netamount": 115313 }, { "outlet": "BANGALORE", "brandname": "HOTEL-4", "itemname": "Party", "transactionType": "LOSS", "netamount": 92141 } ]); </script></body> </html>
Output:
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 303,
"s": 28,
"text": "The expandable table can be achieved by using JavaScript with HTML. By Clicking on a row of the table, it expands and a sub-table pops up. When the user again clicks on that row the content will hide. This can be very useful when the data is complex but it is inter-related."
},
{
"code": null,
"e": 581,
"s": 303,
"text": "Example 1: The following example is implemented using HTML, CSS, and JQuery. It shows data of multiple people working in an organization about their age, salary, and job. By clicking on the row, the table expands and the description about that particular employee is displayed."
},
{
"code": null,
"e": 586,
"s": 581,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://use.fontawesome.com/releases/v5.6.3/css/all.css\"> <script type=\"text/javascript\"> function showHideRow(row) { $(\"#\" + row).toggle(); } </script> <style> body { margin: 0 auto; padding: 0px; text-align: center; width: 100%; font-family: \"Myriad Pro\", \"Helvetica Neue\", Helvetica, Arial, Sans-Serif; } #wrapper { margin: 0 auto; padding: 0px; text-align: center; width: 995px; } #wrapper h1 { margin-top: 50px; font-size: 45px; color: #585858; } #wrapper h1 p { font-size: 20px; } #table_detail { width: 500px; text-align: left; border-collapse: collapse; color: #2E2E2E; border: #A4A4A4; } #table_detail tr:hover { background-color: #F2F2F2; } #table_detail .hidden_row { display: none; } </style></head> <body> <div id=\"wrapper\"> <table border=1 id=\"table_detail\" align=center cellpadding=10> <tr> <th>Name</th> <th>Age</th> <th>Salary</th> <th>Job</th> </tr> <tr onclick=\"showHideRow('hidden_row1');\"> <td>Person-1</td> <td>24</td> <td>60000</td> <td>Computer Programmer</td> </tr> <tr id=\"hidden_row1\" class=\"hidden_row\"> <td colspan=4> Person-1 is 24 years old and he is a computer programmer he earns 60000 per month </td> </tr> <tr onclick=\"showHideRow('hidden_row2');\"> <td>Person-2</td> <td>25</td> <td>100000</td> <td>Web Designer</td> </tr> <tr id=\"hidden_row2\" class=\"hidden_row\"> <td colspan=4> Person-2 is 25 years old and she is a web designer she earns 100000 per month </td> </tr> <tr onclick=\"showHideRow('hidden_row3');\"> <td>Person-3</td> <td>35</td> <td>90000</td> <td>Cyber Security Expert</td> </tr> <tr id=\"hidden_row3\" class=\"hidden_row\"> <td colspan=4> Person is 35 years old and he is a cyber security expert he earns 90000 per month </td> </tr> <tr onclick=\"showHideRow('hidden_row4');\"> <td>Person-4</td> <td>52</td> <td>200000</td> <td>Content Writer</td> </tr> <tr id=\"hidden_row4\" class=\"hidden_row\"> <td colspan=4> Person-4 is 52 years old and he is a content writer he earns 200000 per month </td> </tr> <tr onclick=\"showHideRow('hidden_row5');\"> <td>Person-5</td> <td>38</td> <td>400000</td> <td>Chief Executive</td> </tr> <tr id=\"hidden_row5\" class=\"hidden_row\"> <td colspan=4> Person-5 is 38 years old and he is chief executive he earns 400000 per month </td> </tr> </table> </div></body> </html>",
"e": 4716,
"s": 586,
"text": null
},
{
"code": null,
"e": 4724,
"s": 4716,
"text": "Output:"
},
{
"code": null,
"e": 4997,
"s": 4724,
"text": "Example 2: The following example is implemented using HTML, CSS, and JQuery. In this table, profit and loss are displayed for multiple hotels. By clicking on any of the plus signs, a sub-table is displayed which informs about the hotel’s revenue in three different cities."
},
{
"code": null,
"e": 5002,
"s": 4997,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Expandable Table</title> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js\"></script> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://use.fontawesome.com/releases/v5.6.3/css/all.css\"> <div align=\"center\" class= \"table table-responsive\"> <table id=\"ExpenseTable\" class=\"table table-responsive table-hover table-bordered\"> </table> </div> <style> .add-btn { color: green; cursor: pointer; margin-right: 6px; } </style></head> <body> <script> class CellEntry { constructor() { this.sum = 0; this.percentage = 0; } } class OutletBasedRowEntry { constructor() { this.cells = { Total: new CellEntry() }; this.childRows = {}; } add(entry) { this.cells.Total.sum += entry.netamount; this.getOrCreateCellById( entry.outlet).sum += entry.netamount; } getOrCreateChildRowById(id) { if (!this.childRows[id]) this.childRows[id] = new OutletBasedRowEntry(); return this.childRows[id]; } getOrCreateCellById(id) { if (!this.cells[id]) this.cells[id] = new CellEntry(); return this.cells[id]; } } function tabulizeData(data) { let TotalRowEntry = new OutletBasedRowEntry(); data.forEach(entry => { TotalRowEntry.add(entry); TotalRowEntry.getOrCreateChildRowById( entry.brandname).add(entry); TotalRowEntry.getOrCreateChildRowById( entry.brandname). getOrCreateChildRowById( entry.itemname).add(entry); }); renderTable(TotalRowEntry); } function renderTable(TotalRowEntry) { let $table = $('#ExpenseTable'); let $thead = $('<thead><tr><th>Brand Name</th></tr><tr><th></th></tr><tr><th>Total</th></tr><thead>'), $tbody = $('<tbody>'); let $headingRows = $thead.find('tr'); function addCellEntriesToRow( rowEntry, $row) { for (let cellName in TotalRowEntry.cells) { let cellEntry = rowEntry .getOrCreateCellById(cellName); $('<td>').html(cellEntry.sum) .appendTo($row); $('<td>').html(cellEntry.percentage) .appendTo($row); } } $.each(TotalRowEntry.cells, function (cellName, cellEntry) { $('<th colspan=2>').html(cellName) .appendTo($headingRows.eq(0)); $('<th>PROFIT</th>') .appendTo($headingRows.eq(1)); $('<th>LOSS</th>').appendTo( $headingRows.eq(1)); $('<th>').html(cellEntry.sum) .appendTo($headingRows.eq(2)); $('<th>').html(cellEntry.percentage) .appendTo($headingRows.eq(2)); }); $.each(TotalRowEntry.childRows, function (brandName, rowEntry) { let $row = $('<tr>').appendTo($tbody); let rowId = 'row' + $row.index(); let firstCell = $('<td><i class=\"fas fa-plus add-btn\" data-toggle=\"collapse\" data-target=\".' + rowId + '\"></i>' + brandName + '</td>').appendTo($row); addCellEntriesToRow(rowEntry, $row); $.each(rowEntry.childRows, function ( itemName, rowEntry) { $row = $('<tr>').addClass('collapse ' + rowId).appendTo($tbody); $('<td>').html(itemName).appendTo($row); addCellEntriesToRow(rowEntry, $row); }); }); $thead.appendTo($table); $tbody.appendTo($table); } tabulizeData([{ \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-1\", \"itemname\": \"Restaurant\", \"transactionType\": \"TransferIn\", \"netamount\": 980 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-1\", \"itemname\": \"Hall\", \"transactionType\": \"TransferIn\", \"netamount\": 130 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-1\", \"itemname\": \"Bakery\", \"transactionType\": \"TransferIn\", \"netamount\": 500 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-2\", \"itemname\": \"Restaurant\", \"transactionType\": \"TransferIn\", \"netamount\": 110 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-2\", \"itemname\": \"Party\", \"transactionType\": \"TransferIn\", \"netamount\": 720 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-2\", \"itemname\": \"Pool\", \"transactionType\": \"TransferIn\", \"netamount\": 40000 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-2\", \"itemname\": \"Bakery\", \"transactionType\": \"TransferIn\", \"netamount\": 14000 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-2\", \"itemname\": \"Marriage\", \"transactionType\": \"TransferIn\", \"netamount\": 500 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-2\", \"itemname\": \"Car Valet\", \"transactionType\": \"TransferIn\", \"netamount\": 5500 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-2\", \"itemname\": \"Expense\", \"transactionType\": \"TransferIn\", \"netamount\": 1000 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-3\", \"itemname\": \"Restaurant\", \"transactionType\": \"TransferIn\", \"netamount\": 324 }, { \"outlet\": \"MUMBAI\", \"brandname\": \"HOTEL-4\", \"itemname\": \"Party\", \"transactionType\": \"LOSS\", \"netamount\": 476426 }, { \"outlet\": \"JAIPUR\", \"brandname\": \"HOTEL-4\", \"itemname\": \"Party\", \"transactionType\": \"LOSS\", \"netamount\": 115313 }, { \"outlet\": \"BANGALORE\", \"brandname\": \"HOTEL-4\", \"itemname\": \"Party\", \"transactionType\": \"LOSS\", \"netamount\": 92141 } ]); </script></body> </html>",
"e": 12294,
"s": 5002,
"text": null
},
{
"code": null,
"e": 12302,
"s": 12294,
"text": "Output:"
},
{
"code": null,
"e": 12311,
"s": 12302,
"text": "CSS-Misc"
},
{
"code": null,
"e": 12321,
"s": 12311,
"text": "HTML-Misc"
},
{
"code": null,
"e": 12328,
"s": 12321,
"text": "Picked"
},
{
"code": null,
"e": 12332,
"s": 12328,
"text": "CSS"
},
{
"code": null,
"e": 12337,
"s": 12332,
"text": "HTML"
},
{
"code": null,
"e": 12354,
"s": 12337,
"text": "Web Technologies"
},
{
"code": null,
"e": 12381,
"s": 12354,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 12386,
"s": 12381,
"text": "HTML"
},
{
"code": null,
"e": 12484,
"s": 12386,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12523,
"s": 12484,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 12560,
"s": 12523,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 12599,
"s": 12560,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 12663,
"s": 12599,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 12724,
"s": 12663,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 12748,
"s": 12724,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 12801,
"s": 12748,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 12861,
"s": 12801,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 12900,
"s": 12861,
"text": "Design a Tribute Page using HTML & CSS"
}
] |
MATLAB – Read images using imread() function
|
12 Dec, 2021
MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984. It is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of algorithms, and creation of user interfaces.
In this article, we are going to discuss how to read images using MATLAB.
In-order to read images we are going to use the imread() function in MATLAB. The imread() function reads images from the graphics files.
Syntax:
A = imread(filename)
It simply read the image and stores it in A.
A = imread(filename,fmt)
Reads image in grayscale or color from the specified file.if image is not present in current directory then please provide the full path of image.
A = imread(Name,Value)
It peruses the predefined picture or pictures from a multi-picture record. This grammar applies just to GIF, PGM, PM, PPM, CUR, ICO, TIF, SVS, and HDF4 documents. You should indicate a filename information, and you can alternatively determine fmt.
Example 1:
Below is a program in which we read a color image using imread() function and store it in A (the imread() function restores the picture information in cluster A) and then we display the image using imshow() function.
C++
% reading imageA = imread('g4g.jpg'); % displaying imageimshow(A);
Output:
Example 2:
Here is another example to read an image in MATLAB.
C++
% reading imageA = imread('g4g.jpg'); % displaying imageimshow(A);
Output:
Note: In the event, if the image is grayscale then, A will be a two-dimensional (M-by-N) exhibit, or else A will be a three-dimensional (M-by-N-by-3) exhibit. The class of the returned cluster relies upon the information type utilized by the record design.
adnanirshad158
MATLAB
Advanced Computer Subject
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Markov Decision Process
Getting Started with System Design
Differences between Procedural and Object Oriented Programming
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Structures in C++
Decorators with parameters in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 366,
"s": 28,
"text": "MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984. It is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of algorithms, and creation of user interfaces. "
},
{
"code": null,
"e": 440,
"s": 366,
"text": "In this article, we are going to discuss how to read images using MATLAB."
},
{
"code": null,
"e": 577,
"s": 440,
"text": "In-order to read images we are going to use the imread() function in MATLAB. The imread() function reads images from the graphics files."
},
{
"code": null,
"e": 585,
"s": 577,
"text": "Syntax:"
},
{
"code": null,
"e": 606,
"s": 585,
"text": "A = imread(filename)"
},
{
"code": null,
"e": 651,
"s": 606,
"text": "It simply read the image and stores it in A."
},
{
"code": null,
"e": 676,
"s": 651,
"text": "A = imread(filename,fmt)"
},
{
"code": null,
"e": 823,
"s": 676,
"text": "Reads image in grayscale or color from the specified file.if image is not present in current directory then please provide the full path of image."
},
{
"code": null,
"e": 846,
"s": 823,
"text": "A = imread(Name,Value)"
},
{
"code": null,
"e": 1094,
"s": 846,
"text": "It peruses the predefined picture or pictures from a multi-picture record. This grammar applies just to GIF, PGM, PM, PPM, CUR, ICO, TIF, SVS, and HDF4 documents. You should indicate a filename information, and you can alternatively determine fmt."
},
{
"code": null,
"e": 1105,
"s": 1094,
"text": "Example 1:"
},
{
"code": null,
"e": 1323,
"s": 1105,
"text": "Below is a program in which we read a color image using imread() function and store it in A (the imread() function restores the picture information in cluster A) and then we display the image using imshow() function. "
},
{
"code": null,
"e": 1327,
"s": 1323,
"text": "C++"
},
{
"code": "% reading imageA = imread('g4g.jpg'); % displaying imageimshow(A);",
"e": 1394,
"s": 1327,
"text": null
},
{
"code": null,
"e": 1402,
"s": 1394,
"text": "Output:"
},
{
"code": null,
"e": 1415,
"s": 1404,
"text": "Example 2:"
},
{
"code": null,
"e": 1467,
"s": 1415,
"text": "Here is another example to read an image in MATLAB."
},
{
"code": null,
"e": 1471,
"s": 1467,
"text": "C++"
},
{
"code": "% reading imageA = imread('g4g.jpg'); % displaying imageimshow(A);",
"e": 1538,
"s": 1471,
"text": null
},
{
"code": null,
"e": 1546,
"s": 1538,
"text": "Output:"
},
{
"code": null,
"e": 1803,
"s": 1546,
"text": "Note: In the event, if the image is grayscale then, A will be a two-dimensional (M-by-N) exhibit, or else A will be a three-dimensional (M-by-N-by-3) exhibit. The class of the returned cluster relies upon the information type utilized by the record design."
},
{
"code": null,
"e": 1818,
"s": 1803,
"text": "adnanirshad158"
},
{
"code": null,
"e": 1825,
"s": 1818,
"text": "MATLAB"
},
{
"code": null,
"e": 1851,
"s": 1825,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 1872,
"s": 1851,
"text": "Programming Language"
},
{
"code": null,
"e": 1970,
"s": 1872,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2006,
"s": 1970,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2042,
"s": 2006,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 2086,
"s": 2042,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 2110,
"s": 2086,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2145,
"s": 2110,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 2208,
"s": 2145,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 2249,
"s": 2208,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 2292,
"s": 2249,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 2310,
"s": 2292,
"text": "Structures in C++"
}
] |
Spring – REST Controller
|
26 Nov, 2021
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. In this article, we will discuss what is REST controller is in the spring boot. There are mainly two controllers are used in the spring, controller and the second one is RestController with the help of @controller and @restcontroller annotations. The main difference between the @restcontroller and the @controller is that the @restcontroller combination of the @controller and @ResponseBody annotation.
RestController: RestController is used for making restful web services with the help of the @RestController annotation. This annotation is used at the class level and allows the class to handle the requests made by the client. Let’s understand @RestController annotation using an example. The RestController allows to handle all REST APIs such as GET, POST, Delete, PUT requests.
Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed sequentially as follows.
Step 1: Go to Spring Initializr
Fill in the details as per the requirements. For this application:
Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web
Step 2: Click on Generate which will download the starter project
Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:
Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.
Step 4: Go to src > main > java > com.gfg.Spring.boot.app, create a java class with the name Controller and add the annotation @RestController and other class named as Details.
Details:
Java
public class Details { // Creating an object of ArrayList static ArrayList<Details> Data = new ArrayList<Details>(); int number; String name; Details(int number, String name) { // This keyword refers // to parent instance itself this.number = number; this.name = name; }}
Controller:
Java
@RestController// Classpublic class Controller { // Constructor Controller() { a.add(1); a.add(2); } @GetMapping("/hello/{name}/{age}") public void insert(@PathVariable("name") String name, @PathVariable("age") int age) { // Print and display name and age System.out.println(name); System.out.println(age); } // Creating an empty ArrayList ArrayList<Integer> a = new ArrayList<>(); // Annotation @DeleteMapping("/hello/{id}") // Method public void deleteById(@PathVariable("id") int id) { a.remove(new Integer((id))); print(); } // Handling post request @PostMapping("/EnterDetails") String insert(@RequestBody Details ob) { // Storing the incoming data in the list Data.add(new Details(ob.number, ob.name)); // Iterating using foreach loop for (Details obd : Data) { System.out.println(obd.name + " " + ob.number); } return "Data Inserted"; } // Method void print() { for (int elements : a) { System.out.print(elements); }}
This application is now ready to run.
Step 5: Run the SpringBootAppApplication class and wait for the Tomcat server to start.
Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file.
Let’s make a delete request from the postman
Output: As generated on console
2
This controller.java file is used for handling all incoming requests from the client-side.
Java-Spring
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 880,
"s": 53,
"text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. In this article, we will discuss what is REST controller is in the spring boot. There are mainly two controllers are used in the spring, controller and the second one is RestController with the help of @controller and @restcontroller annotations. The main difference between the @restcontroller and the @controller is that the @restcontroller combination of the @controller and @ResponseBody annotation."
},
{
"code": null,
"e": 1261,
"s": 880,
"text": "RestController: RestController is used for making restful web services with the help of the @RestController annotation. This annotation is used at the class level and allows the class to handle the requests made by the client. Let’s understand @RestController annotation using an example. The RestController allows to handle all REST APIs such as GET, POST, Delete, PUT requests. "
},
{
"code": null,
"e": 1765,
"s": 1261,
"text": "Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed sequentially as follows."
},
{
"code": null,
"e": 1797,
"s": 1765,
"text": "Step 1: Go to Spring Initializr"
},
{
"code": null,
"e": 1864,
"s": 1797,
"text": "Fill in the details as per the requirements. For this application:"
},
{
"code": null,
"e": 1961,
"s": 1864,
"text": "Project: Maven\nLanguage: Java\nSpring Boot: 2.2.8\nPackaging: JAR\nJava: 8\nDependencies: Spring Web"
},
{
"code": null,
"e": 2027,
"s": 1961,
"text": "Step 2: Click on Generate which will download the starter project"
},
{
"code": null,
"e": 2286,
"s": 2027,
"text": "Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:"
},
{
"code": null,
"e": 2424,
"s": 2286,
"text": "Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project."
},
{
"code": null,
"e": 2601,
"s": 2424,
"text": "Step 4: Go to src > main > java > com.gfg.Spring.boot.app, create a java class with the name Controller and add the annotation @RestController and other class named as Details."
},
{
"code": null,
"e": 2610,
"s": 2601,
"text": "Details:"
},
{
"code": null,
"e": 2615,
"s": 2610,
"text": "Java"
},
{
"code": "public class Details { // Creating an object of ArrayList static ArrayList<Details> Data = new ArrayList<Details>(); int number; String name; Details(int number, String name) { // This keyword refers // to parent instance itself this.number = number; this.name = name; }}",
"e": 2941,
"s": 2615,
"text": null
},
{
"code": null,
"e": 2953,
"s": 2941,
"text": "Controller:"
},
{
"code": null,
"e": 2958,
"s": 2953,
"text": "Java"
},
{
"code": "@RestController// Classpublic class Controller { // Constructor Controller() { a.add(1); a.add(2); } @GetMapping(\"/hello/{name}/{age}\") public void insert(@PathVariable(\"name\") String name, @PathVariable(\"age\") int age) { // Print and display name and age System.out.println(name); System.out.println(age); } // Creating an empty ArrayList ArrayList<Integer> a = new ArrayList<>(); // Annotation @DeleteMapping(\"/hello/{id}\") // Method public void deleteById(@PathVariable(\"id\") int id) { a.remove(new Integer((id))); print(); } // Handling post request @PostMapping(\"/EnterDetails\") String insert(@RequestBody Details ob) { // Storing the incoming data in the list Data.add(new Details(ob.number, ob.name)); // Iterating using foreach loop for (Details obd : Data) { System.out.println(obd.name + \" \" + ob.number); } return \"Data Inserted\"; } // Method void print() { for (int elements : a) { System.out.print(elements); }}",
"e": 4123,
"s": 2958,
"text": null
},
{
"code": null,
"e": 4161,
"s": 4123,
"text": "This application is now ready to run."
},
{
"code": null,
"e": 4249,
"s": 4161,
"text": "Step 5: Run the SpringBootAppApplication class and wait for the Tomcat server to start."
},
{
"code": null,
"e": 4356,
"s": 4249,
"text": "Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file."
},
{
"code": null,
"e": 4401,
"s": 4356,
"text": "Let’s make a delete request from the postman"
},
{
"code": null,
"e": 4434,
"s": 4401,
"text": "Output: As generated on console "
},
{
"code": null,
"e": 4436,
"s": 4434,
"text": "2"
},
{
"code": null,
"e": 4527,
"s": 4436,
"text": "This controller.java file is used for handling all incoming requests from the client-side."
},
{
"code": null,
"e": 4539,
"s": 4527,
"text": "Java-Spring"
},
{
"code": null,
"e": 4546,
"s": 4539,
"text": "Picked"
},
{
"code": null,
"e": 4551,
"s": 4546,
"text": "Java"
},
{
"code": null,
"e": 4556,
"s": 4551,
"text": "Java"
},
{
"code": null,
"e": 4654,
"s": 4556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4685,
"s": 4654,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4704,
"s": 4685,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4734,
"s": 4704,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4749,
"s": 4734,
"text": "Stream In Java"
},
{
"code": null,
"e": 4767,
"s": 4749,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4787,
"s": 4767,
"text": "Collections in Java"
},
{
"code": null,
"e": 4811,
"s": 4787,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 4843,
"s": 4811,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 4855,
"s": 4843,
"text": "Set in Java"
}
] |
Sum of non-diagonal parts of a square Matrix
|
16 May, 2022
Given a square matrix of size N X N, the task is to find the sum of all elements at each portion when the matrix is divided into four parts along its diagonals. The elements at the diagonals should not be counted in the sum.Examples:
Input: arr[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output: 68 Explanation:
From the above image, (1, 6, 11, 16) and (4, 7, 10, 13) are the diagonals. The sum of the elements needs to be found are: Top: (2 + 3) = 5 Left: (5 + 9) = 14 Bottom: (14 + 15) = 29 Right: (8 + 12) = 20 Therefore, sum of all parts = 68.Input: arr[][] = { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {1, 3, 1, 5}} Output: 19
Approach: The idea is to use indexing to identify the elements at the diagonals.
In a 2-dimensional matrix, two diagonals are identified in the following way: Principal Diagonal: The first diagonal has the index of the row is equal to the index of the column.
In a 2-dimensional matrix, two diagonals are identified in the following way: Principal Diagonal: The first diagonal has the index of the row is equal to the index of the column.
Principal Diagonal: The first diagonal has the index of the row is equal to the index of the column.
Principal Diagonal: The first diagonal has the index of the row is equal to the index of the column.
Condition for Principal Diagonal:
The row-column condition is row = column.
Secondary Diagonal: The second diagonal has the sum of the index of row and column equal to N(size of the matrix).
Secondary Diagonal: The second diagonal has the sum of the index of row and column equal to N(size of the matrix).
Condition for Secondary Diagonal:
The row-column condition is row = numberOfRows - column -1
After identifying both the diagonals, the matrix can further be divided into two parts using the diagonal passing through the first element of the last row and the last element of the first row: The left part: If the column index is greater than row index, the element belongs to the top portion of the matrix.If the row index is greater than column index, the element belongs to the left portion of the matrix.The right part: If the column index is greater than row index, the element belongs to the right portion of the matrix.If the row index is greater than column index, the element belongs to the bottom portion of the matrix.
After identifying both the diagonals, the matrix can further be divided into two parts using the diagonal passing through the first element of the last row and the last element of the first row: The left part: If the column index is greater than row index, the element belongs to the top portion of the matrix.If the row index is greater than column index, the element belongs to the left portion of the matrix.The right part: If the column index is greater than row index, the element belongs to the right portion of the matrix.If the row index is greater than column index, the element belongs to the bottom portion of the matrix.
The left part: If the column index is greater than row index, the element belongs to the top portion of the matrix.If the row index is greater than column index, the element belongs to the left portion of the matrix.The right part: If the column index is greater than row index, the element belongs to the right portion of the matrix.If the row index is greater than column index, the element belongs to the bottom portion of the matrix.
The left part: If the column index is greater than row index, the element belongs to the top portion of the matrix.If the row index is greater than column index, the element belongs to the left portion of the matrix.
If the column index is greater than row index, the element belongs to the top portion of the matrix.
If the row index is greater than column index, the element belongs to the left portion of the matrix.
The right part: If the column index is greater than row index, the element belongs to the right portion of the matrix.If the row index is greater than column index, the element belongs to the bottom portion of the matrix.
If the column index is greater than row index, the element belongs to the right portion of the matrix.
If the row index is greater than column index, the element belongs to the bottom portion of the matrix.
So in order to get the sum of the non-diagonal parts of the matrix: Traverse the matrix rowwiseIf the element is a part of diagonal, then skip this elementIf the element is part of the left, right, bottom, or top part (i.e. non-diagonal parts), add the element in the resultant sum
So in order to get the sum of the non-diagonal parts of the matrix: Traverse the matrix rowwiseIf the element is a part of diagonal, then skip this elementIf the element is part of the left, right, bottom, or top part (i.e. non-diagonal parts), add the element in the resultant sum
Traverse the matrix rowwise
If the element is a part of diagonal, then skip this element
If the element is part of the left, right, bottom, or top part (i.e. non-diagonal parts), add the element in the resultant sum
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to return a vector which// consists the sum of// four portions of the matrixint sumOfParts(int* arr, int N){ int sum_part1 = 0, sum_part2 = 0, sum_part3 = 0, sum_part4 = 0; int totalsum = 0; // Iterating through the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Condition for selecting all values // before the second diagonal of metrics if (i + j < N - 1) { // Top portion of the matrix if (i < j and i != j and i + j) sum_part1 += (arr + i * N)[j]; // Left portion of the matrix else if (i != j) sum_part2 += (arr + i * N)[j]; } else { // Bottom portion of the matrix if (i > j and i + j != N - 1) sum_part3 += (arr + i * N)[j]; // Right portion of the matrix else { if (i + j != N - 1 and i != j) sum_part4 += (arr + i * N)[j]; } } } } // Adding all the four portions into a vector totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4; return totalsum;} // Driver codeint main(){ int N = 4; int arr[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; cout << sumOfParts((int*)arr, N);}
// Java implementation of the above approachclass GFG{ // Function to return a vector which// consists the sum of// four portions of the matrixstatic int sumOfParts(int[][] arr, int N){ int sum_part1 = 0, sum_part2 = 0, sum_part3 = 0, sum_part4 = 0; int totalsum = 0; // Iterating through the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Condition for selecting all values // before the second diagonal of metrics if (i + j < N - 1) { // Top portion of the matrix if (i < j && i != j && i + j > 0) sum_part1 += arr[i][j]; // Left portion of the matrix else if (i != j) sum_part2 += arr[i][j]; } else { // Bottom portion of the matrix if (i > j && i + j != N - 1) sum_part3 += arr[i][j]; // Right portion of the matrix else { if (i + j != N - 1 && i != j) sum_part4 += arr[i][j]; } } } } // Adding all the four portions into a vector totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4; return totalsum;} // Driver codepublic static void main(String[] args){ int N = 4; int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; System.out.print(sumOfParts(arr, N));}} // This code is contributed by PrinciRaj1992
# Python3 implementation of the above approach # Function to return a vector which# consists the sum of# four portions of the matrixdef sumOfParts(arr,N): sum_part1, sum_part2, sum_part3, \ sum_part4 = 0, 0, 0, 0 totalsum = 0 # Iterating through the matrix for i in range(N): for j in range(N): # Condition for selecting all values # before the second diagonal of metrics if i + j < N - 1: # Top portion of the matrix if(i < j and i != j and i + j): sum_part1 += arr[i][j] # Left portion of the matrix elif i != j: sum_part2 += arr[i][j] else: # Bottom portion of the matrix if i > j and i + j != N - 1: sum_part3 += arr[i][j] else: # Right portion of the matrix if i + j != N - 1 and i != j: sum_part4 += arr[i][j] # Adding all the four portions into a vector return sum_part1 + sum_part2 + sum_part3 + sum_part4 # Driver codeN = 4arr = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]] print(sumOfParts(arr, N)) # This code is contributed by mohit kumar 29
// C# implementation of the above approachusing System; class GFG{ // Function to return a vector which // consists the sum of // four portions of the matrix static int sumOfParts(int[,] arr, int N) { int sum_part1 = 0, sum_part2 = 0, sum_part3 = 0, sum_part4 = 0; int totalsum = 0; // Iterating through the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Condition for selecting all values // before the second diagonal of metrics if (i + j < N - 1) { // Top portion of the matrix if (i < j && i != j && i + j > 0) sum_part1 += arr[i, j]; // Left portion of the matrix else if (i != j) sum_part2 += arr[i, j]; } else { // Bottom portion of the matrix if (i > j && i + j != N - 1) sum_part3 += arr[i, j]; // Right portion of the matrix else { if (i + j != N - 1 && i != j) sum_part4 += arr[i, j]; } } } } // Adding all the four portions into a vector totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4; return totalsum; } // Driver code public static void Main() { int N = 4; int [,]arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; Console.WriteLine(sumOfParts(arr, N)); }} // This code is contributed by Yash_R
<script> // javascript implementation of the above approach // Function to return a vector which// consists the sum of// four portions of the matrixfunction sumOfParts(arr , N){ var sum_part1 = 0, sum_part2 = 0, sum_part3 = 0, sum_part4 = 0; var totalsum = 0; // Iterating through the matrix for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { // Condition for selecting all values // before the second diagonal of metrics if (i + j < N - 1) { // Top portion of the matrix if (i < j && i != j && i + j > 0) sum_part1 += arr[i][j]; // Left portion of the matrix else if (i != j) sum_part2 += arr[i][j]; } else { // Bottom portion of the matrix if (i > j && i + j != N - 1) sum_part3 += arr[i][j]; // Right portion of the matrix else { if (i + j != N - 1 && i != j) sum_part4 += arr[i][j]; } } } } // Adding all the four portions into a vector totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4; return totalsum;} // Driver codevar N = 4;var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; document.write(sumOfParts(arr, N)); // This code is contributed by 29AjayKumar </script>
68
Time Complexity: O(N2) as we are traversing the complete matrix row-wise.
Auxiliary Space: O(1)
mohit kumar 29
princiraj1992
Yash_R
29AjayKumar
vansikasharma1329
sagar0719kumar
ankita_saini
array-traversal-question
Arrays
Mathematical
Matrix
School Programming
Arrays
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 May, 2022"
},
{
"code": null,
"e": 289,
"s": 53,
"text": "Given a square matrix of size N X N, the task is to find the sum of all elements at each portion when the matrix is divided into four parts along its diagonals. The elements at the diagonals should not be counted in the sum.Examples: "
},
{
"code": null,
"e": 396,
"s": 289,
"text": "Input: arr[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output: 68 Explanation: "
},
{
"code": null,
"e": 719,
"s": 396,
"text": "From the above image, (1, 6, 11, 16) and (4, 7, 10, 13) are the diagonals. The sum of the elements needs to be found are: Top: (2 + 3) = 5 Left: (5 + 9) = 14 Bottom: (14 + 15) = 29 Right: (8 + 12) = 20 Therefore, sum of all parts = 68.Input: arr[][] = { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {1, 3, 1, 5}} Output: 19 "
},
{
"code": null,
"e": 804,
"s": 721,
"text": "Approach: The idea is to use indexing to identify the elements at the diagonals. "
},
{
"code": null,
"e": 985,
"s": 804,
"text": "In a 2-dimensional matrix, two diagonals are identified in the following way: Principal Diagonal: The first diagonal has the index of the row is equal to the index of the column. "
},
{
"code": null,
"e": 1166,
"s": 985,
"text": "In a 2-dimensional matrix, two diagonals are identified in the following way: Principal Diagonal: The first diagonal has the index of the row is equal to the index of the column. "
},
{
"code": null,
"e": 1269,
"s": 1166,
"text": "Principal Diagonal: The first diagonal has the index of the row is equal to the index of the column. "
},
{
"code": null,
"e": 1372,
"s": 1269,
"text": "Principal Diagonal: The first diagonal has the index of the row is equal to the index of the column. "
},
{
"code": null,
"e": 1448,
"s": 1372,
"text": "Condition for Principal Diagonal:\nThe row-column condition is row = column."
},
{
"code": null,
"e": 1566,
"s": 1448,
"text": " Secondary Diagonal: The second diagonal has the sum of the index of row and column equal to N(size of the matrix). "
},
{
"code": null,
"e": 1685,
"s": 1568,
"text": "Secondary Diagonal: The second diagonal has the sum of the index of row and column equal to N(size of the matrix). "
},
{
"code": null,
"e": 1778,
"s": 1685,
"text": "Condition for Secondary Diagonal:\nThe row-column condition is row = numberOfRows - column -1"
},
{
"code": null,
"e": 2412,
"s": 1778,
"text": " After identifying both the diagonals, the matrix can further be divided into two parts using the diagonal passing through the first element of the last row and the last element of the first row: The left part: If the column index is greater than row index, the element belongs to the top portion of the matrix.If the row index is greater than column index, the element belongs to the left portion of the matrix.The right part: If the column index is greater than row index, the element belongs to the right portion of the matrix.If the row index is greater than column index, the element belongs to the bottom portion of the matrix."
},
{
"code": null,
"e": 3047,
"s": 2414,
"text": "After identifying both the diagonals, the matrix can further be divided into two parts using the diagonal passing through the first element of the last row and the last element of the first row: The left part: If the column index is greater than row index, the element belongs to the top portion of the matrix.If the row index is greater than column index, the element belongs to the left portion of the matrix.The right part: If the column index is greater than row index, the element belongs to the right portion of the matrix.If the row index is greater than column index, the element belongs to the bottom portion of the matrix."
},
{
"code": null,
"e": 3485,
"s": 3047,
"text": "The left part: If the column index is greater than row index, the element belongs to the top portion of the matrix.If the row index is greater than column index, the element belongs to the left portion of the matrix.The right part: If the column index is greater than row index, the element belongs to the right portion of the matrix.If the row index is greater than column index, the element belongs to the bottom portion of the matrix."
},
{
"code": null,
"e": 3702,
"s": 3485,
"text": "The left part: If the column index is greater than row index, the element belongs to the top portion of the matrix.If the row index is greater than column index, the element belongs to the left portion of the matrix."
},
{
"code": null,
"e": 3803,
"s": 3702,
"text": "If the column index is greater than row index, the element belongs to the top portion of the matrix."
},
{
"code": null,
"e": 3905,
"s": 3803,
"text": "If the row index is greater than column index, the element belongs to the left portion of the matrix."
},
{
"code": null,
"e": 4127,
"s": 3905,
"text": "The right part: If the column index is greater than row index, the element belongs to the right portion of the matrix.If the row index is greater than column index, the element belongs to the bottom portion of the matrix."
},
{
"code": null,
"e": 4230,
"s": 4127,
"text": "If the column index is greater than row index, the element belongs to the right portion of the matrix."
},
{
"code": null,
"e": 4334,
"s": 4230,
"text": "If the row index is greater than column index, the element belongs to the bottom portion of the matrix."
},
{
"code": null,
"e": 4616,
"s": 4334,
"text": "So in order to get the sum of the non-diagonal parts of the matrix: Traverse the matrix rowwiseIf the element is a part of diagonal, then skip this elementIf the element is part of the left, right, bottom, or top part (i.e. non-diagonal parts), add the element in the resultant sum"
},
{
"code": null,
"e": 4898,
"s": 4616,
"text": "So in order to get the sum of the non-diagonal parts of the matrix: Traverse the matrix rowwiseIf the element is a part of diagonal, then skip this elementIf the element is part of the left, right, bottom, or top part (i.e. non-diagonal parts), add the element in the resultant sum"
},
{
"code": null,
"e": 4926,
"s": 4898,
"text": "Traverse the matrix rowwise"
},
{
"code": null,
"e": 4987,
"s": 4926,
"text": "If the element is a part of diagonal, then skip this element"
},
{
"code": null,
"e": 5114,
"s": 4987,
"text": "If the element is part of the left, right, bottom, or top part (i.e. non-diagonal parts), add the element in the resultant sum"
},
{
"code": null,
"e": 5167,
"s": 5114,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 5171,
"s": 5167,
"text": "C++"
},
{
"code": null,
"e": 5176,
"s": 5171,
"text": "Java"
},
{
"code": null,
"e": 5184,
"s": 5176,
"text": "Python3"
},
{
"code": null,
"e": 5187,
"s": 5184,
"text": "C#"
},
{
"code": null,
"e": 5198,
"s": 5187,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to return a vector which// consists the sum of// four portions of the matrixint sumOfParts(int* arr, int N){ int sum_part1 = 0, sum_part2 = 0, sum_part3 = 0, sum_part4 = 0; int totalsum = 0; // Iterating through the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Condition for selecting all values // before the second diagonal of metrics if (i + j < N - 1) { // Top portion of the matrix if (i < j and i != j and i + j) sum_part1 += (arr + i * N)[j]; // Left portion of the matrix else if (i != j) sum_part2 += (arr + i * N)[j]; } else { // Bottom portion of the matrix if (i > j and i + j != N - 1) sum_part3 += (arr + i * N)[j]; // Right portion of the matrix else { if (i + j != N - 1 and i != j) sum_part4 += (arr + i * N)[j]; } } } } // Adding all the four portions into a vector totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4; return totalsum;} // Driver codeint main(){ int N = 4; int arr[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; cout << sumOfParts((int*)arr, N);}",
"e": 6786,
"s": 5198,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG{ // Function to return a vector which// consists the sum of// four portions of the matrixstatic int sumOfParts(int[][] arr, int N){ int sum_part1 = 0, sum_part2 = 0, sum_part3 = 0, sum_part4 = 0; int totalsum = 0; // Iterating through the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Condition for selecting all values // before the second diagonal of metrics if (i + j < N - 1) { // Top portion of the matrix if (i < j && i != j && i + j > 0) sum_part1 += arr[i][j]; // Left portion of the matrix else if (i != j) sum_part2 += arr[i][j]; } else { // Bottom portion of the matrix if (i > j && i + j != N - 1) sum_part3 += arr[i][j]; // Right portion of the matrix else { if (i + j != N - 1 && i != j) sum_part4 += arr[i][j]; } } } } // Adding all the four portions into a vector totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4; return totalsum;} // Driver codepublic static void main(String[] args){ int N = 4; int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; System.out.print(sumOfParts(arr, N));}} // This code is contributed by PrinciRaj1992",
"e": 8408,
"s": 6786,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to return a vector which# consists the sum of# four portions of the matrixdef sumOfParts(arr,N): sum_part1, sum_part2, sum_part3, \\ sum_part4 = 0, 0, 0, 0 totalsum = 0 # Iterating through the matrix for i in range(N): for j in range(N): # Condition for selecting all values # before the second diagonal of metrics if i + j < N - 1: # Top portion of the matrix if(i < j and i != j and i + j): sum_part1 += arr[i][j] # Left portion of the matrix elif i != j: sum_part2 += arr[i][j] else: # Bottom portion of the matrix if i > j and i + j != N - 1: sum_part3 += arr[i][j] else: # Right portion of the matrix if i + j != N - 1 and i != j: sum_part4 += arr[i][j] # Adding all the four portions into a vector return sum_part1 + sum_part2 + sum_part3 + sum_part4 # Driver codeN = 4arr = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]] print(sumOfParts(arr, N)) # This code is contributed by mohit kumar 29",
"e": 9788,
"s": 8408,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to return a vector which // consists the sum of // four portions of the matrix static int sumOfParts(int[,] arr, int N) { int sum_part1 = 0, sum_part2 = 0, sum_part3 = 0, sum_part4 = 0; int totalsum = 0; // Iterating through the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Condition for selecting all values // before the second diagonal of metrics if (i + j < N - 1) { // Top portion of the matrix if (i < j && i != j && i + j > 0) sum_part1 += arr[i, j]; // Left portion of the matrix else if (i != j) sum_part2 += arr[i, j]; } else { // Bottom portion of the matrix if (i > j && i + j != N - 1) sum_part3 += arr[i, j]; // Right portion of the matrix else { if (i + j != N - 1 && i != j) sum_part4 += arr[i, j]; } } } } // Adding all the four portions into a vector totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4; return totalsum; } // Driver code public static void Main() { int N = 4; int [,]arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; Console.WriteLine(sumOfParts(arr, N)); }} // This code is contributed by Yash_R",
"e": 11629,
"s": 9788,
"text": null
},
{
"code": "<script> // javascript implementation of the above approach // Function to return a vector which// consists the sum of// four portions of the matrixfunction sumOfParts(arr , N){ var sum_part1 = 0, sum_part2 = 0, sum_part3 = 0, sum_part4 = 0; var totalsum = 0; // Iterating through the matrix for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { // Condition for selecting all values // before the second diagonal of metrics if (i + j < N - 1) { // Top portion of the matrix if (i < j && i != j && i + j > 0) sum_part1 += arr[i][j]; // Left portion of the matrix else if (i != j) sum_part2 += arr[i][j]; } else { // Bottom portion of the matrix if (i > j && i + j != N - 1) sum_part3 += arr[i][j]; // Right portion of the matrix else { if (i + j != N - 1 && i != j) sum_part4 += arr[i][j]; } } } } // Adding all the four portions into a vector totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4; return totalsum;} // Driver codevar N = 4;var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; document.write(sumOfParts(arr, N)); // This code is contributed by 29AjayKumar </script>",
"e": 13172,
"s": 11629,
"text": null
},
{
"code": null,
"e": 13175,
"s": 13172,
"text": "68"
},
{
"code": null,
"e": 13251,
"s": 13177,
"text": "Time Complexity: O(N2) as we are traversing the complete matrix row-wise."
},
{
"code": null,
"e": 13274,
"s": 13251,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 13289,
"s": 13274,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 13303,
"s": 13289,
"text": "princiraj1992"
},
{
"code": null,
"e": 13310,
"s": 13303,
"text": "Yash_R"
},
{
"code": null,
"e": 13322,
"s": 13310,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13340,
"s": 13322,
"text": "vansikasharma1329"
},
{
"code": null,
"e": 13355,
"s": 13340,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 13368,
"s": 13355,
"text": "ankita_saini"
},
{
"code": null,
"e": 13393,
"s": 13368,
"text": "array-traversal-question"
},
{
"code": null,
"e": 13400,
"s": 13393,
"text": "Arrays"
},
{
"code": null,
"e": 13413,
"s": 13400,
"text": "Mathematical"
},
{
"code": null,
"e": 13420,
"s": 13413,
"text": "Matrix"
},
{
"code": null,
"e": 13439,
"s": 13420,
"text": "School Programming"
},
{
"code": null,
"e": 13446,
"s": 13439,
"text": "Arrays"
},
{
"code": null,
"e": 13459,
"s": 13446,
"text": "Mathematical"
},
{
"code": null,
"e": 13466,
"s": 13459,
"text": "Matrix"
}
] |
Select Rows & Columns by Name or Index in Pandas DataFrame using [ ], loc & iloc
|
10 Jul, 2020
Indexing in Pandas means selecting rows and columns of data from a Dataframe. It can be selecting all the rows and the particular number of columns, a particular number of rows, and all the columns or a particular number of rows and columns each. Indexing is also known as Subset selection.Let’s create a simple dataframe with a list of tuples, say column names are: ‘Name’, ‘Age’, ‘City’ and ‘Salary’.
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary'])# Show the dataframedf
Output:
Method 1: using Dataframe.[ ].[ ] is used to select a column by mentioning the respective column name.
Example 1 : to select single column.Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator [] # to select a columnresult = df["City"] # Show the dataframeresult
Output:
Example 2: to select multiple columns.Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator [] to # select multiple columnsresult = df[["Name", "Age", "Salary"]] # Show the dataframeresult
Output:
Method 2: Using Dataframe.loc[ ]..loc[] the function selects the data by labels of rows or columns. It can select a subset of rows and columns. There are many ways to use this function.Example 1: To select single row.Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Set 'Name' column as index # on a Dataframedf.set_index("Name", inplace = True) # Using the operator .loc[]# to select single rowresult = df.loc["Stuti"] # Show the dataframeresult
Output:
Example 2: To select multiple rows.Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Set index on a Dataframedf.set_index("Name", inplace = True) # Using the operator .loc[]# to select multiple rowsresult = df.loc[["Stuti", "Seema"]] # Show the dataframeresult
Output:
Example 3: To select multiple rows and particular columns.
Syntax: Dataframe.loc[["row1", "row2"...], ["column1", "column2", "column3"...]]
Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Set 'Name' column as index # on a Dataframedf.set_index("Name", inplace = True) # Using the operator .loc[] to # select multiple rows with some# particular columnsresult = df.loc[["Stuti", "Seema"], ["City", "Salary"]] # Show the dataframeresult
Output:
Example 4: To select all the rows with some particular columns. We use single colon [ : ] to select all rows and list of columns which we want to select as given below :
Syntax: Dataframe.loc[[:, ["column1", "column2", "column3"]]
Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Creating a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Set 'Name' column as index # on a Dataframedf.set_index("Name", inplace = True) # Using the operator .loc[] to# select all the rows with # some particular columnsresult = df.loc[:, ["City", "Salary"]] # Show the dataframeresult
Output:
Method 3: Using Dataframe.iloc[ ].iloc[ ] is used for selection based on position. It is similar to loc[] indexer but it takes only integer values to make selections.Example 1 : to select a single row.Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator .iloc[]# to select single rowresult = df.iloc[2] # Show the dataframeresult
Output:
Example 2: to select multiple rows.Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator .iloc[] # to select multiple rowsresult = df.iloc[[2, 3, 5]] # Show the dataframeresult
Output:
Example 3: to select multiple rows with some particular columns.Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Creating a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator .iloc[] # to select multiple rows with# some particular columnsresult = df.iloc[[2, 3, 5], [0, 1]] # Show the dataframeresult
Output:
Example 4: to select all the rows with some particular columns.Code:
# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator .iloc[]# to select all the rows with# some particular columnsresult = df.iloc[:, [0, 1]] # Show the dataframeresult
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 455,
"s": 52,
"text": "Indexing in Pandas means selecting rows and columns of data from a Dataframe. It can be selecting all the rows and the particular number of columns, a particular number of rows, and all the columns or a particular number of rows and columns each. Indexing is also known as Subset selection.Let’s create a simple dataframe with a list of tuples, say column names are: ‘Name’, ‘Age’, ‘City’ and ‘Salary’."
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary'])# Show the dataframedf",
"e": 1048,
"s": 455,
"text": null
},
{
"code": null,
"e": 1056,
"s": 1048,
"text": "Output:"
},
{
"code": null,
"e": 1159,
"s": 1056,
"text": "Method 1: using Dataframe.[ ].[ ] is used to select a column by mentioning the respective column name."
},
{
"code": null,
"e": 1201,
"s": 1159,
"text": "Example 1 : to select single column.Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator [] # to select a columnresult = df[\"City\"] # Show the dataframeresult",
"e": 1865,
"s": 1201,
"text": null
},
{
"code": null,
"e": 1873,
"s": 1865,
"text": "Output:"
},
{
"code": null,
"e": 1917,
"s": 1873,
"text": "Example 2: to select multiple columns.Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator [] to # select multiple columnsresult = df[[\"Name\", \"Age\", \"Salary\"]] # Show the dataframeresult",
"e": 2606,
"s": 1917,
"text": null
},
{
"code": null,
"e": 2614,
"s": 2606,
"text": "Output:"
},
{
"code": null,
"e": 2837,
"s": 2614,
"text": "Method 2: Using Dataframe.loc[ ]..loc[] the function selects the data by labels of rows or columns. It can select a subset of rows and columns. There are many ways to use this function.Example 1: To select single row.Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Set 'Name' column as index # on a Dataframedf.set_index(\"Name\", inplace = True) # Using the operator .loc[]# to select single rowresult = df.loc[\"Stuti\"] # Show the dataframeresult",
"e": 3586,
"s": 2837,
"text": null
},
{
"code": null,
"e": 3594,
"s": 3586,
"text": "Output:"
},
{
"code": null,
"e": 3635,
"s": 3594,
"text": "Example 2: To select multiple rows.Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Set index on a Dataframedf.set_index(\"Name\", inplace = True) # Using the operator .loc[]# to select multiple rowsresult = df.loc[[\"Stuti\", \"Seema\"]] # Show the dataframeresult",
"e": 4396,
"s": 3635,
"text": null
},
{
"code": null,
"e": 4404,
"s": 4396,
"text": "Output:"
},
{
"code": null,
"e": 4463,
"s": 4404,
"text": "Example 3: To select multiple rows and particular columns."
},
{
"code": null,
"e": 4545,
"s": 4463,
"text": "Syntax: Dataframe.loc[[\"row1\", \"row2\"...], [\"column1\", \"column2\", \"column3\"...]]"
},
{
"code": null,
"e": 4551,
"s": 4545,
"text": "Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Set 'Name' column as index # on a Dataframedf.set_index(\"Name\", inplace = True) # Using the operator .loc[] to # select multiple rows with some# particular columnsresult = df.loc[[\"Stuti\", \"Seema\"], [\"City\", \"Salary\"]] # Show the dataframeresult",
"e": 5380,
"s": 4551,
"text": null
},
{
"code": null,
"e": 5388,
"s": 5380,
"text": "Output:"
},
{
"code": null,
"e": 5558,
"s": 5388,
"text": "Example 4: To select all the rows with some particular columns. We use single colon [ : ] to select all rows and list of columns which we want to select as given below :"
},
{
"code": null,
"e": 5619,
"s": 5558,
"text": "Syntax: Dataframe.loc[[:, [\"column1\", \"column2\", \"column3\"]]"
},
{
"code": null,
"e": 5625,
"s": 5619,
"text": "Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Creating a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Set 'Name' column as index # on a Dataframedf.set_index(\"Name\", inplace = True) # Using the operator .loc[] to# select all the rows with # some particular columnsresult = df.loc[:, [\"City\", \"Salary\"]] # Show the dataframeresult",
"e": 6425,
"s": 5625,
"text": null
},
{
"code": null,
"e": 6433,
"s": 6425,
"text": "Output:"
},
{
"code": null,
"e": 6640,
"s": 6433,
"text": "Method 3: Using Dataframe.iloc[ ].iloc[ ] is used for selection based on position. It is similar to loc[] indexer but it takes only integer values to make selections.Example 1 : to select a single row.Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator .iloc[]# to select single rowresult = df.iloc[2] # Show the dataframeresult",
"e": 7305,
"s": 6640,
"text": null
},
{
"code": null,
"e": 7313,
"s": 7305,
"text": "Output:"
},
{
"code": null,
"e": 7354,
"s": 7313,
"text": "Example 2: to select multiple rows.Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator .iloc[] # to select multiple rowsresult = df.iloc[[2, 3, 5]] # Show the dataframeresult",
"e": 8026,
"s": 7354,
"text": null
},
{
"code": null,
"e": 8034,
"s": 8026,
"text": "Output:"
},
{
"code": null,
"e": 8104,
"s": 8034,
"text": "Example 3: to select multiple rows with some particular columns.Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Creating a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator .iloc[] # to select multiple rows with# some particular columnsresult = df.iloc[[2, 3, 5], [0, 1]] # Show the dataframeresult",
"e": 8836,
"s": 8104,
"text": null
},
{
"code": null,
"e": 8844,
"s": 8836,
"text": "Output:"
},
{
"code": null,
"e": 8913,
"s": 8844,
"text": "Example 4: to select all the rows with some particular columns.Code:"
},
{
"code": "# import pandasimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFrame object from list df = pd.DataFrame(employees, columns =['Name', 'Age', 'City', 'Salary']) # Using the operator .iloc[]# to select all the rows with# some particular columnsresult = df.iloc[:, [0, 1]] # Show the dataframeresult",
"e": 9613,
"s": 8913,
"text": null
},
{
"code": null,
"e": 9621,
"s": 9613,
"text": "Output:"
},
{
"code": null,
"e": 9645,
"s": 9621,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 9659,
"s": 9645,
"text": "Python-pandas"
},
{
"code": null,
"e": 9666,
"s": 9659,
"text": "Python"
}
] |
How to close a window in Tkinter?
|
09 Dec, 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 GUI applications. Creating a GUI using tkinter is an easy task.
To close a tkinter window, we can use the destroy() method. The destroy() is a universal widget method i.e we can use this method with any of the available widgets as well as with the main tkinter window.
Example:
In the below example, we are going to implement the destroy() method using a button.
Python
# import required module from tkinter import * # create objectroot = Tk() # create button to implement destroy()Button(root, text="Quit", command=root.destroy).pack() root.mainloop()
Output:
In the above example, on clicking the button the destroy() method is called and the tkinter window is closed.
Python-gui
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Dec, 2020"
},
{
"code": null,
"e": 404,
"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 GUI applications. Creating a GUI using tkinter is an easy task."
},
{
"code": null,
"e": 609,
"s": 404,
"text": "To close a tkinter window, we can use the destroy() method. The destroy() is a universal widget method i.e we can use this method with any of the available widgets as well as with the main tkinter window."
},
{
"code": null,
"e": 618,
"s": 609,
"text": "Example:"
},
{
"code": null,
"e": 705,
"s": 618,
"text": "In the below example, we are going to implement the destroy() method using a button. "
},
{
"code": null,
"e": 712,
"s": 705,
"text": "Python"
},
{
"code": "# import required module from tkinter import * # create objectroot = Tk() # create button to implement destroy()Button(root, text=\"Quit\", command=root.destroy).pack() root.mainloop()",
"e": 898,
"s": 712,
"text": null
},
{
"code": null,
"e": 906,
"s": 898,
"text": "Output:"
},
{
"code": null,
"e": 1016,
"s": 906,
"text": "In the above example, on clicking the button the destroy() method is called and the tkinter window is closed."
},
{
"code": null,
"e": 1027,
"s": 1016,
"text": "Python-gui"
},
{
"code": null,
"e": 1042,
"s": 1027,
"text": "Python-tkinter"
},
{
"code": null,
"e": 1066,
"s": 1042,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1073,
"s": 1066,
"text": "Python"
},
{
"code": null,
"e": 1092,
"s": 1073,
"text": "Technical Scripter"
}
] |
GATE-CS-2015 (Set 3) - GeeksforGeeks
|
08 Oct, 2021
Six selected members are P, Q, R, S, T and U
Portfolios are Home, Power, Defence, Telecom, and Finance.
U does not want any portfolio if S gets one of the five.
R wants either Home or Finance or no portfolio.
Q says that if S gets either Power of telecom, then she must
get the other one.
T insists on a portfolio if P gets one Which is the valid
distribution of portfolios?
A) P-Home, Q-Power, R-Defence, S-Telecom, T-Finance
Not valid as R doesn't get home or finance here
R-Home, S-Power, P-Defence, Q-Telecom, T-Finance
Is valid and satisfies all conditions.
C) P-Home, Q-Power, T-Defence, S-Telecom, U-Finance
Not valid as U is not satisfied. Condition for U is, S should not
get any portfolio.
D) Q-Home, U-Power, T-Defence, R-Telecom, P-Finance
Like A, not valid as R doesn't get home or finance here
The problem can be easily solved by trying point (2, -1)
on thick line, i.e., x = 2, y = -1.
None of the options except (B) satisfy above values.
(i) He was already a successful batsman at the highest level.
(ii) He has to improve his temperament in order to become a great batsman.
(iii) He failed to make many of his good starts count.
(iv) Improving his technical skills will guarantee success.
In 2006 export increased from 70 yo 100 and import increased from 90 to 120.
% increase in import = 30/70 = 42.8 %
% increase in export = 30/90 = 33.33 %
Combined % increase in 2006 is more than any other year.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
|
[
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 30401,
"s": 29577,
"text": "Six selected members are P, Q, R, S, T and U\n\nPortfolios are Home, Power, Defence, Telecom, and Finance. \n\nU does not want any portfolio if S gets one of the five. \n\nR wants either Home or Finance or no portfolio. \n\nQ says that if S gets either Power of telecom, then she must \nget the other one.\n\nT insists on a portfolio if P gets one Which is the valid \ndistribution of portfolios?\n\nA) P-Home, Q-Power, R-Defence, S-Telecom, T-Finance\nNot valid as R doesn't get home or finance here\n\nR-Home, S-Power, P-Defence, Q-Telecom, T-Finance\nIs valid and satisfies all conditions.\n\nC) P-Home, Q-Power, T-Defence, S-Telecom, U-Finance\nNot valid as U is not satisfied. Condition for U is, S should not\nget any portfolio.\n\nD) Q-Home, U-Power, T-Defence, R-Telecom, P-Finance\nLike A, not valid as R doesn't get home or finance here\n\n"
},
{
"code": null,
"e": 30550,
"s": 30401,
"text": "The problem can be easily solved by trying point (2, -1) \non thick line, i.e., x = 2, y = -1.\n\nNone of the options except (B) satisfy above values. "
},
{
"code": null,
"e": 30802,
"s": 30550,
"text": "(i) He was already a successful batsman at the highest level.\n(ii) He has to improve his temperament in order to become a great batsman.\n(iii) He failed to make many of his good starts count.\n(iv) Improving his technical skills will guarantee success."
},
{
"code": null,
"e": 31017,
"s": 30802,
"text": "In 2006 export increased from 70 yo 100 and import increased from 90 to 120.\n\n% increase in import = 30/70 = 42.8 %\n% increase in export = 30/90 = 33.33 %\n\nCombined % increase in 2006 is more than any other year. "
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.