title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Difference between __dirname and ./ in Node.js - GeeksforGeeks
14 Feb, 2020 Working with any technology requires to interact with files and directories. Files and directories maintain a tree structure for easy access. Working with Node.js also requires accessing files using the file path which can be obtained using different commands. There are two ways of getting the current directory in Node.js . However, they are quite different from each other. __dirname ./ The __dirname in a node script returns the path of the folder where the current JavaScript file resides. __filename and __dirname are used to get the filename and directory name of the currently executing file. The ./ gives the current working directory. It works similar to process.cwd() method. The current working directory is the path of the folder where the node command executed. However the current working directory may change during the execution of the script by the usage of process.chdir() API.The only case when ./ gives the path of the currently executing file is when it is used with the require() command which works relative to the current working directory. The ./ allows us import modules based on file structure. Both __dirname and ./ give similar results when the node is running in the same directory as the currently executing file but produce different results when the node run from some other directory. Example: The following examples demonstrate working of __dirname and ./ when node is run from the same directory where the JavaScript file is stored Example 1: // Node.js program to demonstrate the// methods to display directory // Include path modulevar path = require("path"); // Methods to display directoryconsole.log("__dirname: ", __dirname);console.log("process.cwd() : ", process.cwd());console.log("./ : ", path.resolve("./"));console.log("filename: ", __filename); Steps to Run: Open notepad editor and paste the following code and save it with .js extension. For example: index.js Now open a command prompt and move to the directory where code exists. Type node index.js command to run the code. Output: Example 2: // Node.js program to demonstrate the// methods to display directory // Include path modulevar path = require("path"); // Methods to display directoryconsole.log("__dirname: ", __dirname);console.log("process.cwd() : ", process.cwd());console.log("./ : ", path.resolve("./"));console.log("filename: ", __filename); Steps to Run: Open notepad editor and paste the following code and save it with .js extension. For example: index.js Now open a command prompt and if your path is Desktop then type cd.. to move its parent directory. Type node Desktop/index.js command to run the code. Output: Node.js-Misc Picked Technical Scripter 2019 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to read and write Excel file in Node.js ? Express.js res.render() Function How to use an ES6 import in Node.js? Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24577, "s": 24549, "text": "\n14 Feb, 2020" }, { "code": null, "e": 24954, "s": 24577, "text": "Working with any technology requires to interact with files and directories. Files and directories maintain a tree structure for easy access. Working with Node.js also requires accessing files using the file path which can be obtained using different commands. There are two ways of getting the current directory in Node.js . However, they are quite different from each other." }, { "code": null, "e": 24964, "s": 24954, "text": "__dirname" }, { "code": null, "e": 24967, "s": 24964, "text": "./" }, { "code": null, "e": 25178, "s": 24967, "text": "The __dirname in a node script returns the path of the folder where the current JavaScript file resides. __filename and __dirname are used to get the filename and directory name of the currently executing file." }, { "code": null, "e": 25700, "s": 25178, "text": "The ./ gives the current working directory. It works similar to process.cwd() method. The current working directory is the path of the folder where the node command executed. However the current working directory may change during the execution of the script by the usage of process.chdir() API.The only case when ./ gives the path of the currently executing file is when it is used with the require() command which works relative to the current working directory. The ./ allows us import modules based on file structure." }, { "code": null, "e": 25897, "s": 25700, "text": "Both __dirname and ./ give similar results when the node is running in the same directory as the currently executing file but produce different results when the node run from some other directory." }, { "code": null, "e": 26046, "s": 25897, "text": "Example: The following examples demonstrate working of __dirname and ./ when node is run from the same directory where the JavaScript file is stored" }, { "code": null, "e": 26057, "s": 26046, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the// methods to display directory // Include path modulevar path = require(\"path\"); // Methods to display directoryconsole.log(\"__dirname: \", __dirname);console.log(\"process.cwd() : \", process.cwd());console.log(\"./ : \", path.resolve(\"./\"));console.log(\"filename: \", __filename);", "e": 26378, "s": 26057, "text": null }, { "code": null, "e": 26392, "s": 26378, "text": "Steps to Run:" }, { "code": null, "e": 26495, "s": 26392, "text": "Open notepad editor and paste the following code and save it with .js extension. For example: index.js" }, { "code": null, "e": 26566, "s": 26495, "text": "Now open a command prompt and move to the directory where code exists." }, { "code": null, "e": 26610, "s": 26566, "text": "Type node index.js command to run the code." }, { "code": null, "e": 26618, "s": 26610, "text": "Output:" }, { "code": null, "e": 26629, "s": 26618, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the// methods to display directory // Include path modulevar path = require(\"path\"); // Methods to display directoryconsole.log(\"__dirname: \", __dirname);console.log(\"process.cwd() : \", process.cwd());console.log(\"./ : \", path.resolve(\"./\"));console.log(\"filename: \", __filename);", "e": 26950, "s": 26629, "text": null }, { "code": null, "e": 26964, "s": 26950, "text": "Steps to Run:" }, { "code": null, "e": 27067, "s": 26964, "text": "Open notepad editor and paste the following code and save it with .js extension. For example: index.js" }, { "code": null, "e": 27166, "s": 27067, "text": "Now open a command prompt and if your path is Desktop then type cd.. to move its parent directory." }, { "code": null, "e": 27218, "s": 27166, "text": "Type node Desktop/index.js command to run the code." }, { "code": null, "e": 27226, "s": 27218, "text": "Output:" }, { "code": null, "e": 27239, "s": 27226, "text": "Node.js-Misc" }, { "code": null, "e": 27246, "s": 27239, "text": "Picked" }, { "code": null, "e": 27270, "s": 27246, "text": "Technical Scripter 2019" }, { "code": null, "e": 27278, "s": 27270, "text": "Node.js" }, { "code": null, "e": 27297, "s": 27278, "text": "Technical Scripter" }, { "code": null, "e": 27314, "s": 27297, "text": "Web Technologies" }, { "code": null, "e": 27412, "s": 27314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27469, "s": 27412, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27523, "s": 27469, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27569, "s": 27523, "text": "How to read and write Excel file in Node.js ?" }, { "code": null, "e": 27602, "s": 27569, "text": "Express.js res.render() Function" }, { "code": null, "e": 27639, "s": 27602, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 27681, "s": 27639, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27724, "s": 27681, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27786, "s": 27724, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27836, "s": 27786, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Feature Engineering on Date-Time Data | by Pararawendy Indarjo | Towards Data Science
According to Wikipedia, feature engineering refers to the process of using domain knowledge to extract features from raw data via data mining techniques. These features can then be used to improve the performance of machine learning algorithms. Feature engineering does not necessarily have to be fancy though. One simple, yet prevalent, use case of feature engineering is in time-series data. The importance of feature engineering in this realm is due to the fact that (raw) time-series data usually only contains one single column to represent the time attribute, namely date-time (or timestamp). Regarding this date-time data, feature engineering can be seen as extracting useful information from such data as standalone (distinct) features. For example, from a date-time data of “2020–07–01 10:21:05”, we might want to extract the following features from it: Month: 7Day of month: 1Day name: Wednesday (2020–07–01 was Wednesday)Hour: 10 Month: 7 Day of month: 1 Day name: Wednesday (2020–07–01 was Wednesday) Hour: 10 Extracting such kinds of features from date-time data is precisely the objective of the current article. Afterwards, we will incorporate our engineered features as predictors of a gradient boosting regression model. Specifically, we will forecast metro interstate traffic volume. This article will cover the following. A step-by-step guide to extract the below features from a date-time column. MonthDay of monthDay nameHourDaypart (morning, afternoon, etc)Weekend flag (1 if weekend, else 0) Month Day of month Day name Hour Daypart (morning, afternoon, etc) Weekend flag (1 if weekend, else 0) How to incorporate those features in a Gradient Boosting regression model to forecast metro interstate traffic volume. Throughout the article, we use Metro Interstate Traffic Volume Data Set, which can be found in the UCI Machine Learning Repository here. Citing its abstract, the data is about hourly Minneapolis-St Paul, MN traffic volume for westbound I-94, which includes weather and holiday features from 2012–2018. This 48204 rows data contains the following attributes. holiday: Categorical US National holidays plus regional holiday, Minnesota State Fairtemp: Numeric Average temp in kelvinrain_1h: Numeric Amount in mm of rain that occurred in the hoursnow_1h: Numeric Amount in mm of snow that occurred in the hourclouds_all: Numeric Percentage of cloud coverweather_main: Categorical Short textual description of the current weatherweather_description: Categorical Longer textual description of the current weatherdate_time: DateTime Hour of the data collected in local CST timetraffic_volume:Numeric Hourly I-94 ATR 301 reported westbound traffic volume (the target) holiday: Categorical US National holidays plus regional holiday, Minnesota State Fair temp: Numeric Average temp in kelvin rain_1h: Numeric Amount in mm of rain that occurred in the hour snow_1h: Numeric Amount in mm of snow that occurred in the hour clouds_all: Numeric Percentage of cloud cover weather_main: Categorical Short textual description of the current weather weather_description: Categorical Longer textual description of the current weather date_time: DateTime Hour of the data collected in local CST time traffic_volume:Numeric Hourly I-94 ATR 301 reported westbound traffic volume (the target) Let’s load the data. # import librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt# load the dataraw = pd.read_csv('Metro_Interstate_Traffic_Volume.csv')# display first five rowsraw.head()# display details for each columnraw.info() From the output of the info method in the above, we know the date_time column is still in object type. So we need to convert it to datetime type. # convert date_time column to datetime typeraw.date_time = pd.to_datetime(raw.date_time) From the output of info method in the above, we know there are categorical features other than the date_time column. But due to the main topic of this article, we will focus on feature engineering our date_time column. Month It turns out that Pandas has many handy methods to work with datetime typed data. To extract time/date components, all we need to do is calling pd.Series.dt attributes family. pd.Series.dt.month is the one we need to extract the month component. This will yield a Series of the digit of the month component (e.g. 1 for January, 10 for October) in int64 format. # extract month featuremonths = raw.date_time.dt.month Day of month Quite similar as before, we just need to call pd.Series.dt.day. For example, a date-time of 2012–10–27 09:00:00 would be resulted in 27 using this attribute. # extract day of month featureday_of_months = raw.date_time.dt.day Hour This one is also trivial. The attribute pd.Series.dt.hour will result in a Series of hour digits, ranging from 0 to 23. # extract hour featurehours = raw.date_time.dt.hour Day name This one is getting interesting. Our goal is to extract the day name for each date-time in the raw.date_time Series. It consists of two steps. First is to extract the day name literal using pd.Series.dt.day_name() method. Afterwards, we need to one-hot encode the results from the first step using pd.get_dummies() method. # first: extract the day name literalto_one_hot = raw.date_time.dt.day_name()# second: one hot encode to 7 columnsdays = pd.get_dummies(to_one_hot)#display datadays Daypart In this part, we will create a grouping based on the hour digits. On a high level, we want to have six groups representing each daypart. They are Dawn (02.00 — 05.59), Morning (06.00 —09.59), Noon (10.00–13.59), Afternoon (14.00–17.59), Evening (18.00–21.59), and Midnight (22.00–01.59 on Day+1). To this end, we create an identifying function that we later use to feed an apply method of a Series. Afterwards, we perform one-hot encoding on the resulted dayparts. # daypart functiondef daypart(hour): if hour in [2,3,4,5]: return "dawn" elif hour in [6,7,8,9]: return "morning" elif hour in [10,11,12,13]: return "noon" elif hour in [14,15,16,17]: return "afternoon" elif hour in [18,19,20,21]: return "evening" else: return "midnight"# utilize it along with apply methodraw_dayparts = hours.apply(daypart)# one hot encodingdayparts = pd.get_dummies(raw_dayparts)# re-arrange columns for conveniencedayparts = dayparts[['dawn','morning','noon','afternoon','evening','midnight']]#display datadayparts Weekend flag The final feature we engineer from the date_time column is is_weekend. This column indicates whether the given date-time is in the weekend (Saturday or Sunday) or not. To proceed with this objective, we will make use of our previous pd.Series.dt.day_name() method and apply a simple lambda function on top of it. # is_weekend flag day_names = raw.date_time.dt.day_name()is_weekend = day_names.apply(lambda x : 1 if x in ['Saturday','Sunday'] else 0) Holiday flag & weather Lucky on us, the data also contains public holiday information. The information is granular since it mentions the name of each public holiday. Nevertheless, I assumed that there is no significant gain for encoding each of these holidays. Therefore, let’s just create a binary feature indicating whether or not the corresponding date is a holiday. # is_holiday flagis_holiday = raw.holiday.apply(lambda x : 0 if x == "None" else 1) The last categorical feature we need to take care of is the weather column (my assumption strikes again here, I do not include weather_description feature). As you might guess, we just one-hot encode the feature as follows. # one-hot encode weatherweathers = pd.get_dummies(raw.weather_main)#display dataweathers The final data Hurray! We finally have our final — ready-to-train — data! Let’s create a brand new data frame called features that consists of all features, both numerical (we put as-is from the raw data) and categorical (our engineered ones). # features table#first step: include features with single column naturefeatures = pd.DataFrame({ 'temp' : raw.temp, 'rain_1h' : raw.rain_1h, 'snow_1h' : raw.snow_1h, 'clouds_all' : raw.clouds_all, 'month' : months, 'day_of_month' : day_of_months, 'hour' : hours, 'is_holiday' : is_holiday, 'is_weekend' : is_weekend})#second step: concat with one-hot encode typed featuresfeatures = pd.concat([features, days, dayparts, weathers], axis = 1)# target columntarget = raw.traffic_volume Before we feed the data to our model, we need to split the data (training and test data). Notice below we do not shuffle our data, this is due to the time-series nature of the data. #split data into training and test dataX_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.1, shuffle = False) Now we are ready to build our model to forecast metro interstate traffic volume. In this work, we will use the Gradient Boosting regression model. The details of the model are beyond the scope of this article but on a high level, the gradient boosting model belongs to ensemble model family which employs gradient descent algorithm to minimize errors in sequential (additive) weak learner models (decision trees). Model training Let’s instantiate and train the model on the training data! from sklearn import datasets, ensemble# define the model parametersparams = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 5, 'learning_rate': 0.01, 'loss': 'ls'}# instantiate and train the modelgb_reg = ensemble.GradientBoostingRegressor(**params)gb_reg.fit(X_train, y_train) Just wait a little while until the training converged. Model evaluation To evaluate the model, we use two metrics: MAPE (mean absolute percentage error) and R2 score. We will compute these metrics on the test data. # define MAPE functiondef mape(true, predicted): inside_sum = np.abs(predicted - true) / true return round(100 * np.sum(inside_sum ) / inside_sum.size,2)# import r2 scorefrom sklearn.metrics import r2_score# evaluate the metricsy_true = y_testy_pred = gb_reg.predict(X_test)#print(f"GB model MSE is {round(mean_squared_error(y_true, y_pred),2)}")print(f"GB model MAPE is {mape(y_true, y_pred)} %")print(f"GB model R2 is {round(r2_score(y_true, y_pred)* 100 , 2)} %") We can see that our model is quite decent in performance. Our MAPE is less than 15%, while R2 score is a little over 95%. Graphical results To comprehend our model performance visually, let’s have some plot! Due to the length of our test data (4820 data points), we just plot the actual vs model-predicted values on the last 100 data points. Moreover, we also include another model (called gb_reg_lite in the plotting code below) which does not incorporate date-time engineered features as its predictors (it only contains non-date-time column as features, including temp, weather, etc). fig, ax = plt.subplots(figsize = (12,6))index_ordered = raw.date_time.astype('str').tolist()[-len(X_test):][-100:]ax.set_xlabel('Date')ax.set_ylabel('Traffic Volume') # the actual valuesax.plot(index_ordered, y_test[-100:].to_numpy(), color='k', ls='-', label = 'actual')# predictions of model with engineered featuresax.plot(index_ordered, gb_reg.predict(X_test)[-100:], color='b', ls='--', label = 'predicted; with date-time features')# predictions of model without engineered featuresax.plot(index_ordered, gb_reg_lite.predict(X_test_lite)[-100:], color='r', ls='--', label = 'predicted; w/o date-time features')every_nth = 5for n, label in enumerate(ax.xaxis.get_ticklabels()): if n % every_nth != 0: label.set_visible(False)ax.tick_params(axis='x', labelrotation= 90)plt.legend()plt.title('Actual vs predicted on the last 100 data points')plt.draw() The figure supports our previous findings on good evaluation metrics the model attained, as the blue dashed line approximates the with the black solid line closely. That is, our gradient boosting model can forecast the metro traffic decently. Meanwhile, we see that the model which does not use the date-time engineered features falls apart in performance (red dashed line). Why this occurs? Because the target (transportation traffic) would indeed depend on the features we just created. Transportation traffic tends to lower in weekend days, but spikes during rush hours (see the plot above). Thus, we would miss these sound predictors if we do not perform feature engineering on the date-time column! Congratulations for you who have managed reading this far! Now for a short recap. In this article, we learned how to perform feature engineering on date-time data. Afterwards, we incorporated the engineered features to build a powerful gradient boosting regression model, to forecast metro traffic volume. Finally, thanks for reading and let’s connect with me on LinkedIn!
[ { "code": null, "e": 417, "s": 172, "text": "According to Wikipedia, feature engineering refers to the process of using domain knowledge to extract features from raw data via data mining techniques. These features can then be used to improve the performance of machine learning algorithms." }, { "code": null, "e": 771, "s": 417, "text": "Feature engineering does not necessarily have to be fancy though. One simple, yet prevalent, use case of feature engineering is in time-series data. The importance of feature engineering in this realm is due to the fact that (raw) time-series data usually only contains one single column to represent the time attribute, namely date-time (or timestamp)." }, { "code": null, "e": 1035, "s": 771, "text": "Regarding this date-time data, feature engineering can be seen as extracting useful information from such data as standalone (distinct) features. For example, from a date-time data of “2020–07–01 10:21:05”, we might want to extract the following features from it:" }, { "code": null, "e": 1113, "s": 1035, "text": "Month: 7Day of month: 1Day name: Wednesday (2020–07–01 was Wednesday)Hour: 10" }, { "code": null, "e": 1122, "s": 1113, "text": "Month: 7" }, { "code": null, "e": 1138, "s": 1122, "text": "Day of month: 1" }, { "code": null, "e": 1185, "s": 1138, "text": "Day name: Wednesday (2020–07–01 was Wednesday)" }, { "code": null, "e": 1194, "s": 1185, "text": "Hour: 10" }, { "code": null, "e": 1474, "s": 1194, "text": "Extracting such kinds of features from date-time data is precisely the objective of the current article. Afterwards, we will incorporate our engineered features as predictors of a gradient boosting regression model. Specifically, we will forecast metro interstate traffic volume." }, { "code": null, "e": 1513, "s": 1474, "text": "This article will cover the following." }, { "code": null, "e": 1589, "s": 1513, "text": "A step-by-step guide to extract the below features from a date-time column." }, { "code": null, "e": 1687, "s": 1589, "text": "MonthDay of monthDay nameHourDaypart (morning, afternoon, etc)Weekend flag (1 if weekend, else 0)" }, { "code": null, "e": 1693, "s": 1687, "text": "Month" }, { "code": null, "e": 1706, "s": 1693, "text": "Day of month" }, { "code": null, "e": 1715, "s": 1706, "text": "Day name" }, { "code": null, "e": 1720, "s": 1715, "text": "Hour" }, { "code": null, "e": 1754, "s": 1720, "text": "Daypart (morning, afternoon, etc)" }, { "code": null, "e": 1790, "s": 1754, "text": "Weekend flag (1 if weekend, else 0)" }, { "code": null, "e": 1909, "s": 1790, "text": "How to incorporate those features in a Gradient Boosting regression model to forecast metro interstate traffic volume." }, { "code": null, "e": 2046, "s": 1909, "text": "Throughout the article, we use Metro Interstate Traffic Volume Data Set, which can be found in the UCI Machine Learning Repository here." }, { "code": null, "e": 2267, "s": 2046, "text": "Citing its abstract, the data is about hourly Minneapolis-St Paul, MN traffic volume for westbound I-94, which includes weather and holiday features from 2012–2018. This 48204 rows data contains the following attributes." }, { "code": null, "e": 2869, "s": 2267, "text": "holiday: Categorical US National holidays plus regional holiday, Minnesota State Fairtemp: Numeric Average temp in kelvinrain_1h: Numeric Amount in mm of rain that occurred in the hoursnow_1h: Numeric Amount in mm of snow that occurred in the hourclouds_all: Numeric Percentage of cloud coverweather_main: Categorical Short textual description of the current weatherweather_description: Categorical Longer textual description of the current weatherdate_time: DateTime Hour of the data collected in local CST timetraffic_volume:Numeric Hourly I-94 ATR 301 reported westbound traffic volume (the target)" }, { "code": null, "e": 2955, "s": 2869, "text": "holiday: Categorical US National holidays plus regional holiday, Minnesota State Fair" }, { "code": null, "e": 2992, "s": 2955, "text": "temp: Numeric Average temp in kelvin" }, { "code": null, "e": 3056, "s": 2992, "text": "rain_1h: Numeric Amount in mm of rain that occurred in the hour" }, { "code": null, "e": 3120, "s": 3056, "text": "snow_1h: Numeric Amount in mm of snow that occurred in the hour" }, { "code": null, "e": 3166, "s": 3120, "text": "clouds_all: Numeric Percentage of cloud cover" }, { "code": null, "e": 3241, "s": 3166, "text": "weather_main: Categorical Short textual description of the current weather" }, { "code": null, "e": 3324, "s": 3241, "text": "weather_description: Categorical Longer textual description of the current weather" }, { "code": null, "e": 3389, "s": 3324, "text": "date_time: DateTime Hour of the data collected in local CST time" }, { "code": null, "e": 3479, "s": 3389, "text": "traffic_volume:Numeric Hourly I-94 ATR 301 reported westbound traffic volume (the target)" }, { "code": null, "e": 3500, "s": 3479, "text": "Let’s load the data." }, { "code": null, "e": 3736, "s": 3500, "text": "# import librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt# load the dataraw = pd.read_csv('Metro_Interstate_Traffic_Volume.csv')# display first five rowsraw.head()# display details for each columnraw.info()" }, { "code": null, "e": 3882, "s": 3736, "text": "From the output of the info method in the above, we know the date_time column is still in object type. So we need to convert it to datetime type." }, { "code": null, "e": 3971, "s": 3882, "text": "# convert date_time column to datetime typeraw.date_time = pd.to_datetime(raw.date_time)" }, { "code": null, "e": 4190, "s": 3971, "text": "From the output of info method in the above, we know there are categorical features other than the date_time column. But due to the main topic of this article, we will focus on feature engineering our date_time column." }, { "code": null, "e": 4196, "s": 4190, "text": "Month" }, { "code": null, "e": 4557, "s": 4196, "text": "It turns out that Pandas has many handy methods to work with datetime typed data. To extract time/date components, all we need to do is calling pd.Series.dt attributes family. pd.Series.dt.month is the one we need to extract the month component. This will yield a Series of the digit of the month component (e.g. 1 for January, 10 for October) in int64 format." }, { "code": null, "e": 4612, "s": 4557, "text": "# extract month featuremonths = raw.date_time.dt.month" }, { "code": null, "e": 4625, "s": 4612, "text": "Day of month" }, { "code": null, "e": 4783, "s": 4625, "text": "Quite similar as before, we just need to call pd.Series.dt.day. For example, a date-time of 2012–10–27 09:00:00 would be resulted in 27 using this attribute." }, { "code": null, "e": 4850, "s": 4783, "text": "# extract day of month featureday_of_months = raw.date_time.dt.day" }, { "code": null, "e": 4855, "s": 4850, "text": "Hour" }, { "code": null, "e": 4975, "s": 4855, "text": "This one is also trivial. The attribute pd.Series.dt.hour will result in a Series of hour digits, ranging from 0 to 23." }, { "code": null, "e": 5027, "s": 4975, "text": "# extract hour featurehours = raw.date_time.dt.hour" }, { "code": null, "e": 5036, "s": 5027, "text": "Day name" }, { "code": null, "e": 5359, "s": 5036, "text": "This one is getting interesting. Our goal is to extract the day name for each date-time in the raw.date_time Series. It consists of two steps. First is to extract the day name literal using pd.Series.dt.day_name() method. Afterwards, we need to one-hot encode the results from the first step using pd.get_dummies() method." }, { "code": null, "e": 5524, "s": 5359, "text": "# first: extract the day name literalto_one_hot = raw.date_time.dt.day_name()# second: one hot encode to 7 columnsdays = pd.get_dummies(to_one_hot)#display datadays" }, { "code": null, "e": 5532, "s": 5524, "text": "Daypart" }, { "code": null, "e": 5829, "s": 5532, "text": "In this part, we will create a grouping based on the hour digits. On a high level, we want to have six groups representing each daypart. They are Dawn (02.00 — 05.59), Morning (06.00 —09.59), Noon (10.00–13.59), Afternoon (14.00–17.59), Evening (18.00–21.59), and Midnight (22.00–01.59 on Day+1)." }, { "code": null, "e": 5997, "s": 5829, "text": "To this end, we create an identifying function that we later use to feed an apply method of a Series. Afterwards, we perform one-hot encoding on the resulted dayparts." }, { "code": null, "e": 6586, "s": 5997, "text": "# daypart functiondef daypart(hour): if hour in [2,3,4,5]: return \"dawn\" elif hour in [6,7,8,9]: return \"morning\" elif hour in [10,11,12,13]: return \"noon\" elif hour in [14,15,16,17]: return \"afternoon\" elif hour in [18,19,20,21]: return \"evening\" else: return \"midnight\"# utilize it along with apply methodraw_dayparts = hours.apply(daypart)# one hot encodingdayparts = pd.get_dummies(raw_dayparts)# re-arrange columns for conveniencedayparts = dayparts[['dawn','morning','noon','afternoon','evening','midnight']]#display datadayparts" }, { "code": null, "e": 6599, "s": 6586, "text": "Weekend flag" }, { "code": null, "e": 6912, "s": 6599, "text": "The final feature we engineer from the date_time column is is_weekend. This column indicates whether the given date-time is in the weekend (Saturday or Sunday) or not. To proceed with this objective, we will make use of our previous pd.Series.dt.day_name() method and apply a simple lambda function on top of it." }, { "code": null, "e": 7049, "s": 6912, "text": "# is_weekend flag day_names = raw.date_time.dt.day_name()is_weekend = day_names.apply(lambda x : 1 if x in ['Saturday','Sunday'] else 0)" }, { "code": null, "e": 7072, "s": 7049, "text": "Holiday flag & weather" }, { "code": null, "e": 7419, "s": 7072, "text": "Lucky on us, the data also contains public holiday information. The information is granular since it mentions the name of each public holiday. Nevertheless, I assumed that there is no significant gain for encoding each of these holidays. Therefore, let’s just create a binary feature indicating whether or not the corresponding date is a holiday." }, { "code": null, "e": 7503, "s": 7419, "text": "# is_holiday flagis_holiday = raw.holiday.apply(lambda x : 0 if x == \"None\" else 1)" }, { "code": null, "e": 7727, "s": 7503, "text": "The last categorical feature we need to take care of is the weather column (my assumption strikes again here, I do not include weather_description feature). As you might guess, we just one-hot encode the feature as follows." }, { "code": null, "e": 7816, "s": 7727, "text": "# one-hot encode weatherweathers = pd.get_dummies(raw.weather_main)#display dataweathers" }, { "code": null, "e": 7831, "s": 7816, "text": "The final data" }, { "code": null, "e": 8060, "s": 7831, "text": "Hurray! We finally have our final — ready-to-train — data! Let’s create a brand new data frame called features that consists of all features, both numerical (we put as-is from the raw data) and categorical (our engineered ones)." }, { "code": null, "e": 8570, "s": 8060, "text": "# features table#first step: include features with single column naturefeatures = pd.DataFrame({ 'temp' : raw.temp, 'rain_1h' : raw.rain_1h, 'snow_1h' : raw.snow_1h, 'clouds_all' : raw.clouds_all, 'month' : months, 'day_of_month' : day_of_months, 'hour' : hours, 'is_holiday' : is_holiday, 'is_weekend' : is_weekend})#second step: concat with one-hot encode typed featuresfeatures = pd.concat([features, days, dayparts, weathers], axis = 1)# target columntarget = raw.traffic_volume" }, { "code": null, "e": 8752, "s": 8570, "text": "Before we feed the data to our model, we need to split the data (training and test data). Notice below we do not shuffle our data, this is due to the time-series nature of the data." }, { "code": null, "e": 8893, "s": 8752, "text": "#split data into training and test dataX_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.1, shuffle = False)" }, { "code": null, "e": 9040, "s": 8893, "text": "Now we are ready to build our model to forecast metro interstate traffic volume. In this work, we will use the Gradient Boosting regression model." }, { "code": null, "e": 9307, "s": 9040, "text": "The details of the model are beyond the scope of this article but on a high level, the gradient boosting model belongs to ensemble model family which employs gradient descent algorithm to minimize errors in sequential (additive) weak learner models (decision trees)." }, { "code": null, "e": 9322, "s": 9307, "text": "Model training" }, { "code": null, "e": 9382, "s": 9322, "text": "Let’s instantiate and train the model on the training data!" }, { "code": null, "e": 9707, "s": 9382, "text": "from sklearn import datasets, ensemble# define the model parametersparams = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 5, 'learning_rate': 0.01, 'loss': 'ls'}# instantiate and train the modelgb_reg = ensemble.GradientBoostingRegressor(**params)gb_reg.fit(X_train, y_train)" }, { "code": null, "e": 9762, "s": 9707, "text": "Just wait a little while until the training converged." }, { "code": null, "e": 9779, "s": 9762, "text": "Model evaluation" }, { "code": null, "e": 9922, "s": 9779, "text": "To evaluate the model, we use two metrics: MAPE (mean absolute percentage error) and R2 score. We will compute these metrics on the test data." }, { "code": null, "e": 10403, "s": 9922, "text": "# define MAPE functiondef mape(true, predicted): inside_sum = np.abs(predicted - true) / true return round(100 * np.sum(inside_sum ) / inside_sum.size,2)# import r2 scorefrom sklearn.metrics import r2_score# evaluate the metricsy_true = y_testy_pred = gb_reg.predict(X_test)#print(f\"GB model MSE is {round(mean_squared_error(y_true, y_pred),2)}\")print(f\"GB model MAPE is {mape(y_true, y_pred)} %\")print(f\"GB model R2 is {round(r2_score(y_true, y_pred)* 100 , 2)} %\")" }, { "code": null, "e": 10525, "s": 10403, "text": "We can see that our model is quite decent in performance. Our MAPE is less than 15%, while R2 score is a little over 95%." }, { "code": null, "e": 10543, "s": 10525, "text": "Graphical results" }, { "code": null, "e": 10611, "s": 10543, "text": "To comprehend our model performance visually, let’s have some plot!" }, { "code": null, "e": 10991, "s": 10611, "text": "Due to the length of our test data (4820 data points), we just plot the actual vs model-predicted values on the last 100 data points. Moreover, we also include another model (called gb_reg_lite in the plotting code below) which does not incorporate date-time engineered features as its predictors (it only contains non-date-time column as features, including temp, weather, etc)." }, { "code": null, "e": 11856, "s": 10991, "text": "fig, ax = plt.subplots(figsize = (12,6))index_ordered = raw.date_time.astype('str').tolist()[-len(X_test):][-100:]ax.set_xlabel('Date')ax.set_ylabel('Traffic Volume') # the actual valuesax.plot(index_ordered, y_test[-100:].to_numpy(), color='k', ls='-', label = 'actual')# predictions of model with engineered featuresax.plot(index_ordered, gb_reg.predict(X_test)[-100:], color='b', ls='--', label = 'predicted; with date-time features')# predictions of model without engineered featuresax.plot(index_ordered, gb_reg_lite.predict(X_test_lite)[-100:], color='r', ls='--', label = 'predicted; w/o date-time features')every_nth = 5for n, label in enumerate(ax.xaxis.get_ticklabels()): if n % every_nth != 0: label.set_visible(False)ax.tick_params(axis='x', labelrotation= 90)plt.legend()plt.title('Actual vs predicted on the last 100 data points')plt.draw()" }, { "code": null, "e": 12099, "s": 11856, "text": "The figure supports our previous findings on good evaluation metrics the model attained, as the blue dashed line approximates the with the black solid line closely. That is, our gradient boosting model can forecast the metro traffic decently." }, { "code": null, "e": 12560, "s": 12099, "text": "Meanwhile, we see that the model which does not use the date-time engineered features falls apart in performance (red dashed line). Why this occurs? Because the target (transportation traffic) would indeed depend on the features we just created. Transportation traffic tends to lower in weekend days, but spikes during rush hours (see the plot above). Thus, we would miss these sound predictors if we do not perform feature engineering on the date-time column!" }, { "code": null, "e": 12619, "s": 12560, "text": "Congratulations for you who have managed reading this far!" }, { "code": null, "e": 12866, "s": 12619, "text": "Now for a short recap. In this article, we learned how to perform feature engineering on date-time data. Afterwards, we incorporated the engineered features to build a powerful gradient boosting regression model, to forecast metro traffic volume." } ]
GWT - Create Application
As power of GWT lies in Write in Java, Run in JavaScript, we'll be using Java IDE Eclipse to demonstrate our examples. Let's start with a simple HelloWorld application − The first step is to create a simple Web Application Project using Eclipse IDE. Launch project wizard using the option Google Icon > New Web Application Project.... Now name your project as HelloWorld using the wizard window as follows − Unselect Use Google App Engine because we're not using it in this project and leave other default values (keep Generate Sample project code option checked) as such and click Finish Button. Once your project is created successfully, you will have following content in your Project Explorer − Here is brief description of all important folders src Source code (java classes) files. Client folder containing the client-side specific java classes responsible for client UI display. Server folder containing the server-side java classes responsible for server side processing. Shared folder containing the java model class to transfer data from server to client and vice versa. HelloWorld.gwt.xml, a module descriptor file required for GWT compiler to compile the HelloWorld project. test Test code (java classes) source files. Client folder containing the java classes responsible to test gwt client side code. war This is the most important part, it represents the actual deployable web application. WEB-INF containing compiled classes, gwt libraries, servlet libraries. HelloWorld.css, project style sheet. HelloWorld.html, hots HTML which will invoke GWT UI Application. GWT plugin will create a default module descriptor file src/com.tutorialspoint/HelloWorld.gwt.xml which is given below. For this example we are not modifying it, but you can modify it based on your requirement. <?xml version = "1.0" encoding = "UTF-8"?> <module rename-to = 'helloworld'> <!-- Inherit the core Web Toolkit stuff. --> <inherits name = 'com.google.gwt.user.User'/> <!-- Inherit the default GWT style sheet. You can change --> <!-- the theme of your GWT application by uncommenting --> <!-- any one of the following lines. --> <inherits name = 'com.google.gwt.user.theme.clean.Clean'/> <!-- <inherits name = 'com.google.gwt.user.theme.chrome.Chrome'/> --> <!-- <inherits name = 'com.google.gwt.user.theme.dark.Dark'/> --> <!-- Other module inherits --> <!-- Specify the app entry point class. --> <entry-point class = 'com.tutorialspoint.client.HelloWorld'/> <!-- Specify the paths for translatable code --> <source path = 'client'/> <source path = 'shared'/> </module> GWT plugin will create a default Style Sheet file war/HelloWorld.css. Let us modify this file to keep our example at simplest level of understaning − body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } GWT plugin will create a default HTML host file war/HelloWorld.html. Let us modify this file to keep our example at simplest level of understaning − <html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>Hello World</h1> <p>Welcome to first GWT application</p> </body> </html> You can create more static files like HTML, CSS or images in the same source directory or you can create further sub-directories and move files in those sub-directories and configure those sub-directories in module descriptor of the application. GWT plugin will create a default Java file src/com.tutorialspoint/HelloWorld.java, which keeps an entry point for the application. Let us modify this file to display "Hello,World!" package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.Window; public class HelloWorld implements EntryPoint { public void onModuleLoad() { Window.alert("Hello, World!"); } } You can create more Java files in the same source directory to define either entry points or to define helper routines. Once you are ready with all the changes done, its time to compile the project. Use the option Google Icon > GWT Compile Project... to launch GWT Compile dialogue box as shown below − Keep default values intact and click Compile button. If everything goes fine, you will see following output in Eclipse console Compiling module com.tutorialspoint.HelloWorld Compiling 6 permutations Compiling permutation 0... Compiling permutation 1... Compiling permutation 2... Compiling permutation 3... Compiling permutation 4... Compiling permutation 5... Compile of permutations succeeded Linking into C:\workspace\HelloWorld\war\helloworld Link succeeded Compilation succeeded -- 33.029s Now click on Run application menu and select HelloWorld application to run the application. If everything is fine, you must see GWT Development Mode active in Eclipse containing a URL as shown below. Double click the URL to open the GWT application. Because you are running your application in development mode, so you will need to install GWT plugin for your browser. Simply follow the onscreen instructions to install the plugin. If you already have GWT plugin set for your browser, then you should be able to see the following output Congratulations! you have implemented your first application using Google Web Toolkit (GWT). Print Add Notes Bookmark this page
[ { "code": null, "e": 2142, "s": 2023, "text": "As power of GWT lies in Write in Java, Run in JavaScript, we'll be using Java IDE Eclipse to demonstrate our examples." }, { "code": null, "e": 2193, "s": 2142, "text": "Let's start with a simple HelloWorld application −" }, { "code": null, "e": 2432, "s": 2193, "text": "The first step is to create a simple Web Application Project using Eclipse IDE. Launch project wizard using the option Google Icon > New Web Application Project.... Now name your project as HelloWorld using the wizard window as follows −" }, { "code": null, "e": 2621, "s": 2432, "text": "Unselect Use Google App Engine because we're not using it in this project and leave other default values (keep Generate Sample project code option checked) as such and click Finish Button." }, { "code": null, "e": 2723, "s": 2621, "text": "Once your project is created successfully, you will have following content in your Project Explorer −" }, { "code": null, "e": 2774, "s": 2723, "text": "Here is brief description of all important folders" }, { "code": null, "e": 2778, "s": 2774, "text": "src" }, { "code": null, "e": 2812, "s": 2778, "text": "Source code (java classes) files." }, { "code": null, "e": 2910, "s": 2812, "text": "Client folder containing the client-side specific java classes responsible for client UI display." }, { "code": null, "e": 3004, "s": 2910, "text": "Server folder containing the server-side java classes responsible for server side processing." }, { "code": null, "e": 3105, "s": 3004, "text": "Shared folder containing the java model class to transfer data from server to client and vice versa." }, { "code": null, "e": 3211, "s": 3105, "text": "HelloWorld.gwt.xml, a module descriptor file required for GWT compiler to compile the HelloWorld project." }, { "code": null, "e": 3216, "s": 3211, "text": "test" }, { "code": null, "e": 3255, "s": 3216, "text": "Test code (java classes) source files." }, { "code": null, "e": 3339, "s": 3255, "text": "Client folder containing the java classes responsible to test gwt client side code." }, { "code": null, "e": 3343, "s": 3339, "text": "war" }, { "code": null, "e": 3429, "s": 3343, "text": "This is the most important part, it represents the actual deployable web application." }, { "code": null, "e": 3500, "s": 3429, "text": "WEB-INF containing compiled classes, gwt libraries, servlet libraries." }, { "code": null, "e": 3537, "s": 3500, "text": "HelloWorld.css, project style sheet." }, { "code": null, "e": 3602, "s": 3537, "text": "HelloWorld.html, hots HTML which will invoke GWT UI Application." }, { "code": null, "e": 3813, "s": 3602, "text": "GWT plugin will create a default module descriptor file src/com.tutorialspoint/HelloWorld.gwt.xml which is given below. For this example we are not modifying it, but you can modify it based on your requirement." }, { "code": null, "e": 4782, "s": 3813, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. You can change -->\n <!-- the theme of your GWT application by uncommenting -->\n <!-- any one of the following lines. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n <!-- <inherits name = 'com.google.gwt.user.theme.chrome.Chrome'/> -->\n <!-- <inherits name = 'com.google.gwt.user.theme.dark.Dark'/> -->\n\n <!-- Other module inherits -->\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>" }, { "code": null, "e": 4932, "s": 4782, "text": "GWT plugin will create a default Style Sheet file war/HelloWorld.css. Let us modify this file to keep our example at simplest level of understaning −" }, { "code": null, "e": 5118, "s": 4932, "text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}" }, { "code": null, "e": 5267, "s": 5118, "text": "GWT plugin will create a default HTML host file war/HelloWorld.html. Let us modify this file to keep our example at simplest level of understaning −" }, { "code": null, "e": 5584, "s": 5267, "text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>Hello World</h1>\n <p>Welcome to first GWT application</p>\n </body>\n</html>" }, { "code": null, "e": 5830, "s": 5584, "text": "You can create more static files like HTML, CSS or images in the same source directory or you can create further sub-directories and move files in those sub-directories and configure those sub-directories in module descriptor of the application." }, { "code": null, "e": 5961, "s": 5830, "text": "GWT plugin will create a default Java file src/com.tutorialspoint/HelloWorld.java, which keeps an entry point for the application." }, { "code": null, "e": 6011, "s": 5961, "text": "Let us modify this file to display \"Hello,World!\"" }, { "code": null, "e": 6260, "s": 6011, "text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.user.client.Window;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n Window.alert(\"Hello, World!\");\n }\n}" }, { "code": null, "e": 6380, "s": 6260, "text": "You can create more Java files in the same source directory to define either entry points or to define helper routines." }, { "code": null, "e": 6564, "s": 6380, "text": "Once you are ready with all the changes done, its time to compile the project. Use the option Google Icon > GWT Compile Project... to launch GWT Compile dialogue box as shown below −" }, { "code": null, "e": 6691, "s": 6564, "text": "Keep default values intact and click Compile button. If everything goes fine, you will see following output in Eclipse console" }, { "code": null, "e": 7107, "s": 6691, "text": "Compiling module com.tutorialspoint.HelloWorld\n Compiling 6 permutations\n Compiling permutation 0...\n Compiling permutation 1...\n Compiling permutation 2...\n Compiling permutation 3...\n Compiling permutation 4...\n Compiling permutation 5...\n Compile of permutations succeeded\nLinking into C:\\workspace\\HelloWorld\\war\\helloworld\n Link succeeded\n Compilation succeeded -- 33.029s" }, { "code": null, "e": 7200, "s": 7107, "text": "Now click on Run application menu and select HelloWorld application to run the application." }, { "code": null, "e": 7358, "s": 7200, "text": "If everything is fine, you must see GWT Development Mode active in Eclipse containing a URL as shown below. Double click the URL to open the GWT application." }, { "code": null, "e": 7540, "s": 7358, "text": "Because you are running your application in development mode, so you will need to install GWT plugin for your browser. Simply follow the onscreen instructions to install the plugin." }, { "code": null, "e": 7645, "s": 7540, "text": "If you already have GWT plugin set for your browser, then you should be able to see the following output" }, { "code": null, "e": 7738, "s": 7645, "text": "Congratulations! you have implemented your first application using Google Web Toolkit (GWT)." }, { "code": null, "e": 7745, "s": 7738, "text": " Print" }, { "code": null, "e": 7756, "s": 7745, "text": " Add Notes" } ]
Instance Segmentation with Mask R-CNN | Towards Data Science
Object Detection models such as YOLO, R-CNN help us to draw a bounding box surrounding the objects, and the Instance Segmentation provides us the pixel-wise masks for each object in the image. One question may arise that why we need pixel by pixel location? If we just use object detection in the self -driving cars then there is a possibility that the bounding boxes of multiple cars to be overlapped, the self-driving car will get confused in such a situation. Instance segmentation can avoid this flaw. Damage detection and medical diagnosis are some other applications that come to my mind since knowing the extent of damage or the size of the brain tumor could be important than just detecting the presence. In the above, image we can see that the bounding boxes of cars are intersecting and the masks with class name ‘car’ are not intersecting/ overlapping. So, we will go through how to do instance segmentation using Mask R-CNN (Mask Regional-CNN) following that using Mask R-CNN we can obtain both the pixel by pixel locations and the bounding box co-ordinates of each object in the image. Mask R-CNN Mask R-CNN combines Faster R-CNN and FCN (Fully Connected Network) to get additional mask output other than the class and box outputs. That being, Mask R-CNN adopts the same two-stage procedure, with an identical first stage (which is RPN: Region Proposal Network). The second stage extracts feature using RoIPool from each candidate box and perform classification and bounding-box regression. Read this paper to get a more detailed idea of the Mask R-CNN I have used Mask R-CNN built on FPN and ResNet101 by matterport for instance segmentation. This model is pre-trained on MS COCO which is large-scale object detection, segmentation, and captioning dataset with 80 object classes. Before going through the code make sure to install all the required packages and Mask R-CNN. Install Keras and other dependencies: $ pip install numpy scipy keras h5py tensorflow$ pip install pillow scikit-image matplotlib imutils$ pip install "IPython[all]" Clone the GitHub repository and install the matterplot implementation of Mask R-CNN $git clone https://github.com/matterport/Mask_RCNN.git$cd Mask_RCNN$python setup.py install Note: If you have installed or using tensorflow v2.0 then you may face some Traceback errors while executing the script since Mask R-CNN uses tensorflow v1.3.0 To avoid this either you downgrade the tensorflow version or edit the file Mask_RCNN/rcnn/model.py by replacing following functions before installing the Mask R-CNN: tf.log() -> tf.math.log() tf.sets.set_intersection() -> tf.sets.intersection() tf.sparse_tensor_to_dense() -> tf.sparse.to_dense() tf.to_float() -> tf.cast([value], tf.float32) Now, we are set to execute the script: Step I: Import required packages from mrcnn.config import Configfrom mrcnn import model as modellibfrom mrcnn import visualizeimport cv2import colorsysimport argparseimport imutilsimport randomimport osimport numpy as npimport matplotlib.pyplot as pltimport tensorflow as tf Step II: Generate random colors for each class label. Now we create a configuration that defines some properties of the model that is to be loaded in the next step. Feel free to increase the value of the variable IMAGES_PER_GPU if your GPU can handle it otherwise(in case of CPU) keep it 1. class SimpleConfig(Config): # give the configuration a recognizable name NAME = "coco_inference" # set the number of GPUs to use along with the number of images # per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # number of classes on COCO dataset NUM_CLASSES = 81 Step IV: Create a configuration class object and Load the model with weights. You can download the weights from here. config = SimpleConfig()config.display()model = modellib.MaskRCNN(mode="inference", config=config, model_dir=os.getcwd())model.load_weights("mask_rcnn_coco.h5", by_name=True) Step V: Perform a forward pass on any image to get segmented output. In this step, we pass an image through the loaded model in order to get the output variable with class labels, bounding box coordinates, and masks. image = cv2.imread("<image_path&name>")image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)image = imutils.resize(image, width=512)# perform a forward pass of the network to obtain the resultsprint("[INFO] making predictions with Mask R-CNN...")result = model.detect([image], verbose=1 Step VI: Visualize the output r1 = result[0]visualize.display_instances(image, r1['rois'], r1['masks'], r1['class_ids'], CLASS_NAMES, r1['scores']) Sample Output: Summing up this post, I would say instance segmentation is one step further of object detection because it yields pixel by pixel masks of the image. The Faster R-CNN is computationally expensive and we introduce instance segmentation on top of that in Mask R-CNN. Consequently, the Mask R-CNN becomes computationally more expensive. This makes Mask R-CNN difficult to run in real-time on CPU. References Kaiming He, Georgia Gkioxari, Piotr Dollár, Ross Girshick, Mask R-CNN, Source
[ { "code": null, "e": 430, "s": 172, "text": "Object Detection models such as YOLO, R-CNN help us to draw a bounding box surrounding the objects, and the Instance Segmentation provides us the pixel-wise masks for each object in the image. One question may arise that why we need pixel by pixel location?" }, { "code": null, "e": 885, "s": 430, "text": "If we just use object detection in the self -driving cars then there is a possibility that the bounding boxes of multiple cars to be overlapped, the self-driving car will get confused in such a situation. Instance segmentation can avoid this flaw. Damage detection and medical diagnosis are some other applications that come to my mind since knowing the extent of damage or the size of the brain tumor could be important than just detecting the presence." }, { "code": null, "e": 1036, "s": 885, "text": "In the above, image we can see that the bounding boxes of cars are intersecting and the masks with class name ‘car’ are not intersecting/ overlapping." }, { "code": null, "e": 1271, "s": 1036, "text": "So, we will go through how to do instance segmentation using Mask R-CNN (Mask Regional-CNN) following that using Mask R-CNN we can obtain both the pixel by pixel locations and the bounding box co-ordinates of each object in the image." }, { "code": null, "e": 1282, "s": 1271, "text": "Mask R-CNN" }, { "code": null, "e": 1738, "s": 1282, "text": "Mask R-CNN combines Faster R-CNN and FCN (Fully Connected Network) to get additional mask output other than the class and box outputs. That being, Mask R-CNN adopts the same two-stage procedure, with an identical first stage (which is RPN: Region Proposal Network). The second stage extracts feature using RoIPool from each candidate box and perform classification and bounding-box regression. Read this paper to get a more detailed idea of the Mask R-CNN" }, { "code": null, "e": 1966, "s": 1738, "text": "I have used Mask R-CNN built on FPN and ResNet101 by matterport for instance segmentation. This model is pre-trained on MS COCO which is large-scale object detection, segmentation, and captioning dataset with 80 object classes." }, { "code": null, "e": 2059, "s": 1966, "text": "Before going through the code make sure to install all the required packages and Mask R-CNN." }, { "code": null, "e": 2097, "s": 2059, "text": "Install Keras and other dependencies:" }, { "code": null, "e": 2225, "s": 2097, "text": "$ pip install numpy scipy keras h5py tensorflow$ pip install pillow scikit-image matplotlib imutils$ pip install \"IPython[all]\"" }, { "code": null, "e": 2309, "s": 2225, "text": "Clone the GitHub repository and install the matterplot implementation of Mask R-CNN" }, { "code": null, "e": 2401, "s": 2309, "text": "$git clone https://github.com/matterport/Mask_RCNN.git$cd Mask_RCNN$python setup.py install" }, { "code": null, "e": 2561, "s": 2401, "text": "Note: If you have installed or using tensorflow v2.0 then you may face some Traceback errors while executing the script since Mask R-CNN uses tensorflow v1.3.0" }, { "code": null, "e": 2727, "s": 2561, "text": "To avoid this either you downgrade the tensorflow version or edit the file Mask_RCNN/rcnn/model.py by replacing following functions before installing the Mask R-CNN:" }, { "code": null, "e": 2753, "s": 2727, "text": "tf.log() -> tf.math.log()" }, { "code": null, "e": 2806, "s": 2753, "text": "tf.sets.set_intersection() -> tf.sets.intersection()" }, { "code": null, "e": 2858, "s": 2806, "text": "tf.sparse_tensor_to_dense() -> tf.sparse.to_dense()" }, { "code": null, "e": 2904, "s": 2858, "text": "tf.to_float() -> tf.cast([value], tf.float32)" }, { "code": null, "e": 2943, "s": 2904, "text": "Now, we are set to execute the script:" }, { "code": null, "e": 2976, "s": 2943, "text": "Step I: Import required packages" }, { "code": null, "e": 3218, "s": 2976, "text": "from mrcnn.config import Configfrom mrcnn import model as modellibfrom mrcnn import visualizeimport cv2import colorsysimport argparseimport imutilsimport randomimport osimport numpy as npimport matplotlib.pyplot as pltimport tensorflow as tf" }, { "code": null, "e": 3272, "s": 3218, "text": "Step II: Generate random colors for each class label." }, { "code": null, "e": 3383, "s": 3272, "text": "Now we create a configuration that defines some properties of the model that is to be loaded in the next step." }, { "code": null, "e": 3509, "s": 3383, "text": "Feel free to increase the value of the variable IMAGES_PER_GPU if your GPU can handle it otherwise(in case of CPU) keep it 1." }, { "code": null, "e": 3790, "s": 3509, "text": "class SimpleConfig(Config): # give the configuration a recognizable name NAME = \"coco_inference\" # set the number of GPUs to use along with the number of images # per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # number of classes on COCO dataset NUM_CLASSES = 81" }, { "code": null, "e": 3868, "s": 3790, "text": "Step IV: Create a configuration class object and Load the model with weights." }, { "code": null, "e": 3908, "s": 3868, "text": "You can download the weights from here." }, { "code": null, "e": 4082, "s": 3908, "text": "config = SimpleConfig()config.display()model = modellib.MaskRCNN(mode=\"inference\", config=config, model_dir=os.getcwd())model.load_weights(\"mask_rcnn_coco.h5\", by_name=True)" }, { "code": null, "e": 4151, "s": 4082, "text": "Step V: Perform a forward pass on any image to get segmented output." }, { "code": null, "e": 4299, "s": 4151, "text": "In this step, we pass an image through the loaded model in order to get the output variable with class labels, bounding box coordinates, and masks." }, { "code": null, "e": 4579, "s": 4299, "text": "image = cv2.imread(\"<image_path&name>\")image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)image = imutils.resize(image, width=512)# perform a forward pass of the network to obtain the resultsprint(\"[INFO] making predictions with Mask R-CNN...\")result = model.detect([image], verbose=1" }, { "code": null, "e": 4609, "s": 4579, "text": "Step VI: Visualize the output" }, { "code": null, "e": 4729, "s": 4609, "text": "r1 = result[0]visualize.display_instances(image, r1['rois'], r1['masks'], r1['class_ids'], CLASS_NAMES, r1['scores'])" }, { "code": null, "e": 4744, "s": 4729, "text": "Sample Output:" }, { "code": null, "e": 5137, "s": 4744, "text": "Summing up this post, I would say instance segmentation is one step further of object detection because it yields pixel by pixel masks of the image. The Faster R-CNN is computationally expensive and we introduce instance segmentation on top of that in Mask R-CNN. Consequently, the Mask R-CNN becomes computationally more expensive. This makes Mask R-CNN difficult to run in real-time on CPU." }, { "code": null, "e": 5148, "s": 5137, "text": "References" } ]
AI-powered Indian license plate detector. | by Sarthak Vajpayee | Towards Data Science
Inspiration: The guy who hit my car and got away with it! Backstory: After a memorable evening with friends as we were about to leave for our home there was something that made that evening even more memorable, a huge dent in my car’s front bumper, seemed it was hit by another vehicle, but who to blame? There was no one around who would have witnessed that. And what could I do about it? I’ll tell you exactly what I did about it.I used my machine learning and programming skills and decided to make an AI-based Indian License plate detector that was capable enough to keep a watch on a vehicle by detecting the number plates of vehicles around it and in this blog I’ll be taking you guys through my journey of how I did it! First things first: There is always a scope of improvising, so if you come up with some better ideas or doubts regarding this project please do use the response section below. Taking in the image/video (series of images) from surrounding:at the hardware end, we need a pc (or raspberry pi) along with a camera and at the software end, we need a library to capture and process the data (image). I’ve used OpenCV (4.1.0) and Python (3.6.7) for this project. Looking for a license plate in the image:To detect an object(license plate) from an image we need another tool that can recognize an Indian license plate so for that I’ve used Haar cascade, pre-trained on Indian license plates (will be updating soon to YOLO v3). Analyzing and performing some image processing on the License plate:Using OpenCV’s grayscale, threshold, erode, dilate, contour detection and by some parameter tuning, we may easily be able to generate enough information about the plate to decide if the data is useful enough to be passed on to further processes or not (sometime if the image is very distorted or not proper, we may only get suppose 8 out of 10 characters, then there’s no point passing the data down the pipeline but to ignore it and look at the next frame for the plate), also before passing the image to the next process we need to make sure that it is noise-free and processed. Segmenting the alphanumeric characters from the license plate:if everything in the above steps works fine, we should be ready to extract the characters from the plate, this can be done by thresholding, eroding, dilating and blurring the image skillfully such that at the end the image we have is almost noise-free and easy for further functions to work on. We now again use contour detection and some parameter tuning to extract the characters. Considering the characters one by one, recognizing the characters, concatenating the results and giving out the plate number as a string:Now comes the fun part! Since we have all the characters, we need to pass the characters one by one into our trained model, and it should recognize the characters and voilà! We’ll be using Keras for our Convolutional Neural Network model. OpenCV: OpenCV is a library of programming functions mainly aimed at real-time computer vision plus its open-source, fun to work with and my personal favorite. I have used version 4.1.0 for this project. Python: aka swiss army knife of coding. I have used version 3.6.7 here. IDE: I’ll be using Jupyter here. Haar cascade: It is a machine learning object detection algorithm used to identify objects in an image or video and based on the concept of ​​ features proposed by Paul Viola and Michael Jones in their paper “Rapid Object Detection using a Boosted Cascade of Simple Features” in 2001. More info Keras: Easy to use and widely supported, Keras makes deep learning about as simple as deep learning can be. Scikit-Learn: It is a free software machine learning library for the Python programming language. And of course, do not forget the coffee! Creating a workspace. I recommend making a conda environment because it makes project management much easier. Please follow the instructions in this link for installing miniconda. Once installed open cmd/terminal and create an environment using- >conda create -n 'name_of_the_environment' python=3.6.7 Now let’s activate the environment: >conda activate 'name_of_the_environment' This should set us inside our virtual environment. Time to install some libraries- # installing OpenCV>pip install opencv-python==4.1.0# Installing Keras>pip install keras# Installing Jupyter>pip install jupyter#Installing Scikit-Learn>pip install scikit-learn Setting up the environment! We’ll start with running jupyter notebook and then importing necessary libraries in our case OpenCV, Keras and sklearn. # in your conda environment run>jupyter notebook This should open Jupyter notebook in the default web browser. Once open, let’s import the libraries #importing openCV>import cv2#importing numpy>import numpy as np#importing pandas to read the CSV file containing our data>import pandas as pd#importing keras and sub-libraries>from keras.models import Sequential>from keras.layers import Dense>from keras.layers import Dropout>from keras.layers import Flatten, MaxPool2D>from keras.layers.convolutional import Conv2D>from keras.layers.convolutional import MaxPooling2D>from keras import backend as K>from keras.utils import np_utils>from sklearn.model_selection import train_test_split Number plate detection: Let’s start simple by importing a sample image of a car with a license plate and define some functions: The above function works by taking image as input, then applying ‘haar cascade’ that is pre-trained to detect Indian license plates, here the parameter scaleFactor stands for a value by which input image can be scaled for better detection of license plate (know more). minNeighbors is just a parameter to reduce false positives, if this value is low, the algorithm may be more prone to giving a misrecognized outputs. (you can download the haar cascade file as ‘indian_license_plate.xml’ file from my github profile.) Performing some image processing on the License plate. Now let’s process this image further to make the character extraction process easy. We’ll start by defining some more functions for that. The above function takes in the image as input and performs the following operation on it- resizes it to a dimension such that all characters seem distinct and clear convert the colored image to a grey scaled image i.e instead of 3 channels (BGR), the image only has a single 8-bit channel with values ranging from 0–255 where 0 corresponds to black and 255 corresponds to white. We do this to prepare the image for the next process. now the threshold function converts the grey scaled image to a binary image i.e each pixel will now have a value of 0 or 1 where 0 corresponds to black and 1 corresponds to white. It is done by applying a threshold that has a value between 0 and 255, here the value is 200 which means in the grayscaled image for pixels having a value above 200, in the new binary image that pixel will be given a value of 1. And for pixels having value below 200, in the new binary image that pixel will be given a value of 0. The image is now in binary form and ready for the next process Eroding.Eroding is a simple process used for removing unwanted pixels from the object’s boundary meaning pixels that should have a value of 0 but are having a value of 1. It works by considering each pixel in the image one by one and then considering the pixel’s neighbor (the number of neighbors depends on the kernel size), the pixel is given a value 1 only if all its neighboring pixels are 1, otherwise it is given a value of 0. The image is now clean and free of boundary noise, we will now dilate the image to fill up the absent pixels meaning pixels that should have a value of 1 but are having value 0. The function works similar to eroding but with a little catch, it works by considering each pixel in the image one by one and then considering the pixel’s neighbor (the number of neighbors depends on the kernel size), the pixel is given a value 1 if at least one of its neighboring pixels is 1. The next step now is to make the boundaries of the image white. This is to remove any out of the frame pixel in case it is present. Next, we define a list of dimensions that contains 4 values with which we’ll be comparing the character’s dimensions for filtering out the required characters. Through the above processes, we have reduced our image to a processed binary image and we are ready to pass this image for character extraction. Segmenting the alphanumeric characters from the license plate. After step 4 we should have a clean binary image to work on. In this step, we will be applying some more image processing to extract the individual characters from the license plate. The steps involved will be- Finding all the contours in the input image. The function cv2.findContours returns all the contours it finds in the image. Contours can be explained simply as a curve joining all the continuous points (along the boundary), having the same color or intensity. After finding all the contours we consider them one by one and calculate the dimension of their respective bounding rectangle. Now consider bounding rectangle is the smallest rectangle possible that contains the contour. Let me illustrate the bounding rectangle by drawing them for each character here. Since we have the dimensions of these bounding rectangle, all we need to do is do some parameter tuning and filter out the required rectangle containing required characters. For this, we will be performing some dimension comparison by accepting only those rectangle that has a width in a range of 0, (length of the pic)/(number of characters) and length in a range of (width of the pic)/2, 4*(width of the pic)/5. If everything works well we should have all the characters extracted as binary images. The characters may be unsorted but don’t worry, the last few lines of the code take care of that. It sorts the character according to the position of their bounding rectangle from the left boundary of the plate. Creating a Machine Learning model and training it for the characters. The data is all clean and ready, now it’s time do create a Neural Network that will be intelligent enough to recognize the characters after training. For modeling, we will be using a Convolutional Neural Network with 3 layers. ## create model>model = Sequential()>model.add(Conv2D(filters=32, kernel_size=(5,5), input_shape=(28, 28, 1), activation='relu'))>model.add(MaxPooling2D(pool_size=(2, 2)))>model.add(Dropout(rate=0.4))>model.add(Flatten())>model.add(Dense(units=128, activation='relu'))>model.add(Dense(units=36, activation='softmax')) To keep the model simple, we’ll start by creating a sequential object. The first layer will be a convolutional layer with 32 output filters, a convolution window of size (5,5), and ‘Relu’ as activation function. Next, we’ll be adding a max-pooling layer with a window size of (2,2).Max pooling is a sample-based discretization process. The objective is to down-sample an input representation (image, hidden-layer output matrix, etc.), reducing its dimensionality and allowing for assumptions to be made about features contained in the sub-regions binned. Now, we will be adding some dropout rate to take care of overfitting.Dropout is a regularization hyperparameter initialized to prevent Neural Networks from Overfitting. Dropout is a technique where randomly selected neurons are ignored during training. They are “dropped-out” randomly. We have chosen a dropout rate of 0.4 meaning 60% of the node will be retained. Now it’s time to flatten the node data so we add a flatten layer for that. The flatten layer takes data from the previous layer and represents it in a single dimension. Finally, we will be adding 2 dense layers, one with the dimensionality of the output space as 128, activation function=’relu’ and other, our final layer with 36 outputs for categorizing the 26 alphabets (A-Z) + 10 digits (0–9) and activation function=’ softmax’ Training our CNN model. The data we will be using contains images of alphabets (A-Z) and digits (0–9) of size 28x28, also the data is balanced so we won’t have to do any kind of data tuning here. I’ve created a zip file that contains data as per the directory structure below, with a train test split of 80:20 We’ll be using ImageDataGenerator class available in keras to generate some more data using image augmentation techniques like width shift, height shift. To know more about ImageDataGenerator, please check out this nice blog. Width shift: Accepts a float value denoting by what fraction the image will be shifted left and right.Height shift: Accepts a float value denoting by what fraction the image will be shifted up and down. It’s time to train our model now!we will use ‘categorical_crossentropy’ as loss function, ‘Adam’ as optimization function and ‘Accuracy’ as our error matrix. After training for 23 epochs, the model achieved an accuracy of 99.54%. The output. Finally, its time to test our model, remember the binary images of extracted characters from number plate? Let’s feed the images to our model! The output- Final comment Thank you guys for reading the blog, hope this project is useful for some of you aspiring to do projects on OCR, image processing, Machine Learning, IoT. And if you have any doubts regarding this project, please leave a comment in the response section. The full project is available on my Github:https://github.com/SarthakV7/AI-based-indian-license-plate-detection Find me on LinkedIn: www.linkedin.com/in/sarthak-vajpayee
[ { "code": null, "e": 229, "s": 171, "text": "Inspiration: The guy who hit my car and got away with it!" }, { "code": null, "e": 898, "s": 229, "text": "Backstory: After a memorable evening with friends as we were about to leave for our home there was something that made that evening even more memorable, a huge dent in my car’s front bumper, seemed it was hit by another vehicle, but who to blame? There was no one around who would have witnessed that. And what could I do about it? I’ll tell you exactly what I did about it.I used my machine learning and programming skills and decided to make an AI-based Indian License plate detector that was capable enough to keep a watch on a vehicle by detecting the number plates of vehicles around it and in this blog I’ll be taking you guys through my journey of how I did it!" }, { "code": null, "e": 1074, "s": 898, "text": "First things first: There is always a scope of improvising, so if you come up with some better ideas or doubts regarding this project please do use the response section below." }, { "code": null, "e": 1354, "s": 1074, "text": "Taking in the image/video (series of images) from surrounding:at the hardware end, we need a pc (or raspberry pi) along with a camera and at the software end, we need a library to capture and process the data (image). I’ve used OpenCV (4.1.0) and Python (3.6.7) for this project." }, { "code": null, "e": 1617, "s": 1354, "text": "Looking for a license plate in the image:To detect an object(license plate) from an image we need another tool that can recognize an Indian license plate so for that I’ve used Haar cascade, pre-trained on Indian license plates (will be updating soon to YOLO v3)." }, { "code": null, "e": 2266, "s": 1617, "text": "Analyzing and performing some image processing on the License plate:Using OpenCV’s grayscale, threshold, erode, dilate, contour detection and by some parameter tuning, we may easily be able to generate enough information about the plate to decide if the data is useful enough to be passed on to further processes or not (sometime if the image is very distorted or not proper, we may only get suppose 8 out of 10 characters, then there’s no point passing the data down the pipeline but to ignore it and look at the next frame for the plate), also before passing the image to the next process we need to make sure that it is noise-free and processed." }, { "code": null, "e": 2711, "s": 2266, "text": "Segmenting the alphanumeric characters from the license plate:if everything in the above steps works fine, we should be ready to extract the characters from the plate, this can be done by thresholding, eroding, dilating and blurring the image skillfully such that at the end the image we have is almost noise-free and easy for further functions to work on. We now again use contour detection and some parameter tuning to extract the characters." }, { "code": null, "e": 3088, "s": 2711, "text": "Considering the characters one by one, recognizing the characters, concatenating the results and giving out the plate number as a string:Now comes the fun part! Since we have all the characters, we need to pass the characters one by one into our trained model, and it should recognize the characters and voilà! We’ll be using Keras for our Convolutional Neural Network model." }, { "code": null, "e": 3292, "s": 3088, "text": "OpenCV: OpenCV is a library of programming functions mainly aimed at real-time computer vision plus its open-source, fun to work with and my personal favorite. I have used version 4.1.0 for this project." }, { "code": null, "e": 3364, "s": 3292, "text": "Python: aka swiss army knife of coding. I have used version 3.6.7 here." }, { "code": null, "e": 3397, "s": 3364, "text": "IDE: I’ll be using Jupyter here." }, { "code": null, "e": 3692, "s": 3397, "text": "Haar cascade: It is a machine learning object detection algorithm used to identify objects in an image or video and based on the concept of ​​ features proposed by Paul Viola and Michael Jones in their paper “Rapid Object Detection using a Boosted Cascade of Simple Features” in 2001. More info" }, { "code": null, "e": 3800, "s": 3692, "text": "Keras: Easy to use and widely supported, Keras makes deep learning about as simple as deep learning can be." }, { "code": null, "e": 3898, "s": 3800, "text": "Scikit-Learn: It is a free software machine learning library for the Python programming language." }, { "code": null, "e": 3939, "s": 3898, "text": "And of course, do not forget the coffee!" }, { "code": null, "e": 3961, "s": 3939, "text": "Creating a workspace." }, { "code": null, "e": 4185, "s": 3961, "text": "I recommend making a conda environment because it makes project management much easier. Please follow the instructions in this link for installing miniconda. Once installed open cmd/terminal and create an environment using-" }, { "code": null, "e": 4241, "s": 4185, "text": ">conda create -n 'name_of_the_environment' python=3.6.7" }, { "code": null, "e": 4277, "s": 4241, "text": "Now let’s activate the environment:" }, { "code": null, "e": 4319, "s": 4277, "text": ">conda activate 'name_of_the_environment'" }, { "code": null, "e": 4402, "s": 4319, "text": "This should set us inside our virtual environment. Time to install some libraries-" }, { "code": null, "e": 4580, "s": 4402, "text": "# installing OpenCV>pip install opencv-python==4.1.0# Installing Keras>pip install keras# Installing Jupyter>pip install jupyter#Installing Scikit-Learn>pip install scikit-learn" }, { "code": null, "e": 4608, "s": 4580, "text": "Setting up the environment!" }, { "code": null, "e": 4728, "s": 4608, "text": "We’ll start with running jupyter notebook and then importing necessary libraries in our case OpenCV, Keras and sklearn." }, { "code": null, "e": 4777, "s": 4728, "text": "# in your conda environment run>jupyter notebook" }, { "code": null, "e": 4877, "s": 4777, "text": "This should open Jupyter notebook in the default web browser. Once open, let’s import the libraries" }, { "code": null, "e": 5412, "s": 4877, "text": "#importing openCV>import cv2#importing numpy>import numpy as np#importing pandas to read the CSV file containing our data>import pandas as pd#importing keras and sub-libraries>from keras.models import Sequential>from keras.layers import Dense>from keras.layers import Dropout>from keras.layers import Flatten, MaxPool2D>from keras.layers.convolutional import Conv2D>from keras.layers.convolutional import MaxPooling2D>from keras import backend as K>from keras.utils import np_utils>from sklearn.model_selection import train_test_split" }, { "code": null, "e": 5436, "s": 5412, "text": "Number plate detection:" }, { "code": null, "e": 5540, "s": 5436, "text": "Let’s start simple by importing a sample image of a car with a license plate and define some functions:" }, { "code": null, "e": 6058, "s": 5540, "text": "The above function works by taking image as input, then applying ‘haar cascade’ that is pre-trained to detect Indian license plates, here the parameter scaleFactor stands for a value by which input image can be scaled for better detection of license plate (know more). minNeighbors is just a parameter to reduce false positives, if this value is low, the algorithm may be more prone to giving a misrecognized outputs. (you can download the haar cascade file as ‘indian_license_plate.xml’ file from my github profile.)" }, { "code": null, "e": 6113, "s": 6058, "text": "Performing some image processing on the License plate." }, { "code": null, "e": 6251, "s": 6113, "text": "Now let’s process this image further to make the character extraction process easy. We’ll start by defining some more functions for that." }, { "code": null, "e": 6342, "s": 6251, "text": "The above function takes in the image as input and performs the following operation on it-" }, { "code": null, "e": 6417, "s": 6342, "text": "resizes it to a dimension such that all characters seem distinct and clear" }, { "code": null, "e": 6685, "s": 6417, "text": "convert the colored image to a grey scaled image i.e instead of 3 channels (BGR), the image only has a single 8-bit channel with values ranging from 0–255 where 0 corresponds to black and 255 corresponds to white. We do this to prepare the image for the next process." }, { "code": null, "e": 7196, "s": 6685, "text": "now the threshold function converts the grey scaled image to a binary image i.e each pixel will now have a value of 0 or 1 where 0 corresponds to black and 1 corresponds to white. It is done by applying a threshold that has a value between 0 and 255, here the value is 200 which means in the grayscaled image for pixels having a value above 200, in the new binary image that pixel will be given a value of 1. And for pixels having value below 200, in the new binary image that pixel will be given a value of 0." }, { "code": null, "e": 7692, "s": 7196, "text": "The image is now in binary form and ready for the next process Eroding.Eroding is a simple process used for removing unwanted pixels from the object’s boundary meaning pixels that should have a value of 0 but are having a value of 1. It works by considering each pixel in the image one by one and then considering the pixel’s neighbor (the number of neighbors depends on the kernel size), the pixel is given a value 1 only if all its neighboring pixels are 1, otherwise it is given a value of 0." }, { "code": null, "e": 8165, "s": 7692, "text": "The image is now clean and free of boundary noise, we will now dilate the image to fill up the absent pixels meaning pixels that should have a value of 1 but are having value 0. The function works similar to eroding but with a little catch, it works by considering each pixel in the image one by one and then considering the pixel’s neighbor (the number of neighbors depends on the kernel size), the pixel is given a value 1 if at least one of its neighboring pixels is 1." }, { "code": null, "e": 8297, "s": 8165, "text": "The next step now is to make the boundaries of the image white. This is to remove any out of the frame pixel in case it is present." }, { "code": null, "e": 8457, "s": 8297, "text": "Next, we define a list of dimensions that contains 4 values with which we’ll be comparing the character’s dimensions for filtering out the required characters." }, { "code": null, "e": 8602, "s": 8457, "text": "Through the above processes, we have reduced our image to a processed binary image and we are ready to pass this image for character extraction." }, { "code": null, "e": 8665, "s": 8602, "text": "Segmenting the alphanumeric characters from the license plate." }, { "code": null, "e": 8876, "s": 8665, "text": "After step 4 we should have a clean binary image to work on. In this step, we will be applying some more image processing to extract the individual characters from the license plate. The steps involved will be-" }, { "code": null, "e": 9135, "s": 8876, "text": "Finding all the contours in the input image. The function cv2.findContours returns all the contours it finds in the image. Contours can be explained simply as a curve joining all the continuous points (along the boundary), having the same color or intensity." }, { "code": null, "e": 9438, "s": 9135, "text": "After finding all the contours we consider them one by one and calculate the dimension of their respective bounding rectangle. Now consider bounding rectangle is the smallest rectangle possible that contains the contour. Let me illustrate the bounding rectangle by drawing them for each character here." }, { "code": null, "e": 9939, "s": 9438, "text": "Since we have the dimensions of these bounding rectangle, all we need to do is do some parameter tuning and filter out the required rectangle containing required characters. For this, we will be performing some dimension comparison by accepting only those rectangle that has a width in a range of 0, (length of the pic)/(number of characters) and length in a range of (width of the pic)/2, 4*(width of the pic)/5. If everything works well we should have all the characters extracted as binary images." }, { "code": null, "e": 10151, "s": 9939, "text": "The characters may be unsorted but don’t worry, the last few lines of the code take care of that. It sorts the character according to the position of their bounding rectangle from the left boundary of the plate." }, { "code": null, "e": 10221, "s": 10151, "text": "Creating a Machine Learning model and training it for the characters." }, { "code": null, "e": 10371, "s": 10221, "text": "The data is all clean and ready, now it’s time do create a Neural Network that will be intelligent enough to recognize the characters after training." }, { "code": null, "e": 10448, "s": 10371, "text": "For modeling, we will be using a Convolutional Neural Network with 3 layers." }, { "code": null, "e": 10766, "s": 10448, "text": "## create model>model = Sequential()>model.add(Conv2D(filters=32, kernel_size=(5,5), input_shape=(28, 28, 1), activation='relu'))>model.add(MaxPooling2D(pool_size=(2, 2)))>model.add(Dropout(rate=0.4))>model.add(Flatten())>model.add(Dense(units=128, activation='relu'))>model.add(Dense(units=36, activation='softmax'))" }, { "code": null, "e": 10837, "s": 10766, "text": "To keep the model simple, we’ll start by creating a sequential object." }, { "code": null, "e": 10978, "s": 10837, "text": "The first layer will be a convolutional layer with 32 output filters, a convolution window of size (5,5), and ‘Relu’ as activation function." }, { "code": null, "e": 11321, "s": 10978, "text": "Next, we’ll be adding a max-pooling layer with a window size of (2,2).Max pooling is a sample-based discretization process. The objective is to down-sample an input representation (image, hidden-layer output matrix, etc.), reducing its dimensionality and allowing for assumptions to be made about features contained in the sub-regions binned." }, { "code": null, "e": 11686, "s": 11321, "text": "Now, we will be adding some dropout rate to take care of overfitting.Dropout is a regularization hyperparameter initialized to prevent Neural Networks from Overfitting. Dropout is a technique where randomly selected neurons are ignored during training. They are “dropped-out” randomly. We have chosen a dropout rate of 0.4 meaning 60% of the node will be retained." }, { "code": null, "e": 11855, "s": 11686, "text": "Now it’s time to flatten the node data so we add a flatten layer for that. The flatten layer takes data from the previous layer and represents it in a single dimension." }, { "code": null, "e": 12117, "s": 11855, "text": "Finally, we will be adding 2 dense layers, one with the dimensionality of the output space as 128, activation function=’relu’ and other, our final layer with 36 outputs for categorizing the 26 alphabets (A-Z) + 10 digits (0–9) and activation function=’ softmax’" }, { "code": null, "e": 12141, "s": 12117, "text": "Training our CNN model." }, { "code": null, "e": 12313, "s": 12141, "text": "The data we will be using contains images of alphabets (A-Z) and digits (0–9) of size 28x28, also the data is balanced so we won’t have to do any kind of data tuning here." }, { "code": null, "e": 12427, "s": 12313, "text": "I’ve created a zip file that contains data as per the directory structure below, with a train test split of 80:20" }, { "code": null, "e": 12653, "s": 12427, "text": "We’ll be using ImageDataGenerator class available in keras to generate some more data using image augmentation techniques like width shift, height shift. To know more about ImageDataGenerator, please check out this nice blog." }, { "code": null, "e": 12856, "s": 12653, "text": "Width shift: Accepts a float value denoting by what fraction the image will be shifted left and right.Height shift: Accepts a float value denoting by what fraction the image will be shifted up and down." }, { "code": null, "e": 13014, "s": 12856, "text": "It’s time to train our model now!we will use ‘categorical_crossentropy’ as loss function, ‘Adam’ as optimization function and ‘Accuracy’ as our error matrix." }, { "code": null, "e": 13086, "s": 13014, "text": "After training for 23 epochs, the model achieved an accuracy of 99.54%." }, { "code": null, "e": 13098, "s": 13086, "text": "The output." }, { "code": null, "e": 13241, "s": 13098, "text": "Finally, its time to test our model, remember the binary images of extracted characters from number plate? Let’s feed the images to our model!" }, { "code": null, "e": 13253, "s": 13241, "text": "The output-" }, { "code": null, "e": 13267, "s": 13253, "text": "Final comment" }, { "code": null, "e": 13421, "s": 13267, "text": "Thank you guys for reading the blog, hope this project is useful for some of you aspiring to do projects on OCR, image processing, Machine Learning, IoT." }, { "code": null, "e": 13520, "s": 13421, "text": "And if you have any doubts regarding this project, please leave a comment in the response section." }, { "code": null, "e": 13632, "s": 13520, "text": "The full project is available on my Github:https://github.com/SarthakV7/AI-based-indian-license-plate-detection" } ]
Java Program to display a prime number less than the given number
Let’s say the value you have set is 20 and you have to display a prime number less than this value i.e. 19 in this case. The following is an example that displays a prime number less than the given number − Live Demo public class Demo { public static void main(String[] args) { int val = 20; boolean[] isprime = new boolean[val + 1]; for (int i = 0; i<= val; i++) isprime[i] = true; // 0 and 1 is not prime isprime[0] = false; isprime[1] = false; int n = (int) Math.ceil(Math.sqrt(val)); for (int i = 0; i<= n; i++) { if (isprime[i]) for (int j = 2 * i; j<= val; j = j + i) // not prime isprime[j] = false; } int myPrime; for (myPrime = val; !isprime[myPrime]; myPrime--); // empty loop body System.out.println("Largest prime less than or equal to " + val + " = " + myPrime); } } Largest prime less than or equal to 20 = 19 Above, we have set the following as non-prime since both 0 and 1 are non-prime − isprime[0] = false; isprime[1] = false;
[ { "code": null, "e": 1183, "s": 1062, "text": "Let’s say the value you have set is 20 and you have to display a prime number less than this value i.e. 19 in this case." }, { "code": null, "e": 1269, "s": 1183, "text": "The following is an example that displays a prime number less than the given number −" }, { "code": null, "e": 1280, "s": 1269, "text": " Live Demo" }, { "code": null, "e": 1996, "s": 1280, "text": "public class Demo {\n public static void main(String[] args) {\n int val = 20;\n boolean[] isprime = new boolean[val + 1];\n for (int i = 0; i<= val; i++)\n isprime[i] = true;\n // 0 and 1 is not prime\n isprime[0] = false;\n isprime[1] = false;\n int n = (int) Math.ceil(Math.sqrt(val));\n for (int i = 0; i<= n; i++) {\n if (isprime[i])\n for (int j = 2 * i; j<= val; j = j + i)\n // not prime\n isprime[j] = false;\n }\n int myPrime;\n for (myPrime = val; !isprime[myPrime]; myPrime--); // empty loop body\n System.out.println(\"Largest prime less than or equal to \" + val + \" = \" + myPrime);\n }\n}" }, { "code": null, "e": 2040, "s": 1996, "text": "Largest prime less than or equal to 20 = 19" }, { "code": null, "e": 2121, "s": 2040, "text": "Above, we have set the following as non-prime since both 0 and 1 are non-prime −" }, { "code": null, "e": 2161, "s": 2121, "text": "isprime[0] = false;\nisprime[1] = false;" } ]
Requests - SSL Certification
SSL certificate is a security feature that comes with secure urls. When you use Requests library, it also verifies SSL certificates for the https URL given. SSL verification is enabled by default in the requests module and will throw an error if the certificate is not present. Following is the example of working with secure URL − import requests getdata = requests.get(https://jsonplaceholder.typicode.com/users) print(getdata.text) E:\prequests>python makeRequest.py [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ] We are easily getting a response from the above https URL, and it is because the request module can verify the SSL certificate. You can disable the SSL verification by simply adding verify=False as shown in the example below. import requests getdata = requests.get('https://jsonplaceholder.typicode.com/users', verify=False) print(getdata.text) You will get the output, but it will also give a warning message that, the SSL certificate is not verified and adding certificate verification is advised. E:\prequests>python makeRequest.py connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3 .readthedocs.io/en/latest/advanced-usage.htm l#ssl-warnings InsecureRequestWarning) [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ] You can also verify SSL certificate by hosting it at your end, and giving the path using verify param as shown below. import requests getdata = requests.get('https://jsonplaceholder.typicode.com/users', verify='C:\Users\AppData\Local\certificate.txt') print(getdata.text) E:\prequests>python makeRequest.py [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ] Print Add Notes Bookmark this page
[ { "code": null, "e": 2466, "s": 2188, "text": "SSL certificate is a security feature that comes with secure urls. When you use Requests library, it also verifies SSL certificates for the https URL given. SSL verification is enabled by default in the requests module and will throw an error if the certificate is not present." }, { "code": null, "e": 2521, "s": 2466, "text": "Following is the example of working with secure URL − " }, { "code": null, "e": 2625, "s": 2521, "text": "import requests\ngetdata = requests.get(https://jsonplaceholder.typicode.com/users)\nprint(getdata.text) " }, { "code": null, "e": 3278, "s": 2625, "text": "E:\\prequests>python makeRequest.py\n[\n {\n \"id\": 1,\n \"name\": \"Leanne Graham\",\n \"username\": \"Bret\",\n \"email\": \"Sincere@april.biz\",\n \"address\": {\n \"street\": \"Kulas Light\",\n \"suite\": \"Apt. 556\",\n \"city\": \"Gwenborough\",\n \"zipcode\": \"92998-3874\",\n \"geo\": {\n \"lat\": \"-37.3159\",\n \"lng\": \"81.1496\"\n }\n },\n \"phone\": \"1-770-736-8031 x56442\",\n \"website\": \"hildegard.org\",\n \"company\": {\n \"name\": \"Romaguera-Crona\",\n \"catchPhrase\": \"Multi-layered client-server neural-net\",\n \"bs\": \"harness real-time e-markets\"\n }\n }\n]\n" }, { "code": null, "e": 3406, "s": 3278, "text": "We are easily getting a response from the above https URL, and it is because the request module can verify the SSL certificate." }, { "code": null, "e": 3504, "s": 3406, "text": "You can disable the SSL verification by simply adding verify=False as shown in the example below." }, { "code": null, "e": 3624, "s": 3504, "text": "import requests\ngetdata = \nrequests.get('https://jsonplaceholder.typicode.com/users', verify=False)\nprint(getdata.text)" }, { "code": null, "e": 3779, "s": 3624, "text": "You will get the output, but it will also give a warning message that, the SSL certificate is not verified and adding certificate verification is advised." }, { "code": null, "e": 4684, "s": 3779, "text": "E:\\prequests>python makeRequest.py\nconnectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is \nbeing made. Adding certificate verification is strongly advised. See: \nhttps://urllib3\n.readthedocs.io/en/latest/advanced-usage.htm l#ssl-warnings\n InsecureRequestWarning)\n[\n {\n \"id\": 1,\n \"name\": \"Leanne Graham\",\n \"username\": \"Bret\", \n \"email\": \"Sincere@april.biz\",\n \"address\": {\n \"street\": \"Kulas Light\",\n \"suite\": \"Apt. 556\",\n \"city\": \"Gwenborough\",\n \"zipcode\": \"92998-3874\",\n \"geo\": {\n \"lat\": \"-37.3159\",\n \"lng\": \"81.1496\"\n }\n },\n \"phone\": \"1-770-736-8031 x56442\",\n \"website\": \"hildegard.org\",\n \"company\": {\n \"name\": \"Romaguera-Crona\",\n \"catchPhrase\": \"Multi-layered client-server neural-net\",\n \"bs\": \"harness real-time e-markets\"\n }\n }\n]\n" }, { "code": null, "e": 4802, "s": 4684, "text": "You can also verify SSL certificate by hosting it at your end, and giving the path using verify param as shown below." }, { "code": null, "e": 4959, "s": 4802, "text": "import requests\ngetdata = \nrequests.get('https://jsonplaceholder.typicode.com/users', verify='C:\\Users\\AppData\\Local\\certificate.txt')\nprint(getdata.text) " }, { "code": null, "e": 5615, "s": 4959, "text": "E:\\prequests>python makeRequest.py\n[\n {\n \"id\": 1,\n \"name\": \"Leanne Graham\",\n \"username\": \"Bret\",\n \"email\": \"Sincere@april.biz\",\n \"address\": {\n \"street\": \"Kulas Light\",\n \"suite\": \"Apt. 556\",\n \"city\": \"Gwenborough\",\n \"zipcode\": \"92998-3874\",\n \"geo\": {\n \"lat\": \"-37.3159\",\n \"lng\": \"81.1496\"\n }\n },\n \"phone\": \"1-770-736-8031 x56442\",\n \"website\": \"hildegard.org\",\n \"company\": {\n \"name\": \"Romaguera-Crona\",\n \"catchPhrase\": \"Multi-layered client-server neural-net\",\n \"bs\": \"harness real-time e-markets\"\n }\n }\n] \n" }, { "code": null, "e": 5622, "s": 5615, "text": " Print" }, { "code": null, "e": 5633, "s": 5622, "text": " Add Notes" } ]
Plotting in parallel with matplotlib and python | by Paul Gavrikov | Towards Data Science
This is yet another post on how to speed up matplotlib. And it’s not like I am ranting against matplotlib. In fact, it is a daily driver in my projects. But sometimes you need that little extra performance. Here’s one example. For one of my studies, I had to create plenty of violin plots. For those unfamiliar with them, here’s a very brief and oversimplified explanation: Basically, the plots are in some ways similar to histograms but you can actually compare multiple violins in one plot, which is quite hard with histograms. Instead of computing discrete frequencies, violin plots compute the kernel density estimate (KDE) for each axis in question (a continuous function). And then they just plot the resulting polygons. The plotting is rather computationally cheap, but computing the KDE is not. I was dealing with hundreds of millions of data points and multiple axes. So, performance was key. The KDE of each axis can be computed independently and even the plotting could be done independently (on a shared axis). But matplotlib does it sequentially — ugh! I started playing around to get matplotlib working with multiprocessing but I didn’t want to only parallelize KDE computation but any kind of plot that can be separated into multiple plots. Matplotlib is not really thread-safe so most of my approaches failed. I am sure there is some nifty way to achieve parallelism and perhaps I wasn’t digging deep enough but I wanted a simple solution to a simple problem and came up with a cheap trick. Instead of parallelizing the internals of matplotlib I distribute my data to different processes and then let every process create its own plot. Each plot is then rasterized and fed back to the main process which assembles all resulting subplots into one grid-like plot. The output is a full matplotlib plot — you could even feed it into a QT backend and enjoy all the functionality of a GUI. But every subplot is a rasterized image. Which means you can’t zoom in, change axis etc. However, if you just need a fast way to create static plots then this approach should work for you. I published this side-project on GitHub but haven’t published it on PyPi, yet. If you just want to use it, you can stop reading here and just install the library. Follow the GitHub readme for usage info. pip install git+https://github.com/paulgavrikov/parallel-matplolib-grid/ But if you’re curious I’ll also explain the principle with a slightly stripped-down functionality. Let’s dig into it. First, we have to distribute the data to every worker and then assemble the outputs. We can let multiprocessing handle that by using Pool. And assembling means we just create subplots and let every plot show the rasterized output via plt.imshow. Now, it’s time to define the worker. The worker has to create a plot, call a user-defined function that will plot the data to the figure in whatever way, and then rasterize and return the output. matplotlib is not very good at computing the bounds of every plot before saving. Either you accept subplots that may be missing a bit of the plot or use padding (done by default). And now you can call parallel_plot with your data and your custom plotting routine and enjoy quasi-parallel plotting. Let’s create a 5x5 grid of violins: Or a row of 5 scatter plots: You can create any plot you like as long as your plot on the provided fig and axes arguments. Just remember that multiprocessing cannot handle data well that exceeds 4GiB. A little side note. I am well aware that multiprocessing is not the creme de la creme when it comes to actual parallelism. But it works good enough for most cases and my primary usage are jupyter notebooks where I found multiprocessing to be one of the few libraries to work reliably. If you want to use it outside of jupyter and would like to share larger data with workers you may want to consider using ray. ray does not use pickle to serialize data. So, serialization is faster and you can serialize data that is bigger than 4GiB. Accessing the data is also faster since there is no expensive deserialization. But I also had problems with lots of dead processes that occupy RAM and never got it to work within a jupyter notebook.
[ { "code": null, "e": 379, "s": 172, "text": "This is yet another post on how to speed up matplotlib. And it’s not like I am ranting against matplotlib. In fact, it is a daily driver in my projects. But sometimes you need that little extra performance." }, { "code": null, "e": 1238, "s": 379, "text": "Here’s one example. For one of my studies, I had to create plenty of violin plots. For those unfamiliar with them, here’s a very brief and oversimplified explanation: Basically, the plots are in some ways similar to histograms but you can actually compare multiple violins in one plot, which is quite hard with histograms. Instead of computing discrete frequencies, violin plots compute the kernel density estimate (KDE) for each axis in question (a continuous function). And then they just plot the resulting polygons. The plotting is rather computationally cheap, but computing the KDE is not. I was dealing with hundreds of millions of data points and multiple axes. So, performance was key. The KDE of each axis can be computed independently and even the plotting could be done independently (on a shared axis). But matplotlib does it sequentially — ugh!" }, { "code": null, "e": 1679, "s": 1238, "text": "I started playing around to get matplotlib working with multiprocessing but I didn’t want to only parallelize KDE computation but any kind of plot that can be separated into multiple plots. Matplotlib is not really thread-safe so most of my approaches failed. I am sure there is some nifty way to achieve parallelism and perhaps I wasn’t digging deep enough but I wanted a simple solution to a simple problem and came up with a cheap trick." }, { "code": null, "e": 1950, "s": 1679, "text": "Instead of parallelizing the internals of matplotlib I distribute my data to different processes and then let every process create its own plot. Each plot is then rasterized and fed back to the main process which assembles all resulting subplots into one grid-like plot." }, { "code": null, "e": 2261, "s": 1950, "text": "The output is a full matplotlib plot — you could even feed it into a QT backend and enjoy all the functionality of a GUI. But every subplot is a rasterized image. Which means you can’t zoom in, change axis etc. However, if you just need a fast way to create static plots then this approach should work for you." }, { "code": null, "e": 2465, "s": 2261, "text": "I published this side-project on GitHub but haven’t published it on PyPi, yet. If you just want to use it, you can stop reading here and just install the library. Follow the GitHub readme for usage info." }, { "code": null, "e": 2538, "s": 2465, "text": "pip install git+https://github.com/paulgavrikov/parallel-matplolib-grid/" }, { "code": null, "e": 2656, "s": 2538, "text": "But if you’re curious I’ll also explain the principle with a slightly stripped-down functionality. Let’s dig into it." }, { "code": null, "e": 2902, "s": 2656, "text": "First, we have to distribute the data to every worker and then assemble the outputs. We can let multiprocessing handle that by using Pool. And assembling means we just create subplots and let every plot show the rasterized output via plt.imshow." }, { "code": null, "e": 3098, "s": 2902, "text": "Now, it’s time to define the worker. The worker has to create a plot, call a user-defined function that will plot the data to the figure in whatever way, and then rasterize and return the output." }, { "code": null, "e": 3278, "s": 3098, "text": "matplotlib is not very good at computing the bounds of every plot before saving. Either you accept subplots that may be missing a bit of the plot or use padding (done by default)." }, { "code": null, "e": 3396, "s": 3278, "text": "And now you can call parallel_plot with your data and your custom plotting routine and enjoy quasi-parallel plotting." }, { "code": null, "e": 3432, "s": 3396, "text": "Let’s create a 5x5 grid of violins:" }, { "code": null, "e": 3461, "s": 3432, "text": "Or a row of 5 scatter plots:" }, { "code": null, "e": 3633, "s": 3461, "text": "You can create any plot you like as long as your plot on the provided fig and axes arguments. Just remember that multiprocessing cannot handle data well that exceeds 4GiB." }, { "code": null, "e": 4044, "s": 3633, "text": "A little side note. I am well aware that multiprocessing is not the creme de la creme when it comes to actual parallelism. But it works good enough for most cases and my primary usage are jupyter notebooks where I found multiprocessing to be one of the few libraries to work reliably. If you want to use it outside of jupyter and would like to share larger data with workers you may want to consider using ray." } ]
Deep Quantile Regression in Tensorflow | by Jacob Zweig | Towards Data Science
A key challenge in deep learning is how to get estimates on the bounds of predictors. Quantile regression, first introduced in the 70’s by Koenker and Bassett [1], allows us to estimate percentiles of the underlying conditional data distribution even in cases where they are asymmetric, giving us insight on the relationship of the variability between predictors and responses. As described by Koeneker and Hallock [2], the standard approach in OLS regression is to estimate the conditional mean of the data by drawing a line which minimizes distance between the line and all of the points on the graph. In contrast, the goal in quantile regression is to estimate the conditional median, or any other quantile. To do so, we instead weight the distances between points on the graph and our regression line based on the selected quantile. For example, if we selected the 90th quantile to estimate, we’d fit a regression line so that 90% of the data points are below the line and 10% are above. A great recent post on medium by Sachin Abeywardana demonstrated how to perform deep quantile regression using Keras. However, a limitation of this implementation is that it requires separate fitting of models per quantile. Using Tensorflow, however, we can instead fit an arbitrary number of quantiles simultaneously. The notebook for this implementation can be found on the Strong Analytics github. We first instantiate a simple regression model, and add outputs for each of the quantiles we’d like to estimate # Define the quantiles we’d like to estimatequantiles = [.1, .5, .9]# Add placeholders for inputs to the modelx = tf.placeholder(tf.float32, shape=(None, in_shape))y = tf.placeholder(tf.float32, shape=(None, out_shape))# Create model using tf.layers APIlayer0 = tf.layers.dense(x, units=32, activation=tf.nn.relu)layer1 = tf.layers.dense(layer0, units=32, activation=tf.nn.relu)# Now, create an output for each quantileoutputs = []for i, quantile in enumerate(quantiles): output = tf.layers.dense(layer1, 1, name=”{}_q{}”.format(i, int(quantile*100))) outputs.append(output) Now, we create the losses for each quantile losses = []for i, quantile in enumerate(quantiles): error = tf.subtract(y, output[i]) loss = tf.reduce_mean(tf.maximum(quantile*error, (quantile-1)*error), axis=-1) losses.append(loss) Finally, we combine the losses and instantiate our optimizer combined_loss = tf.reduce_mean(tf.add_n(losses))train_step = tf.train.AdamOptimizer().minimize(combined_loss) And that’s basically it! Now we can fit our model and simultaneously estimate all of the specified quantiles: for epoch in range(epochs): # Split data to batches for idx in range(0, data.shape[0], batch_size): batch_data = data[idx : min(idx + batch_size, data.shape[0]),:] batch_labels = labels[idx : min(idx + batch_size, labels.shape[0]),:] feed_dict = {x: batch_data, y: batch_labels} _, c_loss = sess.run([train_step, combined_loss], feed_dict) Fitting this data on a dataset of motorcycle crashes (from here) gives us the following output: 1. Regression Quantiles. Roger Koenker; Gilbert Bassett, Jr. Econometrica, Vol. 46, No1. (Jan., 1978), pp. 33–50. 2. Quantile Regression. Roger Koenker; Kevin F. Hallock. Journal of Economic Perspectives · vol. 15, no. 4, Fall 2001. (pp. 143–156). Want to work on challenging Machine Learning and AI in a variety of industries with a team of top data scientists in Chicago? We’re hiring talented data scientists and engineers! Learn more at strong.io and apply at careers.strong.io
[ { "code": null, "e": 550, "s": 172, "text": "A key challenge in deep learning is how to get estimates on the bounds of predictors. Quantile regression, first introduced in the 70’s by Koenker and Bassett [1], allows us to estimate percentiles of the underlying conditional data distribution even in cases where they are asymmetric, giving us insight on the relationship of the variability between predictors and responses." }, { "code": null, "e": 1164, "s": 550, "text": "As described by Koeneker and Hallock [2], the standard approach in OLS regression is to estimate the conditional mean of the data by drawing a line which minimizes distance between the line and all of the points on the graph. In contrast, the goal in quantile regression is to estimate the conditional median, or any other quantile. To do so, we instead weight the distances between points on the graph and our regression line based on the selected quantile. For example, if we selected the 90th quantile to estimate, we’d fit a regression line so that 90% of the data points are below the line and 10% are above." }, { "code": null, "e": 1483, "s": 1164, "text": "A great recent post on medium by Sachin Abeywardana demonstrated how to perform deep quantile regression using Keras. However, a limitation of this implementation is that it requires separate fitting of models per quantile. Using Tensorflow, however, we can instead fit an arbitrary number of quantiles simultaneously." }, { "code": null, "e": 1565, "s": 1483, "text": "The notebook for this implementation can be found on the Strong Analytics github." }, { "code": null, "e": 1677, "s": 1565, "text": "We first instantiate a simple regression model, and add outputs for each of the quantiles we’d like to estimate" }, { "code": null, "e": 2258, "s": 1677, "text": "# Define the quantiles we’d like to estimatequantiles = [.1, .5, .9]# Add placeholders for inputs to the modelx = tf.placeholder(tf.float32, shape=(None, in_shape))y = tf.placeholder(tf.float32, shape=(None, out_shape))# Create model using tf.layers APIlayer0 = tf.layers.dense(x, units=32, activation=tf.nn.relu)layer1 = tf.layers.dense(layer0, units=32, activation=tf.nn.relu)# Now, create an output for each quantileoutputs = []for i, quantile in enumerate(quantiles): output = tf.layers.dense(layer1, 1, name=”{}_q{}”.format(i, int(quantile*100))) outputs.append(output)" }, { "code": null, "e": 2302, "s": 2258, "text": "Now, we create the losses for each quantile" }, { "code": null, "e": 2493, "s": 2302, "text": "losses = []for i, quantile in enumerate(quantiles): error = tf.subtract(y, output[i]) loss = tf.reduce_mean(tf.maximum(quantile*error, (quantile-1)*error), axis=-1) losses.append(loss)" }, { "code": null, "e": 2554, "s": 2493, "text": "Finally, we combine the losses and instantiate our optimizer" }, { "code": null, "e": 2664, "s": 2554, "text": "combined_loss = tf.reduce_mean(tf.add_n(losses))train_step = tf.train.AdamOptimizer().minimize(combined_loss)" }, { "code": null, "e": 2774, "s": 2664, "text": "And that’s basically it! Now we can fit our model and simultaneously estimate all of the specified quantiles:" }, { "code": null, "e": 3148, "s": 2774, "text": "for epoch in range(epochs): # Split data to batches for idx in range(0, data.shape[0], batch_size): batch_data = data[idx : min(idx + batch_size, data.shape[0]),:] batch_labels = labels[idx : min(idx + batch_size, labels.shape[0]),:] feed_dict = {x: batch_data, y: batch_labels} _, c_loss = sess.run([train_step, combined_loss], feed_dict)" }, { "code": null, "e": 3244, "s": 3148, "text": "Fitting this data on a dataset of motorcycle crashes (from here) gives us the following output:" }, { "code": null, "e": 3358, "s": 3244, "text": "1. Regression Quantiles. Roger Koenker; Gilbert Bassett, Jr. Econometrica, Vol. 46, No1. (Jan., 1978), pp. 33–50." }, { "code": null, "e": 3492, "s": 3358, "text": "2. Quantile Regression. Roger Koenker; Kevin F. Hallock. Journal of Economic Perspectives · vol. 15, no. 4, Fall 2001. (pp. 143–156)." }, { "code": null, "e": 3671, "s": 3492, "text": "Want to work on challenging Machine Learning and AI in a variety of industries with a team of top data scientists in Chicago? We’re hiring talented data scientists and engineers!" } ]
DAX Text - VALUE function
Converts a text string that represents a number to a number in numeric data type. VALUE (<text>) text The text to be converted. A number. The text parameter for the DAX VALUE function can be a constant, a number, a date, or a time in DAX data types. If the text is not in one of these following formats, DAX VALUE function returns an error. If the text represents an integer, the integer is returned. If the text represents an integer, the integer is returned. If the text represents a decimal number with only zero values to the right of the decimal point, then the integer part only is returned. If the text represents a decimal number with only zero values to the right of the decimal point, then the integer part only is returned. If the text represents a decimal number, then the decimal number is returned. If the text represents a decimal number, then the decimal number is returned. = VALUE ("5") returns 5. = VALUE ("5.0") returns 5. = VALUE ("5.1") returns 5.1. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2083, "s": 2001, "text": "Converts a text string that represents a number to a number in numeric data type." }, { "code": null, "e": 2100, "s": 2083, "text": "VALUE (<text>) \n" }, { "code": null, "e": 2105, "s": 2100, "text": "text" }, { "code": null, "e": 2131, "s": 2105, "text": "The text to be converted." }, { "code": null, "e": 2141, "s": 2131, "text": "A number." }, { "code": null, "e": 2253, "s": 2141, "text": "The text parameter for the DAX VALUE function can be a constant, a number, a date, or a time in DAX data types." }, { "code": null, "e": 2344, "s": 2253, "text": "If the text is not in one of these following formats, DAX VALUE function returns an error." }, { "code": null, "e": 2404, "s": 2344, "text": "If the text represents an integer, the integer is returned." }, { "code": null, "e": 2464, "s": 2404, "text": "If the text represents an integer, the integer is returned." }, { "code": null, "e": 2601, "s": 2464, "text": "If the text represents a decimal number with only zero values to the right of the decimal point, then the integer part only is returned." }, { "code": null, "e": 2738, "s": 2601, "text": "If the text represents a decimal number with only zero values to the right of the decimal point, then the integer part only is returned." }, { "code": null, "e": 2816, "s": 2738, "text": "If the text represents a decimal number, then the decimal number is returned." }, { "code": null, "e": 2894, "s": 2816, "text": "If the text represents a decimal number, then the decimal number is returned." }, { "code": null, "e": 2978, "s": 2894, "text": "= VALUE (\"5\") returns 5. \n= VALUE (\"5.0\") returns 5. \n= VALUE (\"5.1\") returns 5.1. " }, { "code": null, "e": 3013, "s": 2978, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3027, "s": 3013, "text": " Abhay Gadiya" }, { "code": null, "e": 3060, "s": 3027, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3074, "s": 3060, "text": " Randy Minder" }, { "code": null, "e": 3109, "s": 3074, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3123, "s": 3109, "text": " Randy Minder" }, { "code": null, "e": 3130, "s": 3123, "text": " Print" }, { "code": null, "e": 3141, "s": 3130, "text": " Add Notes" } ]
JOGL Graphical Shapes
This tutorial describes drawing a straight line and various shapes using straight line. OpenGL API has provided primitive methods for drawing basic graphical elements such as point, vertex, line etc. Using these methods, you can develop shapes such as triangle, polygon and circle. In both, 2D and 3D dimensions. To access programs which are specific to a hardware and operating system platforms, and the libraries written in other languages such as C and C++ (native applications), java uses a programming frame work called Java Native Interface (JNI). JOGL uses this interface internally to access OpenGL functions as shown in the following diagram. All the four methods of GLEventListener interface have the code (java JOGL methods) which internally call OpenGL functions, naming of those JOGL methods is also similar to the naming conventions of OpenGL. If the function name in OpenGL is glBegin(), it is used as gl.glBegin(). Whenever gl.glBegin() method of java JOGL is called, it internally invokes the glBegin() method of OpenGL. This is the reason for installing native library files on user system at the time of installation of JOGL. The Display() method This is an important method which holds the code for developing graphics. This requires GLAutoDrawable interface object as parameter. In Display() method, initially get OpenGL context using object of GL interface (GL inherits GLBase interface which contains methods to generate all OpenGL context objects). Since this tutorial is about JOGL2 let us generate GL2 object. Let us go through code snippet for getting GL2 Object: //Generating GL object GL gl=drawable.getGL(); GL gl=drawable.getGL(); //Using this Getting the Gl2 Object //this can be written in a single line like final GL2 gl = drawable.getGL().getGL2(); Using the object of GL2 interface, one can access the members of GL2 interface, which in turn provide access to OpenGL [1.0... 3.0] functions. GL2 interface contains huge list of methods but here three main important methods are discussed namely glBegin(), glVertex(), and glEnd(). glBegin() This method starts the process of drawing a line. It takes predefined string integer “GL_LINES” as a parameter, which is inherited from GL interface. glVertex3f()/glVertex2f() This method creates the vertex and we have to pass coordinates as parameters 3f and 2f, which denote 3dimentional floating point coordinates and 2dimentional floating point coordinates respectively. glEnd() ends the line Let us go through the program to draw a line: import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; public class Line implements GLEventListener{ @Override public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glBegin (GL2.GL_LINES);//static field gl.glVertex3f(0.50f,-0.50f,0); gl.glVertex3f(-0.50f,0.50f,0); gl.glEnd(); } @Override public void dispose(GLAutoDrawable arg0) { //method body } @Override public void init(GLAutoDrawable arg0) { // method body } @Override public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) { // method body } public static void main(String[] args) { //getting the capabilities object of GL2 profile final GLProfile profile = GLProfile.get(GLProfile.GL2); GLCapabilities capabilities = new GLCapabilities(profile); // The canvas final GLCanvas glcanvas = new GLCanvas(capabilities); Line l = new Line(); glcanvas.addGLEventListener(l); glcanvas.setSize(400, 400); //creating frame final JFrame frame = new JFrame ("straight Line"); //adding canvas to frame frame.getContentPane().add(glcanvas); frame.setSize(frame.getContentPane().getPreferredSize()); frame.setVisible(true); }//end of main }//end of classimport javax.media.opengl.GL2; Let us go through a program to draw a triangle using GL_LINES: import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; public class Triangle implements GLEventListener{ @Override public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glBegin (GL2.GL_LINES); //drawing the base gl.glBegin (GL2.GL_LINES); gl.glVertex3f(-0.50f, -0.50f, 0); gl.glVertex3f(0.50f, -0.50f, 0); gl.glEnd(); //drawing the right edge gl.glBegin (GL2.GL_LINES); gl.glVertex3f(0f, 0.50f, 0); gl.glVertex3f(-0.50f, -0.50f, 0); gl.glEnd(); //drawing the lft edge gl.glBegin (GL2.GL_LINES); gl.glVertex3f(0f, 0.50f, 0); gl.glVertex3f(0.50f, -0.50f, 0); gl.glEnd(); gl.glFlush(); } @Override public void dispose(GLAutoDrawable arg0) { //method body } @Override public void init(GLAutoDrawable arg0) { // method body } @Override public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) { // method body } public static void main(String[] args) { //getting the capabilities object of GL2 profile final GLProfile profile = GLProfile.get(GLProfile.GL2); GLCapabilities capabilities = new GLCapabilities(profile); // The canvas final GLCanvas glcanvas = new GLCanvas(capabilities); Triangle l = new Triangle(); glcanvas.addGLEventListener(l); glcanvas.setSize(400, 400); //creating frame final JFrame frame = new JFrame ("Triangle"); //adding canvas to frame frame.getContentPane().add(glcanvas); frame.setSize(frame.getContentPane().getPreferredSize()); frame.setVisible(true); }//end of main }//end of classimport javax.media.opengl.GL2; If you compile and execute the above program, the following output is generated. It shows a triangle drawn using GL_LINES of glBegin() method. Let us go through a program to draw a rhombus using GL_LINES: import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; public class Rhombus implements GLEventListener{ @Override public void display( GLAutoDrawable drawable ) { final GL2 gl = drawable.getGL().getGL2(); //edge1 gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0.0f,0.75f,0 ); gl.glVertex3f( -0.75f,0f,0 ); gl.glEnd(); //edge2 gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( -0.75f,0f,0 ); gl.glVertex3f( 0f,-0.75f, 0 ); gl.glEnd(); //edge3 gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0f,-0.75f, 0 ); gl.glVertex3f( 0.75f,0f, 0 ); gl.glEnd(); //edge4 gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0.75f,0f, 0 ); gl.glVertex3f( 0.0f,0.75f,0 ); gl.glEnd(); gl.glFlush(); } @Override public void dispose( GLAutoDrawable arg0 ) { //method body } @Override public void init(GLAutoDrawable arg0 ) { // method body } @Override public void reshape( GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4 ) { // method body } public static void main( String[] args ) { //getting the capabilities object of GL2 profile final GLProfile profile = GLProfile.get( GLProfile.GL2 ); GLCapabilities capabilities = new GLCapabilities( profile ); // The canvas final GLCanvas glcanvas = new GLCanvas( capabilities ); Rhombus rhombus = new Rhombus(); glcanvas.addGLEventListener( rhombus ); glcanvas.setSize( 400, 400 ); //creating frame final JFrame frame = new JFrame ( "Rhombus" ); //adding canvas to frame frame.getContentPane().add( glcanvas ); frame.setSize( frame.getContentPane().getPreferredSize() ); frame.setVisible( true ); }//end of main }//end of class If you compile and execute the above program, you get following output. It shows a rhombus generated using GL_LINES of glBegin() method. Let us go through a program to draw a house using GL_LINES: import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; public class House implements GLEventListener{ @Override public void display( GLAutoDrawable drawable ) { final GL2 gl = drawable.getGL().getGL2(); //drawing top gl.glBegin ( GL2.GL_LINES ); gl.glVertex3f( -0.3f, 0.3f, 0 ); gl.glVertex3f( 0.3f,0.3f, 0 ); gl.glEnd(); //drawing bottom gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( -0.3f,-0.3f, 0 ); gl.glVertex3f( 0.3f,-0.3f, 0 ); gl.glEnd(); //drawing the right edge gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( -0.3f,0.3f, 0 ); gl.glVertex3f( -0.3f,-0.3f, 0 ); gl.glEnd(); //drawing the left edge gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0.3f,0.3f,0 ); gl.glVertex3f( 0.3f,-0.3f,0 ); gl.glEnd(); //building roof //building lft dia gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0f,0.6f, 0 ); gl.glVertex3f( -0.3f,0.3f, 0 ); gl.glEnd(); //building rt dia gl.glBegin( GL2.GL_LINES ); gl.glVertex3f( 0f,0.6f, 0 ); gl.glVertex3f( 0.3f,0.3f, 0 ); gl.glEnd(); //building door //drawing top gl.glBegin ( GL2.GL_LINES ); gl.glVertex3f( -0.05f, 0.05f, 0 ); gl.glVertex3f( 0.05f, 0.05f, 0 ); gl.glEnd(); //drawing the left edge gl.glBegin ( GL2.GL_LINES ); gl.glVertex3f( -0.05f, 0.05f, 0 ); gl.glVertex3f( -0.05f, -0.3f, 0 ); gl.glEnd(); //drawing the right edge gl.glBegin ( GL2.GL_LINES ); gl.glVertex3f( 0.05f, 0.05f, 0 ); gl.glVertex3f( 0.05f, -0.3f, 0 ); gl.glEnd(); } @Override public void dispose( GLAutoDrawable arg0 ) { //method body } @Override public void init( GLAutoDrawable arg0 ) { // method body } @Override public void reshape( GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4 ) { // method body } public static void main( String[] args ) { //getting the capabilities object of GL2 profile final GLProfile profile = GLProfile.get( GLProfile.GL2 ); GLCapabilities capabilities = new GLCapabilities( profile ); // The canvas final GLCanvas glcanvas = new GLCanvas( capabilities ); House house = new House(); glcanvas.addGLEventListener( house ); glcanvas.setSize(400, 400); //creating frame final JFrame frame = new JFrame( "House" ); //adding canvas to frame frame.getContentPane().add( glcanvas ); frame.setSize( frame.getContentPane().getPreferredSize() ); frame.setVisible( true ); }//end of main }//end of class If you compile and execute the above program, you get the following output. It shows a house diagram generated using GL_LINES() method. Other than GL_LINES predefined string parameter, glBegin() method accepts eight parameters. You can use it to draw different shapes. These are used same as GL_LINES. The following table shows glBegin() method parameters and description: GL_LINES Creates each pair of vertices as an independent line segment. GL_LINE_STRIP Draws a connected group of line segments from the first vertex to the last. GL_LINE_LOOP Draws a connected group of line segments from the first vertex to the last, again back to the first. GL_TRIANGLES Treats each triplet of vertices as an independent triangle. GL_TRIANGLE_STRIP Draws a connected group of triangles. One triangle is defined for each vertex presented after the first two vertices. GL_TRIANGLE_FAN Draws a connected group of triangles. One triangle is defined for each vertex presented after the first two vertices. GL_QUADS Treats each group of four vertices as an independent quadrilateral. GL_QUAD_STRIP Draws a connected group of quadrilaterals. One quadrilateral is defined for each pair of vertices presented after the first pair. GL_POLYGON Draws a single, convex polygon. Vertices 1,...,n define this polygon. Let us see some examples using glBegin() parameters. Program to draw Line Strip: import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; public class LineStrip implements GLEventListener{ @Override public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glBegin (GL2.GL_LINE_STRIP); gl.glVertex3f(-0.50f,-0.75f, 0); gl.glVertex3f(0.7f,0.5f, 0); gl.glVertex3f(0.70f,-0.70f, 0); gl.glVertex3f(0f,0.5f, 0); gl.glEnd(); } @Override public void dispose(GLAutoDrawable arg0) { //method body } @Override public void init(GLAutoDrawable arg0) { // method body } @Override public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) { // method body } public static void main(String[] args) { //getting the capabilities object of GL2 profile final GLProfile profile = GLProfile.get(GLProfile.GL2); GLCapabilities capabilities = new GLCapabilities(profile); // The canvas final GLCanvas glcanvas = new GLCanvas(capabilities); LineStrip r = new LineStrip(); glcanvas.addGLEventListener(r); glcanvas.setSize(400, 400); //creating frame final JFrame frame = new JFrame ("LineStrip"); //adding canvas to frame frame.getContentPane().add(glcanvas); frame.setSize(frame.getContentPane().getPreferredSize()); frame.setVisible(true); }//end of main }//end of classimport javax.media.opengl.GL2; If you compile and execute the above code, the following output is generated: Code snippet for display() method to draw Line Loop: public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glBegin (GL2.GL_LINE_LOOP); gl.glVertex3f( -0.50f, -0.75f, 0); gl.glVertex3f(0.7f, .5f, 0); gl.glVertex3f(0.70f, -0.70f, 0); gl.glVertex3f(0f, 0.5f, 0); gl.glEnd(); } If you replace display() method of any of the basic template programs with the above code, compile, and execute it, the following output is generated: Code snippet for display() method to draw triangle using GL_TRIANGLES public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glBegin(GL2.GL_TRIANGLES); // Drawing Using Triangles gl.glVertex3f(0.5f,0.7f,0.0f); // Top gl.glVertex3f(-0.2f,-0.50f,0.0f); // Bottom Left gl.glVertex3f(0.5f,-0.5f,0.0f); //Bottom Right gl.glEnd(); } If you replace display method of any of the basic template programs with the above code, compile, and execute it, the following output is generated: Code snippet for display() method to draw Triangle Strip: public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glBegin (GL2.GL_TRIANGLE_STRIP); gl.glVertex3f(0f,0.5f,0); gl.glVertex3f(-0.50f,-0.75f,0); gl.glVertex3f(0.28f,0.06f,0); gl.glVertex3f(0.7f,0.5f,0); gl.glVertex3f(0.7f,-0.7f,0); gl.glEnd(); } If you replace display method of any of the basic template programs with the above code, compile and execute it, the following output is generated: Code snippet for display() method to draw Quadrilateral: public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glBegin(GL2.GL_QUADS); gl.glVertex3f( 0.0f,0.75f,0); gl.glVertex3f(-0.75f,0f,0); gl.glVertex3f(0f,-0.75f,0); gl.glVertex3f(0.75f,0f,0); gl.glEnd(); } If you replace display method of any of the basic template programs with the above code, compile, and execute it, the following output is generated: Code snippet for display() method to draw a polygon: public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glBegin(GL2.GL_POLYGON); gl.glVertex3f(0f,0.5f,0f); gl.glVertex3f(-0.5f,0.2f,0f); gl.glVertex3f(-0.5f,-0.2f,0f); gl.glVertex3f(0f,-0.5f,0f); gl.glVertex3f(0f,0.5f,0f); gl.glVertex3f(0.5f,0.2f,0f); gl.glVertex3f(0.5f,-0.2f,0f); gl.glVertex3f(0f,-0.5f,0f); gl.glEnd(); } If you replace display() method of any of the basic template programs with the above code, compile, and execute it, the following output is generated Print Add Notes Bookmark this page
[ { "code": null, "e": 2332, "s": 2019, "text": "This tutorial describes drawing a straight line and various shapes using straight line. OpenGL API has provided primitive methods for drawing basic graphical elements such as point, vertex, line etc. Using these methods, you can develop shapes such as triangle, polygon and circle. In both, 2D and 3D dimensions." }, { "code": null, "e": 2671, "s": 2332, "text": "To access programs which are specific to a hardware and operating system platforms, and the libraries written in other languages such as C and C++ (native applications), java uses a programming frame work called Java Native Interface (JNI). JOGL uses this interface internally to access OpenGL functions as shown in the following diagram." }, { "code": null, "e": 2950, "s": 2671, "text": "All the four methods of GLEventListener interface have the code (java JOGL methods) which internally call OpenGL functions, naming of those JOGL methods is also similar to the naming conventions of OpenGL. If the function name in OpenGL is glBegin(), it is used as gl.glBegin()." }, { "code": null, "e": 3164, "s": 2950, "text": "Whenever gl.glBegin() method of java JOGL is called, it internally invokes the glBegin() method of OpenGL. This is the reason for installing native library files on user system at the time of installation of JOGL." }, { "code": null, "e": 3185, "s": 3164, "text": "The Display() method" }, { "code": null, "e": 3320, "s": 3185, "text": "This is an important method which holds the code for developing graphics. This requires\n GLAutoDrawable interface object as parameter." }, { "code": null, "e": 3556, "s": 3320, "text": "In Display() method, initially get OpenGL context using object of GL interface (GL inherits GLBase interface which contains methods to generate all OpenGL context objects). Since this tutorial is about JOGL2 let us generate GL2 object." }, { "code": null, "e": 3611, "s": 3556, "text": "Let us go through code snippet for getting GL2 Object:" }, { "code": null, "e": 3825, "s": 3611, "text": "//Generating GL object\nGL gl=drawable.getGL();\nGL gl=drawable.getGL(); \n//Using this Getting the Gl2 Object \n//this can be written in a single line like \nfinal GL2 gl = drawable.getGL().getGL2();" }, { "code": null, "e": 3968, "s": 3825, "text": "Using the object of GL2 interface, one can access the members of GL2 interface, which in turn provide access to OpenGL [1.0... 3.0] functions." }, { "code": null, "e": 4107, "s": 3968, "text": "GL2 interface contains huge list of methods but here three main important methods are discussed namely glBegin(), glVertex(), and glEnd()." }, { "code": null, "e": 4117, "s": 4107, "text": "glBegin()" }, { "code": null, "e": 4267, "s": 4117, "text": "This method starts the process of drawing a line. It takes predefined string integer “GL_LINES” as a parameter, which is inherited from GL interface." }, { "code": null, "e": 4293, "s": 4267, "text": "glVertex3f()/glVertex2f()" }, { "code": null, "e": 4370, "s": 4293, "text": "This method creates the vertex and we have to pass coordinates as parameters" }, { "code": null, "e": 4492, "s": 4370, "text": "3f and 2f, which denote 3dimentional floating point coordinates and 2dimentional floating point coordinates respectively." }, { "code": null, "e": 4500, "s": 4492, "text": "glEnd()" }, { "code": null, "e": 4514, "s": 4500, "text": "ends the line" }, { "code": null, "e": 4561, "s": 4514, "text": "Let us go through the program to draw a line: " }, { "code": null, "e": 6136, "s": 4561, "text": "import javax.media.opengl.GL2;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCapabilities;\nimport javax.media.opengl.GLEventListener;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.awt.GLCanvas;\nimport javax.swing.JFrame;\n\npublic class Line implements GLEventListener{\n @Override\n public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n gl.glBegin (GL2.GL_LINES);//static field\n gl.glVertex3f(0.50f,-0.50f,0);\n gl.glVertex3f(-0.50f,0.50f,0);\n gl.glEnd();\n }\n @Override\n public void dispose(GLAutoDrawable arg0) {\n //method body\n }\n\n @Override\n public void init(GLAutoDrawable arg0) {\n // method body\n }\n @Override\n public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) {\n // method body\n }\n public static void main(String[] args) {\n //getting the capabilities object of GL2 profile\n final GLProfile profile = GLProfile.get(GLProfile.GL2);\n GLCapabilities capabilities = new GLCapabilities(profile);\n // The canvas \n final GLCanvas glcanvas = new GLCanvas(capabilities);\n Line l = new Line();\n glcanvas.addGLEventListener(l);\n glcanvas.setSize(400, 400);\n //creating frame\n final JFrame frame = new JFrame (\"straight Line\");\n //adding canvas to frame\n frame.getContentPane().add(glcanvas);\n frame.setSize(frame.getContentPane().getPreferredSize());\n frame.setVisible(true);\n }//end of main\n}//end of classimport javax.media.opengl.GL2;" }, { "code": null, "e": 6199, "s": 6136, "text": "Let us go through a program to draw a triangle using GL_LINES:" }, { "code": null, "e": 8157, "s": 6199, "text": "import javax.media.opengl.GL2;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCapabilities;\nimport javax.media.opengl.GLEventListener;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.awt.GLCanvas;\nimport javax.swing.JFrame;\n\npublic class Triangle implements GLEventListener{\n @Override\n public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n gl.glBegin (GL2.GL_LINES);\n //drawing the base\n gl.glBegin (GL2.GL_LINES);\n gl.glVertex3f(-0.50f, -0.50f, 0);\n gl.glVertex3f(0.50f, -0.50f, 0);\n gl.glEnd();\n //drawing the right edge\n gl.glBegin (GL2.GL_LINES);\n gl.glVertex3f(0f, 0.50f, 0);\n gl.glVertex3f(-0.50f, -0.50f, 0);\n gl.glEnd();\n //drawing the lft edge\n gl.glBegin (GL2.GL_LINES);\n gl.glVertex3f(0f, 0.50f, 0);\n gl.glVertex3f(0.50f, -0.50f, 0);\n gl.glEnd();\n gl.glFlush();\n }\n @Override\n public void dispose(GLAutoDrawable arg0) {\n //method body\n }\n @Override\n public void init(GLAutoDrawable arg0) {\n // method body\n }\n @Override\n public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,\n int arg4) {\n // method body\n }\n public static void main(String[] args) {\n //getting the capabilities object of GL2 profile\n final GLProfile profile = GLProfile.get(GLProfile.GL2);\n GLCapabilities capabilities = new GLCapabilities(profile);\n // The canvas \n final GLCanvas glcanvas = new GLCanvas(capabilities);\n Triangle l = new Triangle();\n glcanvas.addGLEventListener(l);\n glcanvas.setSize(400, 400);\n //creating frame\n final JFrame frame = new JFrame (\"Triangle\");\n //adding canvas to frame\n frame.getContentPane().add(glcanvas);\n frame.setSize(frame.getContentPane().getPreferredSize());\n frame.setVisible(true);\n }//end of main\n}//end of classimport javax.media.opengl.GL2;" }, { "code": null, "e": 8300, "s": 8157, "text": "If you compile and execute the above program, the following output is generated. It shows a triangle drawn using GL_LINES of glBegin() method." }, { "code": null, "e": 8362, "s": 8300, "text": "Let us go through a program to draw a rhombus using GL_LINES:" }, { "code": null, "e": 10386, "s": 8362, "text": "import javax.media.opengl.GL2;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCapabilities;\nimport javax.media.opengl.GLEventListener;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.awt.GLCanvas;\nimport javax.swing.JFrame;\n\npublic class Rhombus implements GLEventListener{\n @Override\n public void display( GLAutoDrawable drawable ) {\n final GL2 gl = drawable.getGL().getGL2();\n //edge1\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0.0f,0.75f,0 );\n gl.glVertex3f( -0.75f,0f,0 );\n gl.glEnd();\n //edge2\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( -0.75f,0f,0 );\n gl.glVertex3f( 0f,-0.75f, 0 );\n gl.glEnd();\n //edge3\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0f,-0.75f, 0 );\n gl.glVertex3f( 0.75f,0f, 0 );\n gl.glEnd();\n //edge4 \n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0.75f,0f, 0 );\n gl.glVertex3f( 0.0f,0.75f,0 );\n gl.glEnd();\n gl.glFlush();\n }\n @Override\n public void dispose( GLAutoDrawable arg0 ) {\n //method body\n }\n @Override\n public void init(GLAutoDrawable arg0 ) {\n // method body\n }\n @Override\n public void reshape( GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4 ) {\n // method body\n }\n public static void main( String[] args ) {\n //getting the capabilities object of GL2 profile\n final GLProfile profile = GLProfile.get( GLProfile.GL2 );\n GLCapabilities capabilities = new GLCapabilities( profile );\n // The canvas \n final GLCanvas glcanvas = new GLCanvas( capabilities );\n Rhombus rhombus = new Rhombus();\n glcanvas.addGLEventListener( rhombus );\n glcanvas.setSize( 400, 400 );\n //creating frame\n final JFrame frame = new JFrame ( \"Rhombus\" );\n //adding canvas to frame\n frame.getContentPane().add( glcanvas );\n frame.setSize( frame.getContentPane().getPreferredSize() );\n frame.setVisible( true );\n }//end of main\n}//end of class" }, { "code": null, "e": 10523, "s": 10386, "text": "If you compile and execute the above program, you get following output. It shows a rhombus generated using GL_LINES of glBegin() method." }, { "code": null, "e": 10583, "s": 10523, "text": "Let us go through a program to draw a house using GL_LINES:" }, { "code": null, "e": 13460, "s": 10583, "text": "import javax.media.opengl.GL2;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCapabilities;\nimport javax.media.opengl.GLEventListener;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.awt.GLCanvas;\nimport javax.swing.JFrame;\n\npublic class House implements GLEventListener{\n @Override\n public void display( GLAutoDrawable drawable ) {\n final GL2 gl = drawable.getGL().getGL2();\n //drawing top\n gl.glBegin ( GL2.GL_LINES );\n gl.glVertex3f( -0.3f, 0.3f, 0 );\n gl.glVertex3f( 0.3f,0.3f, 0 );\n gl.glEnd();\n //drawing bottom\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( -0.3f,-0.3f, 0 );\n gl.glVertex3f( 0.3f,-0.3f, 0 );\n gl.glEnd();\n //drawing the right edge\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( -0.3f,0.3f, 0 );\n gl.glVertex3f( -0.3f,-0.3f, 0 );\n gl.glEnd();\n //drawing the left edge\n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0.3f,0.3f,0 );\n gl.glVertex3f( 0.3f,-0.3f,0 );\n gl.glEnd();\n //building roof\n //building lft dia \n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0f,0.6f, 0 );\n gl.glVertex3f( -0.3f,0.3f, 0 );\n gl.glEnd();\n //building rt dia \n gl.glBegin( GL2.GL_LINES );\n gl.glVertex3f( 0f,0.6f, 0 );\n gl.glVertex3f( 0.3f,0.3f, 0 );\n gl.glEnd();\n //building door\n //drawing top\n gl.glBegin ( GL2.GL_LINES );\n gl.glVertex3f( -0.05f, 0.05f, 0 );\n gl.glVertex3f( 0.05f, 0.05f, 0 );\n gl.glEnd();\n //drawing the left edge\n gl.glBegin ( GL2.GL_LINES );\n gl.glVertex3f( -0.05f, 0.05f, 0 );\n gl.glVertex3f( -0.05f, -0.3f, 0 );\n gl.glEnd();\n //drawing the right edge\n gl.glBegin ( GL2.GL_LINES );\n gl.glVertex3f( 0.05f, 0.05f, 0 );\n gl.glVertex3f( 0.05f, -0.3f, 0 );\n gl.glEnd();\n }\n @Override\n public void dispose( GLAutoDrawable arg0 ) {\n //method body\n }\n @Override\n public void init( GLAutoDrawable arg0 ) {\n // method body\n }\n @Override\n public void reshape( GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4 ) {\n // method body\n }\n public static void main( String[] args ) {\n //getting the capabilities object of GL2 profile\n final GLProfile profile = GLProfile.get( GLProfile.GL2 );\n GLCapabilities capabilities = new GLCapabilities( profile );\n // The canvas \n final GLCanvas glcanvas = new GLCanvas( capabilities );\n House house = new House();\n glcanvas.addGLEventListener( house );\n glcanvas.setSize(400, 400);\n //creating frame\n final JFrame frame = new JFrame( \"House\" );\n //adding canvas to frame\n frame.getContentPane().add( glcanvas );\n frame.setSize( frame.getContentPane().getPreferredSize() );\n frame.setVisible( true );\n }//end of main\n}//end of class" }, { "code": null, "e": 13596, "s": 13460, "text": "If you compile and execute the above program, you get the following output. It shows a house diagram generated using GL_LINES() method." }, { "code": null, "e": 13762, "s": 13596, "text": "Other than GL_LINES predefined string parameter, glBegin() method accepts eight parameters. You can use it to draw different shapes. These are used same as GL_LINES." }, { "code": null, "e": 13833, "s": 13762, "text": "The following table shows glBegin() method parameters and description:" }, { "code": null, "e": 13842, "s": 13833, "text": "GL_LINES" }, { "code": null, "e": 13904, "s": 13842, "text": "Creates each pair of vertices as an independent line segment." }, { "code": null, "e": 13918, "s": 13904, "text": "GL_LINE_STRIP" }, { "code": null, "e": 13994, "s": 13918, "text": "Draws a connected group of line segments from the first vertex to the last." }, { "code": null, "e": 14007, "s": 13994, "text": "GL_LINE_LOOP" }, { "code": null, "e": 14108, "s": 14007, "text": "Draws a connected group of line segments from the first vertex to the last, again back to the first." }, { "code": null, "e": 14121, "s": 14108, "text": "GL_TRIANGLES" }, { "code": null, "e": 14181, "s": 14121, "text": "Treats each triplet of vertices as an independent triangle." }, { "code": null, "e": 14199, "s": 14181, "text": "GL_TRIANGLE_STRIP" }, { "code": null, "e": 14317, "s": 14199, "text": "Draws a connected group of triangles. One triangle is defined for each vertex presented after the first two vertices." }, { "code": null, "e": 14333, "s": 14317, "text": "GL_TRIANGLE_FAN" }, { "code": null, "e": 14451, "s": 14333, "text": "Draws a connected group of triangles. One triangle is defined for each vertex presented after the first two vertices." }, { "code": null, "e": 14460, "s": 14451, "text": "GL_QUADS" }, { "code": null, "e": 14528, "s": 14460, "text": "Treats each group of four vertices as an independent quadrilateral." }, { "code": null, "e": 14542, "s": 14528, "text": "GL_QUAD_STRIP" }, { "code": null, "e": 14672, "s": 14542, "text": "Draws a connected group of quadrilaterals. One quadrilateral is defined for each pair of vertices presented after the first pair." }, { "code": null, "e": 14683, "s": 14672, "text": "GL_POLYGON" }, { "code": null, "e": 14753, "s": 14683, "text": "Draws a single, convex polygon. Vertices 1,...,n define this polygon." }, { "code": null, "e": 14806, "s": 14753, "text": "Let us see some examples using glBegin() parameters." }, { "code": null, "e": 14834, "s": 14806, "text": "Program to draw Line Strip:" }, { "code": null, "e": 16482, "s": 14834, "text": "import javax.media.opengl.GL2;\nimport javax.media.opengl.GLAutoDrawable;\nimport javax.media.opengl.GLCapabilities;\nimport javax.media.opengl.GLEventListener;\nimport javax.media.opengl.GLProfile;\nimport javax.media.opengl.awt.GLCanvas;\nimport javax.swing.JFrame;\n\npublic class LineStrip implements GLEventListener{\n @Override\n public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n gl.glBegin (GL2.GL_LINE_STRIP);\n gl.glVertex3f(-0.50f,-0.75f, 0);\n gl.glVertex3f(0.7f,0.5f, 0);\n gl.glVertex3f(0.70f,-0.70f, 0);\n gl.glVertex3f(0f,0.5f, 0);\n gl.glEnd();\n }\n @Override\n public void dispose(GLAutoDrawable arg0) {\n //method body\n }\n @Override\n public void init(GLAutoDrawable arg0) {\n // method body\n }\n @Override\n public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) {\n // method body\n }\n public static void main(String[] args) {\n //getting the capabilities object of GL2 profile \n final GLProfile profile = GLProfile.get(GLProfile.GL2);\n GLCapabilities capabilities = new GLCapabilities(profile);\n // The canvas \n final GLCanvas glcanvas = new GLCanvas(capabilities);\n LineStrip r = new LineStrip();\n glcanvas.addGLEventListener(r);\n glcanvas.setSize(400, 400);\n //creating frame\n final JFrame frame = new JFrame (\"LineStrip\");\n //adding canvas to frame\n frame.getContentPane().add(glcanvas);\n frame.setSize(frame.getContentPane().getPreferredSize());\n frame.setVisible(true);\n }//end of main\n}//end of classimport javax.media.opengl.GL2;" }, { "code": null, "e": 16560, "s": 16482, "text": "If you compile and execute the above code, the following output is generated:" }, { "code": null, "e": 16613, "s": 16560, "text": "Code snippet for display() method to draw Line Loop:" }, { "code": null, "e": 16894, "s": 16613, "text": "public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n gl.glBegin (GL2.GL_LINE_LOOP);\n gl.glVertex3f( -0.50f, -0.75f, 0);\n gl.glVertex3f(0.7f, .5f, 0);\n gl.glVertex3f(0.70f, -0.70f, 0);\n gl.glVertex3f(0f, 0.5f, 0);\n gl.glEnd();\n}" }, { "code": null, "e": 17045, "s": 16894, "text": "If you replace display() method of any of the basic template programs with the above code, compile, and execute it, the following output is generated:" }, { "code": null, "e": 17115, "s": 17045, "text": "Code snippet for display() method to draw triangle using GL_TRIANGLES" }, { "code": null, "e": 17445, "s": 17115, "text": "public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n gl.glBegin(GL2.GL_TRIANGLES); // Drawing Using Triangles\n gl.glVertex3f(0.5f,0.7f,0.0f); // Top\n gl.glVertex3f(-0.2f,-0.50f,0.0f); // Bottom Left\n gl.glVertex3f(0.5f,-0.5f,0.0f); //Bottom Right\n gl.glEnd(); \n}" }, { "code": null, "e": 17594, "s": 17445, "text": "If you replace display method of any of the basic template programs with the above code, compile, and execute it, the following output is generated:" }, { "code": null, "e": 17652, "s": 17594, "text": "Code snippet for display() method to draw Triangle Strip:" }, { "code": null, "e": 17963, "s": 17652, "text": "public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n gl.glBegin (GL2.GL_TRIANGLE_STRIP);\n gl.glVertex3f(0f,0.5f,0);\n gl.glVertex3f(-0.50f,-0.75f,0);\n gl.glVertex3f(0.28f,0.06f,0);\n gl.glVertex3f(0.7f,0.5f,0);\n gl.glVertex3f(0.7f,-0.7f,0);\n gl.glEnd(); \n}" }, { "code": null, "e": 18111, "s": 17963, "text": "If you replace display method of any of the basic template programs with the above code, compile and execute it, the following output is generated:" }, { "code": null, "e": 18168, "s": 18111, "text": "Code snippet for display() method to draw Quadrilateral:" }, { "code": null, "e": 18434, "s": 18168, "text": "public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n gl.glBegin(GL2.GL_QUADS);\n gl.glVertex3f( 0.0f,0.75f,0);\n gl.glVertex3f(-0.75f,0f,0);\n gl.glVertex3f(0f,-0.75f,0);\n gl.glVertex3f(0.75f,0f,0);\n gl.glEnd(); \n}" }, { "code": null, "e": 18583, "s": 18434, "text": "If you replace display method of any of the basic template programs with the above code, compile, and execute it, the following output is generated:" }, { "code": null, "e": 18636, "s": 18583, "text": "Code snippet for display() method to draw a polygon:" }, { "code": null, "e": 19030, "s": 18636, "text": "public void display(GLAutoDrawable drawable) {\n final GL2 gl = drawable.getGL().getGL2();\n gl.glBegin(GL2.GL_POLYGON);\n gl.glVertex3f(0f,0.5f,0f);\n gl.glVertex3f(-0.5f,0.2f,0f);\n gl.glVertex3f(-0.5f,-0.2f,0f);\n gl.glVertex3f(0f,-0.5f,0f);\n gl.glVertex3f(0f,0.5f,0f);\n gl.glVertex3f(0.5f,0.2f,0f);\n gl.glVertex3f(0.5f,-0.2f,0f);\n gl.glVertex3f(0f,-0.5f,0f);\n gl.glEnd();\n}" }, { "code": null, "e": 19180, "s": 19030, "text": "If you replace display() method of any of the basic template programs with the above code, compile, and execute it, the following output is generated" }, { "code": null, "e": 19187, "s": 19180, "text": " Print" }, { "code": null, "e": 19198, "s": 19187, "text": " Add Notes" } ]
Creating a simple statistical learning model from scratch: emphasizing prediction in regression | by Alex daSilva | Towards Data Science
Learning about statistical/machine learning can be intimidating, especially if you’re like me and coming from another field (eg., social sciences, life sciences, business, etc). There are hundreds of complex models to choose from and numerous schemes to validate your data. Here, we’re going to take a closer look at a simple model for prediction you probably came across if you completed a statistics course, regression. Why so simple? Regression may not be as sexy as some other methods, but gaining a deeper understanding of the basics is undoubtedly important for moving on to more complex models. When learning about regression, the emphasis probably wasn’t on prediction (or where predicted values come from) but rather on jumping to the output, checking coefficients, and praying that p-values associated with said coefficients fell below .05. Regression need not be just a tool for inferential statistics. As I touched on, if you’ve ran a regression analysis you’ve already completed a computation that involved calculating predicted values. Below, we’ll unpack how prediction unfolds in two different contexts. In the first context, we’ll be working with data where the y value is present — a common situation where an analyst is making inferences about the relationship between the outcome and predictor variables. In the second context, we’ll be predicting new y values on left out data. We’ll do this all without the help of functions or libraries to illustrate how linear regression can be used as a basic predictive tool with the classic iris data set. The first thing to do is to load the iris data set: data("iris") gridExtra::grid.table(head(iris, 10)) Before we get into our own calculations, let’s begin by looking at how we can fit a linear model and use that to predict some new data in base R with the “lm” function. We’ll attempt to predict Sepal Length from the other 3 numeric variables in the iris data set. To begin, we’ll grab some training data (70/30 split) and fit our model. iris_sub <- iris[,c(1:4)] cut <- .7*nrow(iris) iris_train <- iris_sub[1:cut, ] fit <- lm(Sepal.Length ~ ., data = iris_train ) Now, we’ll create some test data and combine that with our model from the training data to create some predictions. iris_test <- iris_sub[(cut+1):nrow(iris_sub), ] preds <- predict(fit, iris_test[, -1]) plot(preds, iris_test[, 1], main = paste('Cor =',round(cor(iris_test[, 1], preds ),2)), xlab = "Observed Values", ylab = "Predicted Values") The predictions look great! If someone accidentally deleted a bunch of information regarding iris’ sepal lengths in a flower database, we can safely say we’d do a sound job recovering that information. Of course, our concern here is to determine what “predict” is doing to come up with those values. We’ll take a look at that in a second; but first, we’ll examine prediction in the context of linear regression models in a more general sense. We’ll start by examining how new values can be predicted on a set of data where both the y values and predictor variables are present (using the iris training data we created as an example). First, we need to separate our x values from our y values. We’ll pad the x matrix with a column of ones to represent the intercept. x <- iris_train[, -1] x <- cbind(Intercept = rep(1, nrow(x)), x) x <- as.matrix(x) y <- as.matrix(iris_train[, 1]) Now, we need to transpose x and multiply it by itself (X’X). This results in a sum of squares/cross-product matrix, SSCP. It turns out with a few manipulations, this matrix can depict the variance/co-variance, correlation, or cosine association between a set of variables. If you’re interested in hearing a bit more about that, check out my post here. XtX <-t(x) %*% x XtX ## Intercept Sepal.Width Petal.Length Petal.Width ## Intercept 105.0 324.80 314.50 89.10 ## Sepal.Width 324.8 1027.66 930.13 259.79 ## Petal.Length 314.5 930.13 1188.37 364.22 ## Petal.Width 89.1 259.79 364.22 115.75 Our calculations match the output from the actual cross-product function. crossprod(x) ## Intercept Sepal.Width Petal.Length Petal.Width ## Intercept 105.0 324.80 314.50 89.10 ## Sepal.Width 324.8 1027.66 930.13 259.79 ## Petal.Length 314.5 930.13 1188.37 364.22 ## Petal.Width 89.1 259.79 364.22 115.75 Next, we are going to calculate a projection matrix or hat matrix (on it’s diagonal are observation leverages). h <- x %*% solve(XtX) %*% t(x) head(data.frame(our_leverages = diag(h), model_leverages = hatvalues(fit)), 5) ## our_leverages model_leverages ## 1 0.02139771 0.02139771 ## 2 0.02869219 0.02869219 ## 3 0.02416413 0.02416413 ## 4 0.02373262 0.02373262 ## 5 0.02397262 0.02397262 all.equal(diag(h), hatvalues(fit)) #matches output from hatvalues function ## [1] TRUE This will allow us to map y into predicted y values. our_fitted_vals <- h %*% y head(data.frame(our_fitted_vals, model_fitted_vals = as.numeric(fit$fitted.values)), 5) ## our_fitted_vals model_fitted_vals ## 1 5.035358 5.035358 ## 2 4.738074 4.738074 ## 3 4.786883 4.786883 ## 4 4.867636 4.867636 ## 5 5.094815 5.094815 all.equal(as.numeric(our_fitted_vals), as.numeric(fit$fitted.values)) #our calculated predicted values match the values accessed from the model ## [1] TRUE So, if we have access to the y values, we can combine them with a projection matrix to obtain predictions. That’s all well and good, but how can we predict new values of y in our test data using our training data? To do that, we need to calculate beta coefficients for our training data that contain information about the relationship between our y and x values. XtY <- t(x) %*% y betas <- solve(XtX) %*% XtY We can ensure that out calculated beta values are indeed correct by comparing them to the values produce by “lm”. data.frame(model_betas = summary(fit)$coefficients[, 1], our_betas = betas) # our calculated betas match betas from lm ## model_betas our_betas ## (Intercept) 2.0952291 2.0952291 ## Sepal.Width 0.5945672 0.5945672 ## Petal.Length 0.7010446 0.7010446 ## Petal.Width -0.6115940 -0.6115940 We can add the model intercept through to our test data and multiply that by the beta coefficients (intercept excluded) to find our predicted values. our_preds <- betas[1] + as.matrix(iris_test[,-1]) %*% betas[-1] head(data.frame(model_preds = as.numeric(preds), our_preds = as.numeric(our_preds)), 5) ## model_preds our_preds ## 1 7.221478 7.221478 ## 2 5.696638 5.696638 ## 3 7.135186 7.135186 ## 4 6.546837 6.546837 ## 5 6.983058 6.983058 all.equal(as.numeric(preds), as.numeric(our_preds)) #our predicted values for our test data match that of the predict function ## [1] TRUE What we’ve learned so far can easily be extended to a kfold cross validation scheme. The function below will create folds and return a list containing the original data set with the folds as a new column. In addition, a list containing the fold indices themselves will also be returned. Let’s create the folds and make sure they make sense. And fit our model using 5 fold cross-validation: We can extract and examine the predictive summary statistics. Finally, we can pass our fold indices to the popular predictive modeling package, caret, and confirm our calculations. Averaging across folds, our statistics match caret’s output. In sum, we took a closer look at how prediction functions in the context of regression. We were ultimately able to apply the computations we covered to make predictions on left out data. Hopefully this tutorial provided a bit of clarity into what happens when you’re pressing ctrl+enter on a line of code containing the “lm” function.
[ { "code": null, "e": 774, "s": 172, "text": "Learning about statistical/machine learning can be intimidating, especially if you’re like me and coming from another field (eg., social sciences, life sciences, business, etc). There are hundreds of complex models to choose from and numerous schemes to validate your data. Here, we’re going to take a closer look at a simple model for prediction you probably came across if you completed a statistics course, regression. Why so simple? Regression may not be as sexy as some other methods, but gaining a deeper understanding of the basics is undoubtedly important for moving on to more complex models." }, { "code": null, "e": 1222, "s": 774, "text": "When learning about regression, the emphasis probably wasn’t on prediction (or where predicted values come from) but rather on jumping to the output, checking coefficients, and praying that p-values associated with said coefficients fell below .05. Regression need not be just a tool for inferential statistics. As I touched on, if you’ve ran a regression analysis you’ve already completed a computation that involved calculating predicted values." }, { "code": null, "e": 1739, "s": 1222, "text": "Below, we’ll unpack how prediction unfolds in two different contexts. In the first context, we’ll be working with data where the y value is present — a common situation where an analyst is making inferences about the relationship between the outcome and predictor variables. In the second context, we’ll be predicting new y values on left out data. We’ll do this all without the help of functions or libraries to illustrate how linear regression can be used as a basic predictive tool with the classic iris data set." }, { "code": null, "e": 1791, "s": 1739, "text": "The first thing to do is to load the iris data set:" }, { "code": null, "e": 1844, "s": 1791, "text": "data(\"iris\")\n\ngridExtra::grid.table(head(iris, 10))\n" }, { "code": null, "e": 2181, "s": 1844, "text": "Before we get into our own calculations, let’s begin by looking at how we can fit a linear model and use that to predict some new data in base R with the “lm” function. We’ll attempt to predict Sepal Length from the other 3 numeric variables in the iris data set. To begin, we’ll grab some training data (70/30 split) and fit our model." }, { "code": null, "e": 2312, "s": 2181, "text": "iris_sub <- iris[,c(1:4)]\n\ncut <- .7*nrow(iris)\n\niris_train <- iris_sub[1:cut, ]\n\nfit <- lm(Sepal.Length ~ ., data = iris_train )\n" }, { "code": null, "e": 2428, "s": 2312, "text": "Now, we’ll create some test data and combine that with our model from the training data to create some predictions." }, { "code": null, "e": 2659, "s": 2428, "text": "iris_test <- iris_sub[(cut+1):nrow(iris_sub), ]\n\npreds <- predict(fit, iris_test[, -1])\n\nplot(preds, iris_test[, 1], main = paste('Cor =',round(cor(iris_test[, 1], preds ),2)), xlab = \"Observed Values\", ylab = \"Predicted Values\")\n" }, { "code": null, "e": 2861, "s": 2659, "text": "The predictions look great! If someone accidentally deleted a bunch of information regarding iris’ sepal lengths in a flower database, we can safely say we’d do a sound job recovering that information." }, { "code": null, "e": 3102, "s": 2861, "text": "Of course, our concern here is to determine what “predict” is doing to come up with those values. We’ll take a look at that in a second; but first, we’ll examine prediction in the context of linear regression models in a more general sense." }, { "code": null, "e": 3425, "s": 3102, "text": "We’ll start by examining how new values can be predicted on a set of data where both the y values and predictor variables are present (using the iris training data we created as an example). First, we need to separate our x values from our y values. We’ll pad the x matrix with a column of ones to represent the intercept." }, { "code": null, "e": 3544, "s": 3425, "text": "x <- iris_train[, -1]\n\nx <- cbind(Intercept = rep(1, nrow(x)), x)\n\nx <- as.matrix(x)\n\ny <- as.matrix(iris_train[, 1])\n" }, { "code": null, "e": 3896, "s": 3544, "text": "Now, we need to transpose x and multiply it by itself (X’X). This results in a sum of squares/cross-product matrix, SSCP. It turns out with a few manipulations, this matrix can depict the variance/co-variance, correlation, or cosine association between a set of variables. If you’re interested in hearing a bit more about that, check out my post here." }, { "code": null, "e": 3919, "s": 3896, "text": "XtX <-t(x) %*% x\n\nXtX\n" }, { "code": null, "e": 4235, "s": 3919, "text": "## Intercept Sepal.Width Petal.Length Petal.Width\n## Intercept 105.0 324.80 314.50 89.10\n## Sepal.Width 324.8 1027.66 930.13 259.79\n## Petal.Length 314.5 930.13 1188.37 364.22\n## Petal.Width 89.1 259.79 364.22 115.75\n" }, { "code": null, "e": 4309, "s": 4235, "text": "Our calculations match the output from the actual cross-product function." }, { "code": null, "e": 4324, "s": 4309, "text": "crossprod(x) \n" }, { "code": null, "e": 4640, "s": 4324, "text": "## Intercept Sepal.Width Petal.Length Petal.Width\n## Intercept 105.0 324.80 314.50 89.10\n## Sepal.Width 324.8 1027.66 930.13 259.79\n## Petal.Length 314.5 930.13 1188.37 364.22\n## Petal.Width 89.1 259.79 364.22 115.75\n" }, { "code": null, "e": 4752, "s": 4640, "text": "Next, we are going to calculate a projection matrix or hat matrix (on it’s diagonal are observation leverages)." }, { "code": null, "e": 4864, "s": 4752, "text": "h <- x %*% solve(XtX) %*% t(x)\n\nhead(data.frame(our_leverages = diag(h), model_leverages = hatvalues(fit)), 5)\n" }, { "code": null, "e": 5075, "s": 4864, "text": "## our_leverages model_leverages\n## 1 0.02139771 0.02139771\n## 2 0.02869219 0.02869219\n## 3 0.02416413 0.02416413\n## 4 0.02373262 0.02373262\n## 5 0.02397262 0.02397262\n" }, { "code": null, "e": 5151, "s": 5075, "text": "all.equal(diag(h), hatvalues(fit)) #matches output from hatvalues function\n" }, { "code": null, "e": 5164, "s": 5151, "text": "## [1] TRUE\n" }, { "code": null, "e": 5217, "s": 5164, "text": "This will allow us to map y into predicted y values." }, { "code": null, "e": 5334, "s": 5217, "text": "our_fitted_vals <- h %*% y\n\nhead(data.frame(our_fitted_vals, model_fitted_vals = as.numeric(fit$fitted.values)), 5)\n" }, { "code": null, "e": 5569, "s": 5334, "text": "## our_fitted_vals model_fitted_vals\n## 1 5.035358 5.035358\n## 2 4.738074 4.738074\n## 3 4.786883 4.786883\n## 4 4.867636 4.867636\n## 5 5.094815 5.094815\n" }, { "code": null, "e": 5714, "s": 5569, "text": "all.equal(as.numeric(our_fitted_vals), as.numeric(fit$fitted.values)) #our calculated predicted values match the values accessed from the model\n" }, { "code": null, "e": 5727, "s": 5714, "text": "## [1] TRUE\n" }, { "code": null, "e": 6090, "s": 5727, "text": "So, if we have access to the y values, we can combine them with a projection matrix to obtain predictions. That’s all well and good, but how can we predict new values of y in our test data using our training data? To do that, we need to calculate beta coefficients for our training data that contain information about the relationship between our y and x values." }, { "code": null, "e": 6138, "s": 6090, "text": "XtY <- t(x) %*% y\n\nbetas <- solve(XtX) %*% XtY\n" }, { "code": null, "e": 6252, "s": 6138, "text": "We can ensure that out calculated beta values are indeed correct by comparing them to the values produce by “lm”." }, { "code": null, "e": 6372, "s": 6252, "text": "data.frame(model_betas = summary(fit)$coefficients[, 1], our_betas = betas) # our calculated betas match betas from lm\n" }, { "code": null, "e": 6568, "s": 6372, "text": "## model_betas our_betas\n## (Intercept) 2.0952291 2.0952291\n## Sepal.Width 0.5945672 0.5945672\n## Petal.Length 0.7010446 0.7010446\n## Petal.Width -0.6115940 -0.6115940\n" }, { "code": null, "e": 6718, "s": 6568, "text": "We can add the model intercept through to our test data and multiply that by the beta coefficients (intercept excluded) to find our predicted values." }, { "code": null, "e": 6872, "s": 6718, "text": "our_preds <- betas[1] + as.matrix(iris_test[,-1]) %*% betas[-1]\n\nhead(data.frame(model_preds = as.numeric(preds), our_preds = as.numeric(our_preds)), 5)\n" }, { "code": null, "e": 7035, "s": 6872, "text": "## model_preds our_preds\n## 1 7.221478 7.221478\n## 2 5.696638 5.696638\n## 3 7.135186 7.135186\n## 4 6.546837 6.546837\n## 5 6.983058 6.983058\n" }, { "code": null, "e": 7164, "s": 7035, "text": "all.equal(as.numeric(preds), as.numeric(our_preds)) #our predicted values for our test data match that of the predict function \n" }, { "code": null, "e": 7177, "s": 7164, "text": "## [1] TRUE\n" }, { "code": null, "e": 7464, "s": 7177, "text": "What we’ve learned so far can easily be extended to a kfold cross validation scheme. The function below will create folds and return a list containing the original data set with the folds as a new column. In addition, a list containing the fold indices themselves will also be returned." }, { "code": null, "e": 7518, "s": 7464, "text": "Let’s create the folds and make sure they make sense." }, { "code": null, "e": 7567, "s": 7518, "text": "And fit our model using 5 fold cross-validation:" }, { "code": null, "e": 7629, "s": 7567, "text": "We can extract and examine the predictive summary statistics." }, { "code": null, "e": 7748, "s": 7629, "text": "Finally, we can pass our fold indices to the popular predictive modeling package, caret, and confirm our calculations." }, { "code": null, "e": 7809, "s": 7748, "text": "Averaging across folds, our statistics match caret’s output." } ]
C# | Get the number of elements in the SortedSet - GeeksforGeeks
01 Feb, 2019 SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.Count Property is used to get the number of elements in the SortedSet. Properties: In C#, SortedSet class can be used to store, remove or view elements. It maintains ascending order and does not store duplicate elements. It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order. Syntax: mySortedSet.Count Here, mySortedSet is a SortedSet. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to get the number of// elements in the SortedSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedSet of integers SortedSet<int> mySortedSet = new SortedSet<int>(); // adding elements in mySortedSet mySortedSet.Add(1); mySortedSet.Add(2); mySortedSet.Add(3); mySortedSet.Add(4); mySortedSet.Add(5); // Displaying the number of elements in // the SortedSet using "Count" function Console.WriteLine("The number of elements in mySortedSet are: " + mySortedSet.Count); }} The number of elements in mySortedSet are: 5 Example 2: // C# code to get the number of// elements in the SortedSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedSet of strings SortedSet<string> mySortedSet = new SortedSet<string>(); // adding elements in mySortedSet mySortedSet.Add("Hey"); mySortedSet.Add("GeeksforGeeks"); mySortedSet.Add("and"); mySortedSet.Add("Geeks Classes"); // Displaying the number of elements in // the SortedSet using "Count" function Console.WriteLine("The number of elements in mySortedSet are: " + mySortedSet.Count); }} The number of elements in mySortedSet are: 4 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1.count?view=netcore-2.1 CSharp-Generic-Namespace CSharp-Generic-SortedSet C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | Inheritance Partial Classes in C# C# | List Class Lambda Expressions in C# Difference between Hashtable and Dictionary in C# Convert String to Character Array in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24521, "s": 24302, "text": "SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.Count Property is used to get the number of elements in the SortedSet." }, { "code": null, "e": 24533, "s": 24521, "text": "Properties:" }, { "code": null, "e": 24603, "s": 24533, "text": "In C#, SortedSet class can be used to store, remove or view elements." }, { "code": null, "e": 24671, "s": 24603, "text": "It maintains ascending order and does not store duplicate elements." }, { "code": null, "e": 24777, "s": 24671, "text": "It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order." }, { "code": null, "e": 24785, "s": 24777, "text": "Syntax:" }, { "code": null, "e": 24804, "s": 24785, "text": "mySortedSet.Count\n" }, { "code": null, "e": 24838, "s": 24804, "text": "Here, mySortedSet is a SortedSet." }, { "code": null, "e": 24918, "s": 24838, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 24929, "s": 24918, "text": "Example 1:" }, { "code": "// C# code to get the number of// elements in the SortedSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedSet of integers SortedSet<int> mySortedSet = new SortedSet<int>(); // adding elements in mySortedSet mySortedSet.Add(1); mySortedSet.Add(2); mySortedSet.Add(3); mySortedSet.Add(4); mySortedSet.Add(5); // Displaying the number of elements in // the SortedSet using \"Count\" function Console.WriteLine(\"The number of elements in mySortedSet are: \" + mySortedSet.Count); }}", "e": 25628, "s": 24929, "text": null }, { "code": null, "e": 25674, "s": 25628, "text": "The number of elements in mySortedSet are: 5\n" }, { "code": null, "e": 25685, "s": 25674, "text": "Example 2:" }, { "code": "// C# code to get the number of// elements in the SortedSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedSet of strings SortedSet<string> mySortedSet = new SortedSet<string>(); // adding elements in mySortedSet mySortedSet.Add(\"Hey\"); mySortedSet.Add(\"GeeksforGeeks\"); mySortedSet.Add(\"and\"); mySortedSet.Add(\"Geeks Classes\"); // Displaying the number of elements in // the SortedSet using \"Count\" function Console.WriteLine(\"The number of elements in mySortedSet are: \" + mySortedSet.Count); }}", "e": 26399, "s": 25685, "text": null }, { "code": null, "e": 26445, "s": 26399, "text": "The number of elements in mySortedSet are: 4\n" }, { "code": null, "e": 26456, "s": 26445, "text": "Reference:" }, { "code": null, "e": 26562, "s": 26456, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1.count?view=netcore-2.1" }, { "code": null, "e": 26587, "s": 26562, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 26612, "s": 26587, "text": "CSharp-Generic-SortedSet" }, { "code": null, "e": 26615, "s": 26612, "text": "C#" }, { "code": null, "e": 26713, "s": 26615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26722, "s": 26713, "text": "Comments" }, { "code": null, "e": 26735, "s": 26722, "text": "Old Comments" }, { "code": null, "e": 26758, "s": 26735, "text": "Extension Method in C#" }, { "code": null, "e": 26786, "s": 26758, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26826, "s": 26786, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26869, "s": 26826, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26886, "s": 26869, "text": "C# | Inheritance" }, { "code": null, "e": 26908, "s": 26886, "text": "Partial Classes in C#" }, { "code": null, "e": 26924, "s": 26908, "text": "C# | List Class" }, { "code": null, "e": 26949, "s": 26924, "text": "Lambda Expressions in C#" }, { "code": null, "e": 26999, "s": 26949, "text": "Difference between Hashtable and Dictionary in C#" } ]
Python math library | exp() method - GeeksforGeeks
06 Jan, 2019 Python has math library and has many functions regarding it. One such function is exp(). This method is used to calculate the power of e i.e. e^y or we can say exponential of y. The value of e is approximately equal to 2.71828..... Syntax : math.exp(y) Parameters :y [Required] – It is any valid python number either positive or negative.Note that if y has value other than number then its return error. Returns: Returns floating point number by calculating e^y. Code # 1: # Python3 code to demonstrate # the working of exp() import math # initializing the value test_int = 4test_neg_int = -3test_float = 0.00 # checking exp() values # with different numbersprint (math.exp(test_int))print (math.exp(test_neg_int))print (math.exp(test_float)) 54.598150033144236 0.049787068367863944 1.0 Code #2: # Python3 code to demonstrate # the working of exp() import math # checking exp() values # with inbuilt numbersprint (math.exp(math.pi))print (math.exp(math.e)) 23.140692632779267 15.154262241479262 Code #3: TypeError # Python3 code to demonstrate # the working of exp() import math # checking for stringprint (math.exp("25")) Output: Traceback (most recent call last): File "/home/c7ae4f1bef0ed8c7756b3f55e7d2ce81.py", line 6, in print (math.exp("25")) TypeError: a float is required Python math-library Python math-library-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24104, "s": 24076, "text": "\n06 Jan, 2019" }, { "code": null, "e": 24336, "s": 24104, "text": "Python has math library and has many functions regarding it. One such function is exp(). This method is used to calculate the power of e i.e. e^y or we can say exponential of y. The value of e is approximately equal to 2.71828....." }, { "code": null, "e": 24357, "s": 24336, "text": "Syntax : math.exp(y)" }, { "code": null, "e": 24508, "s": 24357, "text": "Parameters :y [Required] – It is any valid python number either positive or negative.Note that if y has value other than number then its return error." }, { "code": null, "e": 24567, "s": 24508, "text": "Returns: Returns floating point number by calculating e^y." }, { "code": null, "e": 24577, "s": 24567, "text": "Code # 1:" }, { "code": "# Python3 code to demonstrate # the working of exp() import math # initializing the value test_int = 4test_neg_int = -3test_float = 0.00 # checking exp() values # with different numbersprint (math.exp(test_int))print (math.exp(test_neg_int))print (math.exp(test_float))", "e": 24850, "s": 24577, "text": null }, { "code": null, "e": 24895, "s": 24850, "text": "54.598150033144236\n0.049787068367863944\n1.0\n" }, { "code": null, "e": 24906, "s": 24897, "text": "Code #2:" }, { "code": "# Python3 code to demonstrate # the working of exp() import math # checking exp() values # with inbuilt numbersprint (math.exp(math.pi))print (math.exp(math.e))", "e": 25069, "s": 24906, "text": null }, { "code": null, "e": 25108, "s": 25069, "text": "23.140692632779267\n15.154262241479262\n" }, { "code": null, "e": 25128, "s": 25108, "text": " Code #3: TypeError" }, { "code": "# Python3 code to demonstrate # the working of exp() import math # checking for stringprint (math.exp(\"25\"))", "e": 25239, "s": 25128, "text": null }, { "code": null, "e": 25247, "s": 25239, "text": "Output:" }, { "code": null, "e": 25405, "s": 25247, "text": "Traceback (most recent call last):\n File \"/home/c7ae4f1bef0ed8c7756b3f55e7d2ce81.py\", line 6, in \n print (math.exp(\"25\"))\nTypeError: a float is required\n" }, { "code": null, "e": 25425, "s": 25405, "text": "Python math-library" }, { "code": null, "e": 25455, "s": 25425, "text": "Python math-library-functions" }, { "code": null, "e": 25462, "s": 25455, "text": "Python" }, { "code": null, "e": 25560, "s": 25462, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25578, "s": 25560, "text": "Python Dictionary" }, { "code": null, "e": 25613, "s": 25578, "text": "Read a file line by line in Python" }, { "code": null, "e": 25635, "s": 25613, "text": "Enumerate() in Python" }, { "code": null, "e": 25667, "s": 25635, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25697, "s": 25667, "text": "Iterate over a list in Python" }, { "code": null, "e": 25739, "s": 25697, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25765, "s": 25739, "text": "Python String | replace()" }, { "code": null, "e": 25802, "s": 25765, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25845, "s": 25802, "text": "Python program to convert a list to string" } ]
How to Build a Simple Machine Learning Web App in Python | by Chanin Nantasenamat | Towards Data Science
In this article, I will show you how to build a simple machine learning powered data science web app in Python using the streamlit library in less than 50 lines of code. (Quick Note: You might also want to check out Part 1 of this streamlit tutorial series on building your first web app. Shoutout to Simon for suggesting the mention of Part 1.) The data science life cycle is essentially comprised of data collection, data cleaning, exploratory data analysis, model building and model deployment. For more information, please check out the excellent video by Ken Jee on Different Data Science Roles Explained (by a Data Scientist). A summary infographic of this life cycle is shown below: As a Data Scientist or Machine Learning Engineer, it is extremely important to be able to deploy our data science project as this would help to complete the data science life cycle. Traditional deployment of machine learning models with established framework such as Django or Flask may be a daunting and/or time-consuming task. This article is based on a video that I made on the same topic on the Data Professor YouTube channel (How to Build a Simple Machine Learning Web App in Python) in which you can watch it alongside reading this article. Today, we will be building a simple machine learning-powered web app for predicting the class label of Iris flowers as being setosa, versicolor and virginica. Perhaps, you have seen too many use of the infamous Iris dataset in tutorials and machine learning examples. Please bear with me on this one as the Iris dataset is merely used as a sort of “lorem ipsum” (typically used as fillers words in writing contents). I assure you that I will use other example datasets in future parts of this tutorial series. This will require the use of three Python libraries namely streamlit, pandas and scikit-learn. Let’s take a look at the conceptual flow of the app that will include two major components: (1) the front-end and (2) back-end. In the front-end, the sidebar found on the left will accept input parameters pertaining to features (i.e. petal length, petal width, sepal length and sepal width) of Iris flowers. These features will be relayed to the back-end where the trained model will predict the class labels as a function of the input parameters. Prediction results are sent back to the front-end for display. In the back-end, the user input parameters will be saved into a dataframe that will be used as test data. In the meantime, a classification model will be built using the random forest algorithm from the scikit-learn library. Finally, the model will be applied to make predictions on the user input data and return the predicted class labels as being one of three flower type: setosa, versicolor or virginica. Additionally, the prediction probability will also be provided that will allow us to discern the relative confidence in the predicted class labels. In this tutorial, we will be using three Python libraries namely streamlit, pandas and scikit-learn. You can install these libraries via the pip install command. To install streamlit: pip install streamlit To install pandas: pip install pandas To install scikit-learn: pip install -U scikit-learn Okay, so let’s take a look under the hood and we will see that the app that we are going to be building today is less than 50 lines of code (i.e. or 48 to be exact). And if we delete blank lines and comments (i.e. accounting for 12 lines) we can bring the number down to 36 lines. Okay, so let’s decode and see what each line (or code block) is doing. Lines 1–4Import streamlit and pandas libraries with aliases of st and pd, respectively. Specifically, import the datasets package from the scikit-learn library (sklearn) where we will subsequently make use of the loader function to load the Iris dataset (line 30). Finally, we will specifically impor the RandomForestClassifier() function from the sklearn.ensemble package. Line 11We will be adding the header text of the sidebar by using st.sidebar.header() function. Notice that the use of sidebar in between st and header (i.e. thus st.sidebar.header() function) tells streamlit that you want the header to be placed in the sidebar panel. Lines 13–23Here we will be creating a customized function called user_input_features() that will essentially consolidate the user input parameters (i.e. the 4 flower characteristics that can accept the user specified value by means of the slider bar) and return the results in the form of a dataframe. It is worthy to note that each input parameter will accept user specified values by means of the slider button as in st.sidebar.slider(‘Sepal length’, 4.3, 7.9, 5.4) for the Sepal length. The first of the four input arguments correspond to the label text that will be specified above the slider button which in our case is ‘Sepal length’ while the next 2 values corresponds to the minimum and maximum value of the slider bar. Finally, the last input argument represents the default value that will be selected upon loading the web app, which is set to 5.4. Line 25As previously discussed above, the consolidated user input parameter information in the form of a dataframe will be assigned to the df variable. Lines 30–38This code block pertains to the actual model building phase.* Line 30 — Loads in the Iris dataset from the sklearn.datasets package and assign it to the iris variable.* Line 31 — Creates the X variable containing the 4 flower features (i.e. sepal length, sepal width, petal length and petal width) provided in iris.data.* Line 32 — Creates the Y variable pertaining to the Iris class label provided in iris.target.* Line 34 — Assign the random forest classifier, particularly the RandomForestClassifier() function, to the clf variable.* Line 35 — Train the model via the clf.fit() function by using X and Y variables as input arguments. This essentially means that a classification model will be built by training it using the 4 flower features (X) and class label (Y). Lines 6–9Uses the st.write() function to print out text, which in our case we are using it to print out the title of this app in markdown format (making use of the # symbol to signify header text (line 7) whereas normal descriptive text of the app is provided in the subsequent line (line 8). Lines 27–28This first section will be given the subheader text (assigned by using the st.subheader function) of ‘User Input parameters’. In the subsequent line we will be displaying the contents of the df dataframe via the use of the st.write() function. Lines 40–41In this second section of the main panel, the class labels (i.e. setosa, versicolor and virginica) and their corresponding index numbers (i.e. 0, 1 and 2) are printed out. Lines 43–44Predicted class labels are displayed in this third section of the main panel. It should be noted here that the contents of the prediction variable (line 45) is the predicted class index number and for the class label (i.e. setosa, versicolor and virginica) to be displayed we will need to use the prediction variable as an argument inside the bracket of iris.target_names[prediction]. Lines 47–48In this fourth and last section of the main panel, the prediction probability are displayed. This value allow us to discern the relative confidence for the predicted class labels (i.e. the higher the probability values the higher confidence we have in that prediction). So the code of the web app is saved into the iris-ml-app.py file and now we are ready to run it. You can run the app by typing the following command into your command prompt (terminal window): streamlit run iris-ml-app.py Afterwards, you should see the following message: > streamlit run iris-ml-app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501 A few seconds later, an internet browser window should pop-up and directs you to the created web app by taking you to http://localhost:8501 as shown below. Now, it’s time to give yourself a pat on the back as you have now created a machine learning-powered web app. It’s now time to showcase this in your data science portfolio and website (i.e. you might want to customize the web app by using a dataset that interests you). Make sure to check out these videos on pointers and advice (Building your Data Science Portfolio with GitHub and How to Build a Data Science Portfolio Website with Hugo & Github Pages [feat. Data Professor]). I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page). www.youtube.com ✅ YouTube: http://youtube.com/dataprofessor/✅ Website: http://dataprofessor.org/ (Under construction)✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/✅ Twitter: https://twitter.com/thedataprof✅ FaceBook: http://facebook.com/dataprofessor/✅ GitHub: https://github.com/dataprofessor/✅ Instagram: https://www.instagram.com/data.professor/
[ { "code": null, "e": 342, "s": 172, "text": "In this article, I will show you how to build a simple machine learning powered data science web app in Python using the streamlit library in less than 50 lines of code." }, { "code": null, "e": 518, "s": 342, "text": "(Quick Note: You might also want to check out Part 1 of this streamlit tutorial series on building your first web app. Shoutout to Simon for suggesting the mention of Part 1.)" }, { "code": null, "e": 862, "s": 518, "text": "The data science life cycle is essentially comprised of data collection, data cleaning, exploratory data analysis, model building and model deployment. For more information, please check out the excellent video by Ken Jee on Different Data Science Roles Explained (by a Data Scientist). A summary infographic of this life cycle is shown below:" }, { "code": null, "e": 1191, "s": 862, "text": "As a Data Scientist or Machine Learning Engineer, it is extremely important to be able to deploy our data science project as this would help to complete the data science life cycle. Traditional deployment of machine learning models with established framework such as Django or Flask may be a daunting and/or time-consuming task." }, { "code": null, "e": 1409, "s": 1191, "text": "This article is based on a video that I made on the same topic on the Data Professor YouTube channel (How to Build a Simple Machine Learning Web App in Python) in which you can watch it alongside reading this article." }, { "code": null, "e": 1568, "s": 1409, "text": "Today, we will be building a simple machine learning-powered web app for predicting the class label of Iris flowers as being setosa, versicolor and virginica." }, { "code": null, "e": 1919, "s": 1568, "text": "Perhaps, you have seen too many use of the infamous Iris dataset in tutorials and machine learning examples. Please bear with me on this one as the Iris dataset is merely used as a sort of “lorem ipsum” (typically used as fillers words in writing contents). I assure you that I will use other example datasets in future parts of this tutorial series." }, { "code": null, "e": 2014, "s": 1919, "text": "This will require the use of three Python libraries namely streamlit, pandas and scikit-learn." }, { "code": null, "e": 2142, "s": 2014, "text": "Let’s take a look at the conceptual flow of the app that will include two major components: (1) the front-end and (2) back-end." }, { "code": null, "e": 2525, "s": 2142, "text": "In the front-end, the sidebar found on the left will accept input parameters pertaining to features (i.e. petal length, petal width, sepal length and sepal width) of Iris flowers. These features will be relayed to the back-end where the trained model will predict the class labels as a function of the input parameters. Prediction results are sent back to the front-end for display." }, { "code": null, "e": 3082, "s": 2525, "text": "In the back-end, the user input parameters will be saved into a dataframe that will be used as test data. In the meantime, a classification model will be built using the random forest algorithm from the scikit-learn library. Finally, the model will be applied to make predictions on the user input data and return the predicted class labels as being one of three flower type: setosa, versicolor or virginica. Additionally, the prediction probability will also be provided that will allow us to discern the relative confidence in the predicted class labels." }, { "code": null, "e": 3244, "s": 3082, "text": "In this tutorial, we will be using three Python libraries namely streamlit, pandas and scikit-learn. You can install these libraries via the pip install command." }, { "code": null, "e": 3266, "s": 3244, "text": "To install streamlit:" }, { "code": null, "e": 3288, "s": 3266, "text": "pip install streamlit" }, { "code": null, "e": 3307, "s": 3288, "text": "To install pandas:" }, { "code": null, "e": 3326, "s": 3307, "text": "pip install pandas" }, { "code": null, "e": 3351, "s": 3326, "text": "To install scikit-learn:" }, { "code": null, "e": 3379, "s": 3351, "text": "pip install -U scikit-learn" }, { "code": null, "e": 3660, "s": 3379, "text": "Okay, so let’s take a look under the hood and we will see that the app that we are going to be building today is less than 50 lines of code (i.e. or 48 to be exact). And if we delete blank lines and comments (i.e. accounting for 12 lines) we can bring the number down to 36 lines." }, { "code": null, "e": 3731, "s": 3660, "text": "Okay, so let’s decode and see what each line (or code block) is doing." }, { "code": null, "e": 4105, "s": 3731, "text": "Lines 1–4Import streamlit and pandas libraries with aliases of st and pd, respectively. Specifically, import the datasets package from the scikit-learn library (sklearn) where we will subsequently make use of the loader function to load the Iris dataset (line 30). Finally, we will specifically impor the RandomForestClassifier() function from the sklearn.ensemble package." }, { "code": null, "e": 4373, "s": 4105, "text": "Line 11We will be adding the header text of the sidebar by using st.sidebar.header() function. Notice that the use of sidebar in between st and header (i.e. thus st.sidebar.header() function) tells streamlit that you want the header to be placed in the sidebar panel." }, { "code": null, "e": 5232, "s": 4373, "text": "Lines 13–23Here we will be creating a customized function called user_input_features() that will essentially consolidate the user input parameters (i.e. the 4 flower characteristics that can accept the user specified value by means of the slider bar) and return the results in the form of a dataframe. It is worthy to note that each input parameter will accept user specified values by means of the slider button as in st.sidebar.slider(‘Sepal length’, 4.3, 7.9, 5.4) for the Sepal length. The first of the four input arguments correspond to the label text that will be specified above the slider button which in our case is ‘Sepal length’ while the next 2 values corresponds to the minimum and maximum value of the slider bar. Finally, the last input argument represents the default value that will be selected upon loading the web app, which is set to 5.4." }, { "code": null, "e": 5384, "s": 5232, "text": "Line 25As previously discussed above, the consolidated user input parameter information in the form of a dataframe will be assigned to the df variable." }, { "code": null, "e": 6165, "s": 5384, "text": "Lines 30–38This code block pertains to the actual model building phase.* Line 30 — Loads in the Iris dataset from the sklearn.datasets package and assign it to the iris variable.* Line 31 — Creates the X variable containing the 4 flower features (i.e. sepal length, sepal width, petal length and petal width) provided in iris.data.* Line 32 — Creates the Y variable pertaining to the Iris class label provided in iris.target.* Line 34 — Assign the random forest classifier, particularly the RandomForestClassifier() function, to the clf variable.* Line 35 — Train the model via the clf.fit() function by using X and Y variables as input arguments. This essentially means that a classification model will be built by training it using the 4 flower features (X) and class label (Y)." }, { "code": null, "e": 6458, "s": 6165, "text": "Lines 6–9Uses the st.write() function to print out text, which in our case we are using it to print out the title of this app in markdown format (making use of the # symbol to signify header text (line 7) whereas normal descriptive text of the app is provided in the subsequent line (line 8)." }, { "code": null, "e": 6713, "s": 6458, "text": "Lines 27–28This first section will be given the subheader text (assigned by using the st.subheader function) of ‘User Input parameters’. In the subsequent line we will be displaying the contents of the df dataframe via the use of the st.write() function." }, { "code": null, "e": 6896, "s": 6713, "text": "Lines 40–41In this second section of the main panel, the class labels (i.e. setosa, versicolor and virginica) and their corresponding index numbers (i.e. 0, 1 and 2) are printed out." }, { "code": null, "e": 7292, "s": 6896, "text": "Lines 43–44Predicted class labels are displayed in this third section of the main panel. It should be noted here that the contents of the prediction variable (line 45) is the predicted class index number and for the class label (i.e. setosa, versicolor and virginica) to be displayed we will need to use the prediction variable as an argument inside the bracket of iris.target_names[prediction]." }, { "code": null, "e": 7573, "s": 7292, "text": "Lines 47–48In this fourth and last section of the main panel, the prediction probability are displayed. This value allow us to discern the relative confidence for the predicted class labels (i.e. the higher the probability values the higher confidence we have in that prediction)." }, { "code": null, "e": 7766, "s": 7573, "text": "So the code of the web app is saved into the iris-ml-app.py file and now we are ready to run it. You can run the app by typing the following command into your command prompt (terminal window):" }, { "code": null, "e": 7795, "s": 7766, "text": "streamlit run iris-ml-app.py" }, { "code": null, "e": 7845, "s": 7795, "text": "Afterwards, you should see the following message:" }, { "code": null, "e": 7994, "s": 7845, "text": "> streamlit run iris-ml-app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501" }, { "code": null, "e": 8150, "s": 7994, "text": "A few seconds later, an internet browser window should pop-up and directs you to the created web app by taking you to http://localhost:8501 as shown below." }, { "code": null, "e": 8629, "s": 8150, "text": "Now, it’s time to give yourself a pat on the back as you have now created a machine learning-powered web app. It’s now time to showcase this in your data science portfolio and website (i.e. you might want to customize the web app by using a dataset that interests you). Make sure to check out these videos on pointers and advice (Building your Data Science Portfolio with GitHub and How to Build a Data Science Portfolio Website with Hugo & Github Pages [feat. Data Professor])." }, { "code": null, "e": 8991, "s": 8629, "text": "I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page)." }, { "code": null, "e": 9007, "s": 8991, "text": "www.youtube.com" } ]
Count NaN or missing values in Pandas DataFrame - GeeksforGeeks
02 Jul, 2020 In this article, we will see how to Count NaN or missing values in Pandas DataFrame using isnull() and sum() method of the DataFrame. Pandas isnull() function detect missing values in the given object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing value gets mapped to False. Syntax: DataFrame.isnull() Parameters: None Return Type: Dataframe of Boolean values which are True for NaN values otherwise False. Pandas sum() function return the sum of the values for the requested axis. If the input is index axis then it adds all the values in a column and repeats the same for all the columns and returns a series containing the sum of all the values in each column. It also provides support to skip the missing values while calculating the. Syntax: DataFrame.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs) Parameters : axis : {index (0), columns (1)} skipna : Exclude NA/null values when computing the result. level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. min_count : The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. Returns : sum of Series or DataFrame (if level specified). Let’s create a pandas dataframe. # import numpy library as npimport numpy as np # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', np.NaN, 'Delhi', np.NaN), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', np.NaN, 'Delhi', 'Geu'), ('Shivangi', 35, 'Mumbai', np.NaN ), ('Swapnil', 35, np.NaN, 'Geu'), (np.NaN, 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), (np.NaN, np.NaN, np.NaN, np.NaN) ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) details Output: Example 1 : Count total NaN at each column in DataFrame. # import numpy library as npimport numpy as np # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', np.NaN, 'Delhi', np.NaN), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', np.NaN, 'Delhi', 'Geu'), ('Shivangi', 35, 'Mumbai', np.NaN ), ('Swapnil', 35, np.NaN, 'Geu'), (np.NaN, 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), (np.NaN, np.NaN, np.NaN, np.NaN) ] # Create a DataFrame object from list of tuples # with columns and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # show the boolean dataframe print(" \nshow the boolean Dataframe : \n\n", details.isnull()) # Count total NaN at each column in a DataFrameprint(" \nCount total NaN at each column in a DataFrame : \n\n", details.isnull().sum()) Output: Example 2 : Count total NaN at each row in DataFrame . # import numpy library as npimport numpy as np # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', np.NaN, 'Delhi', np.NaN), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', np.NaN, 'Delhi', 'Geu'), ('Shivangi', 35, 'Mumbai', np.NaN ), ('Swapnil', 35, np.NaN, 'Geu'), (np.NaN, 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), (np.NaN, np.NaN, np.NaN, np.NaN) ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # show the boolean dataframe print(" \nshow the boolean Dataframe : \n\n", details.isnull()) # index attribute of a dataframe# gives index list # Count total NaN at each row in a DataFramefor i in range(len(details.index)) : print(" Total NaN in row", i + 1, ":", details.iloc[i].isnull().sum()) Output: Example 3 : Count total NaN in DataFrame . # import numpy library as npimport numpy as np # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', np.NaN, 'Delhi', np.NaN), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', np.NaN, 'Delhi', 'Geu'), ('Shivangi', 35, 'Mumbai', np.NaN ), ('Swapnil', 35, np.NaN, 'Geu'), (np.NaN, 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), (np.NaN, np.NaN, np.NaN, np.NaN) ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # show the boolean dataframe print(" \nshow the boolean Dataframe : \n\n", details.isnull()) # Count total NaN in a DataFrameprint(" \nCount total NaN in a DataFrame : \n\n", details.isnull().sum().sum()) Output: Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary 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() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24638, "s": 24610, "text": "\n02 Jul, 2020" }, { "code": null, "e": 24772, "s": 24638, "text": "In this article, we will see how to Count NaN or missing values in Pandas DataFrame using isnull() and sum() method of the DataFrame." }, { "code": null, "e": 24990, "s": 24772, "text": "Pandas isnull() function detect missing values in the given object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing value gets mapped to False." }, { "code": null, "e": 25017, "s": 24990, "text": "Syntax: DataFrame.isnull()" }, { "code": null, "e": 25034, "s": 25017, "text": "Parameters: None" }, { "code": null, "e": 25122, "s": 25034, "text": "Return Type: Dataframe of Boolean values which are True for NaN values otherwise False." }, { "code": null, "e": 25454, "s": 25122, "text": "Pandas sum() function return the sum of the values for the requested axis. If the input is index axis then it adds all the values in a column and repeats the same for all the columns and returns a series containing the sum of all the values in each column. It also provides support to skip the missing values while calculating the." }, { "code": null, "e": 25554, "s": 25454, "text": "Syntax: DataFrame.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)" }, { "code": null, "e": 25567, "s": 25554, "text": "Parameters :" }, { "code": null, "e": 25599, "s": 25567, "text": "axis : {index (0), columns (1)}" }, { "code": null, "e": 25658, "s": 25599, "text": "skipna : Exclude NA/null values when computing the result." }, { "code": null, "e": 25767, "s": 25658, "text": "level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series" }, { "code": null, "e": 25921, "s": 25767, "text": "numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series." }, { "code": null, "e": 26068, "s": 25921, "text": "min_count : The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA." }, { "code": null, "e": 26127, "s": 26068, "text": "Returns : sum of Series or DataFrame (if level specified)." }, { "code": null, "e": 26160, "s": 26127, "text": "Let’s create a pandas dataframe." }, { "code": "# import numpy library as npimport numpy as np # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', np.NaN, 'Delhi', np.NaN), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', np.NaN, 'Delhi', 'Geu'), ('Shivangi', 35, 'Mumbai', np.NaN ), ('Swapnil', 35, np.NaN, 'Geu'), (np.NaN, 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), (np.NaN, np.NaN, np.NaN, np.NaN) ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) details", "e": 27035, "s": 26160, "text": null }, { "code": null, "e": 27043, "s": 27035, "text": "Output:" }, { "code": null, "e": 27100, "s": 27043, "text": "Example 1 : Count total NaN at each column in DataFrame." }, { "code": "# import numpy library as npimport numpy as np # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', np.NaN, 'Delhi', np.NaN), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', np.NaN, 'Delhi', 'Geu'), ('Shivangi', 35, 'Mumbai', np.NaN ), ('Swapnil', 35, np.NaN, 'Geu'), (np.NaN, 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), (np.NaN, np.NaN, np.NaN, np.NaN) ] # Create a DataFrame object from list of tuples # with columns and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # show the boolean dataframe print(\" \\nshow the boolean Dataframe : \\n\\n\", details.isnull()) # Count total NaN at each column in a DataFrameprint(\" \\nCount total NaN at each column in a DataFrame : \\n\\n\", details.isnull().sum())", "e": 28214, "s": 27100, "text": null }, { "code": null, "e": 28222, "s": 28214, "text": "Output:" }, { "code": null, "e": 28277, "s": 28222, "text": "Example 2 : Count total NaN at each row in DataFrame ." }, { "code": "# import numpy library as npimport numpy as np # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', np.NaN, 'Delhi', np.NaN), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', np.NaN, 'Delhi', 'Geu'), ('Shivangi', 35, 'Mumbai', np.NaN ), ('Swapnil', 35, np.NaN, 'Geu'), (np.NaN, 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), (np.NaN, np.NaN, np.NaN, np.NaN) ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # show the boolean dataframe print(\" \\nshow the boolean Dataframe : \\n\\n\", details.isnull()) # index attribute of a dataframe# gives index list # Count total NaN at each row in a DataFramefor i in range(len(details.index)) : print(\" Total NaN in row\", i + 1, \":\", details.iloc[i].isnull().sum())", "e": 29467, "s": 28277, "text": null }, { "code": null, "e": 29475, "s": 29467, "text": "Output:" }, { "code": null, "e": 29518, "s": 29475, "text": "Example 3 : Count total NaN in DataFrame ." }, { "code": "# import numpy library as npimport numpy as np # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', np.NaN, 'Delhi', np.NaN), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', np.NaN, 'Delhi', 'Geu'), ('Shivangi', 35, 'Mumbai', np.NaN ), ('Swapnil', 35, np.NaN, 'Geu'), (np.NaN, 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), (np.NaN, np.NaN, np.NaN, np.NaN) ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # show the boolean dataframe print(\" \\nshow the boolean Dataframe : \\n\\n\", details.isnull()) # Count total NaN in a DataFrameprint(\" \\nCount total NaN in a DataFrame : \\n\\n\", details.isnull().sum().sum())", "e": 30609, "s": 29518, "text": null }, { "code": null, "e": 30617, "s": 30609, "text": "Output:" }, { "code": null, "e": 30641, "s": 30617, "text": "Python pandas-dataFrame" }, { "code": null, "e": 30655, "s": 30641, "text": "Python-pandas" }, { "code": null, "e": 30662, "s": 30655, "text": "Python" }, { "code": null, "e": 30760, "s": 30662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30778, "s": 30760, "text": "Python Dictionary" }, { "code": null, "e": 30813, "s": 30778, "text": "Read a file line by line in Python" }, { "code": null, "e": 30835, "s": 30813, "text": "Enumerate() in Python" }, { "code": null, "e": 30867, "s": 30835, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30897, "s": 30867, "text": "Iterate over a list in Python" }, { "code": null, "e": 30939, "s": 30897, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30965, "s": 30939, "text": "Python String | replace()" }, { "code": null, "e": 31002, "s": 30965, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 31045, "s": 31002, "text": "Python program to convert a list to string" } ]
XML - CDATA Sections
In this chapter, we will discuss XML CDATA section. The term CDATA means, Character Data. CDATA is defined as blocks of text that are not parsed by the parser, but are otherwise recognized as markup. The predefined entities such as &lt;, &gt;, and &amp; require typing and are generally difficult to read in the markup. In such cases, CDATA section can be used. By using CDATA section, you are commanding the parser that the particular section of the document contains no markup and should be treated as regular text. Following is the syntax for CDATA section − <![CDATA[ characters with markup ]]> The above syntax is composed of three sections − CDATA Start section − CDATA begins with the nine-character delimiter <![CDATA[ CDATA Start section − CDATA begins with the nine-character delimiter <![CDATA[ CDATA End section − CDATA section ends with ]]> delimiter. CDATA End section − CDATA section ends with ]]> delimiter. CData section − Characters between these two enclosures are interpreted as characters, and not as markup. This section may contain markup characters (<, >, and &), but they are ignored by the XML processor. CData section − Characters between these two enclosures are interpreted as characters, and not as markup. This section may contain markup characters (<, >, and &), but they are ignored by the XML processor. The following markup code shows an example of CDATA. Here, each character written inside the CDATA section is ignored by the parser. <script> <![CDATA[ <message> Welcome to TutorialsPoint </message> ]] > </script > In the above syntax, everything between <message> and </message> is treated as character data and not as markup. The given rules are required to be followed for XML CDATA − CDATA cannot contain the string "]]>" anywhere in the XML document. Nesting is not allowed in CDATA section. 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2161, "s": 1961, "text": "In this chapter, we will discuss XML CDATA section. The term CDATA means, Character Data. CDATA is defined as blocks of text that are not parsed by the parser, but are otherwise recognized as markup." }, { "code": null, "e": 2479, "s": 2161, "text": "The predefined entities such as &lt;, &gt;, and &amp; require typing and are generally difficult to read in the markup. In such cases, CDATA section can be used. By using CDATA section, you are commanding the parser that the particular section of the document contains no markup and should be treated as regular text." }, { "code": null, "e": 2523, "s": 2479, "text": "Following is the syntax for CDATA section −" }, { "code": null, "e": 2563, "s": 2523, "text": "<![CDATA[\n characters with markup\n]]>" }, { "code": null, "e": 2612, "s": 2563, "text": "The above syntax is composed of three sections −" }, { "code": null, "e": 2691, "s": 2612, "text": "CDATA Start section − CDATA begins with the nine-character delimiter <![CDATA[" }, { "code": null, "e": 2770, "s": 2691, "text": "CDATA Start section − CDATA begins with the nine-character delimiter <![CDATA[" }, { "code": null, "e": 2829, "s": 2770, "text": "CDATA End section − CDATA section ends with ]]> delimiter." }, { "code": null, "e": 2888, "s": 2829, "text": "CDATA End section − CDATA section ends with ]]> delimiter." }, { "code": null, "e": 3095, "s": 2888, "text": "CData section − Characters between these two enclosures are interpreted as characters, and not as markup. This section may contain markup characters (<, >, and &), but they are ignored by the XML processor." }, { "code": null, "e": 3302, "s": 3095, "text": "CData section − Characters between these two enclosures are interpreted as characters, and not as markup. This section may contain markup characters (<, >, and &), but they are ignored by the XML processor." }, { "code": null, "e": 3435, "s": 3302, "text": "The following markup code shows an example of CDATA. Here, each character written inside the CDATA section is ignored by the parser." }, { "code": null, "e": 3529, "s": 3435, "text": "<script>\n <![CDATA[\n <message> Welcome to TutorialsPoint </message>\n ]] >\n</script >" }, { "code": null, "e": 3642, "s": 3529, "text": "In the above syntax, everything between <message> and </message> is treated as character data and not as markup." }, { "code": null, "e": 3702, "s": 3642, "text": "The given rules are required to be followed for XML CDATA −" }, { "code": null, "e": 3770, "s": 3702, "text": "CDATA cannot contain the string \"]]>\" anywhere in the XML document." }, { "code": null, "e": 3811, "s": 3770, "text": "Nesting is not allowed in CDATA section." }, { "code": null, "e": 3844, "s": 3811, "text": "\n 84 Lectures \n 6 hours \n" }, { "code": null, "e": 3861, "s": 3844, "text": " Frahaan Hussain" }, { "code": null, "e": 3894, "s": 3861, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 3904, "s": 3894, "text": " YouAccel" }, { "code": null, "e": 3937, "s": 3904, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 3954, "s": 3937, "text": " Jordan Stanchev" }, { "code": null, "e": 3987, "s": 3954, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4001, "s": 3987, "text": " Simon Sez IT" }, { "code": null, "e": 4008, "s": 4001, "text": " Print" }, { "code": null, "e": 4019, "s": 4008, "text": " Add Notes" } ]
Check if Table, View, Trigger, etc present in Oracle - GeeksforGeeks
10 Jan, 2018 Sometimes while working in SQL we often forget the names of the view or sequence or index or synonyms or trigger we earlier created. Also it may happen that we want to verify them in future. Verifying means that we are checking for all the present database object or Trigger in that particular schema.This could be done for above all using the below mentioned queries: PREREQUISITE: DATABASE OBJECTSTriggers 1. verify VIEWS SYNTAX:SELECT VIEW_NAME FROM USER_VIEWS; OR SELECT * FROM USER_VIEWS; SELECT VIEW_NAME FROM USER_VIEWS; OR SELECT * FROM USER_VIEWS; Examples:Input : SELECT VIEW_NAME FROM USER_VIEWS; Output : Input : SELECT * FROM USER_VIEWS; Output : Input : SELECT VIEW_NAME FROM USER_VIEWS; Output : Input : SELECT * FROM USER_VIEWS; Output : 2. verify SEQUENCES SYNTAX:SELECT SEQUENCE_NAME FROM USER_SEQUENCES; OR SELECT * FROM USER_SEQUENCES; SELECT SEQUENCE_NAME FROM USER_SEQUENCES; OR SELECT * FROM USER_SEQUENCES; Examples:Input : SELECT SEQUENCE_NAME FROM USER_SEQUENCES; Output : Input : SELECT * FROM USER_SEQUENCES; Output : Input : SELECT SEQUENCE_NAME FROM USER_SEQUENCES; Output : Input : SELECT * FROM USER_SEQUENCES; Output : 3. verify INDEXES SYNTAX:SELECT INDEX_NAME FROM USER_INDEXES; OR SELECT * FROM USER_INDEXS; SELECT INDEX_NAME FROM USER_INDEXES; OR SELECT * FROM USER_INDEXS; Examples:Input : SELECT INDEX_NAME FROM USER_INDEXES; Output : Input : SELECT * FROM USER_INDEXES; Output : Input : SELECT INDEX_NAME FROM USER_INDEXES; Output : Input : SELECT * FROM USER_INDEXES; Output : 4. verify TABLES SYNTAX:SELECT TABLE_NAME FROM USER_TABLES; OR SELECT * FROM USER_TABLES; SELECT TABLE_NAME FROM USER_TABLES; OR SELECT * FROM USER_TABLES; Examples:Input : SELECT TABLE_NAME FROM USER_TABLES; Output : Input : SELECT * FROM USER_TABLES; Output : Input : SELECT TABLE_NAME FROM USER_TABLES; Output : Input : SELECT * FROM USER_TABLES; Output : 5. verify SYNONYMS SYNTAX:SELECT SYNONYM_NAME FROM USER_SYNONYMS; OR SELECT * FROM USER_SYNONYMS; SELECT SYNONYM_NAME FROM USER_SYNONYMS; OR SELECT * FROM USER_SYNONYMS; Examples:Input : SELECT SYNONYM_NAME FROM USER_SYNONYMS; Output : Input : SELECT * FROM USER_SYNONYMS; Output : Input : SELECT SYNONYM_NAME FROM USER_SYNONYMS; Output : Input : SELECT * FROM USER_SYNONYMS; Output : 6. verify TRIGGERS SYNTAX:SELECT TRIGGER_NAME FROM USER_TRIGGERS; OR SELECT * FROM USER_TRIGGERS; SELECT TRIGGER_NAME FROM USER_TRIGGERS; OR SELECT * FROM USER_TRIGGERS; Examples:Input : SELECT TRIGGER_NAME FROM USER_TRIGGERS; Output : Input : SELECT * FROM USER_TRIGGERS; Output : Input : SELECT TRIGGER_NAME FROM USER_TRIGGERS; Output : Input : SELECT * FROM USER_TRIGGERS; Output : NOTE: Using * means that we need all the attributes for that database object or Trigger to get displayed. DBMS GBlog SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Introduction of Relational Algebra in DBMS What is Temporary Table in SQL? KDD Process in Data Mining Two Phase Locking Protocol Roadmap to Become a Web Developer in 2022 Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Socket Programming in C/C++ DSA Sheet by Love Babbar GET and POST requests using Python
[ { "code": null, "e": 24304, "s": 24276, "text": "\n10 Jan, 2018" }, { "code": null, "e": 24495, "s": 24304, "text": "Sometimes while working in SQL we often forget the names of the view or sequence or index or synonyms or trigger we earlier created. Also it may happen that we want to verify them in future." }, { "code": null, "e": 24673, "s": 24495, "text": "Verifying means that we are checking for all the present database object or Trigger in that particular schema.This could be done for above all using the below mentioned queries:" }, { "code": null, "e": 24712, "s": 24673, "text": "PREREQUISITE: DATABASE OBJECTSTriggers" }, { "code": null, "e": 24728, "s": 24712, "text": "1. verify VIEWS" }, { "code": null, "e": 24809, "s": 24728, "text": "SYNTAX:SELECT VIEW_NAME FROM USER_VIEWS;\n\n OR\n\nSELECT * FROM USER_VIEWS;\n" }, { "code": null, "e": 24883, "s": 24809, "text": "SELECT VIEW_NAME FROM USER_VIEWS;\n\n OR\n\nSELECT * FROM USER_VIEWS;\n" }, { "code": null, "e": 24987, "s": 24883, "text": "Examples:Input : SELECT VIEW_NAME FROM USER_VIEWS;\nOutput :\nInput : SELECT * FROM USER_VIEWS;\nOutput :\n" }, { "code": null, "e": 25039, "s": 24987, "text": "Input : SELECT VIEW_NAME FROM USER_VIEWS;\nOutput :\n" }, { "code": null, "e": 25083, "s": 25039, "text": "Input : SELECT * FROM USER_VIEWS;\nOutput :\n" }, { "code": null, "e": 25103, "s": 25083, "text": "2. verify SEQUENCES" }, { "code": null, "e": 25196, "s": 25103, "text": "SYNTAX:SELECT SEQUENCE_NAME FROM USER_SEQUENCES;\n\n OR\n\nSELECT * FROM USER_SEQUENCES;\n" }, { "code": null, "e": 25282, "s": 25196, "text": "SELECT SEQUENCE_NAME FROM USER_SEQUENCES;\n\n OR\n\nSELECT * FROM USER_SEQUENCES;\n" }, { "code": null, "e": 25398, "s": 25282, "text": "Examples:Input : SELECT SEQUENCE_NAME FROM USER_SEQUENCES;\nOutput :\nInput : SELECT * FROM USER_SEQUENCES;\nOutput :\n" }, { "code": null, "e": 25458, "s": 25398, "text": "Input : SELECT SEQUENCE_NAME FROM USER_SEQUENCES;\nOutput :\n" }, { "code": null, "e": 25506, "s": 25458, "text": "Input : SELECT * FROM USER_SEQUENCES;\nOutput :\n" }, { "code": null, "e": 25524, "s": 25506, "text": "3. verify INDEXES" }, { "code": null, "e": 25609, "s": 25524, "text": "SYNTAX:SELECT INDEX_NAME FROM USER_INDEXES;\n\n OR\n\nSELECT * FROM USER_INDEXS;\n" }, { "code": null, "e": 25687, "s": 25609, "text": "SELECT INDEX_NAME FROM USER_INDEXES;\n\n OR\n\nSELECT * FROM USER_INDEXS;\n" }, { "code": null, "e": 25796, "s": 25687, "text": "Examples:Input : SELECT INDEX_NAME FROM USER_INDEXES;\nOutput :\nInput : SELECT * FROM USER_INDEXES;\nOutput :\n" }, { "code": null, "e": 25851, "s": 25796, "text": "Input : SELECT INDEX_NAME FROM USER_INDEXES;\nOutput :\n" }, { "code": null, "e": 25897, "s": 25851, "text": "Input : SELECT * FROM USER_INDEXES;\nOutput :\n" }, { "code": null, "e": 25914, "s": 25897, "text": "4. verify TABLES" }, { "code": null, "e": 25998, "s": 25914, "text": "SYNTAX:SELECT TABLE_NAME FROM USER_TABLES;\n\n OR\n\nSELECT * FROM USER_TABLES;\n" }, { "code": null, "e": 26075, "s": 25998, "text": "SELECT TABLE_NAME FROM USER_TABLES;\n\n OR\n\nSELECT * FROM USER_TABLES;\n" }, { "code": null, "e": 26182, "s": 26075, "text": "Examples:Input : SELECT TABLE_NAME FROM USER_TABLES;\nOutput :\nInput : SELECT * FROM USER_TABLES;\nOutput :\n" }, { "code": null, "e": 26236, "s": 26182, "text": "Input : SELECT TABLE_NAME FROM USER_TABLES;\nOutput :\n" }, { "code": null, "e": 26281, "s": 26236, "text": "Input : SELECT * FROM USER_TABLES;\nOutput :\n" }, { "code": null, "e": 26300, "s": 26281, "text": "5. verify SYNONYMS" }, { "code": null, "e": 26390, "s": 26300, "text": "SYNTAX:SELECT SYNONYM_NAME FROM USER_SYNONYMS;\n\n OR\n\nSELECT * FROM USER_SYNONYMS;\n" }, { "code": null, "e": 26473, "s": 26390, "text": "SELECT SYNONYM_NAME FROM USER_SYNONYMS;\n\n OR\n\nSELECT * FROM USER_SYNONYMS;\n" }, { "code": null, "e": 26588, "s": 26473, "text": "Examples:Input : SELECT SYNONYM_NAME FROM USER_SYNONYMS;\nOutput : \nInput : SELECT * FROM USER_SYNONYMS;\nOutput : \n" }, { "code": null, "e": 26647, "s": 26588, "text": "Input : SELECT SYNONYM_NAME FROM USER_SYNONYMS;\nOutput : \n" }, { "code": null, "e": 26695, "s": 26647, "text": "Input : SELECT * FROM USER_SYNONYMS;\nOutput : \n" }, { "code": null, "e": 26714, "s": 26695, "text": "6. verify TRIGGERS" }, { "code": null, "e": 26804, "s": 26714, "text": "SYNTAX:SELECT TRIGGER_NAME FROM USER_TRIGGERS;\n\n OR\n\nSELECT * FROM USER_TRIGGERS;\n" }, { "code": null, "e": 26887, "s": 26804, "text": "SELECT TRIGGER_NAME FROM USER_TRIGGERS;\n\n OR\n\nSELECT * FROM USER_TRIGGERS;\n" }, { "code": null, "e": 27002, "s": 26887, "text": "Examples:Input : SELECT TRIGGER_NAME FROM USER_TRIGGERS;\nOutput : \nInput : SELECT * FROM USER_TRIGGERS;\nOutput : \n" }, { "code": null, "e": 27061, "s": 27002, "text": "Input : SELECT TRIGGER_NAME FROM USER_TRIGGERS;\nOutput : \n" }, { "code": null, "e": 27109, "s": 27061, "text": "Input : SELECT * FROM USER_TRIGGERS;\nOutput : \n" }, { "code": null, "e": 27215, "s": 27109, "text": "NOTE: Using * means that we need all the attributes for that database object or Trigger to get displayed." }, { "code": null, "e": 27220, "s": 27215, "text": "DBMS" }, { "code": null, "e": 27226, "s": 27220, "text": "GBlog" }, { "code": null, "e": 27230, "s": 27226, "text": "SQL" }, { "code": null, "e": 27235, "s": 27230, "text": "DBMS" }, { "code": null, "e": 27239, "s": 27235, "text": "SQL" }, { "code": null, "e": 27337, "s": 27239, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27378, "s": 27337, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 27421, "s": 27378, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 27453, "s": 27421, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27480, "s": 27453, "text": "KDD Process in Data Mining" }, { "code": null, "e": 27507, "s": 27480, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 27549, "s": 27507, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27623, "s": 27549, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 27651, "s": 27623, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27676, "s": 27651, "text": "DSA Sheet by Love Babbar" } ]
How to remove duplicate elements of an array in java?
To detect the duplicate values in an array you need to compare each element of the array to all the remaining elements in case of a match you got your duplicate element. One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of the outer loop) to avoid repetitions. Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add a library to your project. <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> </dependencies> This package provides a class named ArrayUtils using the remove() method of this class you can delete the detected duplicate elements of the given array. import java.util.Arrays; import java.util.Scanner; import org.apache.commons.lang3.ArrayUtils; public class DeleteDuplicate { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created::"); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array ::"); for(int i=0; i<size; i++) { myArray[i] = sc.nextInt(); } System.out.println("The array created is ::"+Arrays.toString(myArray)); for(int i=0; i<myArray.length-1; i++) { for (int j=i+1; j<myArray.length; j++) { if(myArray[i] == myArray[j]) { myArray = ArrayUtils.remove(myArray, j); } } } System.out.println("Array after removing elements ::"+Arrays.toString(myArray)); } } Enter the size of the array that is to be created :: 6 Enter the elements of the array :: 232 232 65 47 89 42 The array created is :: [232, 232, 65, 47, 89, 42] Array after removing elements :: [232, 65, 47, 89, 42]
[ { "code": null, "e": 1232, "s": 1062, "text": "To detect the duplicate values in an array you need to compare each element of the array to all the remaining elements in case of a match you got your duplicate element." }, { "code": null, "e": 1392, "s": 1232, "text": "One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of the outer loop) to avoid repetitions." }, { "code": null, "e": 1530, "s": 1392, "text": "Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add a library to your project." }, { "code": null, "e": 1712, "s": 1530, "text": "<dependencies>\n <dependency>\n <groupId>org.apache.commons</groupId>\n <artifactId>commons-lang3</artifactId>\n <version>3.0</version>\n </dependency>\n</dependencies>" }, { "code": null, "e": 1866, "s": 1712, "text": "This package provides a class named ArrayUtils using the remove() method of this class you can delete the detected duplicate elements of the given array." }, { "code": null, "e": 2770, "s": 1866, "text": "import java.util.Arrays;\nimport java.util.Scanner;\nimport org.apache.commons.lang3.ArrayUtils;\npublic class DeleteDuplicate {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created::\");\n int size = sc.nextInt();\n int[] myArray = new int[size];\n System.out.println(\"Enter the elements of the array ::\");\n for(int i=0; i<size; i++) {\n myArray[i] = sc.nextInt();\n }\n System.out.println(\"The array created is ::\"+Arrays.toString(myArray));\n for(int i=0; i<myArray.length-1; i++) {\n for (int j=i+1; j<myArray.length; j++) {\n if(myArray[i] == myArray[j]) {\n myArray = ArrayUtils.remove(myArray, j);\n }\n }\n }\n System.out.println(\"Array after removing elements ::\"+Arrays.toString(myArray));\n }\n}" }, { "code": null, "e": 2986, "s": 2770, "text": "Enter the size of the array that is to be created ::\n6\nEnter the elements of the array ::\n232\n232\n65\n47\n89\n42\nThe array created is :: [232, 232, 65, 47, 89, 42]\nArray after removing elements :: [232, 65, 47, 89, 42]" } ]
Python Number hypot() Method
Python number method hypot() return the Euclidean norm, sqrt(x*x + y*y). Following is the syntax for hypot() method − hypot(x, y) Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object. x − This must be a numeric value. x − This must be a numeric value. y − This must be a numeric value. y − This must be a numeric value. This method returns Euclidean norm, sqrt(x*x + y*y). The following example shows the usage of hypot() method. #!/usr/bin/python import math print "hypot(3, 2) : ", math.hypot(3, 2) print "hypot(-3, 3) : ", math.hypot(-3, 3) print "hypot(0, 2) : ", math.hypot(0, 2) When we run above program, it produces following result − hypot(3, 2) : 3.60555127546 hypot(-3, 3) : 4.24264068712 hypot(0, 2) : 2.0 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2318, "s": 2244, "text": "Python number method hypot() return the Euclidean norm, sqrt(x*x + y*y)." }, { "code": null, "e": 2363, "s": 2318, "text": "Following is the syntax for hypot() method −" }, { "code": null, "e": 2376, "s": 2363, "text": "hypot(x, y)\n" }, { "code": null, "e": 2523, "s": 2376, "text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object." }, { "code": null, "e": 2557, "s": 2523, "text": "x − This must be a numeric value." }, { "code": null, "e": 2591, "s": 2557, "text": "x − This must be a numeric value." }, { "code": null, "e": 2625, "s": 2591, "text": "y − This must be a numeric value." }, { "code": null, "e": 2659, "s": 2625, "text": "y − This must be a numeric value." }, { "code": null, "e": 2712, "s": 2659, "text": "This method returns Euclidean norm, sqrt(x*x + y*y)." }, { "code": null, "e": 2769, "s": 2712, "text": "The following example shows the usage of hypot() method." }, { "code": null, "e": 2928, "s": 2769, "text": "#!/usr/bin/python\nimport math\n\nprint \"hypot(3, 2) : \", math.hypot(3, 2)\nprint \"hypot(-3, 3) : \", math.hypot(-3, 3)\nprint \"hypot(0, 2) : \", math.hypot(0, 2)" }, { "code": null, "e": 2986, "s": 2928, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3065, "s": 2986, "text": "hypot(3, 2) : 3.60555127546\nhypot(-3, 3) : 4.24264068712\nhypot(0, 2) : 2.0\n" }, { "code": null, "e": 3102, "s": 3065, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3118, "s": 3102, "text": " Malhar Lathkar" }, { "code": null, "e": 3151, "s": 3118, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3170, "s": 3151, "text": " Arnab Chakraborty" }, { "code": null, "e": 3205, "s": 3170, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3227, "s": 3205, "text": " In28Minutes Official" }, { "code": null, "e": 3261, "s": 3227, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3289, "s": 3261, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3324, "s": 3289, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3338, "s": 3324, "text": " Lets Kode It" }, { "code": null, "e": 3371, "s": 3338, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3388, "s": 3371, "text": " Abhilash Nelson" }, { "code": null, "e": 3395, "s": 3388, "text": " Print" }, { "code": null, "e": 3406, "s": 3395, "text": " Add Notes" } ]
How to Create an Empty Figure with Matplotlib in Python? - GeeksforGeeks
11 Dec, 2020 Creating a figure explicitly is an object-oriented style of interfacing with matplotlib. The figure is a basic building block of creating a plot as Matplotlib graphs our data on figures. This figure keeps track of all other components such as child axes, legends, title, axis, etc. Steps to create an empty figure : First, we import the matplotlib library specifically the pyplot module of matplotlib. Then we create a figure object using plt.figure() and keep a reference to that by setting it equal to the ‘fig’ variable. This figure object is empty as we have not added any figure components such as axis, legend, axis, etc. We are using jupyter notebook, and we have to change out backend to ipympl(interactive backend) as with the default backend it was showing a Non-Gui backend error. For installing the ipympl run this command into your terminal: For conda environment. conda install ipympl -c conda-forge For normal python terminal: pip install ipympl Below is the implementation: Example1 : Python3 # importing the libraryimport matplotlib # Enabling interactive backend ipympl in# jupyter notebook or you can use# any other backend%matplotlib ipympl import matplotlib.pyplot as plt # an empty figure with no axesfig = plt.figure() Output: Example 2 : You can also use another interactive backend to display your figure like TkAgg( requires TkInter installed). Python3 # using different backendimport matplotlib%matplotlib tkimport matplotlib.pyplot as plt #creating a figurefig = plt.figure() Output : Figure2_gfg Note: Displaying the figure in a different editor or python shell will need you to play with backends. show() method also displays an empty figure but you have to save that figure before using show() command. Example : In the following example, I have used figsize attribute to change the size of the figure. Python3 import matplotlib # changing backend%matplotlib tkimport matplotlib.pyplot as plt # saving the figureplt.savefig('testfigure.png', dpi = 100) # displaying the figureplt.show() Output : figure3_gfg Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python 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
[ { "code": null, "e": 25060, "s": 25032, "text": "\n11 Dec, 2020" }, { "code": null, "e": 25342, "s": 25060, "text": "Creating a figure explicitly is an object-oriented style of interfacing with matplotlib. The figure is a basic building block of creating a plot as Matplotlib graphs our data on figures. This figure keeps track of all other components such as child axes, legends, title, axis, etc." }, { "code": null, "e": 25377, "s": 25342, "text": "Steps to create an empty figure : " }, { "code": null, "e": 25463, "s": 25377, "text": "First, we import the matplotlib library specifically the pyplot module of matplotlib." }, { "code": null, "e": 25689, "s": 25463, "text": "Then we create a figure object using plt.figure() and keep a reference to that by setting it equal to the ‘fig’ variable. This figure object is empty as we have not added any figure components such as axis, legend, axis, etc." }, { "code": null, "e": 25853, "s": 25689, "text": "We are using jupyter notebook, and we have to change out backend to ipympl(interactive backend) as with the default backend it was showing a Non-Gui backend error." }, { "code": null, "e": 25916, "s": 25853, "text": "For installing the ipympl run this command into your terminal:" }, { "code": null, "e": 25939, "s": 25916, "text": "For conda environment." }, { "code": null, "e": 25975, "s": 25939, "text": "conda install ipympl -c conda-forge" }, { "code": null, "e": 26003, "s": 25975, "text": "For normal python terminal:" }, { "code": null, "e": 26022, "s": 26003, "text": "pip install ipympl" }, { "code": null, "e": 26051, "s": 26022, "text": "Below is the implementation:" }, { "code": null, "e": 26062, "s": 26051, "text": "Example1 :" }, { "code": null, "e": 26070, "s": 26062, "text": "Python3" }, { "code": "# importing the libraryimport matplotlib # Enabling interactive backend ipympl in# jupyter notebook or you can use# any other backend%matplotlib ipympl import matplotlib.pyplot as plt # an empty figure with no axesfig = plt.figure() ", "e": 26308, "s": 26070, "text": null }, { "code": null, "e": 26316, "s": 26308, "text": "Output:" }, { "code": null, "e": 26328, "s": 26316, "text": "Example 2 :" }, { "code": null, "e": 26437, "s": 26328, "text": "You can also use another interactive backend to display your figure like TkAgg( requires TkInter installed)." }, { "code": null, "e": 26445, "s": 26437, "text": "Python3" }, { "code": "# using different backendimport matplotlib%matplotlib tkimport matplotlib.pyplot as plt #creating a figurefig = plt.figure()", "e": 26571, "s": 26445, "text": null }, { "code": null, "e": 26580, "s": 26571, "text": "Output :" }, { "code": null, "e": 26592, "s": 26580, "text": "Figure2_gfg" }, { "code": null, "e": 26695, "s": 26592, "text": "Note: Displaying the figure in a different editor or python shell will need you to play with backends." }, { "code": null, "e": 26801, "s": 26695, "text": "show() method also displays an empty figure but you have to save that figure before using show() command." }, { "code": null, "e": 26811, "s": 26801, "text": "Example :" }, { "code": null, "e": 26901, "s": 26811, "text": "In the following example, I have used figsize attribute to change the size of the figure." }, { "code": null, "e": 26909, "s": 26901, "text": "Python3" }, { "code": "import matplotlib # changing backend%matplotlib tkimport matplotlib.pyplot as plt # saving the figureplt.savefig('testfigure.png', dpi = 100) # displaying the figureplt.show()", "e": 27099, "s": 26909, "text": null }, { "code": null, "e": 27108, "s": 27099, "text": "Output :" }, { "code": null, "e": 27120, "s": 27108, "text": "figure3_gfg" }, { "code": null, "e": 27138, "s": 27120, "text": "Python-matplotlib" }, { "code": null, "e": 27145, "s": 27138, "text": "Python" }, { "code": null, "e": 27243, "s": 27145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27261, "s": 27243, "text": "Python Dictionary" }, { "code": null, "e": 27296, "s": 27261, "text": "Read a file line by line in Python" }, { "code": null, "e": 27318, "s": 27296, "text": "Enumerate() in Python" }, { "code": null, "e": 27350, "s": 27318, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27380, "s": 27350, "text": "Iterate over a list in Python" }, { "code": null, "e": 27422, "s": 27380, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27448, "s": 27422, "text": "Python String | replace()" }, { "code": null, "e": 27491, "s": 27448, "text": "Python program to convert a list to string" }, { "code": null, "e": 27528, "s": 27491, "text": "Create a Pandas DataFrame from Lists" } ]
show.bs.tab event in Bootstrap
The show.bs.event fires when the tab is about to be displayed. Display the tab using the nav-tabs class − <ul class="nav nav-tabs"> <li class="active"><a href="#home">Home</a></li> <li><a href="#two">Java</a></li> <li><a href="#three">CSS</a></li> <li><a href="#four">Bootstrap</a></li> <li><a href="#five">jQuery</a></li> </ul> After that, you need to use the show.bs.tab class to generate an alert after the tab is clicked, but just before it is displayed − $('.nav-tabs a').on('show.bs.tab', function(){ alert('New tab will be visible now!'); }); You can try to run the following code to implement the show.bs.tab event − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Learn</h2> <ul class="nav nav-tabs"> <li class="active"><a href="#home">Home</a></li> <li><a href="#two">Java</a></li> <li><a href="#three">CSS</a></li> <li><a href="#four">Bootstrap</a></li> <li><a href="#five">jQuery</a></li> </ul> <div class="tab-content"> <div id="home" class="tab-pane fade in active"> <h3>Home</h3> <p>This is demo text!</p> </div> <div id="two" class="tab-pane fade"> <h3>PHP</h3> <p>This is demo text!</p> </div> <div id="three" class="tab-pane fade"> <h3>C#.NET</h3> <p>This is demo text!</p> </div> <div id="four" class="tab-pane fade"> <h3>Ruby</h3> <p>This is demo text!</p> </div> <div id="five" class="tab-pane fade"> <h3>HTML5</h3> <p>This is demo text!</p> </div> </div> </div> <script> $(document).ready(function(){ $(".nav-tabs a").click(function(){ $(this).tab('show'); }); $('.nav-tabs a').on('show.bs.tab', function(){ alert('New tab will be visible now!'); }); $('.nav-tabs a').on('shown.bs.tab', function(){ alert('New tab is now visible!'); }); $('.nav-tabs a').on('hide.bs.tab', function(e){ alert('Previous tab will hide now!'); }); $('.nav-tabs a').on('hidden.bs.tab', function(){ alert('Previous Tab is hidden now!'); }); }); </script> </body> </html>
[ { "code": null, "e": 1125, "s": 1062, "text": "The show.bs.event fires when the tab is about to be displayed." }, { "code": null, "e": 1168, "s": 1125, "text": "Display the tab using the nav-tabs class −" }, { "code": null, "e": 1401, "s": 1168, "text": "<ul class=\"nav nav-tabs\">\n <li class=\"active\"><a href=\"#home\">Home</a></li>\n <li><a href=\"#two\">Java</a></li>\n <li><a href=\"#three\">CSS</a></li>\n <li><a href=\"#four\">Bootstrap</a></li>\n <li><a href=\"#five\">jQuery</a></li>\n</ul>" }, { "code": null, "e": 1532, "s": 1401, "text": "After that, you need to use the show.bs.tab class to generate an alert after the tab is clicked, but just before it is displayed −" }, { "code": null, "e": 1624, "s": 1532, "text": "$('.nav-tabs a').on('show.bs.tab', function(){\n alert('New tab will be visible now!');\n});" }, { "code": null, "e": 1699, "s": 1624, "text": "You can try to run the following code to implement the show.bs.tab event −" }, { "code": null, "e": 1709, "s": 1699, "text": "Live Demo" }, { "code": null, "e": 3634, "s": 1709, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n\n <body>\n <div class=\"container\">\n <h2>Learn</h2>\n <ul class=\"nav nav-tabs\">\n <li class=\"active\"><a href=\"#home\">Home</a></li>\n <li><a href=\"#two\">Java</a></li>\n <li><a href=\"#three\">CSS</a></li>\n <li><a href=\"#four\">Bootstrap</a></li>\n <li><a href=\"#five\">jQuery</a></li>\n </ul>\n\n <div class=\"tab-content\">\n <div id=\"home\" class=\"tab-pane fade in active\">\n <h3>Home</h3>\n <p>This is demo text!</p>\n </div>\n <div id=\"two\" class=\"tab-pane fade\">\n <h3>PHP</h3>\n <p>This is demo text!</p>\n </div>\n <div id=\"three\" class=\"tab-pane fade\">\n <h3>C#.NET</h3>\n <p>This is demo text!</p>\n </div>\n <div id=\"four\" class=\"tab-pane fade\">\n <h3>Ruby</h3>\n <p>This is demo text!</p>\n </div>\n <div id=\"five\" class=\"tab-pane fade\">\n <h3>HTML5</h3>\n <p>This is demo text!</p>\n </div>\n </div>\n </div>\n\n<script>\n$(document).ready(function(){\n $(\".nav-tabs a\").click(function(){\n $(this).tab('show');\n });\n $('.nav-tabs a').on('show.bs.tab', function(){\n alert('New tab will be visible now!');\n });\n $('.nav-tabs a').on('shown.bs.tab', function(){\n alert('New tab is now visible!');\n });\n $('.nav-tabs a').on('hide.bs.tab', function(e){\n alert('Previous tab will hide now!');\n });\n $('.nav-tabs a').on('hidden.bs.tab', function(){\n alert('Previous Tab is hidden now!');\n });\n});\n\n</script>\n\n</body>\n</html>" } ]
MVVM – Dependency Injection
In this chapter, we will briefly discuss about dependency injection. We have already covered data binding decouples Views and ViewModels from each other that allows them to communicate without knowing explicitly what is going on at the other end of the communication. Now we need something similar to decouple our ViewModel from the client services. In early days of object-oriented programming, developers have faced the issue of creating and retrieving instances of classes in applications. Various solutions have been proposed for this problem. For the past few years, dependency injection and inversion of control (IoC) have gained popularity among developers and have taken precedence over some older solutions such as the Singleton pattern. IoC and dependency injection are two design patterns that are closely related and the container is basically a chunk of infrastructure code that does both of those patterns for you. IoC pattern is about delegating responsibility for construction and the dependency injection pattern is about providing dependencies to an object that's already been constructed. IoC pattern is about delegating responsibility for construction and the dependency injection pattern is about providing dependencies to an object that's already been constructed. They can both be treated as a two-phase approach to constructing. When you use a container, the container takes several responsibilities which are as follows − It constructs an object when asked. The container will determine what that object depends on. Constructing those dependencies. Injecting them into the object being constructed. Recursively doing process. They can both be treated as a two-phase approach to constructing. When you use a container, the container takes several responsibilities which are as follows − It constructs an object when asked. The container will determine what that object depends on. Constructing those dependencies. Injecting them into the object being constructed. Recursively doing process. Let's have a look at how we can use dependency injection to break decoupling between ViewModels and the client services. We will wire up the save handling AddEditCustomerViewModel form by using dependency injection related to that. First we need to create a new interface in our project in Services folder. If you don’t have a services folder in your project then create it first and add the following interface in the Services folder. using MVVMHierarchiesDemo.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVMHierarchiesDemo.Services { public interface ICustomersRepository { Task<List<Customer>> GetCustomersAsync(); Task<Customer> GetCustomerAsync(Guid id); Task<Customer> AddCustomerAsync(Customer customer); Task<Customer> UpdateCustomerAsync(Customer customer); Task DeleteCustomerAsync(Guid customerId); } } Following is the implementation of ICustomersRepository. using MVVMHierarchiesDemo.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVMHierarchiesDemo.Services { public class CustomersRepository : ICustomersRepository { ZzaDbContext _context = new ZzaDbContext(); public Task<List<Customer>> GetCustomersAsync() { return _context.Customers.ToListAsync(); } public Task<Customer> GetCustomerAsync(Guid id) { return _context.Customers.FirstOrDefaultAsync(c => c.Id == id); } public async Task<Customer> AddCustomerAsync(Customer customer){ _context.Customers.Add(customer); await _context.SaveChangesAsync(); return customer; } public async Task<Customer> UpdateCustomerAsync(Customer customer) { if (!_context.Customers.Local.Any(c => c.Id == customer.Id)) { _context.Customers.Attach(customer); } _context.Entry(customer).State = EntityState.Modified; await _context.SaveChangesAsync(); return customer; } public async Task DeleteCustomerAsync(Guid customerId) { var customer = _context.Customers.FirstOrDefault(c => c.Id == customerId); if (customer != null) { _context.Customers.Remove(customer); } await _context.SaveChangesAsync(); } } } The simple way to do Save handling is to add a new instance of ICustomersRepository in AddEditCustomerViewModel and overload the AddEditCustomerViewModel and CustomerListViewModel constructor. private ICustomersRepository _repo; public AddEditCustomerViewModel(ICustomersRepository repo) { _repo = repo; CancelCommand = new MyIcommand(OnCancel); SaveCommand = new MyIcommand(OnSave, CanSave); } Update the OnSave method as shown in the following code. private async void OnSave() { UpdateCustomer(Customer, _editingCustomer); if (EditMode) await _repo.UpdateCustomerAsync(_editingCustomer); else await _repo.AddCustomerAsync(_editingCustomer); Done(); } private void UpdateCustomer(SimpleEditableCustomer source, Customer target) { target.FirstName = source.FirstName; target.LastName = source.LastName; target.Phone = source.Phone; target.Email = source.Email; } Following is the complete AddEditCustomerViewModel. using MVVMHierarchiesDemo.Model; using MVVMHierarchiesDemo.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVMHierarchiesDemo.ViewModel { class AddEditCustomerViewModel : BindableBase { private ICustomersRepository _repo; public AddEditCustomerViewModel(ICustomersRepository repo) { _repo = repo; CancelCommand = new MyIcommand(OnCancel); SaveCommand = new MyIcommand(OnSave, CanSave); } private bool _EditMode; public bool EditMode { get { return _EditMode; } set { SetProperty(ref _EditMode, value); } } private SimpleEditableCustomer _Customer; public SimpleEditableCustomer Customer { get { return _Customer; } set { SetProperty(ref _Customer, value); } } private Customer _editingCustomer = null; public void SetCustomer(Customer cust) { _editingCustomer = cust; if (Customer != null) Customer.ErrorsChanged -= RaiseCanExecuteChanged; Customer = new SimpleEditableCustomer(); Customer.ErrorsChanged += RaiseCanExecuteChanged; CopyCustomer(cust, Customer); } private void RaiseCanExecuteChanged(object sender, EventArgs e) { SaveCommand.RaiseCanExecuteChanged(); } public MyIcommand CancelCommand { get; private set; } public MyIcommand SaveCommand { get; private set; } public event Action Done = delegate { }; private void OnCancel() { Done(); } private async void OnSave() { UpdateCustomer(Customer, _editingCustomer); if (EditMode) await _repo.UpdateCustomerAsync(_editingCustomer); else await _repo.AddCustomerAsync(_editingCustomer); Done(); } private void UpdateCustomer(SimpleEditableCustomer source, Customer target) { target.FirstName = source.FirstName; target.LastName = source.LastName; target.Phone = source.Phone; target.Email = source.Email; } private bool CanSave() { return !Customer.HasErrors; } private void CopyCustomer(Customer source, SimpleEditableCustomer target) { target.Id = source.Id; if (EditMode) { target.FirstName = source.FirstName; target.LastName = source.LastName; target.Phone = source.Phone; target.Email = source.Email; } } } } When the above code is compiled and executed, you will see the same output but now ViewModels are more loosely decoupled. When you press the Add Customer button, you will see the following view. When the user leaves any field empty, then it will become highlighted and the save button will become disabled. 38 Lectures 2 hours Skillbakerystudios 22 Lectures 1 hours CLEMENT OCHIENG 14 Lectures 2 hours DevTechie Print Add Notes Bookmark this page
[ { "code": null, "e": 2210, "s": 1942, "text": "In this chapter, we will briefly discuss about dependency injection. We have already covered data binding decouples Views and ViewModels from each other that allows them to communicate without knowing explicitly what is going on at the other end of the communication." }, { "code": null, "e": 2292, "s": 2210, "text": "Now we need something similar to decouple our ViewModel from the client services." }, { "code": null, "e": 2490, "s": 2292, "text": "In early days of object-oriented programming, developers have faced the issue of creating and retrieving instances of classes in applications. Various solutions have been proposed for this problem." }, { "code": null, "e": 2689, "s": 2490, "text": "For the past few years, dependency injection and inversion of control (IoC) have gained popularity among developers and have taken precedence over some older solutions such as the Singleton pattern." }, { "code": null, "e": 2871, "s": 2689, "text": "IoC and dependency injection are two design patterns that are closely related and the container is basically a chunk of infrastructure code that does both of those patterns for you." }, { "code": null, "e": 3050, "s": 2871, "text": "IoC pattern is about delegating responsibility for construction and the dependency injection pattern is about providing dependencies to an object that's already been constructed." }, { "code": null, "e": 3229, "s": 3050, "text": "IoC pattern is about delegating responsibility for construction and the dependency injection pattern is about providing dependencies to an object that's already been constructed." }, { "code": null, "e": 3596, "s": 3229, "text": "They can both be treated as a two-phase approach to constructing. When you use a container, the container takes several responsibilities which are as follows −\n\nIt constructs an object when asked.\nThe container will determine what that object depends on.\nConstructing those dependencies.\nInjecting them into the object being constructed.\nRecursively doing process.\n\n" }, { "code": null, "e": 3756, "s": 3596, "text": "They can both be treated as a two-phase approach to constructing. When you use a container, the container takes several responsibilities which are as follows −" }, { "code": null, "e": 3792, "s": 3756, "text": "It constructs an object when asked." }, { "code": null, "e": 3850, "s": 3792, "text": "The container will determine what that object depends on." }, { "code": null, "e": 3883, "s": 3850, "text": "Constructing those dependencies." }, { "code": null, "e": 3933, "s": 3883, "text": "Injecting them into the object being constructed." }, { "code": null, "e": 3960, "s": 3933, "text": "Recursively doing process." }, { "code": null, "e": 4192, "s": 3960, "text": "Let's have a look at how we can use dependency injection to break decoupling between ViewModels and the client services. We will wire up the save handling AddEditCustomerViewModel form by using dependency injection related to that." }, { "code": null, "e": 4396, "s": 4192, "text": "First we need to create a new interface in our project in Services folder. If you don’t have a services folder in your project then create it first and add the following interface in the Services folder." }, { "code": null, "e": 4916, "s": 4396, "text": "using MVVMHierarchiesDemo.Model; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace MVVMHierarchiesDemo.Services { \n\n public interface ICustomersRepository { \n Task<List<Customer>> GetCustomersAsync(); \n Task<Customer> GetCustomerAsync(Guid id); \n Task<Customer> AddCustomerAsync(Customer customer); \n Task<Customer> UpdateCustomerAsync(Customer customer); \n Task DeleteCustomerAsync(Guid customerId); \n } \n}" }, { "code": null, "e": 4973, "s": 4916, "text": "Following is the implementation of ICustomersRepository." }, { "code": null, "e": 6415, "s": 4973, "text": "using MVVMHierarchiesDemo.Model; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; using System.Text; \nusing System.Threading.Tasks;\n\nnamespace MVVMHierarchiesDemo.Services { \n\n public class CustomersRepository : ICustomersRepository {\n ZzaDbContext _context = new ZzaDbContext();\n\n public Task<List<Customer>> GetCustomersAsync() { \n return _context.Customers.ToListAsync(); \n }\n\n public Task<Customer> GetCustomerAsync(Guid id) { \n return _context.Customers.FirstOrDefaultAsync(c => c.Id == id); \n }\n\t\t\n public async Task<Customer> AddCustomerAsync(Customer customer){ \n _context.Customers.Add(customer); \n await _context.SaveChangesAsync(); \n return customer;\n }\n\n public async Task<Customer> UpdateCustomerAsync(Customer customer) {\n\t\t\n if (!_context.Customers.Local.Any(c => c.Id == customer.Id)) { \n _context.Customers.Attach(customer); \n } \n\t\t\t\n _context.Entry(customer).State = EntityState.Modified;\n await _context.SaveChangesAsync(); \n return customer;\n\t\t\t\n }\n\n public async Task DeleteCustomerAsync(Guid customerId) {\n var customer = _context.Customers.FirstOrDefault(c => c.Id == customerId); \n\t\t\t\n if (customer != null) {\n _context.Customers.Remove(customer); \n }\n\t\t\t\n await _context.SaveChangesAsync(); \n } \n } \n}" }, { "code": null, "e": 6608, "s": 6415, "text": "The simple way to do Save handling is to add a new instance of ICustomersRepository in AddEditCustomerViewModel and overload the AddEditCustomerViewModel and CustomerListViewModel constructor." }, { "code": null, "e": 6824, "s": 6608, "text": "private ICustomersRepository _repo; \n\npublic AddEditCustomerViewModel(ICustomersRepository repo) { \n _repo = repo; \n CancelCommand = new MyIcommand(OnCancel);\n SaveCommand = new MyIcommand(OnSave, CanSave); \n}" }, { "code": null, "e": 6881, "s": 6824, "text": "Update the OnSave method as shown in the following code." }, { "code": null, "e": 7345, "s": 6881, "text": "private async void OnSave() { \n UpdateCustomer(Customer, _editingCustomer); \n\t\n if (EditMode) \n await _repo.UpdateCustomerAsync(_editingCustomer); \n else \n await _repo.AddCustomerAsync(_editingCustomer); \n Done(); \n} \n\nprivate void UpdateCustomer(SimpleEditableCustomer source, Customer target) { \n target.FirstName = source.FirstName; \n target.LastName = source.LastName; \n target.Phone = source.Phone; \n target.Email = source.Email; \n}" }, { "code": null, "e": 7397, "s": 7345, "text": "Following is the complete AddEditCustomerViewModel." }, { "code": null, "e": 10028, "s": 7397, "text": "using MVVMHierarchiesDemo.Model; \nusing MVVMHierarchiesDemo.Services; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace MVVMHierarchiesDemo.ViewModel { \n\n class AddEditCustomerViewModel : BindableBase { \n private ICustomersRepository _repo; \n\t\t\n public AddEditCustomerViewModel(ICustomersRepository repo) { \n _repo = repo;\n CancelCommand = new MyIcommand(OnCancel); \n SaveCommand = new MyIcommand(OnSave, CanSave); \n } \n\t\t\n private bool _EditMode; \n\t\t\n public bool EditMode { \n get { return _EditMode; } \n set { SetProperty(ref _EditMode, value); } \n }\n\n private SimpleEditableCustomer _Customer; \n\t\t\n public SimpleEditableCustomer Customer { \n get { return _Customer; } \n set { SetProperty(ref _Customer, value); } \n }\n\t\t\n private Customer _editingCustomer = null;\n\n public void SetCustomer(Customer cust) { \n _editingCustomer = cust; \n\t\t\t\n if (Customer != null) Customer.ErrorsChanged -= RaiseCanExecuteChanged; \n Customer = new SimpleEditableCustomer();\n Customer.ErrorsChanged += RaiseCanExecuteChanged;\n CopyCustomer(cust, Customer); \n }\n\n private void RaiseCanExecuteChanged(object sender, EventArgs e) { \n SaveCommand.RaiseCanExecuteChanged(); \n }\n\n public MyIcommand CancelCommand { get; private set; } \n public MyIcommand SaveCommand { get; private set; }\n\n public event Action Done = delegate { };\n\t\t\n private void OnCancel() { \n Done(); \n }\n\n private async void OnSave() { \n UpdateCustomer(Customer, _editingCustomer); \n\t\t\t\n if (EditMode) \n await _repo.UpdateCustomerAsync(_editingCustomer); \n else \n await _repo.AddCustomerAsync(_editingCustomer); \n Done(); \n }\n\n private void UpdateCustomer(SimpleEditableCustomer source, Customer target) { \n target.FirstName = source.FirstName; \n target.LastName = source.LastName; \n target.Phone = source.Phone; \n target.Email = source.Email; \n }\n\n private bool CanSave() { \n return !Customer.HasErrors; \n }\n\t\t\n private void CopyCustomer(Customer source, SimpleEditableCustomer target) { \n target.Id = source.Id; \n\t\t\t\n if (EditMode) { \n target.FirstName = source.FirstName; \n target.LastName = source.LastName; \n target.Phone = source.Phone; \n target.Email = source.Email; \n }\n } \n } \n}" }, { "code": null, "e": 10150, "s": 10028, "text": "When the above code is compiled and executed, you will see the same output but now ViewModels are more loosely decoupled." }, { "code": null, "e": 10335, "s": 10150, "text": "When you press the Add Customer button, you will see the following view. When the user leaves any field empty, then it will become highlighted and the save button will become disabled." }, { "code": null, "e": 10368, "s": 10335, "text": "\n 38 Lectures \n 2 hours \n" }, { "code": null, "e": 10388, "s": 10368, "text": " Skillbakerystudios" }, { "code": null, "e": 10421, "s": 10388, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 10438, "s": 10421, "text": " CLEMENT OCHIENG" }, { "code": null, "e": 10471, "s": 10438, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 10482, "s": 10471, "text": " DevTechie" }, { "code": null, "e": 10489, "s": 10482, "text": " Print" }, { "code": null, "e": 10500, "s": 10489, "text": " Add Notes" } ]
Generate Captcha Using Python - GeeksforGeeks
08 Oct, 2021 In this article, we are going to see how to generate a captcha using Python package captcha to generate our own CAPTCHA (Completely Automated Public Turing Test to Tell Computers and Humans Apart) in picture form. CAPTCHA is a form of challenge-response authentication security mechanism. CAPTCHA prevents automated systems from reading the distorted characters in the picture. pip install captcha Here we are going to generate an image captcha: Step 1: Import module and create an instance of ImageCaptcha(). image = ImageCaptcha(width = 280, height = 90) Step 2: Create image object with image.generate(CAPTCHA_Text). data = image.generate(captcha_text) Step 3: Save the image to a file image.write(). image.write(captcha_text, 'CAPTCHA.png') Below is the full implementation: Python3 # Import the following modulesfrom captcha.image import ImageCaptcha # Create an image instance of the given sizeimage = ImageCaptcha(width = 280, height = 90) # Image captcha textcaptcha_text = 'GeeksforGeeks' # generate the image of the given textdata = image.generate(captcha_text) # write the image on the given file and save itimage.write(captcha_text, 'CAPTCHA.png') Output: Image CAPTCHA Here we are going to generate an audio captcha: Step 1: Import module and create an instance of AudioCaptcha(). image = audioCaptcha(width = 280, height = 90) Step 2: Create an audio object with audio.generate(CAPTCHA_Text). data = audio.generate(captcha_text) Step 3: Save the image to file audio.write(). audio.write(captcha_text, audio_file) Below is the full implementation: Python3 # Import the following modulesfrom captcha.audio import AudioCaptcha # Create an audio instanceaudio = AudioCaptcha() # Audio captcha textcaptcha_text = "5454" # generate the audio of the given textaudio_data = audio.generate(captcha_text) # Give the name of the audio fileaudio_file = "audio"+captcha_text+'.wav' # Finally write the audio file and save itaudio.write(captcha_text, audio_file) Output: gabaa406 python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24670, "s": 24292, "text": "In this article, we are going to see how to generate a captcha using Python package captcha to generate our own CAPTCHA (Completely Automated Public Turing Test to Tell Computers and Humans Apart) in picture form. CAPTCHA is a form of challenge-response authentication security mechanism. CAPTCHA prevents automated systems from reading the distorted characters in the picture." }, { "code": null, "e": 24690, "s": 24670, "text": "pip install captcha" }, { "code": null, "e": 24738, "s": 24690, "text": "Here we are going to generate an image captcha:" }, { "code": null, "e": 24802, "s": 24738, "text": "Step 1: Import module and create an instance of ImageCaptcha()." }, { "code": null, "e": 24849, "s": 24802, "text": "image = ImageCaptcha(width = 280, height = 90)" }, { "code": null, "e": 24912, "s": 24849, "text": "Step 2: Create image object with image.generate(CAPTCHA_Text)." }, { "code": null, "e": 24950, "s": 24912, "text": "data = image.generate(captcha_text) " }, { "code": null, "e": 24998, "s": 24950, "text": "Step 3: Save the image to a file image.write()." }, { "code": null, "e": 25039, "s": 24998, "text": "image.write(captcha_text, 'CAPTCHA.png')" }, { "code": null, "e": 25073, "s": 25039, "text": "Below is the full implementation:" }, { "code": null, "e": 25081, "s": 25073, "text": "Python3" }, { "code": "# Import the following modulesfrom captcha.image import ImageCaptcha # Create an image instance of the given sizeimage = ImageCaptcha(width = 280, height = 90) # Image captcha textcaptcha_text = 'GeeksforGeeks' # generate the image of the given textdata = image.generate(captcha_text) # write the image on the given file and save itimage.write(captcha_text, 'CAPTCHA.png')", "e": 25456, "s": 25081, "text": null }, { "code": null, "e": 25464, "s": 25456, "text": "Output:" }, { "code": null, "e": 25478, "s": 25464, "text": "Image CAPTCHA" }, { "code": null, "e": 25526, "s": 25478, "text": "Here we are going to generate an audio captcha:" }, { "code": null, "e": 25590, "s": 25526, "text": "Step 1: Import module and create an instance of AudioCaptcha()." }, { "code": null, "e": 25637, "s": 25590, "text": "image = audioCaptcha(width = 280, height = 90)" }, { "code": null, "e": 25703, "s": 25637, "text": "Step 2: Create an audio object with audio.generate(CAPTCHA_Text)." }, { "code": null, "e": 25741, "s": 25703, "text": "data = audio.generate(captcha_text) " }, { "code": null, "e": 25787, "s": 25741, "text": "Step 3: Save the image to file audio.write()." }, { "code": null, "e": 25825, "s": 25787, "text": "audio.write(captcha_text, audio_file)" }, { "code": null, "e": 25859, "s": 25825, "text": "Below is the full implementation:" }, { "code": null, "e": 25867, "s": 25859, "text": "Python3" }, { "code": "# Import the following modulesfrom captcha.audio import AudioCaptcha # Create an audio instanceaudio = AudioCaptcha() # Audio captcha textcaptcha_text = \"5454\" # generate the audio of the given textaudio_data = audio.generate(captcha_text) # Give the name of the audio fileaudio_file = \"audio\"+captcha_text+'.wav' # Finally write the audio file and save itaudio.write(captcha_text, audio_file)", "e": 26262, "s": 25867, "text": null }, { "code": null, "e": 26270, "s": 26262, "text": "Output:" }, { "code": null, "e": 26279, "s": 26270, "text": "gabaa406" }, { "code": null, "e": 26294, "s": 26279, "text": "python-modules" }, { "code": null, "e": 26309, "s": 26294, "text": "python-utility" }, { "code": null, "e": 26316, "s": 26309, "text": "Python" }, { "code": null, "e": 26414, "s": 26316, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26446, "s": 26414, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26502, "s": 26446, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26544, "s": 26502, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26586, "s": 26544, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26608, "s": 26586, "text": "Defaultdict in Python" }, { "code": null, "e": 26647, "s": 26608, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26678, "s": 26647, "text": "Python | os.path.join() method" }, { "code": null, "e": 26733, "s": 26678, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26762, "s": 26733, "text": "Create a directory in Python" } ]
Convert Hex to RGBa for background opacity using SASS - GeeksforGeeks
19 Aug, 2020 Sass rgba function uses Red-green-blue-alpha model to describe colours where alpha is used to add opacity to the color. It’s value ranges between 0.0 (completely transparent) to 1.0 (completely opaque). The function takes two input values- the hex color code and alpha and converts Hex code to RGBa format. Syntax: Using background-color property:element { background-color: rgba(hex_value, opacity_value); } element { background-color: rgba(hex_value, opacity_value); } Using mixins with background-color property that provides hex fallback:@mixin background-opacity($color, $opacity) { background: $color; /*Fallback */ background: rgba($color, $opacity); } body { @include background-opacity(hex_value, opacity_value); } @mixin background-opacity($color, $opacity) { background: $color; /*Fallback */ background: rgba($color, $opacity); } body { @include background-opacity(hex_value, opacity_value); } Below examples illustrate the above approach: Example 1: Adding 70% opacity to a Hex code <!DOCTYPE html><html><head><title>Converting Hex to RGBA for background opacity</title></head><body> <p>GeeksforGeeks</p></body></html> SASS code:@mixin background-opacity($color, $opacity) { background: $color; background: rgba($color, $opacity);} body { @include background-opacity(#32DF07, 0.7);} @mixin background-opacity($color, $opacity) { background: $color; background: rgba($color, $opacity);} body { @include background-opacity(#32DF07, 0.7);} Converted CSS code:body { background: #32DF07; background: rgba(50, 223, 7, 0.7); } body { background: #32DF07; background: rgba(50, 223, 7, 0.7); } Output: Example 2: Adding 50% opacity to a Hex code <!DOCTYPE html> <html> <head> <title>Converting Hex to RGBA for background opacity </title> </head><body> <p>GeeksforGeeks</p></body></html> SASS code:@mixin background-opacity($color, $opacity) { background: $color; background: rgba($color, $opacity);} body { @include background-opacity(#32DF07, 0.5);} @mixin background-opacity($color, $opacity) { background: $color; background: rgba($color, $opacity);} body { @include background-opacity(#32DF07, 0.5);} Converted CSS code:body { background: #32DF07; background: rgba(50, 223, 7, 0.5); } body { background: #32DF07; background: rgba(50, 223, 7, 0.5); } Output: Picked SASS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25254, "s": 25226, "text": "\n19 Aug, 2020" }, { "code": null, "e": 25561, "s": 25254, "text": "Sass rgba function uses Red-green-blue-alpha model to describe colours where alpha is used to add opacity to the color. It’s value ranges between 0.0 (completely transparent) to 1.0 (completely opaque). The function takes two input values- the hex color code and alpha and converts Hex code to RGBa format." }, { "code": null, "e": 25569, "s": 25561, "text": "Syntax:" }, { "code": null, "e": 25667, "s": 25569, "text": "Using background-color property:element {\n background-color: rgba(hex_value, opacity_value);\n}" }, { "code": null, "e": 25733, "s": 25667, "text": "element {\n background-color: rgba(hex_value, opacity_value);\n}" }, { "code": null, "e": 26001, "s": 25733, "text": "Using mixins with background-color property that provides hex fallback:@mixin background-opacity($color, $opacity) {\n background: $color; /*Fallback */\n background: rgba($color, $opacity);\n}\n\nbody {\n @include background-opacity(hex_value, opacity_value);\n}" }, { "code": null, "e": 26198, "s": 26001, "text": "@mixin background-opacity($color, $opacity) {\n background: $color; /*Fallback */\n background: rgba($color, $opacity);\n}\n\nbody {\n @include background-opacity(hex_value, opacity_value);\n}" }, { "code": null, "e": 26244, "s": 26198, "text": "Below examples illustrate the above approach:" }, { "code": null, "e": 26288, "s": 26244, "text": "Example 1: Adding 70% opacity to a Hex code" }, { "code": "<!DOCTYPE html><html><head><title>Converting Hex to RGBA for background opacity</title></head><body> <p>GeeksforGeeks</p></body></html>", "e": 26425, "s": 26288, "text": null }, { "code": null, "e": 26600, "s": 26425, "text": "SASS code:@mixin background-opacity($color, $opacity) { background: $color; background: rgba($color, $opacity);} body { @include background-opacity(#32DF07, 0.7);}" }, { "code": "@mixin background-opacity($color, $opacity) { background: $color; background: rgba($color, $opacity);} body { @include background-opacity(#32DF07, 0.7);}", "e": 26765, "s": 26600, "text": null }, { "code": null, "e": 26853, "s": 26765, "text": "Converted CSS code:body {\n background: #32DF07;\n background: rgba(50, 223, 7, 0.7);\n}" }, { "code": null, "e": 26922, "s": 26853, "text": "body {\n background: #32DF07;\n background: rgba(50, 223, 7, 0.7);\n}" }, { "code": null, "e": 26930, "s": 26922, "text": "Output:" }, { "code": null, "e": 26974, "s": 26930, "text": "Example 2: Adding 50% opacity to a Hex code" }, { "code": "<!DOCTYPE html> <html> <head> <title>Converting Hex to RGBA for background opacity </title> </head><body> <p>GeeksforGeeks</p></body></html>", "e": 27139, "s": 26974, "text": null }, { "code": null, "e": 27314, "s": 27139, "text": "SASS code:@mixin background-opacity($color, $opacity) { background: $color; background: rgba($color, $opacity);} body { @include background-opacity(#32DF07, 0.5);}" }, { "code": "@mixin background-opacity($color, $opacity) { background: $color; background: rgba($color, $opacity);} body { @include background-opacity(#32DF07, 0.5);}", "e": 27479, "s": 27314, "text": null }, { "code": null, "e": 27567, "s": 27479, "text": "Converted CSS code:body {\n background: #32DF07;\n background: rgba(50, 223, 7, 0.5);\n}" }, { "code": null, "e": 27636, "s": 27567, "text": "body {\n background: #32DF07;\n background: rgba(50, 223, 7, 0.5);\n}" }, { "code": null, "e": 27644, "s": 27636, "text": "Output:" }, { "code": null, "e": 27651, "s": 27644, "text": "Picked" }, { "code": null, "e": 27656, "s": 27651, "text": "SASS" }, { "code": null, "e": 27660, "s": 27656, "text": "CSS" }, { "code": null, "e": 27677, "s": 27660, "text": "Web Technologies" }, { "code": null, "e": 27775, "s": 27677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27833, "s": 27775, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27870, "s": 27833, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27911, "s": 27870, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 27948, "s": 27911, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28009, "s": 27948, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28051, "s": 28009, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28084, "s": 28051, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28127, "s": 28084, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28172, "s": 28127, "text": "Convert a string to an integer in JavaScript" } ]
Lua - Object Oriented
Object Oriented Programming (OOP), is one the most used programming technique that is used in the modern era of programming. There are a number of programming languages that support OOP which include, C++ Java Objective-C Smalltalk C# Ruby Class − A class is an extensible template for creating objects, providing initial values for state (member variables) and implementations of behavior. Class − A class is an extensible template for creating objects, providing initial values for state (member variables) and implementations of behavior. Objects − It is an instance of class and has separate memory allocated for itself. Objects − It is an instance of class and has separate memory allocated for itself. Inheritance − It is a concept by which variables and functions of one class is inherited by another class. Inheritance − It is a concept by which variables and functions of one class is inherited by another class. Encapsulation − It is the process of combining the data and functions inside a class. Data can be accessed outside the class with the help of functions. It is also known as data abstraction. Encapsulation − It is the process of combining the data and functions inside a class. Data can be accessed outside the class with the help of functions. It is also known as data abstraction. You can implement object orientation in Lua with the help of tables and first class functions of Lua. By placing functions and related data into a table, an object is formed. Inheritance can be implemented with the help of metatables, providing a look up mechanism for nonexistent functions(methods) and fields in parent object(s). Tables in Lua have the features of object like state and identity that is independent of its values. Two objects (tables) with the same value are different objects, whereas an object can have different values at different times, but it is always the same object. Like objects, tables have a life cycle that is independent of who created them or where they were created. The concept of object orientation is widely used but you need to understand it clearly for proper and maximum benefit. Let us consider a simple math example. We often encounter situations where we work on different shapes like circle, rectangle and square. The shapes can have a common property Area. So, we can extend other shapes from the base object shape with the common property area. Each of the shapes can have its own properties and functions like a rectangle can have properties length, breadth, area as its properties and printArea and calculateArea as its functions. A simple class implementation for a rectangle with three properties area, length, and breadth is shown below. It also has a printArea function to print the area calculated. -- Meta class Rectangle = {area = 0, length = 0, breadth = 0} -- Derived class method new function Rectangle:new (o,length,breadth) o = o or {} setmetatable(o, self) self.__index = self self.length = length or 0 self.breadth = breadth or 0 self.area = length*breadth; return o end -- Derived class method printArea function Rectangle:printArea () print("The area of Rectangle is ",self.area) end Creating an object is the process of allocating memory for the class instance. Each of the objects has its own memory and share the common class data. r = Rectangle:new(nil,10,20) We can access the properties in the class using the dot operator as shown below − print(r.length) You can access a member function using the colon operator with the object as shown below − r:printArea() The memory gets allocated and the initial values are set. The initialization process can be compared to constructors in other object oriented languages. It is nothing but a function that enables setting values as shown above. Lets look at a complete example using object orientation in Lua. -- Meta class Shape = {area = 0} -- Base class method new function Shape:new (o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or 0 self.area = side*side; return o end -- Base class method printArea function Shape:printArea () print("The area is ",self.area) end -- Creating an object myshape = Shape:new(nil,10) myshape:printArea() When you run the above program, you will get the following output. The area is 100 Inheritance is the process of extending simple base objects like shape to rectangles, squares and so on. It is often used in the real world to share and extend the basic properties and functions. Let us see a simple class extension. We have a class as shown below. -- Meta class Shape = {area = 0} -- Base class method new function Shape:new (o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or 0 self.area = side*side; return o end -- Base class method printArea function Shape:printArea () print("The area is ",self.area) end We can extend the shape to a square class as shown below. Square = Shape:new() -- Derived class method new function Square:new (o,side) o = o or Shape:new(o,side) setmetatable(o, self) self.__index = self return o end We can override the base class functions that is instead of using the function in the base class, derived class can have its own implementation as shown below − -- Derived class method printArea function Square:printArea () print("The area of square is ",self.area) end We can extend the simple class implementation in Lua as shown above with the help of another new method with the help of metatables. All the member variables and functions of base class are retained in the derived class. -- Meta class Shape = {area = 0} -- Base class method new function Shape:new (o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or 0 self.area = side*side; return o end -- Base class method printArea function Shape:printArea () print("The area is ",self.area) end -- Creating an object myshape = Shape:new(nil,10) myshape:printArea() Square = Shape:new() -- Derived class method new function Square:new (o,side) o = o or Shape:new(o,side) setmetatable(o, self) self.__index = self return o end -- Derived class method printArea function Square:printArea () print("The area of square is ",self.area) end -- Creating an object mysquare = Square:new(nil,10) mysquare:printArea() Rectangle = Shape:new() -- Derived class method new function Rectangle:new (o,length,breadth) o = o or Shape:new(o) setmetatable(o, self) self.__index = self self.area = length * breadth return o end -- Derived class method printArea function Rectangle:printArea () print("The area of Rectangle is ",self.area) end -- Creating an object myrectangle = Rectangle:new(nil,10,20) myrectangle:printArea() When we run the above program, we will get the following output − The area is 100 The area of square is 100 The area of Rectangle is 200 In the above example, we have created two derived classes − Rectangle and Square from the base class Square. It is possible to override the functions of the base class in derived class. In this example, the derived class overrides the function printArea. 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2304, "s": 2103, "text": "Object Oriented Programming (OOP), is one the most used programming technique that is used in the modern era of programming. There are a number of programming languages that support OOP which include," }, { "code": null, "e": 2308, "s": 2304, "text": "C++" }, { "code": null, "e": 2313, "s": 2308, "text": "Java" }, { "code": null, "e": 2325, "s": 2313, "text": "Objective-C" }, { "code": null, "e": 2335, "s": 2325, "text": "Smalltalk" }, { "code": null, "e": 2338, "s": 2335, "text": "C#" }, { "code": null, "e": 2343, "s": 2338, "text": "Ruby" }, { "code": null, "e": 2494, "s": 2343, "text": "Class − A class is an extensible template for creating objects, providing initial values for state (member variables) and implementations of behavior." }, { "code": null, "e": 2645, "s": 2494, "text": "Class − A class is an extensible template for creating objects, providing initial values for state (member variables) and implementations of behavior." }, { "code": null, "e": 2728, "s": 2645, "text": "Objects − It is an instance of class and has separate memory allocated for itself." }, { "code": null, "e": 2811, "s": 2728, "text": "Objects − It is an instance of class and has separate memory allocated for itself." }, { "code": null, "e": 2918, "s": 2811, "text": "Inheritance − It is a concept by which variables and functions of one class is inherited by another class." }, { "code": null, "e": 3025, "s": 2918, "text": "Inheritance − It is a concept by which variables and functions of one class is inherited by another class." }, { "code": null, "e": 3216, "s": 3025, "text": "Encapsulation − It is the process of combining the data and functions inside a class. Data can be accessed outside the class with the help of functions. It is also known as data abstraction." }, { "code": null, "e": 3407, "s": 3216, "text": "Encapsulation − It is the process of combining the data and functions inside a class. Data can be accessed outside the class with the help of functions. It is also known as data abstraction." }, { "code": null, "e": 3739, "s": 3407, "text": "You can implement object orientation in Lua with the help of tables and first class functions of Lua. By placing functions and related data into a table, an object is formed. Inheritance can be implemented with the help of metatables, providing a look up mechanism for nonexistent functions(methods) and fields in parent object(s)." }, { "code": null, "e": 4109, "s": 3739, "text": "Tables in Lua have the features of object like state and identity that is independent of its values. Two objects (tables) with the same value are different objects, whereas an object can have different values at different times, but it is always the same object. Like objects, tables have a life cycle that is independent of who created them or where they were created." }, { "code": null, "e": 4228, "s": 4109, "text": "The concept of object orientation is widely used but you need to understand it clearly for proper and maximum benefit." }, { "code": null, "e": 4366, "s": 4228, "text": "Let us consider a simple math example. We often encounter situations where we work on different shapes like circle, rectangle and square." }, { "code": null, "e": 4687, "s": 4366, "text": "The shapes can have a common property Area. So, we can extend other shapes from the base object shape with the common property area. Each of the shapes can have its own properties and functions like a rectangle can have properties length, breadth, area as its properties and printArea and calculateArea as its functions." }, { "code": null, "e": 4860, "s": 4687, "text": "A simple class implementation for a rectangle with three properties area, length, and breadth is shown below. It also has a printArea function to print the area calculated." }, { "code": null, "e": 5284, "s": 4860, "text": "-- Meta class\nRectangle = {area = 0, length = 0, breadth = 0}\n\n-- Derived class method new\n\nfunction Rectangle:new (o,length,breadth)\n o = o or {}\n setmetatable(o, self)\n self.__index = self\n self.length = length or 0\n self.breadth = breadth or 0\n self.area = length*breadth;\n return o\nend\n\n-- Derived class method printArea\n\nfunction Rectangle:printArea ()\n print(\"The area of Rectangle is \",self.area)\nend" }, { "code": null, "e": 5435, "s": 5284, "text": "Creating an object is the process of allocating memory for the class instance. Each of the objects has its own memory and share the common class data." }, { "code": null, "e": 5465, "s": 5435, "text": "r = Rectangle:new(nil,10,20)\n" }, { "code": null, "e": 5547, "s": 5465, "text": "We can access the properties in the class using the dot operator as shown below −" }, { "code": null, "e": 5564, "s": 5547, "text": "print(r.length)\n" }, { "code": null, "e": 5655, "s": 5564, "text": "You can access a member function using the colon operator with the object as shown below −" }, { "code": null, "e": 5670, "s": 5655, "text": "r:printArea()\n" }, { "code": null, "e": 5896, "s": 5670, "text": "The memory gets allocated and the initial values are set. The initialization process can be compared to constructors in other object oriented languages. It is nothing but a function that enables setting values as shown above." }, { "code": null, "e": 5961, "s": 5896, "text": "Lets look at a complete example using object orientation in Lua." }, { "code": null, "e": 6346, "s": 5961, "text": "-- Meta class\nShape = {area = 0}\n\n-- Base class method new\n\nfunction Shape:new (o,side)\n o = o or {}\n setmetatable(o, self)\n self.__index = self\n side = side or 0\n self.area = side*side;\n return o\nend\n\n-- Base class method printArea\n\nfunction Shape:printArea ()\n print(\"The area is \",self.area)\nend\n\n-- Creating an object\nmyshape = Shape:new(nil,10)\n\nmyshape:printArea()" }, { "code": null, "e": 6413, "s": 6346, "text": "When you run the above program, you will get the following output." }, { "code": null, "e": 6431, "s": 6413, "text": "The area is \t100\n" }, { "code": null, "e": 6627, "s": 6431, "text": "Inheritance is the process of extending simple base objects like shape to rectangles, squares and so on. It is often used in the real world to share and extend the basic properties and functions." }, { "code": null, "e": 6696, "s": 6627, "text": "Let us see a simple class extension. We have a class as shown below." }, { "code": null, "e": 7009, "s": 6696, "text": "-- Meta class\nShape = {area = 0}\n\n-- Base class method new\n\nfunction Shape:new (o,side)\n o = o or {}\n setmetatable(o, self)\n self.__index = self\n side = side or 0\n self.area = side*side;\n return o\nend\n\n-- Base class method printArea\n\nfunction Shape:printArea ()\n print(\"The area is \",self.area)\nend" }, { "code": null, "e": 7067, "s": 7009, "text": "We can extend the shape to a square class as shown below." }, { "code": null, "e": 7241, "s": 7067, "text": "Square = Shape:new()\n\n-- Derived class method new\n\nfunction Square:new (o,side)\n o = o or Shape:new(o,side)\n setmetatable(o, self)\n self.__index = self\n return o\nend" }, { "code": null, "e": 7402, "s": 7241, "text": "We can override the base class functions that is instead of using the function in the base class, derived class can have its own implementation as shown below −" }, { "code": null, "e": 7515, "s": 7402, "text": "-- Derived class method printArea\n\nfunction Square:printArea ()\n print(\"The area of square is \",self.area)\nend" }, { "code": null, "e": 7736, "s": 7515, "text": "We can extend the simple class implementation in Lua as shown above with the help of another new method with the help of metatables. All the member variables and functions of base class are retained in the derived class." }, { "code": null, "e": 8909, "s": 7736, "text": "-- Meta class\nShape = {area = 0}\n\n-- Base class method new\n\nfunction Shape:new (o,side)\n o = o or {}\n setmetatable(o, self)\n self.__index = self\n side = side or 0\n self.area = side*side;\n return o\nend\n\n-- Base class method printArea\n\nfunction Shape:printArea ()\n print(\"The area is \",self.area)\nend\n\n-- Creating an object\nmyshape = Shape:new(nil,10)\nmyshape:printArea()\n\nSquare = Shape:new()\n\n-- Derived class method new\n\nfunction Square:new (o,side)\n o = o or Shape:new(o,side)\n setmetatable(o, self)\n self.__index = self\n return o\nend\n\n-- Derived class method printArea\n\nfunction Square:printArea ()\n print(\"The area of square is \",self.area)\nend\n\n-- Creating an object\nmysquare = Square:new(nil,10)\nmysquare:printArea()\n\nRectangle = Shape:new()\n\n-- Derived class method new\n\nfunction Rectangle:new (o,length,breadth)\n o = o or Shape:new(o)\n setmetatable(o, self)\n self.__index = self\n self.area = length * breadth\n return o\nend\n\n-- Derived class method printArea\n\nfunction Rectangle:printArea ()\n print(\"The area of Rectangle is \",self.area)\nend\n\n-- Creating an object\n\nmyrectangle = Rectangle:new(nil,10,20)\nmyrectangle:printArea()" }, { "code": null, "e": 8975, "s": 8909, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 9050, "s": 8975, "text": "The area is \t100\nThe area of square is \t100\nThe area of Rectangle is \t200\n" }, { "code": null, "e": 9305, "s": 9050, "text": "In the above example, we have created two derived classes − Rectangle and Square from the base class Square. It is possible to override the functions of the base class in derived class. In this example, the derived class overrides the function printArea." }, { "code": null, "e": 9338, "s": 9305, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 9352, "s": 9338, "text": " Manish Gupta" }, { "code": null, "e": 9385, "s": 9352, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 9401, "s": 9385, "text": " Sanjeev Mittal" }, { "code": null, "e": 9436, "s": 9401, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9452, "s": 9436, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 9459, "s": 9452, "text": " Print" }, { "code": null, "e": 9470, "s": 9459, "text": " Add Notes" } ]
AWK - Ternary Operator
We can easily implement a condition expression using ternary operator. The following example demonstrates this − condition expression ? statement1 : statement2 When the condition expression returns true, statement1 gets executed; otherwise statement2 is executed. For instance, the following example finds the largest number from two given numbers. [jerry]$ awk 'BEGIN { a = 10; b = 20; (a > b) ? max = a : max = b; print "Max =", max}' On executing this code, you get the following result − Max = 20 Print Add Notes Bookmark this page
[ { "code": null, "e": 1970, "s": 1857, "text": "We can easily implement a condition expression using ternary operator. The following example demonstrates this −" }, { "code": null, "e": 2018, "s": 1970, "text": "condition expression ? statement1 : statement2\n" }, { "code": null, "e": 2207, "s": 2018, "text": "When the condition expression returns true, statement1 gets executed; otherwise statement2 is executed. For instance, the following example finds the largest number from two given numbers." }, { "code": null, "e": 2295, "s": 2207, "text": "[jerry]$ awk 'BEGIN { a = 10; b = 20; (a > b) ? max = a : max = b; print \"Max =\", max}'" }, { "code": null, "e": 2350, "s": 2295, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2360, "s": 2350, "text": "Max = 20\n" }, { "code": null, "e": 2367, "s": 2360, "text": " Print" }, { "code": null, "e": 2378, "s": 2367, "text": " Add Notes" } ]
Construct a Turing Machine for language L = {wwr | w ∈ {0, 1}} - GeeksforGeeks
08 May, 2018 Prerequisite – Turing MachineThe language L = {wwr | w ∈ {0, 1}} represents a kind of language where you use only 2 character, i.e., 0 and 1. The first part of language can be any string of 0 and 1. The second part is the reverse of the first part. Combining both these parts out string will be formed. Any such string which falls in this category will be accepted by this language. The beginning and end of string is marked by $ sign. For example, if first part w = 1 1 0 0 1 then second part wr = 1 0 0 1 1. It is clearly visible that wr is the reverse of w, so the string 1 1 0 0 1 1 0 0 1 1 is a part of given language. Examples – Input : 0 0 1 1 1 1 0 0 Output : Accepted Input : 1 0 1 0 0 1 0 1 Output : Accepted Basic Representation – Assumption: We will replace 0 by Y and 1 by X. Approach Used –First check the first symbol, if it’s 0 then replace it by Y and by X if it’s 1. Then go to the end of string. So last symbol is same as first. We replace it also by X or Y depending on it.Now again come back to the position next to the symbol replace from the starting and repeat the same process as told above. One important thing to note is that since wr is reverse of w of both of them will have equal number of symbols. Every time replace a nth symbol from beginning of string, replace a corresponding nth symbol from the end. Step-1:If symbol is 0 replace it by Y and move right, Go to state Q2If symbol is 1 replace it by X and move right, Go to state Q1 Step-2:If symbol is 0 replace it by 0 and move right, remain on same stateIf symbol is 1 replace it by 1 and move right, remain on same state——————————————————————-If symbol is X replace it by X and move right, Go to state Q3If symbol is Y replace it by Y and move right, Go to state Q3If symbol is $ replace it by $ and move right, Go to state Q3 Step-3:If symbol is 1 replace it by X and move left, Go to state Q4If symbol is 0 replace it by Y and move left, Go to state Q5 Step-4:If symbol is 1 replace it by 1 and move leftIf symbol is 0 replace it by 0 and move leftRemain on same state Step-5:If symbol is X replace it by X and move rightIf symbol is Y replace it by Y and move rightGo to state Q0 Step-6:If symbol is X replace it by X and move rightIf symbol is Y replace it by Y and move rightGo to state Q6ELSEGo to step 1 Step-7:If symbol is X replace it by X and move right, Remain on same stateIf symbol is Y replace it by Y and move right, Remain on same stateIf symbol is $ replace it by $ and move left, STRING IS ACCEPTED, GO TO FINAL STATE Q7 GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Layers of OSI Model ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Difference between DFA and NFA Design 101 sequence detector (Mealy machine) Conversion of Epsilon-NFA to NFA Boyer-Moore Majority Voting Algorithm Regular expression to ∈-NFA
[ { "code": null, "e": 29756, "s": 29728, "text": "\n08 May, 2018" }, { "code": null, "e": 30192, "s": 29756, "text": "Prerequisite – Turing MachineThe language L = {wwr | w ∈ {0, 1}} represents a kind of language where you use only 2 character, i.e., 0 and 1. The first part of language can be any string of 0 and 1. The second part is the reverse of the first part. Combining both these parts out string will be formed. Any such string which falls in this category will be accepted by this language. The beginning and end of string is marked by $ sign." }, { "code": null, "e": 30380, "s": 30192, "text": "For example, if first part w = 1 1 0 0 1 then second part wr = 1 0 0 1 1. It is clearly visible that wr is the reverse of w, so the string 1 1 0 0 1 1 0 0 1 1 is a part of given language." }, { "code": null, "e": 30391, "s": 30380, "text": "Examples –" }, { "code": null, "e": 30477, "s": 30391, "text": "Input : 0 0 1 1 1 1 0 0\nOutput : Accepted\nInput : 1 0 1 0 0 1 0 1 \nOutput : Accepted\n" }, { "code": null, "e": 30500, "s": 30477, "text": "Basic Representation –" }, { "code": null, "e": 30547, "s": 30500, "text": "Assumption: We will replace 0 by Y and 1 by X." }, { "code": null, "e": 30875, "s": 30547, "text": "Approach Used –First check the first symbol, if it’s 0 then replace it by Y and by X if it’s 1. Then go to the end of string. So last symbol is same as first. We replace it also by X or Y depending on it.Now again come back to the position next to the symbol replace from the starting and repeat the same process as told above." }, { "code": null, "e": 31094, "s": 30875, "text": "One important thing to note is that since wr is reverse of w of both of them will have equal number of symbols. Every time replace a nth symbol from beginning of string, replace a corresponding nth symbol from the end." }, { "code": null, "e": 31224, "s": 31094, "text": "Step-1:If symbol is 0 replace it by Y and move right, Go to state Q2If symbol is 1 replace it by X and move right, Go to state Q1" }, { "code": null, "e": 31572, "s": 31224, "text": "Step-2:If symbol is 0 replace it by 0 and move right, remain on same stateIf symbol is 1 replace it by 1 and move right, remain on same state——————————————————————-If symbol is X replace it by X and move right, Go to state Q3If symbol is Y replace it by Y and move right, Go to state Q3If symbol is $ replace it by $ and move right, Go to state Q3" }, { "code": null, "e": 31700, "s": 31572, "text": "Step-3:If symbol is 1 replace it by X and move left, Go to state Q4If symbol is 0 replace it by Y and move left, Go to state Q5" }, { "code": null, "e": 31816, "s": 31700, "text": "Step-4:If symbol is 1 replace it by 1 and move leftIf symbol is 0 replace it by 0 and move leftRemain on same state" }, { "code": null, "e": 31928, "s": 31816, "text": "Step-5:If symbol is X replace it by X and move rightIf symbol is Y replace it by Y and move rightGo to state Q0" }, { "code": null, "e": 32056, "s": 31928, "text": "Step-6:If symbol is X replace it by X and move rightIf symbol is Y replace it by Y and move rightGo to state Q6ELSEGo to step 1" }, { "code": null, "e": 32284, "s": 32056, "text": "Step-7:If symbol is X replace it by X and move right, Remain on same stateIf symbol is Y replace it by Y and move right, Remain on same stateIf symbol is $ replace it by $ and move left, STRING IS ACCEPTED, GO TO FINAL STATE Q7" }, { "code": null, "e": 32292, "s": 32284, "text": "GATE CS" }, { "code": null, "e": 32325, "s": 32292, "text": "Theory of Computation & Automata" }, { "code": null, "e": 32423, "s": 32325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32432, "s": 32423, "text": "Comments" }, { "code": null, "e": 32445, "s": 32432, "text": "Old Comments" }, { "code": null, "e": 32465, "s": 32445, "text": "Layers of OSI Model" }, { "code": null, "e": 32489, "s": 32465, "text": "ACID Properties in DBMS" }, { "code": null, "e": 32516, "s": 32489, "text": "Types of Operating Systems" }, { "code": null, "e": 32537, "s": 32516, "text": "Normal Forms in DBMS" }, { "code": null, "e": 32586, "s": 32537, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 32617, "s": 32586, "text": "Difference between DFA and NFA" }, { "code": null, "e": 32662, "s": 32617, "text": "Design 101 sequence detector (Mealy machine)" }, { "code": null, "e": 32695, "s": 32662, "text": "Conversion of Epsilon-NFA to NFA" }, { "code": null, "e": 32733, "s": 32695, "text": "Boyer-Moore Majority Voting Algorithm" } ]
Types of Software Testing
24 Jun, 2022 Testing is the process of executing a program to find errors. To make our software perform well it should be error-free. If testing is done successfully it will remove all the errors from the software. (i) All the tests should meet the customer requirements.(ii) To make our software testing should be performed by a third party.(iii) Exhaustive testing is not possible. As we need the optimal amount of testing based on the risk assessment of the application. (iv) All the tests to be conducted should be planned before implementing it (v) It follows the Pareto rule(80/20 rule) which states that 80% of errors come from 20% of program components. (vi) Start testing with small parts and extend it to large parts. It focuses on the smallest unit of software design. In this, we test an individual unit or group of interrelated units. It is often done by the programmer by using sample input and observing its corresponding outputs. Example: a) In a program we are checking if the loop, method, or function is working fine b) Misunderstood or incorrect, arithmetic precedence. c) Incorrect initialization The objective is to take unit-tested components and build a program structure that has been dictated by design. Integration testing is testing in which a group of components is combined to produce output. Integration testing is of four types: (i) Top-down (ii) Bottom-up (iii) Sandwich (iv) Big-Bang Example: (a) Black Box testing:- It is used for validation. In this, we ignore internal working mechanisms and focus on what is the output?. (b) White box testing:- It is used for verification. In this, we focus on internal mechanisms i.e. how the output is achieved? Every time a new module is added leads to changes in the program. This type of testing makes sure that the whole component works properly even after adding components to the complete program. Example In school, record suppose we have module staff, students and finance combining these modules and checking if on integration of these modules works fine in regression testing This test is done to make sure that the software under testing is ready or stable for further testing It is called a smoke test as the testing of an initial pass is done to check if it did not catch the fire or smoke in the initial switch on. Example: If the project has 2 modules so before going to the module make sure that module 1 works properly This is a type of validation testing. It is a type of acceptance testing which is done before the product is released to customers. It is typically done by QA people. Example: When software testing is performed internally within the organization The beta test is conducted at one or more customer sites by the end-user of the software. This version is released for a limited number of users for testing in a real-time environment Example: When software testing is performed for the limited number of people This software is tested such that it works fine for the different operating systems. It is covered under the black box testing technique. In this, we just focus on the required input and output without focusing on internal working. In this, we have security testing, recovery testing, stress testing, and performance testing Example: This includes functional as well as nonfunctional testing In this, we give unfavorable conditions to the system and check how they perform in those conditions. Example: (a) Test cases that require maximum memory or other resources are executed (b) Test cases that may cause thrashing in a virtual operating system (c) Test cases that may cause excessive disk requirement It is designed to test the run-time performance of software within the context of an integrated system. It is used to test the speed and effectiveness of the program. It is also called load testing. In it we check, what is the performance of the system in the given load.Example: Checking several processor cycles. This testing is a combination of various testing techniques that help to verify and validate object-oriented software. This testing is done in the following manner: Testing of Requirements, Design and Analysis of Testing, Testing of Code, Integration testing, System testing, User Testing. Acceptance testing is done by the customers to check whether the delivered products perform the desired tasks or not, as stated in requirements. We use this OOT, for discussing test plans and for executing the projects. This article is contributed by Kritka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. pp_pankaj agnneil kushalkrajput752000 simmytarika5 guptavivek0503 geeky01adarsh Software Testing GBlog Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 255, "s": 52, "text": "Testing is the process of executing a program to find errors. To make our software perform well it should be error-free. If testing is done successfully it will remove all the errors from the software. " }, { "code": null, "e": 769, "s": 255, "text": "(i) All the tests should meet the customer requirements.(ii) To make our software testing should be performed by a third party.(iii) Exhaustive testing is not possible. As we need the optimal amount of testing based on the risk assessment of the application. (iv) All the tests to be conducted should be planned before implementing it (v) It follows the Pareto rule(80/20 rule) which states that 80% of errors come from 20% of program components. (vi) Start testing with small parts and extend it to large parts. " }, { "code": null, "e": 988, "s": 769, "text": "It focuses on the smallest unit of software design. In this, we test an individual unit or group of interrelated units. It is often done by the programmer by using sample input and observing its corresponding outputs. " }, { "code": null, "e": 997, "s": 988, "text": "Example:" }, { "code": null, "e": 1164, "s": 997, "text": "a) In a program we are checking if the loop, method, or \n function is working fine\nb) Misunderstood or incorrect, arithmetic precedence.\nc) Incorrect initialization" }, { "code": null, "e": 1370, "s": 1164, "text": "The objective is to take unit-tested components and build a program structure that has been dictated by design. Integration testing is testing in which a group of components is combined to produce output. " }, { "code": null, "e": 1474, "s": 1370, "text": "Integration testing is of four types: (i) Top-down (ii) Bottom-up (iii) Sandwich (iv) Big-Bang Example:" }, { "code": null, "e": 1737, "s": 1474, "text": "(a) Black Box testing:- It is used for validation. \nIn this, we ignore internal working mechanisms and \nfocus on what is the output?.\n\n(b) White box testing:- It is used for verification. \nIn this, we focus on internal mechanisms i.e.\nhow the output is achieved?" }, { "code": null, "e": 1938, "s": 1737, "text": "Every time a new module is added leads to changes in the program. This type of testing makes sure that the whole component works properly even after adding components to the complete program. Example " }, { "code": null, "e": 2115, "s": 1938, "text": "In school, record suppose we have module staff, students \nand finance combining these modules and checking if on \nintegration of these modules works fine in regression testing " }, { "code": null, "e": 2368, "s": 2115, "text": "This test is done to make sure that the software under testing is ready or stable for further testing It is called a smoke test as the testing of an initial pass is done to check if it did not catch the fire or smoke in the initial switch on. Example: " }, { "code": null, "e": 2467, "s": 2368, "text": "If the project has 2 modules so before going to the module \nmake sure that module 1 works properly" }, { "code": null, "e": 2644, "s": 2467, "text": "This is a type of validation testing. It is a type of acceptance testing which is done before the product is released to customers. It is typically done by QA people. Example: " }, { "code": null, "e": 2714, "s": 2644, "text": "When software testing is performed internally within\nthe organization" }, { "code": null, "e": 2908, "s": 2714, "text": "The beta test is conducted at one or more customer sites by the end-user of the software. This version is released for a limited number of users for testing in a real-time environment Example: " }, { "code": null, "e": 2976, "s": 2908, "text": "When software testing is performed for the limited\nnumber of people" }, { "code": null, "e": 3311, "s": 2976, "text": "This software is tested such that it works fine for the different operating systems. It is covered under the black box testing technique. In this, we just focus on the required input and output without focusing on internal working. In this, we have security testing, recovery testing, stress testing, and performance testing Example: " }, { "code": null, "e": 3370, "s": 3311, "text": "This includes functional as well as nonfunctional \ntesting" }, { "code": null, "e": 3482, "s": 3370, "text": "In this, we give unfavorable conditions to the system and check how they perform in those conditions. Example: " }, { "code": null, "e": 3693, "s": 3482, "text": "(a) Test cases that require maximum memory or other\n resources are executed\n(b) Test cases that may cause thrashing in a virtual \n operating system\n(c) Test cases that may cause excessive disk requirement" }, { "code": null, "e": 3974, "s": 3693, "text": "It is designed to test the run-time performance of software within the context of an integrated system. It is used to test the speed and effectiveness of the program. It is also called load testing. In it we check, what is the performance of the system in the given load.Example: " }, { "code": null, "e": 4009, "s": 3974, "text": "Checking several processor cycles." }, { "code": null, "e": 4175, "s": 4009, "text": "This testing is a combination of various testing techniques that help to verify and validate object-oriented software. This testing is done in the following manner: " }, { "code": null, "e": 4200, "s": 4175, "text": "Testing of Requirements," }, { "code": null, "e": 4232, "s": 4200, "text": "Design and Analysis of Testing," }, { "code": null, "e": 4249, "s": 4232, "text": "Testing of Code," }, { "code": null, "e": 4270, "s": 4249, "text": "Integration testing," }, { "code": null, "e": 4286, "s": 4270, "text": "System testing," }, { "code": null, "e": 4300, "s": 4286, "text": "User Testing." }, { "code": null, "e": 4447, "s": 4300, "text": "Acceptance testing is done by the customers to check whether the delivered products perform the desired tasks or not, as stated in requirements. " }, { "code": null, "e": 4522, "s": 4447, "text": "We use this OOT, for discussing test plans and for executing the projects." }, { "code": null, "e": 4813, "s": 4522, "text": "This article is contributed by Kritka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 4941, "s": 4813, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 4951, "s": 4941, "text": "pp_pankaj" }, { "code": null, "e": 4959, "s": 4951, "text": "agnneil" }, { "code": null, "e": 4979, "s": 4959, "text": "kushalkrajput752000" }, { "code": null, "e": 4992, "s": 4979, "text": "simmytarika5" }, { "code": null, "e": 5007, "s": 4992, "text": "guptavivek0503" }, { "code": null, "e": 5021, "s": 5007, "text": "geeky01adarsh" }, { "code": null, "e": 5038, "s": 5021, "text": "Software Testing" }, { "code": null, "e": 5044, "s": 5038, "text": "GBlog" }, { "code": null, "e": 5065, "s": 5044, "text": "Software Engineering" } ]
Java Program to Print the Elements of an Array
12 Nov, 2020 An array is to be created in java and elements will be stored in it. After successful insertion, all the elements of the array are printed present in the array. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. Users can access the elements simply by referring to the index number of the first element inserted. It is because of the traits of this data structure consisting of a group of like-typed variables in sequential order in the memory.that are referred to by a common name element by referring to the index number. In java, arrays do work differently as they do work in C/C++. In Java, all arrays are dynamically allocated. Since arrays are objects in Java, user can find their length using the object property length. This is different from C/C++ where length is calculated using function sizeof() A Java array variable can also be declared like other variables with [] after the data type. The variables in the array are ordered and each has an index beginning from 0. Java array can be also be used as a static field, a local variable, or a method parameter. The size of an array must be specified by an int value and not long or short. The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable. Examples: array_mame = {2 , 7 , 4 , 1 , 4} Output: 2 7 4 1 4 array_name = {2 , 7, -1 , 6 , -3} Output: 2 7 -1 6 -3 Approaches: Using loops Using standard library arrays Approach 1: Printing elements of an array using loops Algorithm: Declare and initialize an arrayLoop through the array by incrementing the value of the iterative variable/sPrint out each element of the array Declare and initialize an array Loop through the array by incrementing the value of the iterative variable/s Print out each element of the array Implementation: Below is the java example illustrating printing elements of an array Java // Java Program to Print the Elements of an Array// Using loops (considering for loop here)public class GFG { // Main driver method public static void main(String[] args) { // Initialize array of random numbers and size // Suppose array named 'arr' contains 9 elements int[] arr = { -7, -5, 5, 10, 0, 3, 20, 25, 12 }; System.out.print("Elements of given array are: "); // Looping through array by incrementing value of i //'i' is an index of array 'arr' for (int i = 0; i < arr.length; i++) { // Print array element present at index i System.out.print(arr[i] + " "); } }} Output : Elements of given array are: -7 -5 5 10 0 3 20 25 12 Time Complexity: O(n) Here other no major execution is taking place except just the cell memory taken by variables that even get destroyed as the scope is over. Whenever there is iteration just by using one loop time taken is of the order of n always. If nested then the order of number of loops that are nested Space Complexity: O(n) As whatever loop is used considering the worst case where the complete array is filled up, so it takes up simply the space taken by the array in memory. Approach 2: Printing elements of an array using standard library arrays Algorithm: Declare and initialize an arrayUse Arrays.toString() function inside the print statement to print array Declare and initialize an array Use Arrays.toString() function inside the print statement to print array Implementation: Java Program to print the elements of an array using standard library arrays: Java // Java Program to Print the Elements of an Array // Importing specific array class// so as to use inbuilt functionsimport java.util.Arrays; public class GFG { // Main driver method public static void main(String[] args) { // Initialize array // Array 'arr' contains 9 elements int[] arr = { -7, -5, 5, 10, 0, 3, 20, 25, 12 }; System.out.print("Elements of given array are: "); // Pass the array 'arr' in Arrays.toString() // function to print array System.out.println(Arrays.toString(arr)); }} Output : Elements of given array are: [-7, -5, 5, 10, 0, 3, 20, 25, 12] Time Complexity: O(n) Space Complexity: O(n) Java-Array-Programs Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Nov, 2020" }, { "code": null, "e": 189, "s": 28, "text": "An array is to be created in java and elements will be stored in it. After successful insertion, all the elements of the array are printed present in the array." }, { "code": null, "e": 682, "s": 189, "text": "Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. Users can access the elements simply by referring to the index number of the first element inserted. It is because of the traits of this data structure consisting of a group of like-typed variables in sequential order in the memory.that are referred to by a common name element by referring to the index number. In java, arrays do work differently as they do work in C/C++." }, { "code": null, "e": 729, "s": 682, "text": "In Java, all arrays are dynamically allocated." }, { "code": null, "e": 905, "s": 729, "text": "Since arrays are objects in Java, user can find their length using the object property length. This is different from C/C++ where length is calculated using function sizeof()" }, { "code": null, "e": 998, "s": 905, "text": "A Java array variable can also be declared like other variables with [] after the data type." }, { "code": null, "e": 1077, "s": 998, "text": "The variables in the array are ordered and each has an index beginning from 0." }, { "code": null, "e": 1168, "s": 1077, "text": "Java array can be also be used as a static field, a local variable, or a method parameter." }, { "code": null, "e": 1246, "s": 1168, "text": "The size of an array must be specified by an int value and not long or short." }, { "code": null, "e": 1296, "s": 1246, "text": "The direct superclass of an array type is Object." }, { "code": null, "e": 1375, "s": 1296, "text": "Every array type implements the interfaces Cloneable and java.io.Serializable." }, { "code": null, "e": 1385, "s": 1375, "text": "Examples:" }, { "code": null, "e": 1492, "s": 1385, "text": "array_mame = {2 , 7 , 4 , 1 , 4}\nOutput: 2 7 4 1 4\n\narray_name = {2 , 7, -1 , 6 , -3}\nOutput: 2 7 -1 6 -3\n" }, { "code": null, "e": 1504, "s": 1492, "text": "Approaches:" }, { "code": null, "e": 1516, "s": 1504, "text": "Using loops" }, { "code": null, "e": 1546, "s": 1516, "text": "Using standard library arrays" }, { "code": null, "e": 1600, "s": 1546, "text": "Approach 1: Printing elements of an array using loops" }, { "code": null, "e": 1611, "s": 1600, "text": "Algorithm:" }, { "code": null, "e": 1755, "s": 1611, "text": " Declare and initialize an arrayLoop through the array by incrementing the value of the iterative variable/sPrint out each element of the array" }, { "code": null, "e": 1788, "s": 1755, "text": " Declare and initialize an array" }, { "code": null, "e": 1865, "s": 1788, "text": "Loop through the array by incrementing the value of the iterative variable/s" }, { "code": null, "e": 1901, "s": 1865, "text": "Print out each element of the array" }, { "code": null, "e": 1917, "s": 1901, "text": "Implementation:" }, { "code": null, "e": 1986, "s": 1917, "text": "Below is the java example illustrating printing elements of an array" }, { "code": null, "e": 1991, "s": 1986, "text": "Java" }, { "code": "// Java Program to Print the Elements of an Array// Using loops (considering for loop here)public class GFG { // Main driver method public static void main(String[] args) { // Initialize array of random numbers and size // Suppose array named 'arr' contains 9 elements int[] arr = { -7, -5, 5, 10, 0, 3, 20, 25, 12 }; System.out.print(\"Elements of given array are: \"); // Looping through array by incrementing value of i //'i' is an index of array 'arr' for (int i = 0; i < arr.length; i++) { // Print array element present at index i System.out.print(arr[i] + \" \"); } }}", "e": 2663, "s": 1991, "text": null }, { "code": null, "e": 2672, "s": 2663, "text": "Output :" }, { "code": null, "e": 2727, "s": 2672, "text": "Elements of given array are: -7 -5 5 10 0 3 20 25 12 \n" }, { "code": null, "e": 3039, "s": 2727, "text": "Time Complexity: O(n) Here other no major execution is taking place except just the cell memory taken by variables that even get destroyed as the scope is over. Whenever there is iteration just by using one loop time taken is of the order of n always. If nested then the order of number of loops that are nested" }, { "code": null, "e": 3215, "s": 3039, "text": "Space Complexity: O(n) As whatever loop is used considering the worst case where the complete array is filled up, so it takes up simply the space taken by the array in memory." }, { "code": null, "e": 3287, "s": 3215, "text": "Approach 2: Printing elements of an array using standard library arrays" }, { "code": null, "e": 3298, "s": 3287, "text": "Algorithm:" }, { "code": null, "e": 3404, "s": 3298, "text": "Declare and initialize an arrayUse Arrays.toString() function inside the print statement to print array " }, { "code": null, "e": 3436, "s": 3404, "text": "Declare and initialize an array" }, { "code": null, "e": 3511, "s": 3436, "text": "Use Arrays.toString() function inside the print statement to print array " }, { "code": null, "e": 3527, "s": 3511, "text": "Implementation:" }, { "code": null, "e": 3605, "s": 3527, "text": "Java Program to print the elements of an array using standard library arrays:" }, { "code": null, "e": 3610, "s": 3605, "text": "Java" }, { "code": "// Java Program to Print the Elements of an Array // Importing specific array class// so as to use inbuilt functionsimport java.util.Arrays; public class GFG { // Main driver method public static void main(String[] args) { // Initialize array // Array 'arr' contains 9 elements int[] arr = { -7, -5, 5, 10, 0, 3, 20, 25, 12 }; System.out.print(\"Elements of given array are: \"); // Pass the array 'arr' in Arrays.toString() // function to print array System.out.println(Arrays.toString(arr)); }}", "e": 4176, "s": 3610, "text": null }, { "code": null, "e": 4185, "s": 4176, "text": "Output :" }, { "code": null, "e": 4249, "s": 4185, "text": "Elements of given array are: [-7, -5, 5, 10, 0, 3, 20, 25, 12]\n" }, { "code": null, "e": 4271, "s": 4249, "text": "Time Complexity: O(n)" }, { "code": null, "e": 4294, "s": 4271, "text": "Space Complexity: O(n)" }, { "code": null, "e": 4314, "s": 4294, "text": "Java-Array-Programs" }, { "code": null, "e": 4321, "s": 4314, "text": "Picked" }, { "code": null, "e": 4326, "s": 4321, "text": "Java" }, { "code": null, "e": 4340, "s": 4326, "text": "Java Programs" }, { "code": null, "e": 4345, "s": 4340, "text": "Java" }, { "code": null, "e": 4443, "s": 4345, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4458, "s": 4443, "text": "Stream In Java" }, { "code": null, "e": 4479, "s": 4458, "text": "Introduction to Java" }, { "code": null, "e": 4500, "s": 4479, "text": "Constructors in Java" }, { "code": null, "e": 4519, "s": 4500, "text": "Exceptions in Java" }, { "code": null, "e": 4536, "s": 4519, "text": "Generics in Java" }, { "code": null, "e": 4562, "s": 4536, "text": "Java Programming Examples" }, { "code": null, "e": 4596, "s": 4562, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4643, "s": 4596, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4681, "s": 4643, "text": "Factory method design pattern in Java" } ]
for loop – Django Template Tags
11 Jan, 2022 A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, extends etc.This article revolves about how to use for tag in Templates. for tag loops over each item in an array, making the item available in a context variable. {% for i in list %} {% endfor %} For example, to display a list of athletes provided in athlete_list: html <ul>{% for athlete in athlete_list %} <li>{{ athlete.name }}</li>{% endfor %}</ul> Illustration of How to use for tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Now create a view through which we will pass the context dictionary,In geeks/views.py, Python3 # import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { "data" : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], } # return response return render(request, "geeks.html", context) Create a url path to map to this view. In geeks/urls.py, Python3 from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),] html {% for i in data %} <div class="row"> {{ i }} </div>{% endfor %} One can use variables, too. For example, if you have two template variables, rowvalue1 and rowvalue2, you can alternate between their values like this: html {% for o in some_list %} <tr class="{% cycle rowvalue1 rowvalue2 %}"> ... </tr>{% endfor %} One can loop over a list in reverse by using {% for obj in list reversed %}. If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of (x, y) coordinates called points, you could use the following to output the list of points: {% for x, y in points %} There is a point at {{ x }}, {{ y }} {% endfor %} This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary: {% for key, value in data.items %} {{ key }}: {{ value }} {% endfor %} surindertarika1234 Django-templates Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jan, 2022" }, { "code": null, "e": 590, "s": 52, "text": "A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, extends etc.This article revolves about how to use for tag in Templates. for tag loops over each item in an array, making the item available in a context variable." }, { "code": null, "e": 624, "s": 590, "text": "{% for i in list %}\n{% endfor %}\n" }, { "code": null, "e": 693, "s": 624, "text": "For example, to display a list of athletes provided in athlete_list:" }, { "code": null, "e": 698, "s": 693, "text": "html" }, { "code": "<ul>{% for athlete in athlete_list %} <li>{{ athlete.name }}</li>{% endfor %}</ul>", "e": 784, "s": 698, "text": null }, { "code": null, "e": 923, "s": 784, "text": "Illustration of How to use for tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 1010, "s": 923, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 1061, "s": 1010, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1094, "s": 1061, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1181, "s": 1094, "text": "Now create a view through which we will pass the context dictionary,In geeks/views.py," }, { "code": null, "e": 1189, "s": 1181, "text": "Python3" }, { "code": "# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { \"data\" : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], } # return response return render(request, \"geeks.html\", context)", "e": 1468, "s": 1189, "text": null }, { "code": null, "e": 1525, "s": 1468, "text": "Create a url path to map to this view. In geeks/urls.py," }, { "code": null, "e": 1533, "s": 1525, "text": "Python3" }, { "code": "from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),]", "e": 1667, "s": 1533, "text": null }, { "code": null, "e": 1672, "s": 1667, "text": "html" }, { "code": "{% for i in data %} <div class=\"row\"> {{ i }} </div>{% endfor %}", "e": 1750, "s": 1672, "text": null }, { "code": null, "e": 1902, "s": 1750, "text": "One can use variables, too. For example, if you have two template variables, rowvalue1 and rowvalue2, you can alternate between their values like this:" }, { "code": null, "e": 1907, "s": 1902, "text": "html" }, { "code": "{% for o in some_list %} <tr class=\"{% cycle rowvalue1 rowvalue2 %}\"> ... </tr>{% endfor %}", "e": 2012, "s": 1907, "text": null }, { "code": null, "e": 2089, "s": 2012, "text": "One can loop over a list in reverse by using {% for obj in list reversed %}." }, { "code": null, "e": 2340, "s": 2089, "text": "If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of (x, y) coordinates called points, you could use the following to output the list of points:" }, { "code": null, "e": 2419, "s": 2340, "text": "{% for x, y in points %}\n There is a point at {{ x }}, {{ y }}\n{% endfor %}" }, { "code": null, "e": 2617, "s": 2419, "text": "This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:" }, { "code": null, "e": 2692, "s": 2617, "text": "{% for key, value in data.items %}\n {{ key }}: {{ value }}\n{% endfor %}" }, { "code": null, "e": 2711, "s": 2692, "text": "surindertarika1234" }, { "code": null, "e": 2728, "s": 2711, "text": "Django-templates" }, { "code": null, "e": 2742, "s": 2728, "text": "Python Django" }, { "code": null, "e": 2749, "s": 2742, "text": "Python" } ]
Check for possible path in 2D matrix
22 Feb, 2022 Given a 2D array(m x n). The task is to check if there is any path from top left to bottom right. In the matrix, -1 is considered as blockage (can’t go through this cell) and 0 is considered path cell (can go through it). Note: Top left cell always contains 0 Examples: Input : arr[][] = {{ 0, 0, 0, -1, 0}, {-1, 0, 0, -1, -1}, { 0, 0, 0, -1, 0}, {-1, 0, 0, 0, 0}, { 0, 0, -1, 0, 0}} Output : Yes Explanation: The red cells are blocked, white cell denotes the path and the green cells are not blocked cells. Input : arr[][] = {{ 0, 0, 0, -1, 0}, {-1, 0, 0, -1, -1}, { 0, 0, 0, -1, 0}, {-1, 0, -1, 0, 0}, { 0, 0, -1, 0, 0}} Output : No Explanation: There exists no path from start to end. The red cells are blocked, white cell denotes the path and the green cells are not blocked cells. Method 1 Approach: The solution is to perform BFS or DFS to find whether there is a path or not. The graph needs not to be created to perform the bfs, but the matrix itself will be used as a graph. Start the traversal from the top right corner and if there is a way to reach the bottom right corner then there is a path. Algorithm: Create a queue that stores pairs (i,j) and insert the (0,0) in the queue.Run a loop till the queue is empty.In each iteration dequeue the queue (a,b), if the front element is the destination (row-1,col-1) then return 1, i,e there is a path and change the value of mat[a][b] to -1, i.e. visited.Else insert the adjacent indices where the value of matrix[i][j] is not -1. Create a queue that stores pairs (i,j) and insert the (0,0) in the queue.Run a loop till the queue is empty.In each iteration dequeue the queue (a,b), if the front element is the destination (row-1,col-1) then return 1, i,e there is a path and change the value of mat[a][b] to -1, i.e. visited.Else insert the adjacent indices where the value of matrix[i][j] is not -1. Create a queue that stores pairs (i,j) and insert the (0,0) in the queue. Run a loop till the queue is empty. In each iteration dequeue the queue (a,b), if the front element is the destination (row-1,col-1) then return 1, i,e there is a path and change the value of mat[a][b] to -1, i.e. visited. Else insert the adjacent indices where the value of matrix[i][j] is not -1. Implementation: C++ Java Python3 Javascript // C++ program to find if there is path// from top left to right bottom#include <bits/stdc++.h>using namespace std; #define row 5#define col 5 // to find the path from// top left to bottom rightbool isPath(int arr[row][col]){ // directions int dir[4][2] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; // queue queue<pair<int, int> > q; // insert the top right corner. q.push(make_pair(0, 0)); // until queue is empty while (q.size() > 0) { pair<int, int> p = q.front(); q.pop(); // mark as visited arr[p.first][p.second] = -1; // destination is reached. if (p == make_pair(row - 1, col - 1)) return true; // check all four directions for (int i = 0; i < 4; i++) { // using the direction array int a = p.first + dir[i][0]; int b = p.second + dir[i][1]; // not blocked and valid if (arr[a][b] != -1 && a >= 0 && b >= 0 && a < row && b < col) { q.push(make_pair(a, b)); } } } return false;} // Driver Codeint main(){ // Given array int arr[row][col] = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, 0, 0, 0 }, { 0, 0, -1, 0, 0 } }; // path from arr[0][0] to arr[row][col] if (isPath(arr)) cout << "Yes"; else cout << "No"; return 0;} // Java program to find if there is path// from top left to right bottomimport java.io.*;import java.util.*; class pair { int Item1, Item2; pair(int f, int s) { Item1 = f; Item2 = s; }} class GFG { static int row = 5; static int col = 5; // To find the path from // top left to bottom right static boolean isPath(int[][] arr) { // Directions int[][] dir = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; // Queue Queue<pair> q = new LinkedList<>(); // Insert the top right corner. q.add(new pair(0, 0)); // Until queue is empty while (q.size() > 0) { pair p = (q.peek()); q.remove(); // Mark as visited arr[p.Item1][p.Item2] = -1; // Destination is reached. if (p.Item1 == row - 1 && p.Item2 == col - 1) return true; // Check all four directions for (int i = 0; i < 4; i++) { // Using the direction array int a = p.Item1 + dir[i][0]; int b = p.Item2 + dir[i][1]; // Not blocked and valid if (a >= 0 && b >= 0 && a < row && b < col && arr[a][b] != -1) { if (a == row - 1 && b == col - 1) return true; q.add(new pair(a, b)); } } } return false; } // Driver Code public static void main(String[] args) { // Given array int[][] arr = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, 0, 0, 0 }, { 0, 0, -1, 0, 0 } }; // Path from arr[0][0] to arr[row][col] if (isPath(arr)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by avanitrachhadiya2155 # Python3 program to find if there is path# from top left to right bottomrow = 5col = 5 # to find the path from# top left to bottom rightdef isPath(arr) : # directions Dir = [ [0, 1], [0, -1], [1, 0], [-1, 0]] # queue q = [] # insert the top right corner. q.append((0, 0)) # until queue is empty while(len(q) > 0) : p = q[0] q.pop(0) # mark as visited arr[p[0]][p[1]] = -1 # destination is reached. if(p == (row - 1, col - 1)) : return True # check all four directions for i in range(4) : # using the direction array a = p[0] + Dir[i][0] b = p[1] + Dir[i][1] # not blocked and valid if(a >= 0 and b >= 0 and a < row and b < col and arr[a][b] != -1) : q.append((a, b)) return False # Given arrayarr = [[ 0, 0, 0, -1, 0 ], [ -1, 0, 0, -1, -1], [ 0, 0, 0, -1, 0 ], [ -1, 0, 0, 0, 0 ], [ 0, 0, -1, 0, 0 ] ] # path from arr[0][0] to arr[row][col]if (isPath(arr)) : print("Yes")else : print("No") # This code is contributed by divyesh072019 <script> // JavaScript program to find if there is path // from top left to right bottom var row = 5;var col = 5; // To find the path from// top left to bottom rightfunction isPath(arr){ // Directions var dir = [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ]; // Queue var q = []; // Insert the top right corner. q.push([0, 0]); // Until queue is empty while (q.length > 0) { var p = q[0]; q.shift(); // Mark as visited arr[p[0]][p[1]] = -1; // Destination is reached. if (p[0]==row-1 && p[1]==col-1) return true; // Check all four directions for(var i = 0; i < 4; i++) { // Using the direction array var a = p[0] + dir[i][0]; var b = p[1] + dir[i][1]; // Not blocked and valid if (a >= 0 && b >= 0 && a < row && b < col && arr[a][b] != -1) { if (a==row - 1 && b==col - 1) return true; q.push([a,b]); } } } return false;} // Driver Code// Given arrayvar arr = [[ 0, 0, 0, -1, 0 ], [ -1, 0, 0, -1, -1], [ 0, 0, 0, -1, 0 ], [ -1, 0, 0, 0, 0 ], [ 0, 0, -1, 0, 0 ] ]; // Path from arr[0][0] to arr[row][col]if (isPath(arr)) document.write("Yes");else document.write("No"); </script> Output: No Complexity Analysis: Time Complexity: O(R*C). Every element of the matrix can be inserted once in the queue, so time Complexity is O(R*C).Space Complexity: O(R*C). To store all the elements in a queue O(R*C) space is needed. Time Complexity: O(R*C). Every element of the matrix can be inserted once in the queue, so time Complexity is O(R*C). Space Complexity: O(R*C). To store all the elements in a queue O(R*C) space is needed. Method 2 Approach: The only problem with the above solution is it uses extra space. This approach will eliminate the need for extra space. The basic idea is very similar. This algorithm will also perform BFS but the need for extra space will be eliminated by marking the array. So First run a loop and check which elements of the first column and the first row is accessible from 0,0 by using only the first row and column. mark them as 1. Now traverse the matrix from start to the end row-wise in increasing index of rows and columns. If the cell is not blocked then check that any of its adjacent cells is marked 1 or not. If marked 1 then mark the cell 1. Algorithm: Mark the cell 0,0 as 1.Run a loop from 0 to row length and if the cell above is marked 1 and the current cell is not blocked then mark the current cell as 1.Run a loop from 0 to column length and if the left cell is marked 1 and the current cell is not blocked then mark the current cell as 1.Traverse the matrix from start to the end row-wise in increasing index of rows and columns.If the cell is not blocked then check that any of its adjacent cells (check only the cell above and the cell to the left). is marked 1 or not. If marked 1 then mark the cell 1.If the cell (row-1, col-1) is marked 1 return true else return false. Mark the cell 0,0 as 1.Run a loop from 0 to row length and if the cell above is marked 1 and the current cell is not blocked then mark the current cell as 1.Run a loop from 0 to column length and if the left cell is marked 1 and the current cell is not blocked then mark the current cell as 1.Traverse the matrix from start to the end row-wise in increasing index of rows and columns.If the cell is not blocked then check that any of its adjacent cells (check only the cell above and the cell to the left). is marked 1 or not. If marked 1 then mark the cell 1.If the cell (row-1, col-1) is marked 1 return true else return false. Mark the cell 0,0 as 1. Run a loop from 0 to row length and if the cell above is marked 1 and the current cell is not blocked then mark the current cell as 1. Run a loop from 0 to column length and if the left cell is marked 1 and the current cell is not blocked then mark the current cell as 1. Traverse the matrix from start to the end row-wise in increasing index of rows and columns. If the cell is not blocked then check that any of its adjacent cells (check only the cell above and the cell to the left). is marked 1 or not. If marked 1 then mark the cell 1. If the cell (row-1, col-1) is marked 1 return true else return false. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to find if there is path// from top left to right bottom#include <iostream>using namespace std; #define row 5#define col 5 // to find the path from// top left to bottom rightbool isPath(int arr[row][col]){ // set arr[0][0] = 1 arr[0][0] = 1; // Mark reachable (from top left) nodes // in first row and first column. for (int i = 1; i < row; i++) if (arr[i][0] != -1) arr[i][0] = arr[i - 1][0]; for (int j = 1; j < col; j++) if (arr[0][j] != -1) arr[0][j] = arr[0][j - 1]; // Mark reachable nodes in remaining // matrix. for (int i = 1; i < row; i++) for (int j = 1; j < col; j++) if (arr[i][j] != -1) arr[i][j] = max(arr[i][j - 1], arr[i - 1][j]); // return yes if right bottom // index is 1 return (arr[row - 1][col - 1] == 1);} // Driver Codeint main(){ // Given array int arr[row][col] = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, -1, 0, -1 }, { 0, 0, -1, 0, 0 } }; // path from arr[0][0] to arr[row][col] if (isPath(arr)) cout << "Yes"; else cout << "No"; return 0;} // Java program to find if there is path// from top left to right bottomclass GFG{ // to find the path from // top left to bottom right static boolean isPath(int arr[][]) { // set arr[0][0] = 1 arr[0][0] = 1; // Mark reachable (from top left) nodes // in first row and first column. for (int i = 1; i < 5; i++) if (arr[0][i] != -1) arr[0][i] = arr[0][i - 1]; for (int j = 1; j < 5; j++) if (arr[j][0] != -1) arr[j][0] = arr[j - 1][0]; // Mark reachable nodes in // remaining matrix. for (int i = 1; i < 5; i++) for (int j = 1; j < 5; j++) if (arr[i][j] != -1) arr[i][j] = Math.max(arr[i][j - 1], arr[i - 1][j]); // return yes if right // bottom index is 1 return (arr[5 - 1][5 - 1] == 1); } //Driver code public static void main(String[] args) { // Given array int arr[][] = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, -1, 0, -1 }, { 0, 0, -1, 0, 0 } }; // path from arr[0][0] // to arr[row][col] if (isPath(arr)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed// by prerna saini # Python3 program to find if there# is path from top left to right bottomrow = 5col = 5 # to find the path from# top left to bottom rightdef isPath(arr): # set arr[0][0] = 1 arr[0][0] = 1 # Mark reachable (from top left) # nodes in first row and first column. for i in range(1, row): if (arr[i][0] != -1): arr[i][0] = arr[i-1][0] for j in range(1, col): if (arr[0][j] != -1): arr[0][j] = arr[0][j-1] # Mark reachable nodes in # remaining matrix. for i in range(1, row): for j in range(1, col): if (arr[i][j] != -1): arr[i][j] = max(arr[i][j - 1], arr[i - 1][j]) # return yes if right # bottom index is 1 return (arr[row - 1][col - 1] == 1) # Driver Code # Given arrayarr = [[ 0, 0, 0, -1, 0 ], [-1, 0, 0, -1, -1], [ 0, 0, 0, -1, 0 ], [-1, 0, -1, 0, -1], [ 0, 0, -1, 0, 0 ]] # path from arr[0][0] to arr[row][col]if (isPath(arr)): print("Yes")else: print("No") # This code is contributed# by sahilshelangia // C# program to find if there is path// from top left to right bottomusing System; class GFG{ // to find the path from // top left to bottom right static bool isPath(int [,]arr) { // set arr[0][0] = 1 arr[0, 0] = 1; // Mark reachable (from top left) nodes // in first row and first column. for (int i = 1; i < 5; i++) if (arr[i, 0] != -1) arr[i, 0] = arr[i - 1, 0]; for (int j = 1; j < 5; j++) if (arr[0,j] != -1) arr[0,j] = arr[0, j - 1]; // Mark reachable nodes in // remaining matrix. for (int i = 1; i < 5; i++) for (int j = 1; j < 5; j++) if (arr[i, j] != -1) arr[i, j] = Math.Max(arr[i, j - 1], arr[i - 1, j]); // return yes if right // bottom index is 1 return (arr[5 - 1, 5 - 1] == 1); } //Driver code public static void Main() { // Given array int [,]arr = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, -1, 0, -1 }, { 0, 0, -1, 0, 0 } }; // path from arr[0][0] // to arr[row][col] if (isPath(arr)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed// by vt_m <?php// PHP program to find if// there is path from top// left to right bottom$row = 5;$col = 5; // to find the path from// top left to bottom rightfunction isPath($arr){ global $row, $col; $arr[0][0] = 1; // Mark reachable (from // top left) nodes in // first row and first column. for ($i = 1; $i < $row; $i++) if ($arr[$i][0] != -1) $arr[$i][0] = $arr[$i - 1][0]; for ($j = 1; $j < $col; $j++) if ($arr[0][$j] != -1) $arr[0][$j] = $arr[0][$j - 1]; // Mark reachable nodes // in remaining matrix. for ($i = 1; $i < $row; $i++) for ($j = 1; $j < $col; $j++) if ($arr[$i][$j] != -1) $arr[$i][$j] = max($arr[$i][$j - 1], $arr[$i - 1][$j]); // return yes if right // bottom index is 1 return ($arr[$row - 1][$col - 1] == 1);} // Driver Code // Given array$arr = array(array(0, 0, 0, 1, 0), array(-1, 0, 0, -1, -1), array(0, 0, 0, -1, 0), array(-1, 0, -1, 0, -1), array(0, 0, -1, 0, 0)); // path from arr[0][0]// to arr[row][col]if (isPath($arr))echo "Yes";elseecho "No"; // This code is contributed by anuj_67.?> <script> // JavaScript program to find if there is path// from top left to right bottomvar arr = [[5], [5]]// to find the path from// top left to bottom rightfunction isPath(arr){ // set arr[0][0] = 1 arr[0][0] = 1; // Mark reachable (from top left) nodes // in first row and first column. for (var i = 1; i < 5; i++) if (arr[i][0] != -1) arr[i][0] = arr[i - 1][0]; for (var j = 1; j < 5; j++) if (arr[0][j] != -1) arr[0][j] = arr[0][j - 1]; // Mark reachable nodes in remaining // matrix. for (var i = 1; i < 5; i++) for (var j = 1; j < 5; j++) if (arr[i][j] != -1) arr[i][j] = Math.max(arr[i][j - 1], arr[i - 1][j]); // return yes if right bottom // index is 1 return (arr[5 - 1][5 - 1] == 1);} // Driver Code // Given array var arr = [ [ 0, 0, 0, -1, 0 ], [ -1, 0, 0, -1, -1 ], [ 0, 0, 0, -1, 0 ], [ -1, 0, -1, 0, -1 ], [ 0, 0, -1, 0, 0 ] ]; // path from arr[0][0] to arr[row][col] if (isPath(arr)) document.write("Yes"); else document.write("No"); // This code is contributed by Mayank Tyagi </script> Output: No Complexity Analysis: Time Complexity: O(R*C). Every element of the matrix is traversed, so time Complexity is O(R*C).Space Complexity: O(1). No extra space is needed. Time Complexity: O(R*C). Every element of the matrix is traversed, so time Complexity is O(R*C). Space Complexity: O(1). No extra space is needed. vt_m sahilshelangia RedKnightro yashjaiswal10 andrew1234 coderboy2901 divyeshrabadiya07 divyesh072019 mayanktyagi1709 itsok avanitrachhadiya2155 nehakumariintern Dynamic Programming Matrix Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in an undirected graph Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Bellman–Ford Algorithm | DP-23 Print a given matrix in spiral form Program to find largest element in an array Matrix Chain Multiplication | DP-8 Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Feb, 2022" }, { "code": null, "e": 276, "s": 54, "text": "Given a 2D array(m x n). The task is to check if there is any path from top left to bottom right. In the matrix, -1 is considered as blockage (can’t go through this cell) and 0 is considered path cell (can go through it)." }, { "code": null, "e": 314, "s": 276, "text": "Note: Top left cell always contains 0" }, { "code": null, "e": 325, "s": 314, "text": "Examples: " }, { "code": null, "e": 467, "s": 325, "text": "Input : arr[][] = {{ 0, 0, 0, -1, 0}, {-1, 0, 0, -1, -1}, { 0, 0, 0, -1, 0}, {-1, 0, 0, 0, 0}, { 0, 0, -1, 0, 0}} Output : Yes Explanation: " }, { "code": null, "e": 565, "s": 467, "text": "The red cells are blocked, white cell denotes the path and the green cells are not blocked cells." }, { "code": null, "e": 747, "s": 565, "text": "Input : arr[][] = {{ 0, 0, 0, -1, 0}, {-1, 0, 0, -1, -1}, { 0, 0, 0, -1, 0}, {-1, 0, -1, 0, 0}, { 0, 0, -1, 0, 0}} Output : No Explanation: There exists no path from start to end. " }, { "code": null, "e": 846, "s": 747, "text": "The red cells are blocked, white cell denotes the path and the green cells are not blocked cells. " }, { "code": null, "e": 855, "s": 846, "text": "Method 1" }, { "code": null, "e": 1167, "s": 855, "text": "Approach: The solution is to perform BFS or DFS to find whether there is a path or not. The graph needs not to be created to perform the bfs, but the matrix itself will be used as a graph. Start the traversal from the top right corner and if there is a way to reach the bottom right corner then there is a path." }, { "code": null, "e": 1548, "s": 1167, "text": "Algorithm: Create a queue that stores pairs (i,j) and insert the (0,0) in the queue.Run a loop till the queue is empty.In each iteration dequeue the queue (a,b), if the front element is the destination (row-1,col-1) then return 1, i,e there is a path and change the value of mat[a][b] to -1, i.e. visited.Else insert the adjacent indices where the value of matrix[i][j] is not -1." }, { "code": null, "e": 1918, "s": 1548, "text": "Create a queue that stores pairs (i,j) and insert the (0,0) in the queue.Run a loop till the queue is empty.In each iteration dequeue the queue (a,b), if the front element is the destination (row-1,col-1) then return 1, i,e there is a path and change the value of mat[a][b] to -1, i.e. visited.Else insert the adjacent indices where the value of matrix[i][j] is not -1." }, { "code": null, "e": 1992, "s": 1918, "text": "Create a queue that stores pairs (i,j) and insert the (0,0) in the queue." }, { "code": null, "e": 2028, "s": 1992, "text": "Run a loop till the queue is empty." }, { "code": null, "e": 2215, "s": 2028, "text": "In each iteration dequeue the queue (a,b), if the front element is the destination (row-1,col-1) then return 1, i,e there is a path and change the value of mat[a][b] to -1, i.e. visited." }, { "code": null, "e": 2291, "s": 2215, "text": "Else insert the adjacent indices where the value of matrix[i][j] is not -1." }, { "code": null, "e": 2307, "s": 2291, "text": "Implementation:" }, { "code": null, "e": 2311, "s": 2307, "text": "C++" }, { "code": null, "e": 2316, "s": 2311, "text": "Java" }, { "code": null, "e": 2324, "s": 2316, "text": "Python3" }, { "code": null, "e": 2335, "s": 2324, "text": "Javascript" }, { "code": "// C++ program to find if there is path// from top left to right bottom#include <bits/stdc++.h>using namespace std; #define row 5#define col 5 // to find the path from// top left to bottom rightbool isPath(int arr[row][col]){ // directions int dir[4][2] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; // queue queue<pair<int, int> > q; // insert the top right corner. q.push(make_pair(0, 0)); // until queue is empty while (q.size() > 0) { pair<int, int> p = q.front(); q.pop(); // mark as visited arr[p.first][p.second] = -1; // destination is reached. if (p == make_pair(row - 1, col - 1)) return true; // check all four directions for (int i = 0; i < 4; i++) { // using the direction array int a = p.first + dir[i][0]; int b = p.second + dir[i][1]; // not blocked and valid if (arr[a][b] != -1 && a >= 0 && b >= 0 && a < row && b < col) { q.push(make_pair(a, b)); } } } return false;} // Driver Codeint main(){ // Given array int arr[row][col] = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, 0, 0, 0 }, { 0, 0, -1, 0, 0 } }; // path from arr[0][0] to arr[row][col] if (isPath(arr)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 3841, "s": 2335, "text": null }, { "code": "// Java program to find if there is path// from top left to right bottomimport java.io.*;import java.util.*; class pair { int Item1, Item2; pair(int f, int s) { Item1 = f; Item2 = s; }} class GFG { static int row = 5; static int col = 5; // To find the path from // top left to bottom right static boolean isPath(int[][] arr) { // Directions int[][] dir = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; // Queue Queue<pair> q = new LinkedList<>(); // Insert the top right corner. q.add(new pair(0, 0)); // Until queue is empty while (q.size() > 0) { pair p = (q.peek()); q.remove(); // Mark as visited arr[p.Item1][p.Item2] = -1; // Destination is reached. if (p.Item1 == row - 1 && p.Item2 == col - 1) return true; // Check all four directions for (int i = 0; i < 4; i++) { // Using the direction array int a = p.Item1 + dir[i][0]; int b = p.Item2 + dir[i][1]; // Not blocked and valid if (a >= 0 && b >= 0 && a < row && b < col && arr[a][b] != -1) { if (a == row - 1 && b == col - 1) return true; q.add(new pair(a, b)); } } } return false; } // Driver Code public static void main(String[] args) { // Given array int[][] arr = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, 0, 0, 0 }, { 0, 0, -1, 0, 0 } }; // Path from arr[0][0] to arr[row][col] if (isPath(arr)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by avanitrachhadiya2155", "e": 5833, "s": 3841, "text": null }, { "code": "# Python3 program to find if there is path# from top left to right bottomrow = 5col = 5 # to find the path from# top left to bottom rightdef isPath(arr) : # directions Dir = [ [0, 1], [0, -1], [1, 0], [-1, 0]] # queue q = [] # insert the top right corner. q.append((0, 0)) # until queue is empty while(len(q) > 0) : p = q[0] q.pop(0) # mark as visited arr[p[0]][p[1]] = -1 # destination is reached. if(p == (row - 1, col - 1)) : return True # check all four directions for i in range(4) : # using the direction array a = p[0] + Dir[i][0] b = p[1] + Dir[i][1] # not blocked and valid if(a >= 0 and b >= 0 and a < row and b < col and arr[a][b] != -1) : q.append((a, b)) return False # Given arrayarr = [[ 0, 0, 0, -1, 0 ], [ -1, 0, 0, -1, -1], [ 0, 0, 0, -1, 0 ], [ -1, 0, 0, 0, 0 ], [ 0, 0, -1, 0, 0 ] ] # path from arr[0][0] to arr[row][col]if (isPath(arr)) : print(\"Yes\")else : print(\"No\") # This code is contributed by divyesh072019", "e": 7060, "s": 5833, "text": null }, { "code": "<script> // JavaScript program to find if there is path // from top left to right bottom var row = 5;var col = 5; // To find the path from// top left to bottom rightfunction isPath(arr){ // Directions var dir = [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ]; // Queue var q = []; // Insert the top right corner. q.push([0, 0]); // Until queue is empty while (q.length > 0) { var p = q[0]; q.shift(); // Mark as visited arr[p[0]][p[1]] = -1; // Destination is reached. if (p[0]==row-1 && p[1]==col-1) return true; // Check all four directions for(var i = 0; i < 4; i++) { // Using the direction array var a = p[0] + dir[i][0]; var b = p[1] + dir[i][1]; // Not blocked and valid if (a >= 0 && b >= 0 && a < row && b < col && arr[a][b] != -1) { if (a==row - 1 && b==col - 1) return true; q.push([a,b]); } } } return false;} // Driver Code// Given arrayvar arr = [[ 0, 0, 0, -1, 0 ], [ -1, 0, 0, -1, -1], [ 0, 0, 0, -1, 0 ], [ -1, 0, 0, 0, 0 ], [ 0, 0, -1, 0, 0 ] ]; // Path from arr[0][0] to arr[row][col]if (isPath(arr)) document.write(\"Yes\");else document.write(\"No\"); </script>", "e": 8558, "s": 7060, "text": null }, { "code": null, "e": 8567, "s": 8558, "text": "Output: " }, { "code": null, "e": 8570, "s": 8567, "text": "No" }, { "code": null, "e": 8795, "s": 8570, "text": "Complexity Analysis: Time Complexity: O(R*C). Every element of the matrix can be inserted once in the queue, so time Complexity is O(R*C).Space Complexity: O(R*C). To store all the elements in a queue O(R*C) space is needed." }, { "code": null, "e": 8913, "s": 8795, "text": "Time Complexity: O(R*C). Every element of the matrix can be inserted once in the queue, so time Complexity is O(R*C)." }, { "code": null, "e": 9000, "s": 8913, "text": "Space Complexity: O(R*C). To store all the elements in a queue O(R*C) space is needed." }, { "code": null, "e": 9010, "s": 9000, "text": "Method 2 " }, { "code": null, "e": 9660, "s": 9010, "text": "Approach: The only problem with the above solution is it uses extra space. This approach will eliminate the need for extra space. The basic idea is very similar. This algorithm will also perform BFS but the need for extra space will be eliminated by marking the array. So First run a loop and check which elements of the first column and the first row is accessible from 0,0 by using only the first row and column. mark them as 1. Now traverse the matrix from start to the end row-wise in increasing index of rows and columns. If the cell is not blocked then check that any of its adjacent cells is marked 1 or not. If marked 1 then mark the cell 1." }, { "code": null, "e": 10301, "s": 9660, "text": "Algorithm: Mark the cell 0,0 as 1.Run a loop from 0 to row length and if the cell above is marked 1 and the current cell is not blocked then mark the current cell as 1.Run a loop from 0 to column length and if the left cell is marked 1 and the current cell is not blocked then mark the current cell as 1.Traverse the matrix from start to the end row-wise in increasing index of rows and columns.If the cell is not blocked then check that any of its adjacent cells (check only the cell above and the cell to the left). is marked 1 or not. If marked 1 then mark the cell 1.If the cell (row-1, col-1) is marked 1 return true else return false." }, { "code": null, "e": 10931, "s": 10301, "text": "Mark the cell 0,0 as 1.Run a loop from 0 to row length and if the cell above is marked 1 and the current cell is not blocked then mark the current cell as 1.Run a loop from 0 to column length and if the left cell is marked 1 and the current cell is not blocked then mark the current cell as 1.Traverse the matrix from start to the end row-wise in increasing index of rows and columns.If the cell is not blocked then check that any of its adjacent cells (check only the cell above and the cell to the left). is marked 1 or not. If marked 1 then mark the cell 1.If the cell (row-1, col-1) is marked 1 return true else return false." }, { "code": null, "e": 10955, "s": 10931, "text": "Mark the cell 0,0 as 1." }, { "code": null, "e": 11090, "s": 10955, "text": "Run a loop from 0 to row length and if the cell above is marked 1 and the current cell is not blocked then mark the current cell as 1." }, { "code": null, "e": 11227, "s": 11090, "text": "Run a loop from 0 to column length and if the left cell is marked 1 and the current cell is not blocked then mark the current cell as 1." }, { "code": null, "e": 11319, "s": 11227, "text": "Traverse the matrix from start to the end row-wise in increasing index of rows and columns." }, { "code": null, "e": 11496, "s": 11319, "text": "If the cell is not blocked then check that any of its adjacent cells (check only the cell above and the cell to the left). is marked 1 or not. If marked 1 then mark the cell 1." }, { "code": null, "e": 11566, "s": 11496, "text": "If the cell (row-1, col-1) is marked 1 return true else return false." }, { "code": null, "e": 11582, "s": 11566, "text": "Implementation:" }, { "code": null, "e": 11586, "s": 11582, "text": "C++" }, { "code": null, "e": 11591, "s": 11586, "text": "Java" }, { "code": null, "e": 11599, "s": 11591, "text": "Python3" }, { "code": null, "e": 11602, "s": 11599, "text": "C#" }, { "code": null, "e": 11606, "s": 11602, "text": "PHP" }, { "code": null, "e": 11617, "s": 11606, "text": "Javascript" }, { "code": "// C++ program to find if there is path// from top left to right bottom#include <iostream>using namespace std; #define row 5#define col 5 // to find the path from// top left to bottom rightbool isPath(int arr[row][col]){ // set arr[0][0] = 1 arr[0][0] = 1; // Mark reachable (from top left) nodes // in first row and first column. for (int i = 1; i < row; i++) if (arr[i][0] != -1) arr[i][0] = arr[i - 1][0]; for (int j = 1; j < col; j++) if (arr[0][j] != -1) arr[0][j] = arr[0][j - 1]; // Mark reachable nodes in remaining // matrix. for (int i = 1; i < row; i++) for (int j = 1; j < col; j++) if (arr[i][j] != -1) arr[i][j] = max(arr[i][j - 1], arr[i - 1][j]); // return yes if right bottom // index is 1 return (arr[row - 1][col - 1] == 1);} // Driver Codeint main(){ // Given array int arr[row][col] = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, -1, 0, -1 }, { 0, 0, -1, 0, 0 } }; // path from arr[0][0] to arr[row][col] if (isPath(arr)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 12906, "s": 11617, "text": null }, { "code": "// Java program to find if there is path// from top left to right bottomclass GFG{ // to find the path from // top left to bottom right static boolean isPath(int arr[][]) { // set arr[0][0] = 1 arr[0][0] = 1; // Mark reachable (from top left) nodes // in first row and first column. for (int i = 1; i < 5; i++) if (arr[0][i] != -1) arr[0][i] = arr[0][i - 1]; for (int j = 1; j < 5; j++) if (arr[j][0] != -1) arr[j][0] = arr[j - 1][0]; // Mark reachable nodes in // remaining matrix. for (int i = 1; i < 5; i++) for (int j = 1; j < 5; j++) if (arr[i][j] != -1) arr[i][j] = Math.max(arr[i][j - 1], arr[i - 1][j]); // return yes if right // bottom index is 1 return (arr[5 - 1][5 - 1] == 1); } //Driver code public static void main(String[] args) { // Given array int arr[][] = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, -1, 0, -1 }, { 0, 0, -1, 0, 0 } }; // path from arr[0][0] // to arr[row][col] if (isPath(arr)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed// by prerna saini", "e": 14369, "s": 12906, "text": null }, { "code": "# Python3 program to find if there# is path from top left to right bottomrow = 5col = 5 # to find the path from# top left to bottom rightdef isPath(arr): # set arr[0][0] = 1 arr[0][0] = 1 # Mark reachable (from top left) # nodes in first row and first column. for i in range(1, row): if (arr[i][0] != -1): arr[i][0] = arr[i-1][0] for j in range(1, col): if (arr[0][j] != -1): arr[0][j] = arr[0][j-1] # Mark reachable nodes in # remaining matrix. for i in range(1, row): for j in range(1, col): if (arr[i][j] != -1): arr[i][j] = max(arr[i][j - 1], arr[i - 1][j]) # return yes if right # bottom index is 1 return (arr[row - 1][col - 1] == 1) # Driver Code # Given arrayarr = [[ 0, 0, 0, -1, 0 ], [-1, 0, 0, -1, -1], [ 0, 0, 0, -1, 0 ], [-1, 0, -1, 0, -1], [ 0, 0, -1, 0, 0 ]] # path from arr[0][0] to arr[row][col]if (isPath(arr)): print(\"Yes\")else: print(\"No\") # This code is contributed# by sahilshelangia", "e": 15494, "s": 14369, "text": null }, { "code": "// C# program to find if there is path// from top left to right bottomusing System; class GFG{ // to find the path from // top left to bottom right static bool isPath(int [,]arr) { // set arr[0][0] = 1 arr[0, 0] = 1; // Mark reachable (from top left) nodes // in first row and first column. for (int i = 1; i < 5; i++) if (arr[i, 0] != -1) arr[i, 0] = arr[i - 1, 0]; for (int j = 1; j < 5; j++) if (arr[0,j] != -1) arr[0,j] = arr[0, j - 1]; // Mark reachable nodes in // remaining matrix. for (int i = 1; i < 5; i++) for (int j = 1; j < 5; j++) if (arr[i, j] != -1) arr[i, j] = Math.Max(arr[i, j - 1], arr[i - 1, j]); // return yes if right // bottom index is 1 return (arr[5 - 1, 5 - 1] == 1); } //Driver code public static void Main() { // Given array int [,]arr = { { 0, 0, 0, -1, 0 }, { -1, 0, 0, -1, -1 }, { 0, 0, 0, -1, 0 }, { -1, 0, -1, 0, -1 }, { 0, 0, -1, 0, 0 } }; // path from arr[0][0] // to arr[row][col] if (isPath(arr)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed// by vt_m", "e": 16938, "s": 15494, "text": null }, { "code": "<?php// PHP program to find if// there is path from top// left to right bottom$row = 5;$col = 5; // to find the path from// top left to bottom rightfunction isPath($arr){ global $row, $col; $arr[0][0] = 1; // Mark reachable (from // top left) nodes in // first row and first column. for ($i = 1; $i < $row; $i++) if ($arr[$i][0] != -1) $arr[$i][0] = $arr[$i - 1][0]; for ($j = 1; $j < $col; $j++) if ($arr[0][$j] != -1) $arr[0][$j] = $arr[0][$j - 1]; // Mark reachable nodes // in remaining matrix. for ($i = 1; $i < $row; $i++) for ($j = 1; $j < $col; $j++) if ($arr[$i][$j] != -1) $arr[$i][$j] = max($arr[$i][$j - 1], $arr[$i - 1][$j]); // return yes if right // bottom index is 1 return ($arr[$row - 1][$col - 1] == 1);} // Driver Code // Given array$arr = array(array(0, 0, 0, 1, 0), array(-1, 0, 0, -1, -1), array(0, 0, 0, -1, 0), array(-1, 0, -1, 0, -1), array(0, 0, -1, 0, 0)); // path from arr[0][0]// to arr[row][col]if (isPath($arr))echo \"Yes\";elseecho \"No\"; // This code is contributed by anuj_67.?>", "e": 18144, "s": 16938, "text": null }, { "code": "<script> // JavaScript program to find if there is path// from top left to right bottomvar arr = [[5], [5]]// to find the path from// top left to bottom rightfunction isPath(arr){ // set arr[0][0] = 1 arr[0][0] = 1; // Mark reachable (from top left) nodes // in first row and first column. for (var i = 1; i < 5; i++) if (arr[i][0] != -1) arr[i][0] = arr[i - 1][0]; for (var j = 1; j < 5; j++) if (arr[0][j] != -1) arr[0][j] = arr[0][j - 1]; // Mark reachable nodes in remaining // matrix. for (var i = 1; i < 5; i++) for (var j = 1; j < 5; j++) if (arr[i][j] != -1) arr[i][j] = Math.max(arr[i][j - 1], arr[i - 1][j]); // return yes if right bottom // index is 1 return (arr[5 - 1][5 - 1] == 1);} // Driver Code // Given array var arr = [ [ 0, 0, 0, -1, 0 ], [ -1, 0, 0, -1, -1 ], [ 0, 0, 0, -1, 0 ], [ -1, 0, -1, 0, -1 ], [ 0, 0, -1, 0, 0 ] ]; // path from arr[0][0] to arr[row][col] if (isPath(arr)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by Mayank Tyagi </script>", "e": 19431, "s": 18144, "text": null }, { "code": null, "e": 19440, "s": 19431, "text": "Output: " }, { "code": null, "e": 19443, "s": 19440, "text": "No" }, { "code": null, "e": 19610, "s": 19443, "text": "Complexity Analysis: Time Complexity: O(R*C). Every element of the matrix is traversed, so time Complexity is O(R*C).Space Complexity: O(1). No extra space is needed." }, { "code": null, "e": 19707, "s": 19610, "text": "Time Complexity: O(R*C). Every element of the matrix is traversed, so time Complexity is O(R*C)." }, { "code": null, "e": 19757, "s": 19707, "text": "Space Complexity: O(1). No extra space is needed." }, { "code": null, "e": 19764, "s": 19759, "text": "vt_m" }, { "code": null, "e": 19779, "s": 19764, "text": "sahilshelangia" }, { "code": null, "e": 19791, "s": 19779, "text": "RedKnightro" }, { "code": null, "e": 19805, "s": 19791, "text": "yashjaiswal10" }, { "code": null, "e": 19816, "s": 19805, "text": "andrew1234" }, { "code": null, "e": 19829, "s": 19816, "text": "coderboy2901" }, { "code": null, "e": 19847, "s": 19829, "text": "divyeshrabadiya07" }, { "code": null, "e": 19861, "s": 19847, "text": "divyesh072019" }, { "code": null, "e": 19877, "s": 19861, "text": "mayanktyagi1709" }, { "code": null, "e": 19883, "s": 19877, "text": "itsok" }, { "code": null, "e": 19904, "s": 19883, "text": "avanitrachhadiya2155" }, { "code": null, "e": 19921, "s": 19904, "text": "nehakumariintern" }, { "code": null, "e": 19941, "s": 19921, "text": "Dynamic Programming" }, { "code": null, "e": 19948, "s": 19941, "text": "Matrix" }, { "code": null, "e": 19968, "s": 19948, "text": "Dynamic Programming" }, { "code": null, "e": 19975, "s": 19968, "text": "Matrix" }, { "code": null, "e": 20073, "s": 19975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20141, "s": 20073, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 20168, "s": 20141, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 20206, "s": 20168, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 20239, "s": 20206, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 20270, "s": 20239, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 20306, "s": 20270, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 20350, "s": 20306, "text": "Program to find largest element in an array" }, { "code": null, "e": 20385, "s": 20350, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 20416, "s": 20385, "text": "Rat in a Maze | Backtracking-2" } ]
Java Program to Extract Digits from A Given Integer
24 Feb, 2022 Problem Statement: For any random number taken into consideration the goal is to access every digit of the number. Illustration: Simply taking two numbers be it, 12345 and 110102 absolutely random pick over which computation takes place as illustrated: Input: 12345 Output: 1 // 1 digit 2 // Digit next to 1st digit 3 4 5 // Last Digit of the number Input: 110102 Output: 1 1 0 1 0 2 Now, In order to access the digits of a number, there are several approaches ranging from the brute-force approach to the most optimal approach. Two standard approaches are as follows: Approaches: Using Integer.toString Function (Using inbuilt Method) Using modulo operator Approach 1: Using Integer.toString Method This method is an inbuilt method present already in the directory of java which returns the string object. This string object is representing the integer value. Syntax: As it is awarded that Strings are immutable in Java meaning String is a class in java. So, public static String toString() The directory in which it is present is as follows: java.lang.Integer.toString() Return Method: As seen above in the syntax itself this method returns the string object of the integer value over which it is applied. Also In this approach we will convert the integer into a string then we will traverse the string. Take the integer input.Convert the input into string data.Traverse through the string and print the character at each position that is the digits of the number. Take the integer input. Convert the input into string data. Traverse through the string and print the character at each position that is the digits of the number. Below is the implementation of the above approach: Java // Java program to Extract Digits from A Given Integer // Importing Librariesimport java.util.*;import java.io.*; class GFG { // Main driver function public static void main(String[] args) { // Declaring the number int number = 110102; // Converting the integer input to string data String string_number = Integer.toString(number); // Traversing through the string using for loop for (int i = 0; i < string_number.length(); i++) { // Printing the characters at each position System.out.println(string_number.charAt(i)); } }} Output: 1 1 0 1 0 2 Approach 2: Using Modulo Operator Without using inbuilt methods whenever it comes down to extraction of digit straightaway modulo with 10 is the answer because it extracts out the last digit. Similarly, if the process is carried for the number obtained after removing the digit that is already extracted will extract out the last digit from the small number. The same process is iterated till the end is extracted. So, In this approach, the last digit from the number and then remove it and is carried on till reaching the last digit. Take the integer input.Finding the last digit of the number.Print the last digit obtained and then remove it from the number.Keep on following the step 2 and 3 till we reach the last digit. Take the integer input. Finding the last digit of the number. Print the last digit obtained and then remove it from the number. Keep on following the step 2 and 3 till we reach the last digit. Below is the implementation of the above approach: Java // Java program to Extract Digits from A Given Integer // Importing Librariesimport java.util.*;import java.io.*; class GFG { // Main driver function public static void main(String[] args) { // Declaring the number int number = 110102; // Printing the last digit of the number while (number > 0) { // Finding the remainder (Last Digit) int remainder = number % 10; // Printing the remainder/current last digit System.out.println(remainder); // Removing the last digit/current last digit number = number / 10; } }} Output: 2 0 1 0 1 1 whoibrar Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Feb, 2022" }, { "code": null, "e": 169, "s": 52, "text": "Problem Statement: For any random number taken into consideration the goal is to access every digit of the number. " }, { "code": null, "e": 308, "s": 169, "text": "Illustration: Simply taking two numbers be it, 12345 and 110102 absolutely random pick over which computation takes place as illustrated:" }, { "code": null, "e": 483, "s": 308, "text": "Input: 12345\n\nOutput: 1 // 1 digit\n 2 // Digit next to 1st digit\n 3\n 4\n 5 // Last Digit of the number \n\nInput: 110102\n \nOutput: 1\n 1\n 0\n 1\n 0\n 2" }, { "code": null, "e": 668, "s": 483, "text": "Now, In order to access the digits of a number, there are several approaches ranging from the brute-force approach to the most optimal approach. Two standard approaches are as follows:" }, { "code": null, "e": 681, "s": 668, "text": "Approaches: " }, { "code": null, "e": 736, "s": 681, "text": "Using Integer.toString Function (Using inbuilt Method)" }, { "code": null, "e": 758, "s": 736, "text": "Using modulo operator" }, { "code": null, "e": 800, "s": 758, "text": "Approach 1: Using Integer.toString Method" }, { "code": null, "e": 961, "s": 800, "text": "This method is an inbuilt method present already in the directory of java which returns the string object. This string object is representing the integer value." }, { "code": null, "e": 1061, "s": 961, "text": "Syntax: As it is awarded that Strings are immutable in Java meaning String is a class in java. So, " }, { "code": null, "e": 1093, "s": 1061, "text": "public static String toString()" }, { "code": null, "e": 1145, "s": 1093, "text": "The directory in which it is present is as follows:" }, { "code": null, "e": 1174, "s": 1145, "text": "java.lang.Integer.toString()" }, { "code": null, "e": 1315, "s": 1174, "text": "Return Method: As seen above in the syntax itself this method returns the string object of the integer value over which it is applied. Also " }, { "code": null, "e": 1408, "s": 1315, "text": "In this approach we will convert the integer into a string then we will traverse the string." }, { "code": null, "e": 1569, "s": 1408, "text": "Take the integer input.Convert the input into string data.Traverse through the string and print the character at each position that is the digits of the number." }, { "code": null, "e": 1593, "s": 1569, "text": "Take the integer input." }, { "code": null, "e": 1629, "s": 1593, "text": "Convert the input into string data." }, { "code": null, "e": 1732, "s": 1629, "text": "Traverse through the string and print the character at each position that is the digits of the number." }, { "code": null, "e": 1783, "s": 1732, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1788, "s": 1783, "text": "Java" }, { "code": "// Java program to Extract Digits from A Given Integer // Importing Librariesimport java.util.*;import java.io.*; class GFG { // Main driver function public static void main(String[] args) { // Declaring the number int number = 110102; // Converting the integer input to string data String string_number = Integer.toString(number); // Traversing through the string using for loop for (int i = 0; i < string_number.length(); i++) { // Printing the characters at each position System.out.println(string_number.charAt(i)); } }}", "e": 2400, "s": 1788, "text": null }, { "code": null, "e": 2408, "s": 2400, "text": "Output:" }, { "code": null, "e": 2420, "s": 2408, "text": "1\n1\n0\n1\n0\n2" }, { "code": null, "e": 2456, "s": 2422, "text": "Approach 2: Using Modulo Operator" }, { "code": null, "e": 2842, "s": 2456, "text": "Without using inbuilt methods whenever it comes down to extraction of digit straightaway modulo with 10 is the answer because it extracts out the last digit. Similarly, if the process is carried for the number obtained after removing the digit that is already extracted will extract out the last digit from the small number. The same process is iterated till the end is extracted. So, " }, { "code": null, "e": 2958, "s": 2842, "text": "In this approach, the last digit from the number and then remove it and is carried on till reaching the last digit." }, { "code": null, "e": 3148, "s": 2958, "text": "Take the integer input.Finding the last digit of the number.Print the last digit obtained and then remove it from the number.Keep on following the step 2 and 3 till we reach the last digit." }, { "code": null, "e": 3172, "s": 3148, "text": "Take the integer input." }, { "code": null, "e": 3210, "s": 3172, "text": "Finding the last digit of the number." }, { "code": null, "e": 3276, "s": 3210, "text": "Print the last digit obtained and then remove it from the number." }, { "code": null, "e": 3341, "s": 3276, "text": "Keep on following the step 2 and 3 till we reach the last digit." }, { "code": null, "e": 3392, "s": 3341, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3397, "s": 3392, "text": "Java" }, { "code": "// Java program to Extract Digits from A Given Integer // Importing Librariesimport java.util.*;import java.io.*; class GFG { // Main driver function public static void main(String[] args) { // Declaring the number int number = 110102; // Printing the last digit of the number while (number > 0) { // Finding the remainder (Last Digit) int remainder = number % 10; // Printing the remainder/current last digit System.out.println(remainder); // Removing the last digit/current last digit number = number / 10; } }}", "e": 4030, "s": 3397, "text": null }, { "code": null, "e": 4038, "s": 4030, "text": "Output:" }, { "code": null, "e": 4050, "s": 4038, "text": "2\n0\n1\n0\n1\n1" }, { "code": null, "e": 4059, "s": 4050, "text": "whoibrar" }, { "code": null, "e": 4064, "s": 4059, "text": "Java" }, { "code": null, "e": 4078, "s": 4064, "text": "Java Programs" }, { "code": null, "e": 4083, "s": 4078, "text": "Java" } ]
Node.js crypto.pbkdf2Sync() Method
23 May, 2022 The crypto.pbkdf2Sync() method gives a synchronous Password-Based Key Derivation Function 2 i.e, (PBKDF2) implementation. Moreover, a particular HMAC digest algorithm which is defined by digest is implemented to derive a key of the required byte length (keylen) from the stated password, salt, and iterations. Syntax: crypto.pbkdf2Sync( password, salt, iterations, keylen, digest ) Parameters: This method accepts five parameters as mentioned above and described below: password: It is of type string, Buffer, TypedArray, or DataView. salt: It must be as unique as possible. However, it is recommended that a salt is arbitrary and in any case, it is at least 16 bytes long. It is of type string, Buffer, TypedArray, or DataView. iterations: It must be a number and should be set as high as possible. So, the more is the number of iterations, the more secure the derived key will be, but in that case, it takes a greater amount of time to complete. It is of type number. keylen: It is the key of the required byte length and it is of type number. digest: It is a digest algorithm of string type. Return Type: It returns the derived key as buffer. The below examples illustrate the use of crypto.pbkdf2Sync() method in Node.js: Example 1: javascript // Node.js program to demonstrate the// crypto.pbkdf2Sync() method // Including crypto moduleconst crypto = require('crypto'); // Implementing pbkdf2Syncconst key = crypto.pbkdf2Sync('secret', 'salt', 2000, 64, 'sha512'); // Prints bufferconsole.log(key); Output: <Buffer 3c f1 85 49 62 52 38 64 2a 4e b1 4c f6 25 2e 1e fc d7 8e 01 c9 40 d7 84 63 5e 24 ef 71 0f 91 83 bb 6d 03 bd 73 43 33 ec 78 a9 78 c8 1f ea7a dc 8c a6 ...> Example 2: javascript // Node.js program to demonstrate the// crypto.pbkdf2Sync() method // Including crypto moduleconst crypto = require('crypto'); // Implementing pbkdf2Syncconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 100, 'sha512'); // Prints key which is encoded and converted// to stringconsole.log(key.toString('hex')); Output: 3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e4 7471cc47ed941c7ad618e827304f083f8707f12b7cfdd5f489b782f10cc269 e3c08d59ae04919ee902c99dba309cde75569fbe8e6d5c341d6f2576f6618c 589e77911a261ee964e2 Reference: https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest Vyshnav S Deepak Node.js-crypto-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2022" }, { "code": null, "e": 339, "s": 28, "text": "The crypto.pbkdf2Sync() method gives a synchronous Password-Based Key Derivation Function 2 i.e, (PBKDF2) implementation. Moreover, a particular HMAC digest algorithm which is defined by digest is implemented to derive a key of the required byte length (keylen) from the stated password, salt, and iterations. " }, { "code": null, "e": 347, "s": 339, "text": "Syntax:" }, { "code": null, "e": 411, "s": 347, "text": "crypto.pbkdf2Sync( password, salt, iterations, keylen, digest )" }, { "code": null, "e": 499, "s": 411, "text": "Parameters: This method accepts five parameters as mentioned above and described below:" }, { "code": null, "e": 564, "s": 499, "text": "password: It is of type string, Buffer, TypedArray, or DataView." }, { "code": null, "e": 758, "s": 564, "text": "salt: It must be as unique as possible. However, it is recommended that a salt is arbitrary and in any case, it is at least 16 bytes long. It is of type string, Buffer, TypedArray, or DataView." }, { "code": null, "e": 999, "s": 758, "text": "iterations: It must be a number and should be set as high as possible. So, the more is the number of iterations, the more secure the derived key will be, but in that case, it takes a greater amount of time to complete. It is of type number." }, { "code": null, "e": 1075, "s": 999, "text": "keylen: It is the key of the required byte length and it is of type number." }, { "code": null, "e": 1124, "s": 1075, "text": "digest: It is a digest algorithm of string type." }, { "code": null, "e": 1256, "s": 1124, "text": "Return Type: It returns the derived key as buffer. The below examples illustrate the use of crypto.pbkdf2Sync() method in Node.js: " }, { "code": null, "e": 1268, "s": 1256, "text": "Example 1: " }, { "code": null, "e": 1279, "s": 1268, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// crypto.pbkdf2Sync() method // Including crypto moduleconst crypto = require('crypto'); // Implementing pbkdf2Syncconst key = crypto.pbkdf2Sync('secret', 'salt', 2000, 64, 'sha512'); // Prints bufferconsole.log(key);", "e": 1545, "s": 1279, "text": null }, { "code": null, "e": 1553, "s": 1545, "text": "Output:" }, { "code": null, "e": 1715, "s": 1553, "text": "<Buffer 3c f1 85 49 62 52 38 64 2a 4e b1 4c f6 25 2e 1e fc\nd7 8e 01 c9 40 d7 84 63 5e 24 ef 71 0f 91 83 bb 6d 03 bd\n73 43 33 ec 78 a9 78 c8 1f ea7a dc 8c a6 ...>" }, { "code": null, "e": 1727, "s": 1715, "text": "Example 2: " }, { "code": null, "e": 1738, "s": 1727, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// crypto.pbkdf2Sync() method // Including crypto moduleconst crypto = require('crypto'); // Implementing pbkdf2Syncconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 100, 'sha512'); // Prints key which is encoded and converted// to stringconsole.log(key.toString('hex'));", "e": 2059, "s": 1738, "text": null }, { "code": null, "e": 2067, "s": 2059, "text": "Output:" }, { "code": null, "e": 2271, "s": 2067, "text": "3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e4\n7471cc47ed941c7ad618e827304f083f8707f12b7cfdd5f489b782f10cc269\ne3c08d59ae04919ee902c99dba309cde75569fbe8e6d5c341d6f2576f6618c\n589e77911a261ee964e2" }, { "code": null, "e": 2381, "s": 2271, "text": "Reference: https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest" }, { "code": null, "e": 2398, "s": 2381, "text": "Vyshnav S Deepak" }, { "code": null, "e": 2420, "s": 2398, "text": "Node.js-crypto-module" }, { "code": null, "e": 2428, "s": 2420, "text": "Node.js" }, { "code": null, "e": 2445, "s": 2428, "text": "Web Technologies" } ]
Create login in SQL Server
18 Aug, 2020 A login is an user account that you can use to access the SQL server. Logins are attached to users by the security identifier (SID). Permissions to create login :Users with membership in the security-admin or sysadmin fixed server role can create logins on the server. Creating a login with a password :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>'; Note : Passwords are case-sensitive.Example to create a login for a particular user with password.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks'; Creating a login with a password that has got to be changed :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>' MUST_CHANGE, CHECK_EXPIRATION = ON; Example to create a login for a user with password.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks' MUST_CHANGE, CHECK_EXPIRATION = ON; Note –The MUST_CHANGE option requires users to change this password the first time they connect to the server. The MUST_CHANGE option can’t be used when CHECK_EXPIRATION is OFF.Creating a login from a Windows domain account :Syntax –CREATE LOGIN [<domainname>\<loginname>] FROM WINDOWS; Example to create a login from a Windows domain account.CREATE LOGIN [AD\geeks] FROM WINDOWS; Creating a login from a SID :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>', SID = 0x241C11948AEEB749B0D22646DB1AXXXX; Example to create a login from SID.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks', SID = 0x241C11948AEEB749B0D22646DB1AXXXX; Creating a login with multiple argumentsSyntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>', DEFAULT_DATABASE = <Databasename>, CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF ; Example to create login using multiple arguments together.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks' DEFAULT_DATABASE = GeeksDB, CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF ; Note :A combination of CHECK_POLICY = OFF and CHECK_EXPIRATION = ON is not supported. Creating a login with a password :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>'; Note : Passwords are case-sensitive.Example to create a login for a particular user with password.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks'; Syntax – CREATE LOGIN <loginname> WITH PASSWORD = '<Password>'; Note : Passwords are case-sensitive. Example to create a login for a particular user with password. CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks'; Creating a login with a password that has got to be changed :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>' MUST_CHANGE, CHECK_EXPIRATION = ON; Example to create a login for a user with password.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks' MUST_CHANGE, CHECK_EXPIRATION = ON; Note –The MUST_CHANGE option requires users to change this password the first time they connect to the server. The MUST_CHANGE option can’t be used when CHECK_EXPIRATION is OFF. Syntax – CREATE LOGIN <loginname> WITH PASSWORD = '<Password>' MUST_CHANGE, CHECK_EXPIRATION = ON; Example to create a login for a user with password. CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks' MUST_CHANGE, CHECK_EXPIRATION = ON; Note –The MUST_CHANGE option requires users to change this password the first time they connect to the server. The MUST_CHANGE option can’t be used when CHECK_EXPIRATION is OFF. Creating a login from a Windows domain account :Syntax –CREATE LOGIN [<domainname>\<loginname>] FROM WINDOWS; Example to create a login from a Windows domain account.CREATE LOGIN [AD\geeks] FROM WINDOWS; Syntax – CREATE LOGIN [<domainname>\<loginname>] FROM WINDOWS; Example to create a login from a Windows domain account. CREATE LOGIN [AD\geeks] FROM WINDOWS; Creating a login from a SID :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>', SID = 0x241C11948AEEB749B0D22646DB1AXXXX; Example to create a login from SID.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks', SID = 0x241C11948AEEB749B0D22646DB1AXXXX; Syntax – CREATE LOGIN <loginname> WITH PASSWORD = '<Password>', SID = 0x241C11948AEEB749B0D22646DB1AXXXX; Example to create a login from SID. CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks', SID = 0x241C11948AEEB749B0D22646DB1AXXXX; Creating a login with multiple argumentsSyntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>', DEFAULT_DATABASE = <Databasename>, CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF ; Example to create login using multiple arguments together.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks' DEFAULT_DATABASE = GeeksDB, CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF ; Note :A combination of CHECK_POLICY = OFF and CHECK_EXPIRATION = ON is not supported. Syntax – CREATE LOGIN <loginname> WITH PASSWORD = '<Password>', DEFAULT_DATABASE = <Databasename>, CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF ; Example to create login using multiple arguments together. CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks' DEFAULT_DATABASE = GeeksDB, CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF ; Note :A combination of CHECK_POLICY = OFF and CHECK_EXPIRATION = ON is not supported. SQL-Server DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2020" }, { "code": null, "e": 161, "s": 28, "text": "A login is an user account that you can use to access the SQL server. Logins are attached to users by the security identifier (SID)." }, { "code": null, "e": 297, "s": 161, "text": "Permissions to create login :Users with membership in the security-admin or sysadmin fixed server role can create logins on the server." }, { "code": null, "e": 1942, "s": 297, "text": "Creating a login with a password :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>';\nNote : Passwords are case-sensitive.Example to create a login for a particular user with password.CREATE LOGIN geeks \nWITH PASSWORD = 'gEe@kF0rG##ks'; Creating a login with a password that has got to be changed :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>'\nMUST_CHANGE, CHECK_EXPIRATION = ON;\nExample to create a login for a user with password.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks'\nMUST_CHANGE, CHECK_EXPIRATION = ON;\nNote –The MUST_CHANGE option requires users to change this password the first time they connect to the server. The MUST_CHANGE option can’t be used when CHECK_EXPIRATION is OFF.Creating a login from a Windows domain account :Syntax –CREATE LOGIN [<domainname>\\<loginname>] \nFROM WINDOWS;\nExample to create a login from a Windows domain account.CREATE LOGIN [AD\\geeks] FROM WINDOWS; Creating a login from a SID :Syntax –CREATE LOGIN <loginname> \nWITH PASSWORD = '<Password>', \nSID = 0x241C11948AEEB749B0D22646DB1AXXXX;\nExample to create a login from SID.CREATE LOGIN geeks \nWITH PASSWORD = 'gEe@kF0rG##ks', \nSID = 0x241C11948AEEB749B0D22646DB1AXXXX; Creating a login with multiple argumentsSyntax –CREATE LOGIN <loginname>\nWITH PASSWORD = '<Password>',\nDEFAULT_DATABASE = <Databasename>,\nCHECK_POLICY = OFF,\nCHECK_EXPIRATION = OFF ; Example to create login using multiple arguments together.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks'\nDEFAULT_DATABASE = GeeksDB,\nCHECK_POLICY = OFF,\nCHECK_EXPIRATION = OFF ; Note :A combination of CHECK_POLICY = OFF and CHECK_EXPIRATION = ON is not supported." }, { "code": null, "e": 2191, "s": 1942, "text": "Creating a login with a password :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>';\nNote : Passwords are case-sensitive.Example to create a login for a particular user with password.CREATE LOGIN geeks \nWITH PASSWORD = 'gEe@kF0rG##ks'; " }, { "code": null, "e": 2200, "s": 2191, "text": "Syntax –" }, { "code": null, "e": 2256, "s": 2200, "text": "CREATE LOGIN <loginname> WITH PASSWORD = '<Password>';\n" }, { "code": null, "e": 2293, "s": 2256, "text": "Note : Passwords are case-sensitive." }, { "code": null, "e": 2356, "s": 2293, "text": "Example to create a login for a particular user with password." }, { "code": null, "e": 2410, "s": 2356, "text": "CREATE LOGIN geeks \nWITH PASSWORD = 'gEe@kF0rG##ks'; " }, { "code": null, "e": 2885, "s": 2410, "text": "Creating a login with a password that has got to be changed :Syntax –CREATE LOGIN <loginname> WITH PASSWORD = '<Password>'\nMUST_CHANGE, CHECK_EXPIRATION = ON;\nExample to create a login for a user with password.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks'\nMUST_CHANGE, CHECK_EXPIRATION = ON;\nNote –The MUST_CHANGE option requires users to change this password the first time they connect to the server. The MUST_CHANGE option can’t be used when CHECK_EXPIRATION is OFF." }, { "code": null, "e": 2894, "s": 2885, "text": "Syntax –" }, { "code": null, "e": 2985, "s": 2894, "text": "CREATE LOGIN <loginname> WITH PASSWORD = '<Password>'\nMUST_CHANGE, CHECK_EXPIRATION = ON;\n" }, { "code": null, "e": 3037, "s": 2985, "text": "Example to create a login for a user with password." }, { "code": null, "e": 3125, "s": 3037, "text": "CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks'\nMUST_CHANGE, CHECK_EXPIRATION = ON;\n" }, { "code": null, "e": 3303, "s": 3125, "text": "Note –The MUST_CHANGE option requires users to change this password the first time they connect to the server. The MUST_CHANGE option can’t be used when CHECK_EXPIRATION is OFF." }, { "code": null, "e": 3509, "s": 3303, "text": "Creating a login from a Windows domain account :Syntax –CREATE LOGIN [<domainname>\\<loginname>] \nFROM WINDOWS;\nExample to create a login from a Windows domain account.CREATE LOGIN [AD\\geeks] FROM WINDOWS; " }, { "code": null, "e": 3518, "s": 3509, "text": "Syntax –" }, { "code": null, "e": 3574, "s": 3518, "text": "CREATE LOGIN [<domainname>\\<loginname>] \nFROM WINDOWS;\n" }, { "code": null, "e": 3631, "s": 3574, "text": "Example to create a login from a Windows domain account." }, { "code": null, "e": 3670, "s": 3631, "text": "CREATE LOGIN [AD\\geeks] FROM WINDOWS; " }, { "code": null, "e": 3938, "s": 3670, "text": "Creating a login from a SID :Syntax –CREATE LOGIN <loginname> \nWITH PASSWORD = '<Password>', \nSID = 0x241C11948AEEB749B0D22646DB1AXXXX;\nExample to create a login from SID.CREATE LOGIN geeks \nWITH PASSWORD = 'gEe@kF0rG##ks', \nSID = 0x241C11948AEEB749B0D22646DB1AXXXX; " }, { "code": null, "e": 3947, "s": 3938, "text": "Syntax –" }, { "code": null, "e": 4047, "s": 3947, "text": "CREATE LOGIN <loginname> \nWITH PASSWORD = '<Password>', \nSID = 0x241C11948AEEB749B0D22646DB1AXXXX;\n" }, { "code": null, "e": 4083, "s": 4047, "text": "Example to create a login from SID." }, { "code": null, "e": 4180, "s": 4083, "text": "CREATE LOGIN geeks \nWITH PASSWORD = 'gEe@kF0rG##ks', \nSID = 0x241C11948AEEB749B0D22646DB1AXXXX; " }, { "code": null, "e": 4631, "s": 4180, "text": "Creating a login with multiple argumentsSyntax –CREATE LOGIN <loginname>\nWITH PASSWORD = '<Password>',\nDEFAULT_DATABASE = <Databasename>,\nCHECK_POLICY = OFF,\nCHECK_EXPIRATION = OFF ; Example to create login using multiple arguments together.CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks'\nDEFAULT_DATABASE = GeeksDB,\nCHECK_POLICY = OFF,\nCHECK_EXPIRATION = OFF ; Note :A combination of CHECK_POLICY = OFF and CHECK_EXPIRATION = ON is not supported." }, { "code": null, "e": 4640, "s": 4631, "text": "Syntax –" }, { "code": null, "e": 4776, "s": 4640, "text": "CREATE LOGIN <loginname>\nWITH PASSWORD = '<Password>',\nDEFAULT_DATABASE = <Databasename>,\nCHECK_POLICY = OFF,\nCHECK_EXPIRATION = OFF ; " }, { "code": null, "e": 4835, "s": 4776, "text": "Example to create login using multiple arguments together." }, { "code": null, "e": 4960, "s": 4835, "text": "CREATE LOGIN geeks WITH PASSWORD = 'gEe@kF0rG##ks'\nDEFAULT_DATABASE = GeeksDB,\nCHECK_POLICY = OFF,\nCHECK_EXPIRATION = OFF ; " }, { "code": null, "e": 5046, "s": 4960, "text": "Note :A combination of CHECK_POLICY = OFF and CHECK_EXPIRATION = ON is not supported." }, { "code": null, "e": 5057, "s": 5046, "text": "SQL-Server" }, { "code": null, "e": 5062, "s": 5057, "text": "DBMS" }, { "code": null, "e": 5066, "s": 5062, "text": "SQL" }, { "code": null, "e": 5071, "s": 5066, "text": "DBMS" }, { "code": null, "e": 5075, "s": 5071, "text": "SQL" } ]
NLP | Proper Noun Extraction
26 Feb, 2019 Chunking all proper nouns (tagged with NNP) is a very simple way to perform named entity extraction. A simple grammar that combines all proper nouns into a NAME chunk can be created using the RegexpParser class. Then, we can test this on the first tagged sentence of treebank_chunk to compare the results with the previous recipe: Code #1 : Testing it on the first tagged sentence of treebank_chunk from nltk.corpus import treebank_chunkfrom nltk.chunk import RegexpParserfrom chunkers import sub_leaves chunker = RegexpParser(r''' NAME: {<NNP>+} ''') print ("Named Entities : \n", sub_leaves(chunker.parse( treebank_chunk.tagged_sents()[0]), 'NAME')) Output : Named Entities : [[('Pierre', 'NNP'), ('Vinken', 'NNP')], [('Nov.', 'NNP')]] Note : The code above returns all the proper nouns – ‘Pierre’, ‘Vinken’, ‘Nov.’NAME chunker is a simple usage of the RegexpParser class. All sequences of NNP tagged words are combined into NAME chunks.PersonChunker class can be used if one only want to chunk the names of people. Code #2 : PersonChunker class from nltk.chunk import ChunkParserIfrom nltk.chunk.util import conlltags2treefrom nltk.corpus import names class PersonChunker(ChunkParserI): def __init__(self): self.name_set = set(names.words()) def parse(self, tagged_sent): iobs = [] in_person = False for word, tag in tagged_sent: if word in self.name_set and in_person: iobs.append((word, tag, 'I-PERSON')) elif word in self.name_set: iobs.append((word, tag, 'B-PERSON')) in_person = True else: iobs.append((word, tag, 'O')) in_person = False return conlltags2tree(iobs) PersonChunker class checks whether each word is in its names_set (constructed from the names corpus) by iterating over the tagged sentence. It either uses B-PERSON or I-PERSON IOB tags if the current word is in the names_set, depending on whether the previous word was also in the names_set. O IOB tag is assigned to the word that’s not in the names_set argument. IOB tags list is converted to a Tree using conlltags2tree() after completion. Code #3 : Using PersonChunker class on the same tagged sentence from nltk.corpus import treebank_chunkfrom nltk.chunk import RegexpParserfrom chunkers import sub_leaves from chunkers import PersonChunkerchunker = PersonChunker()print ("Person name : ", sub_leaves(chunker.parse( treebank_chunk.tagged_sents()[0]), 'PERSON')) Output : Person name : [[('Pierre', 'NNP')]] Natural-language-processing Python-nltk Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Feb, 2019" }, { "code": null, "e": 240, "s": 28, "text": "Chunking all proper nouns (tagged with NNP) is a very simple way to perform named entity extraction. A simple grammar that combines all proper nouns into a NAME chunk can be created using the RegexpParser class." }, { "code": null, "e": 359, "s": 240, "text": "Then, we can test this on the first tagged sentence of treebank_chunk to compare the results with the previous recipe:" }, { "code": null, "e": 427, "s": 359, "text": "Code #1 : Testing it on the first tagged sentence of treebank_chunk" }, { "code": "from nltk.corpus import treebank_chunkfrom nltk.chunk import RegexpParserfrom chunkers import sub_leaves chunker = RegexpParser(r''' NAME: {<NNP>+} ''') print (\"Named Entities : \\n\", sub_leaves(chunker.parse( treebank_chunk.tagged_sents()[0]), 'NAME'))", "e": 775, "s": 427, "text": null }, { "code": null, "e": 784, "s": 775, "text": "Output :" }, { "code": null, "e": 863, "s": 784, "text": "Named Entities : \n[[('Pierre', 'NNP'), ('Vinken', 'NNP')], [('Nov.', 'NNP')]]\n" }, { "code": null, "e": 1173, "s": 863, "text": "Note : The code above returns all the proper nouns – ‘Pierre’, ‘Vinken’, ‘Nov.’NAME chunker is a simple usage of the RegexpParser class. All sequences of NNP tagged words are combined into NAME chunks.PersonChunker class can be used if one only want to chunk the names of people. Code #2 : PersonChunker class" }, { "code": "from nltk.chunk import ChunkParserIfrom nltk.chunk.util import conlltags2treefrom nltk.corpus import names class PersonChunker(ChunkParserI): def __init__(self): self.name_set = set(names.words()) def parse(self, tagged_sent): iobs = [] in_person = False for word, tag in tagged_sent: if word in self.name_set and in_person: iobs.append((word, tag, 'I-PERSON')) elif word in self.name_set: iobs.append((word, tag, 'B-PERSON')) in_person = True else: iobs.append((word, tag, 'O')) in_person = False return conlltags2tree(iobs)", "e": 1887, "s": 1173, "text": null }, { "code": null, "e": 2393, "s": 1887, "text": "PersonChunker class checks whether each word is in its names_set (constructed from the names corpus) by iterating over the tagged sentence. It either uses B-PERSON or I-PERSON IOB tags if the current word is in the names_set, depending on whether the previous word was also in the names_set. O IOB tag is assigned to the word that’s not in the names_set argument. IOB tags list is converted to a Tree using conlltags2tree() after completion. Code #3 : Using PersonChunker class on the same tagged sentence" }, { "code": "from nltk.corpus import treebank_chunkfrom nltk.chunk import RegexpParserfrom chunkers import sub_leaves from chunkers import PersonChunkerchunker = PersonChunker()print (\"Person name : \", sub_leaves(chunker.parse( treebank_chunk.tagged_sents()[0]), 'PERSON'))", "e": 2677, "s": 2393, "text": null }, { "code": null, "e": 2686, "s": 2677, "text": "Output :" }, { "code": null, "e": 2724, "s": 2686, "text": "Person name : [[('Pierre', 'NNP')]]\n" }, { "code": null, "e": 2752, "s": 2724, "text": "Natural-language-processing" }, { "code": null, "e": 2764, "s": 2752, "text": "Python-nltk" }, { "code": null, "e": 2771, "s": 2764, "text": "Python" } ]
Time Formatting in Golang
17 May, 2020 Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time.Time object. Syntax: func (t Time) Format(layout string) string We can either provide custom format or predefined date and timestamp format constants are also available which are shown as follows. Layouts must use the reference time Mon Jan 2 15:04:05 MST 2006 to show the pattern with which to format/parse a given time/string. Example 1: // Golang program to illustrate the time// formatting using custom layouts package main import ( "fmt" "time") func main() { // this function returns the present time current_time := time.Now() // individual elements of time can // also be called to print accordingly fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n", current_time.Year(), current_time.Month(), current_time.Day(), current_time.Hour(), current_time.Minute(), current_time.Second()) // formatting time using // custom formats fmt.Println(current_time.Format("2006-01-02 15:04:05")) fmt.Println(current_time.Format("2006-January-02")) fmt.Println(current_time.Format("2006-01-02 3:4:5 pm"))} Output: 2009-11-10T23:00:00-00:00 2009-11-10 23:00:00 2009-November-10 2009-11-10 11:0:0 pm Example 2: // Golang program to illustrate the time// formatting using format constantspackage main import ( "fmt" "time") func main() { // this function returns the present time current_time := time.Now() // using inbuilt format constants // shown in the table above fmt.Println("ANSIC: ", current_time.Format(time.ANSIC)) fmt.Println("UnixDate: ", current_time.Format(time.UnixDate)) fmt.Println("RFC1123: ", current_time.Format(time.RFC1123)) fmt.Println("RFC3339Nano: ", current_time.Format(time.RFC3339Nano)) fmt.Println("RubyDate: ", current_time.Format(time.RubyDate))} Output: ANSIC: Tue Nov 10 23:00:00 2009 UnixDate: Tue Nov 10 23:00:00 UTC 2009 RFC1123: Tue, 10 Nov 2009 23:00:00 UTC RFC3339Nano: 2009-11-10T23:00:00Z RubyDate: Tue Nov 10 23:00:00 +0000 2009 Golang-Program GoLang-time Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 May, 2020" }, { "code": null, "e": 202, "s": 54, "text": "Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time.Time object." }, { "code": null, "e": 210, "s": 202, "text": "Syntax:" }, { "code": null, "e": 253, "s": 210, "text": "func (t Time) Format(layout string) string" }, { "code": null, "e": 386, "s": 253, "text": "We can either provide custom format or predefined date and timestamp format constants are also available which are shown as follows." }, { "code": null, "e": 518, "s": 386, "text": "Layouts must use the reference time Mon Jan 2 15:04:05 MST 2006 to show the pattern with which to format/parse a given time/string." }, { "code": null, "e": 529, "s": 518, "text": "Example 1:" }, { "code": "// Golang program to illustrate the time// formatting using custom layouts package main import ( \"fmt\" \"time\") func main() { // this function returns the present time current_time := time.Now() // individual elements of time can // also be called to print accordingly fmt.Printf(\"%d-%02d-%02dT%02d:%02d:%02d-00:00\\n\", current_time.Year(), current_time.Month(), current_time.Day(), current_time.Hour(), current_time.Minute(), current_time.Second()) // formatting time using // custom formats fmt.Println(current_time.Format(\"2006-01-02 15:04:05\")) fmt.Println(current_time.Format(\"2006-January-02\")) fmt.Println(current_time.Format(\"2006-01-02 3:4:5 pm\"))}", "e": 1236, "s": 529, "text": null }, { "code": null, "e": 1244, "s": 1236, "text": "Output:" }, { "code": null, "e": 1329, "s": 1244, "text": "2009-11-10T23:00:00-00:00\n2009-11-10 23:00:00\n2009-November-10\n2009-11-10 11:0:0 pm\n" }, { "code": null, "e": 1340, "s": 1329, "text": "Example 2:" }, { "code": "// Golang program to illustrate the time// formatting using format constantspackage main import ( \"fmt\" \"time\") func main() { // this function returns the present time current_time := time.Now() // using inbuilt format constants // shown in the table above fmt.Println(\"ANSIC: \", current_time.Format(time.ANSIC)) fmt.Println(\"UnixDate: \", current_time.Format(time.UnixDate)) fmt.Println(\"RFC1123: \", current_time.Format(time.RFC1123)) fmt.Println(\"RFC3339Nano: \", current_time.Format(time.RFC3339Nano)) fmt.Println(\"RubyDate: \", current_time.Format(time.RubyDate))}", "e": 1945, "s": 1340, "text": null }, { "code": null, "e": 1953, "s": 1945, "text": "Output:" }, { "code": null, "e": 2144, "s": 1953, "text": "ANSIC: Tue Nov 10 23:00:00 2009\nUnixDate: Tue Nov 10 23:00:00 UTC 2009\nRFC1123: Tue, 10 Nov 2009 23:00:00 UTC\nRFC3339Nano: 2009-11-10T23:00:00Z\nRubyDate: Tue Nov 10 23:00:00 +0000 2009\n" }, { "code": null, "e": 2159, "s": 2144, "text": "Golang-Program" }, { "code": null, "e": 2171, "s": 2159, "text": "GoLang-time" }, { "code": null, "e": 2178, "s": 2171, "text": "Picked" }, { "code": null, "e": 2190, "s": 2178, "text": "Go Language" } ]
Regular Expression in grep
30 Jan, 2019 Prerequisite: grep Basic Regular Expression Regular Expression provides an ability to match a “string of text” in a very flexible and concise manner. A “string of text” can be further defined as a single character, word, sentence or particular pattern of characters. Like the shell’s wild–cards which match similar filenames with a single expression, grep uses an expression of a different sort to match a group of similar patterns. [ ]: Matches any one of a set characters [ ] with hyphen: Matches any one of a range characters ^: The pattern following it must occur at the beginning of each line ^ with [ ] : The pattern must not contain any character in the set specified $: The pattern preceding it must occur at the end of each line . (dot): Matches any one character \ (backslash): Ignores the special meaning of the character following it *: zero or more occurrences of the previous character (dot).*: Nothing or any numbers of characters. Examples (a) [ ] : Matches any one of a set characters $grep “New[abc]” filename It specifies the search pattern as :Newa , Newb or Newc $grep “[aA]g[ar][ar]wal” filename It specifies the search pattern asAgarwal , Agaawal , Agrawal , Agrrwal agarwal , agaawal , agrawal , agrrwal $grep “New[abc]” filename It specifies the search pattern as :Newa , Newb or Newc $grep “New[abc]” filename It specifies the search pattern as : Newa , Newb or Newc $grep “[aA]g[ar][ar]wal” filename It specifies the search pattern asAgarwal , Agaawal , Agrawal , Agrrwal agarwal , agaawal , agrawal , agrrwal $grep “[aA]g[ar][ar]wal” filename It specifies the search pattern as Agarwal , Agaawal , Agrawal , Agrrwal agarwal , agaawal , agrawal , agrrwal (b) Use [ ] with hyphen: Matches any one of a range characters $grep “New[a-e]” filename It specifies the search pattern asNewa , Newb or Newc , Newd, Newe $grep “New[0-9][a-z]” filename It specifies the search pattern as: New followed by a number and then an alphabet.New0d, New4f etc $grep “New[a-e]” filename It specifies the search pattern asNewa , Newb or Newc , Newd, Newe $grep “New[a-e]” filename It specifies the search pattern as Newa , Newb or Newc , Newd, Newe $grep “New[0-9][a-z]” filename It specifies the search pattern as: New followed by a number and then an alphabet.New0d, New4f etc $grep “New[0-9][a-z]” filename It specifies the search pattern as: New followed by a number and then an alphabet. New0d, New4f etc (c ) Use ^: The pattern following it must occur at the beginning of each line $grep “^san” filename Search lines beginning with san. It specifies the search pattern assanjeev ,sanjay, sanrit , sanchit , sandeep etc. $ls –l |grep “^d” Display list of directories only$ls –l |grep “^-” Display list of regular files only $grep “^san” filename Search lines beginning with san. It specifies the search pattern assanjeev ,sanjay, sanrit , sanchit , sandeep etc. $grep “^san” filename Search lines beginning with san. It specifies the search pattern as sanjeev ,sanjay, sanrit , sanchit , sandeep etc. $ls –l |grep “^d” Display list of directories only $ls –l |grep “^d” Display list of directories only $ls –l |grep “^-” Display list of regular files only $ls –l |grep “^-” Display list of regular files only (d) Use ^ with [ ]: The pattern must not contain any character in the set specified $grep “New[^a-c]” filename It specifies the pattern containing the word “New” followed by any character other than an ‘a’,’b’, or ‘c’$grep “^[^a-z A-Z]” filename Search lines beginning with an non-alphabetic character $grep “New[^a-c]” filename It specifies the pattern containing the word “New” followed by any character other than an ‘a’,’b’, or ‘c’ $grep “New[^a-c]” filename It specifies the pattern containing the word “New” followed by any character other than an ‘a’,’b’, or ‘c’ $grep “^[^a-z A-Z]” filename Search lines beginning with an non-alphabetic character $grep “^[^a-z A-Z]” filename Search lines beginning with an non-alphabetic character (e) Use $: The pattern preceding it must occur at the end of each line $ grep "vedik$" file.txt (f) Use . (dot): Matches any one character $ grep "..vik" file.txt $ grep "7..9$" file.txt (g) Use \ (backslash): Ignores the special meaning of the character following it $ grep "New\.\[abc\]" file.txtIt specifies the search pattern as New.[abc]$ grep "S\.K\.Kumar" file.txt It specifies the search pattern asS.K.Kumar $ grep "New\.\[abc\]" file.txtIt specifies the search pattern as New.[abc] $ grep "New\.\[abc\]" file.txt It specifies the search pattern as New.[abc] $ grep "S\.K\.Kumar" file.txt It specifies the search pattern asS.K.Kumar $ grep "S\.K\.Kumar" file.txt It specifies the search pattern as S.K.Kumar (h) Use *: zero or more occurrences of the previous character $ grep "[aA]gg*[ar][ar]wal" file.txt (i) Use (dot).*: Nothing or any numbers of characters. $ grep "S.*Kumar" file.txt This article is contributed by Akshay Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. linux-command 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": "\n30 Jan, 2019" }, { "code": null, "e": 71, "s": 52, "text": "Prerequisite: grep" }, { "code": null, "e": 96, "s": 71, "text": "Basic Regular Expression" }, { "code": null, "e": 319, "s": 96, "text": "Regular Expression provides an ability to match a “string of text” in a very flexible and concise manner. A “string of text” can be further defined as a single character, word, sentence or particular pattern of characters." }, { "code": null, "e": 485, "s": 319, "text": "Like the shell’s wild–cards which match similar filenames with a single expression, grep uses an expression of a different sort to match a group of similar patterns." }, { "code": null, "e": 526, "s": 485, "text": "[ ]: Matches any one of a set characters" }, { "code": null, "e": 581, "s": 526, "text": "[ ] with hyphen: Matches any one of a range characters" }, { "code": null, "e": 650, "s": 581, "text": "^: The pattern following it must occur at the beginning of each line" }, { "code": null, "e": 727, "s": 650, "text": "^ with [ ] : The pattern must not contain any character in the set specified" }, { "code": null, "e": 790, "s": 727, "text": "$: The pattern preceding it must occur at the end of each line" }, { "code": null, "e": 825, "s": 790, "text": ". (dot): Matches any one character" }, { "code": null, "e": 898, "s": 825, "text": "\\ (backslash): Ignores the special meaning of the character following it" }, { "code": null, "e": 952, "s": 898, "text": "*: zero or more occurrences of the previous character" }, { "code": null, "e": 999, "s": 952, "text": "(dot).*: Nothing or any numbers of characters." }, { "code": null, "e": 1008, "s": 999, "text": "Examples" }, { "code": null, "e": 1054, "s": 1008, "text": "(a) [ ] : Matches any one of a set characters" }, { "code": null, "e": 1286, "s": 1054, "text": "$grep “New[abc]” filename\nIt specifies the search pattern as :Newa , Newb or Newc\n$grep “[aA]g[ar][ar]wal” filename\nIt specifies the search pattern asAgarwal , Agaawal , Agrawal , Agrrwal\n\nagarwal , agaawal , agrawal , agrrwal\n" }, { "code": null, "e": 1371, "s": 1286, "text": "$grep “New[abc]” filename\nIt specifies the search pattern as :Newa , Newb or Newc\n" }, { "code": null, "e": 1400, "s": 1371, "text": "$grep “New[abc]” filename\n" }, { "code": null, "e": 1437, "s": 1400, "text": "It specifies the search pattern as :" }, { "code": null, "e": 1458, "s": 1437, "text": "Newa , Newb or Newc\n" }, { "code": null, "e": 1606, "s": 1458, "text": "$grep “[aA]g[ar][ar]wal” filename\nIt specifies the search pattern asAgarwal , Agaawal , Agrawal , Agrrwal\n\nagarwal , agaawal , agrawal , agrrwal\n" }, { "code": null, "e": 1643, "s": 1606, "text": "$grep “[aA]g[ar][ar]wal” filename\n" }, { "code": null, "e": 1678, "s": 1643, "text": "It specifies the search pattern as" }, { "code": null, "e": 1756, "s": 1678, "text": "Agarwal , Agaawal , Agrawal , Agrrwal\n\nagarwal , agaawal , agrawal , agrrwal\n" }, { "code": null, "e": 1819, "s": 1756, "text": "(b) Use [ ] with hyphen: Matches any one of a range characters" }, { "code": null, "e": 2046, "s": 1819, "text": "$grep “New[a-e]” filename\nIt specifies the search pattern asNewa , Newb or Newc , Newd, Newe\n$grep “New[0-9][a-z]” filename\nIt specifies the search pattern as: New followed by a number and then an alphabet.New0d, New4f etc\n" }, { "code": null, "e": 2141, "s": 2046, "text": "$grep “New[a-e]” filename\nIt specifies the search pattern asNewa , Newb or Newc , Newd, Newe\n" }, { "code": null, "e": 2169, "s": 2141, "text": "$grep “New[a-e]” filename\n" }, { "code": null, "e": 2204, "s": 2169, "text": "It specifies the search pattern as" }, { "code": null, "e": 2238, "s": 2204, "text": "Newa , Newb or Newc , Newd, Newe\n" }, { "code": null, "e": 2371, "s": 2238, "text": "$grep “New[0-9][a-z]” filename\nIt specifies the search pattern as: New followed by a number and then an alphabet.New0d, New4f etc\n" }, { "code": null, "e": 2405, "s": 2371, "text": "$grep “New[0-9][a-z]” filename\n" }, { "code": null, "e": 2488, "s": 2405, "text": "It specifies the search pattern as: New followed by a number and then an alphabet." }, { "code": null, "e": 2506, "s": 2488, "text": "New0d, New4f etc\n" }, { "code": null, "e": 2584, "s": 2506, "text": "(c ) Use ^: The pattern following it must occur at the beginning of each line" }, { "code": null, "e": 2831, "s": 2584, "text": "$grep “^san” filename\nSearch lines beginning with san. It specifies the search pattern assanjeev ,sanjay, sanrit , sanchit , sandeep etc.\n$ls –l |grep “^d” \nDisplay list of directories only$ls –l |grep “^-” \nDisplay list of regular files only" }, { "code": null, "e": 2972, "s": 2831, "text": "$grep “^san” filename\nSearch lines beginning with san. It specifies the search pattern assanjeev ,sanjay, sanrit , sanchit , sandeep etc.\n" }, { "code": null, "e": 2997, "s": 2972, "text": "$grep “^san” filename\n" }, { "code": null, "e": 3065, "s": 2997, "text": "Search lines beginning with san. It specifies the search pattern as" }, { "code": null, "e": 3115, "s": 3065, "text": "sanjeev ,sanjay, sanrit , sanchit , sandeep etc.\n" }, { "code": null, "e": 3168, "s": 3115, "text": "$ls –l |grep “^d” \nDisplay list of directories only" }, { "code": null, "e": 3189, "s": 3168, "text": "$ls –l |grep “^d” \n" }, { "code": null, "e": 3222, "s": 3189, "text": "Display list of directories only" }, { "code": null, "e": 3277, "s": 3222, "text": "$ls –l |grep “^-” \nDisplay list of regular files only" }, { "code": null, "e": 3298, "s": 3277, "text": "$ls –l |grep “^-” \n" }, { "code": null, "e": 3333, "s": 3298, "text": "Display list of regular files only" }, { "code": null, "e": 3417, "s": 3333, "text": "(d) Use ^ with [ ]: The pattern must not contain any character in the set specified" }, { "code": null, "e": 3639, "s": 3417, "text": "$grep “New[^a-c]” filename\nIt specifies the pattern containing the word “New” followed by any character other than an ‘a’,’b’, or ‘c’$grep “^[^a-z A-Z]” filename\nSearch lines beginning with an non-alphabetic character" }, { "code": null, "e": 3775, "s": 3639, "text": "$grep “New[^a-c]” filename\nIt specifies the pattern containing the word “New” followed by any character other than an ‘a’,’b’, or ‘c’" }, { "code": null, "e": 3805, "s": 3775, "text": "$grep “New[^a-c]” filename\n" }, { "code": null, "e": 3912, "s": 3805, "text": "It specifies the pattern containing the word “New” followed by any character other than an ‘a’,’b’, or ‘c’" }, { "code": null, "e": 3999, "s": 3912, "text": "$grep “^[^a-z A-Z]” filename\nSearch lines beginning with an non-alphabetic character" }, { "code": null, "e": 4031, "s": 3999, "text": "$grep “^[^a-z A-Z]” filename\n" }, { "code": null, "e": 4087, "s": 4031, "text": "Search lines beginning with an non-alphabetic character" }, { "code": null, "e": 4158, "s": 4087, "text": "(e) Use $: The pattern preceding it must occur at the end of each line" }, { "code": null, "e": 4184, "s": 4158, "text": "$ grep \"vedik$\" file.txt\n" }, { "code": null, "e": 4227, "s": 4184, "text": "(f) Use . (dot): Matches any one character" }, { "code": null, "e": 4276, "s": 4227, "text": "$ grep \"..vik\" file.txt\n$ grep \"7..9$\" file.txt\n" }, { "code": null, "e": 4357, "s": 4276, "text": "(g) Use \\ (backslash): Ignores the special meaning of the character following it" }, { "code": null, "e": 4506, "s": 4357, "text": "$ grep \"New\\.\\[abc\\]\" file.txtIt specifies the search pattern as New.[abc]$ grep \"S\\.K\\.Kumar\" file.txt\nIt specifies the search pattern asS.K.Kumar\n" }, { "code": null, "e": 4581, "s": 4506, "text": "$ grep \"New\\.\\[abc\\]\" file.txtIt specifies the search pattern as New.[abc]" }, { "code": null, "e": 4612, "s": 4581, "text": "$ grep \"New\\.\\[abc\\]\" file.txt" }, { "code": null, "e": 4657, "s": 4612, "text": "It specifies the search pattern as New.[abc]" }, { "code": null, "e": 4732, "s": 4657, "text": "$ grep \"S\\.K\\.Kumar\" file.txt\nIt specifies the search pattern asS.K.Kumar\n" }, { "code": null, "e": 4763, "s": 4732, "text": "$ grep \"S\\.K\\.Kumar\" file.txt\n" }, { "code": null, "e": 4798, "s": 4763, "text": "It specifies the search pattern as" }, { "code": null, "e": 4809, "s": 4798, "text": "S.K.Kumar\n" }, { "code": null, "e": 4871, "s": 4809, "text": "(h) Use *: zero or more occurrences of the previous character" }, { "code": null, "e": 4909, "s": 4871, "text": "$ grep \"[aA]gg*[ar][ar]wal\" file.txt\n" }, { "code": null, "e": 4964, "s": 4909, "text": "(i) Use (dot).*: Nothing or any numbers of characters." }, { "code": null, "e": 4991, "s": 4964, "text": "$ grep \"S.*Kumar\" file.txt" }, { "code": null, "e": 5294, "s": 4993, "text": "This article is contributed by Akshay Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5419, "s": 5294, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5433, "s": 5419, "text": "linux-command" }, { "code": null, "e": 5444, "s": 5433, "text": "Linux-Unix" } ]
Python | SMS Bomber using Selenium
26 May, 2021 Here, we are going to learn a simple SMS bomber trick (for fun and educational purpose). Selenium is a free tool for automated testing across different browsers. In this tutorial, we will learn to send automatically number of spam SMS for given number of frequency and interval.Requirement: You need to install chromedriver and set path. Click here to download.Below are the steps: First go to flipkart website using this Link. Then click on inspect element by pressing ctrl + shift + i or going in setting of browser and clicking on inspect element manually. Then find the class name of “Enter the number” input field and “Forgot?” link. We will use it later. Now, Run the script by putting appropriate class name for each element. Now it will automatically send spam sms to your friend’s mobile number. Note: This tutorial is for educational purpose only, please don’t use it for disturbing anyone or any unethical way.Below is the implementation: Python3 from selenium import webdriverimport time # create instance of Chrome webdriverbrowser = webdriver.Chrome() # set the frequency of sms which is approx maximum to 10 per 24 daysfrequency = 10 # target mobile number, change it to victim's number and# also ensure that it's registered on flipkartmobile_number ="1234567890" for i in range(frequency): browser.get('https://www.flipkart.com/account/login?ret=/') # find the element where we have to # enter the number using the class name number = browser.find_element_by_xpath('//*[@id="container"]/div/div[3]/div/div[2]/div/form/div[1]/input') # automatically type the target number number.send_keys("1234567890") # find the element to send a forgot password # request using it's class name forgot = browser.find_element_by_link_text('Forgot?') # clicking on that element forgot.click() # set the interval to send each sms time.sleep(2) # Close the browserbrowser.quit() singhanubhav selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2021" }, { "code": null, "e": 438, "s": 54, "text": "Here, we are going to learn a simple SMS bomber trick (for fun and educational purpose). Selenium is a free tool for automated testing across different browsers. In this tutorial, we will learn to send automatically number of spam SMS for given number of frequency and interval.Requirement: You need to install chromedriver and set path. Click here to download.Below are the steps: " }, { "code": null, "e": 484, "s": 438, "text": "First go to flipkart website using this Link." }, { "code": null, "e": 616, "s": 484, "text": "Then click on inspect element by pressing ctrl + shift + i or going in setting of browser and clicking on inspect element manually." }, { "code": null, "e": 717, "s": 616, "text": "Then find the class name of “Enter the number” input field and “Forgot?” link. We will use it later." }, { "code": null, "e": 789, "s": 717, "text": "Now, Run the script by putting appropriate class name for each element." }, { "code": null, "e": 861, "s": 789, "text": "Now it will automatically send spam sms to your friend’s mobile number." }, { "code": null, "e": 1008, "s": 861, "text": "Note: This tutorial is for educational purpose only, please don’t use it for disturbing anyone or any unethical way.Below is the implementation: " }, { "code": null, "e": 1016, "s": 1008, "text": "Python3" }, { "code": "from selenium import webdriverimport time # create instance of Chrome webdriverbrowser = webdriver.Chrome() # set the frequency of sms which is approx maximum to 10 per 24 daysfrequency = 10 # target mobile number, change it to victim's number and# also ensure that it's registered on flipkartmobile_number =\"1234567890\" for i in range(frequency): browser.get('https://www.flipkart.com/account/login?ret=/') # find the element where we have to # enter the number using the class name number = browser.find_element_by_xpath('//*[@id=\"container\"]/div/div[3]/div/div[2]/div/form/div[1]/input') # automatically type the target number number.send_keys(\"1234567890\") # find the element to send a forgot password # request using it's class name forgot = browser.find_element_by_link_text('Forgot?') # clicking on that element forgot.click() # set the interval to send each sms time.sleep(2) # Close the browserbrowser.quit()", "e": 1994, "s": 1016, "text": null }, { "code": null, "e": 2007, "s": 1994, "text": "singhanubhav" }, { "code": null, "e": 2016, "s": 2007, "text": "selenium" }, { "code": null, "e": 2023, "s": 2016, "text": "Python" } ]
Get Financial Data from Yahoo Finance with Python
16 Jun, 2021 In this article, we will see how to get financial data from Yahoo Finance using Python. We can retrieve company financial information (e.g. financial ratios), as well as historical market data by using this. Installation: Let us install them via pip commands pip install yfinance Once it is installed, we can import yfinance package in python code We need to pass as an argument of Ticker i.e. the ticker of the company Note: A stock symbol or a ticker is a unique series of letters assigned to a security for trading purposes. For example: For Amazon, it is “AMZN”For Facebook, it is “FB”For Google, it is “GOOGL” For Amazon, it is “AMZN” For Facebook, it is “FB” For Google, it is “GOOGL” Below are various programs which depict how to retrieve Financial Data from Yahoo Finance: Let us take the results for Facebook and hence using “FB”. Python3 import yfinance as yahooFinance # Here We are getting Facebook financial information# We need to pass FB as argument for thatGetFacebookInformation = yahooFinance.Ticker("FB") # whole python dictionary is printed hereprint(GetFacebookInformation.info) Output : We can retrieve financial key metrics like Company Sector, Price Earnings Ratio, and Company Beta from the above dictionary of items easily. Let us see the below code. Python3 import yfinance as yahooFinance GetFacebookInformation = yahooFinance.Ticker("FB") # display Company Sectorprint("Company Sector : ", GetFacebookInformation.info['sector']) # display Price Earnings Ratioprint("Price Earnings Ratio : ", GetFacebookInformation.info['trailingPE']) # display Company Betaprint(" Company Beta : ", GetFacebookInformation.info['beta']) Output : Company Sector : Communication Services Price Earnings Ratio : 31.029732 Company Beta : 1.286265 Though we have retrieved few financial key metrics, as it is a dictionary value, we can split that by means of key-value pair. Python3 import yfinance as yahooFinanceGetFacebookInformation = yahooFinance.Ticker("FB") # get all key value pairs that are availablefor key, value in GetFacebookInformation.info.items(): print(key, ":", value) Output : We can retrieve historical market prices too and display them. Python3 import yfinance as yahooFinance GetFacebookInformation = yahooFinance.Ticker("FB") # Let us get historical stock prices for Facebook# covering the past few years.# max->maximum number of daily prices available# for Facebook.# Valid options are 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y,# 5y, 10y and ytd.print(GetFacebookInformation.history(period="max")) Output : Even we can have the data for 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, and ytd. Let us check out for 6 months Python3 import yfinance as yahooFinance GetFacebookInformation = yahooFinance.Ticker("FB") # Valid options are 1d, 5d, 1mo, 3mo, 6mo, 1y,# 2y, 5y, 10y and ytd.print(GetFacebookInformation.history(period="6mo")) Output : We have the flexibility to get historical market data for the provided start and end dates too. Python3 import yfinance as yahooFinance # in order to specify start date and# end date we need datetime packageimport datetime # startDate , as per our convenience we can modifystartDate = datetime.datetime(2019, 5, 31) # endDate , as per our convenience we can modifyendDate = datetime.datetime(2021, 1, 30)GetFacebookInformation = yahooFinance.Ticker("FB") # pass the parameters as the taken dates for start and endprint(GetFacebookInformation.history(start=startDate, end=endDate)) Output : simranarora5sos Picked python-modules Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2021" }, { "code": null, "e": 237, "s": 28, "text": "In this article, we will see how to get financial data from Yahoo Finance using Python. We can retrieve company financial information (e.g. financial ratios), as well as historical market data by using this. " }, { "code": null, "e": 251, "s": 237, "text": "Installation:" }, { "code": null, "e": 288, "s": 251, "text": "Let us install them via pip commands" }, { "code": null, "e": 309, "s": 288, "text": "pip install yfinance" }, { "code": null, "e": 449, "s": 309, "text": "Once it is installed, we can import yfinance package in python code We need to pass as an argument of Ticker i.e. the ticker of the company" }, { "code": null, "e": 570, "s": 449, "text": "Note: A stock symbol or a ticker is a unique series of letters assigned to a security for trading purposes. For example:" }, { "code": null, "e": 644, "s": 570, "text": "For Amazon, it is “AMZN”For Facebook, it is “FB”For Google, it is “GOOGL”" }, { "code": null, "e": 669, "s": 644, "text": "For Amazon, it is “AMZN”" }, { "code": null, "e": 694, "s": 669, "text": "For Facebook, it is “FB”" }, { "code": null, "e": 720, "s": 694, "text": "For Google, it is “GOOGL”" }, { "code": null, "e": 812, "s": 720, "text": "Below are various programs which depict how to retrieve Financial Data from Yahoo Finance: " }, { "code": null, "e": 871, "s": 812, "text": "Let us take the results for Facebook and hence using “FB”." }, { "code": null, "e": 879, "s": 871, "text": "Python3" }, { "code": "import yfinance as yahooFinance # Here We are getting Facebook financial information# We need to pass FB as argument for thatGetFacebookInformation = yahooFinance.Ticker(\"FB\") # whole python dictionary is printed hereprint(GetFacebookInformation.info)", "e": 1131, "s": 879, "text": null }, { "code": null, "e": 1140, "s": 1131, "text": "Output :" }, { "code": null, "e": 1308, "s": 1140, "text": "We can retrieve financial key metrics like Company Sector, Price Earnings Ratio, and Company Beta from the above dictionary of items easily. Let us see the below code." }, { "code": null, "e": 1316, "s": 1308, "text": "Python3" }, { "code": "import yfinance as yahooFinance GetFacebookInformation = yahooFinance.Ticker(\"FB\") # display Company Sectorprint(\"Company Sector : \", GetFacebookInformation.info['sector']) # display Price Earnings Ratioprint(\"Price Earnings Ratio : \", GetFacebookInformation.info['trailingPE']) # display Company Betaprint(\" Company Beta : \", GetFacebookInformation.info['beta'])", "e": 1681, "s": 1316, "text": null }, { "code": null, "e": 1690, "s": 1681, "text": "Output :" }, { "code": null, "e": 1791, "s": 1690, "text": "Company Sector : Communication Services\nPrice Earnings Ratio : 31.029732\n Company Beta : 1.286265" }, { "code": null, "e": 1919, "s": 1791, "text": "Though we have retrieved few financial key metrics, as it is a dictionary value, we can split that by means of key-value pair. " }, { "code": null, "e": 1927, "s": 1919, "text": "Python3" }, { "code": "import yfinance as yahooFinanceGetFacebookInformation = yahooFinance.Ticker(\"FB\") # get all key value pairs that are availablefor key, value in GetFacebookInformation.info.items(): print(key, \":\", value)", "e": 2134, "s": 1927, "text": null }, { "code": null, "e": 2147, "s": 2138, "text": "Output :" }, { "code": null, "e": 2214, "s": 2151, "text": "We can retrieve historical market prices too and display them." }, { "code": null, "e": 2224, "s": 2216, "text": "Python3" }, { "code": "import yfinance as yahooFinance GetFacebookInformation = yahooFinance.Ticker(\"FB\") # Let us get historical stock prices for Facebook# covering the past few years.# max->maximum number of daily prices available# for Facebook.# Valid options are 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y,# 5y, 10y and ytd.print(GetFacebookInformation.history(period=\"max\"))", "e": 2570, "s": 2224, "text": null }, { "code": null, "e": 2583, "s": 2574, "text": "Output :" }, { "code": null, "e": 2667, "s": 2587, "text": "Even we can have the data for 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, and ytd. " }, { "code": null, "e": 2699, "s": 2669, "text": "Let us check out for 6 months" }, { "code": null, "e": 2709, "s": 2701, "text": "Python3" }, { "code": "import yfinance as yahooFinance GetFacebookInformation = yahooFinance.Ticker(\"FB\") # Valid options are 1d, 5d, 1mo, 3mo, 6mo, 1y,# 2y, 5y, 10y and ytd.print(GetFacebookInformation.history(period=\"6mo\"))", "e": 2913, "s": 2709, "text": null }, { "code": null, "e": 2926, "s": 2917, "text": "Output :" }, { "code": null, "e": 3026, "s": 2930, "text": "We have the flexibility to get historical market data for the provided start and end dates too." }, { "code": null, "e": 3036, "s": 3028, "text": "Python3" }, { "code": "import yfinance as yahooFinance # in order to specify start date and# end date we need datetime packageimport datetime # startDate , as per our convenience we can modifystartDate = datetime.datetime(2019, 5, 31) # endDate , as per our convenience we can modifyendDate = datetime.datetime(2021, 1, 30)GetFacebookInformation = yahooFinance.Ticker(\"FB\") # pass the parameters as the taken dates for start and endprint(GetFacebookInformation.history(start=startDate, end=endDate))", "e": 3549, "s": 3036, "text": null }, { "code": null, "e": 3558, "s": 3549, "text": "Output :" }, { "code": null, "e": 3574, "s": 3558, "text": "simranarora5sos" }, { "code": null, "e": 3581, "s": 3574, "text": "Picked" }, { "code": null, "e": 3596, "s": 3581, "text": "python-modules" }, { "code": null, "e": 3609, "s": 3596, "text": "Web-scraping" }, { "code": null, "e": 3616, "s": 3609, "text": "Python" } ]
PyQt5 – Changing background color of Push Button when mouse hover over it
22 Apr, 2020 In this article we will see how to set background color to a push button when mouse hover. It gets back to its default color when cursor is not on the push button. In order to do this we have to change the style sheet and had to add background color of push button when mouse hover over it. Below is the style sheet code. QPushButton::hover { background-color : lightgreen; } Below is the implementation. # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating push button button = QPushButton("Geek Button", self) # setting geometry of the push button button.setGeometry(200, 150, 100, 40) # setting background color to push button when mouse hover over it button.setStyleSheet("QPushButton::hover" "{" "background-color : lightgreen;" "}") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 192, "s": 28, "text": "In this article we will see how to set background color to a push button when mouse hover. It gets back to its default color when cursor is not on the push button." }, { "code": null, "e": 350, "s": 192, "text": "In order to do this we have to change the style sheet and had to add background color of push button when mouse hover over it. Below is the style sheet code." }, { "code": null, "e": 405, "s": 350, "text": "QPushButton::hover\n{\nbackground-color : lightgreen;\n}\n" }, { "code": null, "e": 434, "s": 405, "text": "Below is the implementation." }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating push button button = QPushButton(\"Geek Button\", self) # setting geometry of the push button button.setGeometry(200, 150, 100, 40) # setting background color to push button when mouse hover over it button.setStyleSheet(\"QPushButton::hover\" \"{\" \"background-color : lightgreen;\" \"}\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1519, "s": 434, "text": null }, { "code": null, "e": 1528, "s": 1519, "text": "Output :" }, { "code": null, "e": 1539, "s": 1528, "text": "Python-gui" }, { "code": null, "e": 1551, "s": 1539, "text": "Python-PyQt" }, { "code": null, "e": 1558, "s": 1551, "text": "Python" } ]
CSS Introduction
07 Jun, 2022 Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this independent of the HTML that makes up each web page. It describes how a webpage should look: it prescribes colors, fonts, spacing, and much more. In short, you can make your website look however you want. CSS lets developers and designers define how it behaves, including how elements are positioned in the browser. while html uses tags, css uses rulesets.CSS is easy to learn and understand, but it provides powerful control over the presentation of an HTML document. WHY CSS? CSS saves time: You can write CSS once and reuse the same sheet in multiple HTML pages. Easy Maintenance: To make a global change simply change the style, and all elements in all the webpages will be updated automatically. Search Engines: CSS is considered a clean coding technique, which means search engines won’t have to struggle to “read” its content. Superior styles to HTML: CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes. Offline Browsing: CSS can store web applications locally with the help of an offline cache. Using this we can view offline websites. CSS Syntax:A CSS comprises style rules that are interpreted by the browser and then applied to the corresponding elements in your document.A style rule set consists of a selector and declaration block. Selector -- h1 Declaration -- {color:blue;font size:12px;} The selector points to the HTML element you want to style. The declaration block contains one or more declarations separated by semicolons. Each declaration includes a CSS property name and a value, separated by a colon.For Example:–; color is property and blue is value.–; font-size is property and 12px is value. A CSS declaration always ends with a semicolon, and declaration blocks are surrounded by curly braces. Example : In the following example all p elements will be center-aligned, with a blue text color: CSS p { color: blue; text-align: center; } CSS SelectorsCSS selectors are used to “find” (or select) HTML elements based on their element name, id, class, attribute, and more. 1. THE UNIVERSAL SELECTORS: Rather than selecting elements of a specific type, the universal selector quite simply matches the name of any element type CSS * { color: #000000; } This rule renders the content of every element in our document in black. 2. THE ELEMENT SELECTOR: The element selector selects elements based on the element name. You can select all p elements on a page like this (in this case, all p elements will be center-aligned, with a red text color) : CSS p { text-align: center; color: red; } 3. THE DESCENDANT SELECTOR: Suppose you want to apply a style rule to a particular element only when it lies inside a particular element. As given in the following example, the style rule will apply to the em element only when it lies inside the ul tag. CSS ul em { color: #000000; } 4. THE ID SELECTOR : The id selector uses the id attribute of an HTML element to select a specific element. The id of an element should be unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element. The style rule below will be applied to the HTML element with id=”para1′′: 5. THE CLASS SELECTORS : The class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class. In the example below, all HTML elements with class=”center” will be red and center-aligned: You can apply more than one class selector to a given element. Consider the following example: html <p class="center large">This paragraph refers to two classes.</p> 6. GROUPING SELECTORS If you have elements with the same style definitions, like this: CSS h1 { text-align: center; color: blue; } h2 { text-align: center; color: blue; } p { text-align: center; color: blue; } It will be better to group the selectors, to minimize the code. To group selectors, separate each selector with a comma. In the example below we have grouped the selectors from the code above: CSS h1, h2, p { text-align: center; color: red; } Before CSS: html <!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> <main> <h1>HTML Page</h1> <p>This is a basic web page.</p> </main> </body> </html> After CSS In this example, we add some CSS. html <!DOCTYPE html> <html> <head> <title>Example</title> <style> main { width: 200px; height: 200px; padding: 10px; background: beige; } h1 { font-family: fantasy, cursive, serif; color: olivedrab; border-bottom: 1px dotted darkgreen; } p { font-family: sans-serif; color: orange; } </style> </head> <body> <main> <h1>HTML Page</h1> <p>This is a basic web page.</p> </main> </body> </html> All we did was add the following code to the example: CSS <style> main { width: 200px; height: 200px; padding: 10px; background: beige; } h1 { font-family: cursive; color: olivedrab; border-bottom: 1px dotted darkgreen; } p { font-family: sans-serif; color: orange; } </style> CSS Versions CSS1 CSS2 CSS3 CSS4Version 4 comes with:- CSS-Pro CSS-Mobile CSS1 CSS2 CSS3 CSS4Version 4 comes with:- CSS-Pro CSS-Mobile CSS-Pro CSS-Mobile Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari JyotiGoyal1 ghoshsuman0129 ysachin2314 clintra niharikatanwar61 dishaagrawal1 CSS-Basics CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 57, "s": 26, "text": " \n07 Jun, 2022\n" }, { "code": null, "e": 611, "s": 57, "text": "Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this independent of the HTML that makes up each web page. It describes how a webpage should look: it prescribes colors, fonts, spacing, and much more. In short, you can make your website look however you want. CSS lets developers and designers define how it behaves, including how elements are positioned in the browser. " }, { "code": null, "e": 764, "s": 611, "text": "while html uses tags, css uses rulesets.CSS is easy to learn and understand, but it provides powerful control over the presentation of an HTML document." }, { "code": null, "e": 774, "s": 764, "text": "WHY CSS? " }, { "code": null, "e": 862, "s": 774, "text": "CSS saves time: You can write CSS once and reuse the same sheet in multiple HTML pages." }, { "code": null, "e": 997, "s": 862, "text": "Easy Maintenance: To make a global change simply change the style, and all elements in all the webpages will be updated automatically." }, { "code": null, "e": 1130, "s": 997, "text": "Search Engines: CSS is considered a clean coding technique, which means search engines won’t have to struggle to “read” its content." }, { "code": null, "e": 1293, "s": 1130, "text": "Superior styles to HTML: CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes." }, { "code": null, "e": 1426, "s": 1293, "text": "Offline Browsing: CSS can store web applications locally with the help of an offline cache. Using this we can view offline websites." }, { "code": null, "e": 1629, "s": 1426, "text": "CSS Syntax:A CSS comprises style rules that are interpreted by the browser and then applied to the corresponding elements in your document.A style rule set consists of a selector and declaration block. " }, { "code": null, "e": 1689, "s": 1629, "text": "Selector -- h1\nDeclaration -- {color:blue;font size:12px;} " }, { "code": null, "e": 1748, "s": 1689, "text": "The selector points to the HTML element you want to style." }, { "code": null, "e": 1829, "s": 1748, "text": "The declaration block contains one or more declarations separated by semicolons." }, { "code": null, "e": 2004, "s": 1829, "text": "Each declaration includes a CSS property name and a value, separated by a colon.For Example:–; color is property and blue is value.–; font-size is property and 12px is value." }, { "code": null, "e": 2107, "s": 2004, "text": "A CSS declaration always ends with a semicolon, and declaration blocks are surrounded by curly braces." }, { "code": null, "e": 2206, "s": 2107, "text": "Example : In the following example all p elements will be center-aligned, with a blue text color: " }, { "code": null, "e": 2210, "s": 2206, "text": "CSS" }, { "code": "\n\n\n\n\n\n\np {\n color: blue;\n text-align: center;\n}\n\n\n\n\n\n", "e": 2280, "s": 2220, "text": null }, { "code": null, "e": 2414, "s": 2280, "text": "CSS SelectorsCSS selectors are used to “find” (or select) HTML elements based on their element name, id, class, attribute, and more. " }, { "code": null, "e": 2568, "s": 2414, "text": "1. THE UNIVERSAL SELECTORS: Rather than selecting elements of a specific type, the universal selector quite simply matches the name of any element type " }, { "code": null, "e": 2572, "s": 2568, "text": "CSS" }, { "code": "\n\n\n\n\n\n\n* { \n color: #000000; \n}\n\n\n\n\n\n", "e": 2622, "s": 2582, "text": null }, { "code": null, "e": 2696, "s": 2622, "text": "This rule renders the content of every element in our document in black. " }, { "code": null, "e": 2916, "s": 2696, "text": "2. THE ELEMENT SELECTOR: The element selector selects elements based on the element name. You can select all p elements on a page like this (in this case, all p elements will be center-aligned, with a red text color) : " }, { "code": null, "e": 2920, "s": 2916, "text": "CSS" }, { "code": "\n\n\n\n\n\n\np {\n text-align: center;\n color: red;\n}\n\n\n\n\n\n", "e": 2989, "s": 2930, "text": null }, { "code": null, "e": 3246, "s": 2991, "text": "3. THE DESCENDANT SELECTOR: Suppose you want to apply a style rule to a particular element only when it lies inside a particular element. As given in the following example, the style rule will apply to the em element only when it lies inside the ul tag. " }, { "code": null, "e": 3250, "s": 3246, "text": "CSS" }, { "code": "\n\n\n\n\n\n\nul em {\n color: #000000; \n}\n\n\n\n\n\n", "e": 3303, "s": 3260, "text": null }, { "code": null, "e": 3327, "s": 3305, "text": "4. THE ID SELECTOR : " }, { "code": null, "e": 3414, "s": 3327, "text": "The id selector uses the id attribute of an HTML element to select a specific element." }, { "code": null, "e": 3524, "s": 3414, "text": "The id of an element should be unique within a page, so the id selector is used to select one unique element!" }, { "code": null, "e": 3628, "s": 3524, "text": "To select an element with a specific id, write a hash (#) character, followed by the id of the element." }, { "code": null, "e": 3703, "s": 3628, "text": "The style rule below will be applied to the HTML element with id=”para1′′:" }, { "code": null, "e": 3729, "s": 3703, "text": "5. THE CLASS SELECTORS : " }, { "code": null, "e": 3798, "s": 3729, "text": "The class selector selects elements with a specific class attribute." }, { "code": null, "e": 3905, "s": 3798, "text": "To select elements with a specific class, write a period (.) character, followed by the name of the class." }, { "code": null, "e": 3997, "s": 3905, "text": "In the example below, all HTML elements with class=”center” will be red and center-aligned:" }, { "code": null, "e": 4093, "s": 3997, "text": "You can apply more than one class selector to a given element. Consider the following example: " }, { "code": null, "e": 4098, "s": 4093, "text": "html" }, { "code": "\n\n\n\n\n\n\n<p class=\"center large\">This paragraph refers to two classes.</p>\n\n\n\n\n\n", "e": 4187, "s": 4108, "text": null }, { "code": null, "e": 4209, "s": 4187, "text": "6. GROUPING SELECTORS" }, { "code": null, "e": 4275, "s": 4209, "text": "If you have elements with the same style definitions, like this: " }, { "code": null, "e": 4279, "s": 4275, "text": "CSS" }, { "code": "\n\n\n\n\n\n\nh1 {\n text-align: center;\n color: blue;\n}\n \nh2 {\n text-align: center;\n color: blue;\n}\n \np {\n text-align: center;\n color: blue;\n}\n\n\n\n\n\n", "e": 4449, "s": 4289, "text": null }, { "code": null, "e": 4643, "s": 4449, "text": "It will be better to group the selectors, to minimize the code. To group selectors, separate each selector with a comma. In the example below we have grouped the selectors from the code above: " }, { "code": null, "e": 4647, "s": 4643, "text": "CSS" }, { "code": "\n\n\n\n\n\n\nh1, h2, p {\n text-align: center;\n color: red;\n}\n\n\n\n\n\n", "e": 4724, "s": 4657, "text": null }, { "code": null, "e": 4736, "s": 4724, "text": "Before CSS:" }, { "code": null, "e": 4741, "s": 4736, "text": "html" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html>\n<html>\n <head>\n <title>Example</title>\n </head>\n <body>\n <main>\n <h1>HTML Page</h1>\n \n \n \n \n \n<p>This is a basic web page.</p>\n \n \n \n \n \n \n </main>\n </body>\n</html>\n\n\n\n\n\n", "e": 4969, "s": 4751, "text": null }, { "code": null, "e": 4979, "s": 4969, "text": "After CSS" }, { "code": null, "e": 5014, "s": 4979, "text": "In this example, we add some CSS. " }, { "code": null, "e": 5019, "s": 5014, "text": "html" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html>\n<html>\n <head>\n <title>Example</title>\n <style>\n main {\n width: 200px;\n height: 200px;\n padding: 10px;\n background: beige;\n }\n h1 {\n font-family: fantasy, cursive, serif;\n color: olivedrab;\n border-bottom: 1px dotted darkgreen;\n }\n p {\n font-family: sans-serif;\n color: orange;\n }\n </style>\n </head>\n <body>\n <main>\n <h1>HTML Page</h1>\n \n \n \n \n \n<p>This is a basic web page.</p>\n \n \n \n \n \n \n </main>\n </body>\n</html>\n\n\n\n\n\n", "e": 5598, "s": 5029, "text": null }, { "code": null, "e": 5653, "s": 5598, "text": "All we did was add the following code to the example: " }, { "code": null, "e": 5657, "s": 5653, "text": "CSS" }, { "code": "\n\n\n\n\n\n\n<style>\n main {\n width: 200px;\n height: 200px;\n padding: 10px;\n background: beige;\n }\n h1 {\n font-family: cursive;\n color: olivedrab;\n border-bottom: 1px dotted darkgreen;\n }\n p {\n font-family: sans-serif;\n color: orange;\n }\n</style>\n\n\n\n\n\n", "e": 5947, "s": 5667, "text": null }, { "code": null, "e": 5960, "s": 5947, "text": "CSS Versions" }, { "code": null, "e": 6026, "s": 5960, "text": "\nCSS1\nCSS2\nCSS3\nCSS4Version 4 comes with:-\n\nCSS-Pro\nCSS-Mobile\n\n\n" }, { "code": null, "e": 6031, "s": 6026, "text": "CSS1" }, { "code": null, "e": 6036, "s": 6031, "text": "CSS2" }, { "code": null, "e": 6041, "s": 6036, "text": "CSS3" }, { "code": null, "e": 6090, "s": 6041, "text": "CSS4Version 4 comes with:-\n\nCSS-Pro\nCSS-Mobile\n\n" }, { "code": null, "e": 6098, "s": 6090, "text": "CSS-Pro" }, { "code": null, "e": 6109, "s": 6098, "text": "CSS-Mobile" }, { "code": null, "e": 6128, "s": 6109, "text": "Supported Browser:" }, { "code": null, "e": 6142, "s": 6128, "text": "Google Chrome" }, { "code": null, "e": 6157, "s": 6142, "text": "Microsoft Edge" }, { "code": null, "e": 6165, "s": 6157, "text": "Firefox" }, { "code": null, "e": 6171, "s": 6165, "text": "Opera" }, { "code": null, "e": 6178, "s": 6171, "text": "Safari" }, { "code": null, "e": 6190, "s": 6178, "text": "JyotiGoyal1" }, { "code": null, "e": 6205, "s": 6190, "text": "ghoshsuman0129" }, { "code": null, "e": 6217, "s": 6205, "text": "ysachin2314" }, { "code": null, "e": 6225, "s": 6217, "text": "clintra" }, { "code": null, "e": 6242, "s": 6225, "text": "niharikatanwar61" }, { "code": null, "e": 6256, "s": 6242, "text": "dishaagrawal1" }, { "code": null, "e": 6269, "s": 6256, "text": "\nCSS-Basics\n" }, { "code": null, "e": 6275, "s": 6269, "text": "\nCSS\n" }, { "code": null, "e": 6282, "s": 6275, "text": "\nHTML\n" }, { "code": null, "e": 6301, "s": 6282, "text": "\nWeb Technologies\n" }, { "code": null, "e": 6306, "s": 6301, "text": "HTML" } ]
Output of C Programs | Set 5
17 May, 2021 Predict the output of below programs Question 1 c int main(){ while(1){ if(printf("%d",printf("%d"))) break; else continue; } return 0;} Output: Can’t be predictedExplanation: The condition in while loop is 1 so at first shot it looks infinite loop. Then there are break and continue in the body of the while loop, so it may not be infinite loop. The break statement will be executed if the condition under if is met, otherwise continue will be executed. Since there’s no other statements after continue in the while loop, continue doesn’t serve any purpose. In fact it is extraneous. So let us see the if condition. If we look carefully, we will notice that the condition of the if will be met always, so break will be executed at the first iteration itself and we will come out of while loop. The reason why the condition of if will be met is printf function. Function printf always returns the no. of bytes it has output. For example, the return value of printf(“geeks”) will be 5 because printf will output 5 characters here. In our case, the inner printf will be executed first but this printf doesn’t have argument for format specifier i.e. %d. It means this printf will print any arbitrary value. But notice that even for any arbitrary value, the no. of bytes output by inner printf would be non-zero. And those no. of bytes will work as argument to outer printf. The outer printf will print that many no. of bytes and return non-zero value always. So the condition for if is also true always. Therefore, the while loop be executed only once. As a side note, even without outer printf also, the condition for if is always true. Question 2 c int main(){ unsigned int i=10; while(i-- >= 0) printf("%u ",i); return 0;} Output: 9 8 7 6 5 4 3 2 1 0 4294967295 4294967294 ...... (on a machine where int is 4 bytes long)9 8 7 6 5 4 3 2 1 0 65535 65534 .... (on a machine where int is 2 bytes long)Explanation: Let us examine the condition of while loop. It is obvious that as far as the condition of while loop is met, printf will be executed. There are two operators in the condition of while loop: post-decrement operator and comparison operator. From operator precedence, we know that unary operator post-decrement has higher priority than comparison operator. But due to post-decrement property, the value of i will be decremented only after it had been used for comparison. So at the first iteration, the condition is true because 10>=0 and then i is decremented. Therefore 9 will be printed. Similarly the loop continues and the value of i keeps on decrementing. Let us see what happen when condition of while loop becomes 0 >= 0. At this time, condition is met and i is decremented. Since i is unsigned integer, the roll-over happens and i takes the value of the highest +ve value an unsigned int can take. So i is never negative. Therefore, it becomes infinite while loop. As a side note, if i was signed int, the while loop would have been terminated after printing the highest positive value.Question 3 c int main(){ int x,y=2,z,a; if ( x = y%2) z =2; a=2; printf("%d %d ",z,x); return 0;} Output: < some garbage value of z > 0Explanation: This question has some stuff for operator precedence. If the condition of if is met, then z will be initialized to 2 otherwise z will contain garbage value. But the condition of if has two operators: assignment operator and modulus operator. The precedence of modulus is higher than assignment. So y%2 is zero and it’ll be assigned to x. So the value of x becomes zero which is also the effective condition for if. And therefore, condition of if is false. Question 4 c int main(){ int a[10]; printf("%d",*a+1-*a+3); return 0;} Output: 4Explanation: From operator precedence, de-reference operator has higher priority than addition/subtraction operator. So de-reference will be applied first. Here, a is an array which is not initialized. If we use a, then it will point to the first element of the array. Therefore *a will be the first element of the array. Suppose first element of array is x, then the argument inside printf becomes as follows. It’s effective value is 4.x + 1 – x + 3 = 4Question 5 c #define prod(a,b) a*bint main(){ int x=3,y=4; printf("%d",prod(x+2,y-1)); return 0;} Output: 10Explanation: This program deals with macros, their side effects and operator precedence. Here prod is a macro which multiplies its two arguments a and b. Let us take a closer look.prod(a, b) = a*b prod(x+2, y-1) = x+2*y-1 = 3+2*4-1 = 3+8-1=10If the programmer really wanted to multiply x+2 and y-1, he should have put parenthesis around a and b as follows.prod(a,b) = (a)*(b)This type of mistake in macro definition is called – macro side-effects. rakesh patel 1 clintra C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 May, 2021" }, { "code": null, "e": 102, "s": 52, "text": "Predict the output of below programs Question 1 " }, { "code": null, "e": 104, "s": 102, "text": "c" }, { "code": "int main(){ while(1){ if(printf(\"%d\",printf(\"%d\"))) break; else continue; } return 0;}", "e": 236, "s": 104, "text": null }, { "code": null, "e": 1747, "s": 236, "text": "Output: Can’t be predictedExplanation: The condition in while loop is 1 so at first shot it looks infinite loop. Then there are break and continue in the body of the while loop, so it may not be infinite loop. The break statement will be executed if the condition under if is met, otherwise continue will be executed. Since there’s no other statements after continue in the while loop, continue doesn’t serve any purpose. In fact it is extraneous. So let us see the if condition. If we look carefully, we will notice that the condition of the if will be met always, so break will be executed at the first iteration itself and we will come out of while loop. The reason why the condition of if will be met is printf function. Function printf always returns the no. of bytes it has output. For example, the return value of printf(“geeks”) will be 5 because printf will output 5 characters here. In our case, the inner printf will be executed first but this printf doesn’t have argument for format specifier i.e. %d. It means this printf will print any arbitrary value. But notice that even for any arbitrary value, the no. of bytes output by inner printf would be non-zero. And those no. of bytes will work as argument to outer printf. The outer printf will print that many no. of bytes and return non-zero value always. So the condition for if is also true always. Therefore, the while loop be executed only once. As a side note, even without outer printf also, the condition for if is always true. Question 2 " }, { "code": null, "e": 1749, "s": 1747, "text": "c" }, { "code": "int main(){ unsigned int i=10; while(i-- >= 0) printf(\"%u \",i); return 0;}", "e": 1840, "s": 1749, "text": null }, { "code": null, "e": 3132, "s": 1840, "text": "Output: 9 8 7 6 5 4 3 2 1 0 4294967295 4294967294 ...... (on a machine where int is 4 bytes long)9 8 7 6 5 4 3 2 1 0 65535 65534 .... (on a machine where int is 2 bytes long)Explanation: Let us examine the condition of while loop. It is obvious that as far as the condition of while loop is met, printf will be executed. There are two operators in the condition of while loop: post-decrement operator and comparison operator. From operator precedence, we know that unary operator post-decrement has higher priority than comparison operator. But due to post-decrement property, the value of i will be decremented only after it had been used for comparison. So at the first iteration, the condition is true because 10>=0 and then i is decremented. Therefore 9 will be printed. Similarly the loop continues and the value of i keeps on decrementing. Let us see what happen when condition of while loop becomes 0 >= 0. At this time, condition is met and i is decremented. Since i is unsigned integer, the roll-over happens and i takes the value of the highest +ve value an unsigned int can take. So i is never negative. Therefore, it becomes infinite while loop. As a side note, if i was signed int, the while loop would have been terminated after printing the highest positive value.Question 3 " }, { "code": null, "e": 3134, "s": 3132, "text": "c" }, { "code": "int main(){ int x,y=2,z,a; if ( x = y%2) z =2; a=2; printf(\"%d %d \",z,x); return 0;}", "e": 3242, "s": 3134, "text": null }, { "code": null, "e": 3761, "s": 3242, "text": "Output: < some garbage value of z > 0Explanation: This question has some stuff for operator precedence. If the condition of if is met, then z will be initialized to 2 otherwise z will contain garbage value. But the condition of if has two operators: assignment operator and modulus operator. The precedence of modulus is higher than assignment. So y%2 is zero and it’ll be assigned to x. So the value of x becomes zero which is also the effective condition for if. And therefore, condition of if is false. Question 4 " }, { "code": null, "e": 3763, "s": 3761, "text": "c" }, { "code": "int main(){ int a[10]; printf(\"%d\",*a+1-*a+3); return 0;}", "e": 3830, "s": 3763, "text": null }, { "code": null, "e": 4306, "s": 3830, "text": "Output: 4Explanation: From operator precedence, de-reference operator has higher priority than addition/subtraction operator. So de-reference will be applied first. Here, a is an array which is not initialized. If we use a, then it will point to the first element of the array. Therefore *a will be the first element of the array. Suppose first element of array is x, then the argument inside printf becomes as follows. It’s effective value is 4.x + 1 – x + 3 = 4Question 5 " }, { "code": null, "e": 4308, "s": 4306, "text": "c" }, { "code": "#define prod(a,b) a*bint main(){ int x=3,y=4; printf(\"%d\",prod(x+2,y-1)); return 0;}", "e": 4402, "s": 4308, "text": null }, { "code": null, "e": 4861, "s": 4402, "text": "Output: 10Explanation: This program deals with macros, their side effects and operator precedence. Here prod is a macro which multiplies its two arguments a and b. Let us take a closer look.prod(a, b) = a*b prod(x+2, y-1) = x+2*y-1 = 3+2*4-1 = 3+8-1=10If the programmer really wanted to multiply x+2 and y-1, he should have put parenthesis around a and b as follows.prod(a,b) = (a)*(b)This type of mistake in macro definition is called – macro side-effects. " }, { "code": null, "e": 4876, "s": 4861, "text": "rakesh patel 1" }, { "code": null, "e": 4884, "s": 4876, "text": "clintra" }, { "code": null, "e": 4893, "s": 4884, "text": "C-Output" }, { "code": null, "e": 4908, "s": 4893, "text": "Program Output" } ]
Slicing, Indexing, Manipulating and Cleaning Pandas Dataframe
05 Sep, 2020 With the help of Pandas, we can perform many functions on data set like Slicing, Indexing, Manipulating, and Cleaning Data frame. Case 1: Slicing Pandas Data frame using DataFrame.iloc[] Example 1: Slicing Rows Python3 # importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', 38, 74, 3428000], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', 40, 100, 4528000], ['J.Root', 33, 72, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) # data frame before slicingdf Output: Python3 # Slicing rows in data framedf1 = df.iloc[0:4] # data frame after slicingdf1 Output: In the above example, we sliced the rows from the data frame. Example 2: Slicing Columns Python3 # importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', 38, 74, 3428000], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', 40, 100, 4528000], ['J.Root', 33, 72, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) # data frame before slicingdf Output: Python3 # Slicing columnss in data framedf1 = df.iloc[:,0:2] # data frame after slicingdf1 Output: In the above example, we sliced the columns from the data frame. Case 2: Indexing Pandas Data frame Python3 # importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', 38, 74, 3428000], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', 40, 100, 4528000], ['J.Root', 33, 72, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframe and indexing it using Aplhabetsdf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary'], index=['A', 'B', 'C', 'D', 'E', 'F', 'G']) # Displaying data framedf Output: In the above example, we do indexing of the data frame. Case 3: Manipulating Pandas Data frame Manipulation of the data frame can be done in multiple ways like applying functions, changing a data type of columns, splitting, adding rows and columns to a data frame, etc. Example 1: Applying lambda function to a column using Dataframe.assign() Python3 # importing pandas libraryimport pandas as pd # creating and initializing a listvalues = [['Rohan', 455], ['Elvish', 250], ['Deepak', 495], ['Sai', 400], ['Radha', 350], ['Vansh', 450]] # creating a pandas dataframedf = pd.DataFrame(values, columns=['Name', 'Univ_Marks']) # Applying lambda function to find percentage of# 'Univ_Marks' column using df.assign()df = df.assign(Percentage=lambda x: (x['Univ_Marks'] / 500 * 100)) # displaying the data framedf Output: In the above example, the lambda function is applied to the ‘Univ_Marks’ column and a new column ‘Percentage’ is formed with the help of it. Example 2: Sorting the Data frame in Ascending order Python3 # importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', 38, 74, 3428000], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', 40, 100, 4528000], ['J.Root', 33, 72, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) # Sorting by column 'Weight'df.sort_values(by=['Weight']) Output: In the above example, we sort the data frame by column ‘Weight”. Case 4: Cleaning Pandas Data frame Python3 # importing pandas and Numpy librariesimport pandas as pdimport numpy as np # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', np.nan, 74, np.nan], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', np.nan, 100, np.nan], [np.nan, 33, np.nan, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) df Output: Python3 # Checking for missing valuesdf.isnull().sum() Output: Python3 # dropping or cleaning the missing data df= df.dropna() df Output: In the above example, we clean all the missing values from the data set. 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": 54, "s": 26, "text": "\n05 Sep, 2020" }, { "code": null, "e": 185, "s": 54, "text": "With the help of Pandas, we can perform many functions on data set like Slicing, Indexing, Manipulating, and Cleaning Data frame. " }, { "code": null, "e": 242, "s": 185, "text": "Case 1: Slicing Pandas Data frame using DataFrame.iloc[]" }, { "code": null, "e": 267, "s": 242, "text": "Example 1: Slicing Rows " }, { "code": null, "e": 275, "s": 267, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', 38, 74, 3428000], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', 40, 100, 4528000], ['J.Root', 33, 72, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) # data frame before slicingdf", "e": 826, "s": 275, "text": null }, { "code": null, "e": 834, "s": 826, "text": "Output:" }, { "code": null, "e": 842, "s": 834, "text": "Python3" }, { "code": "# Slicing rows in data framedf1 = df.iloc[0:4] # data frame after slicingdf1", "e": 920, "s": 842, "text": null }, { "code": null, "e": 928, "s": 920, "text": "Output:" }, { "code": null, "e": 990, "s": 928, "text": "In the above example, we sliced the rows from the data frame." }, { "code": null, "e": 1018, "s": 990, "text": "Example 2: Slicing Columns " }, { "code": null, "e": 1026, "s": 1018, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', 38, 74, 3428000], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', 40, 100, 4528000], ['J.Root', 33, 72, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) # data frame before slicingdf", "e": 1575, "s": 1026, "text": null }, { "code": null, "e": 1583, "s": 1575, "text": "Output:" }, { "code": null, "e": 1591, "s": 1583, "text": "Python3" }, { "code": "# Slicing columnss in data framedf1 = df.iloc[:,0:2] # data frame after slicingdf1", "e": 1675, "s": 1591, "text": null }, { "code": null, "e": 1683, "s": 1675, "text": "Output:" }, { "code": null, "e": 1748, "s": 1683, "text": "In the above example, we sliced the columns from the data frame." }, { "code": null, "e": 1784, "s": 1748, "text": "Case 2: Indexing Pandas Data frame " }, { "code": null, "e": 1792, "s": 1784, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', 38, 74, 3428000], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', 40, 100, 4528000], ['J.Root', 33, 72, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframe and indexing it using Aplhabetsdf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary'], index=['A', 'B', 'C', 'D', 'E', 'F', 'G']) # Displaying data framedf", "e": 2433, "s": 1792, "text": null }, { "code": null, "e": 2441, "s": 2433, "text": "Output:" }, { "code": null, "e": 2497, "s": 2441, "text": "In the above example, we do indexing of the data frame." }, { "code": null, "e": 2536, "s": 2497, "text": "Case 3: Manipulating Pandas Data frame" }, { "code": null, "e": 2711, "s": 2536, "text": "Manipulation of the data frame can be done in multiple ways like applying functions, changing a data type of columns, splitting, adding rows and columns to a data frame, etc." }, { "code": null, "e": 2784, "s": 2711, "text": "Example 1: Applying lambda function to a column using Dataframe.assign()" }, { "code": null, "e": 2792, "s": 2784, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # creating and initializing a listvalues = [['Rohan', 455], ['Elvish', 250], ['Deepak', 495], ['Sai', 400], ['Radha', 350], ['Vansh', 450]] # creating a pandas dataframedf = pd.DataFrame(values, columns=['Name', 'Univ_Marks']) # Applying lambda function to find percentage of# 'Univ_Marks' column using df.assign()df = df.assign(Percentage=lambda x: (x['Univ_Marks'] / 500 * 100)) # displaying the data framedf", "e": 3262, "s": 2792, "text": null }, { "code": null, "e": 3270, "s": 3262, "text": "Output:" }, { "code": null, "e": 3411, "s": 3270, "text": "In the above example, the lambda function is applied to the ‘Univ_Marks’ column and a new column ‘Percentage’ is formed with the help of it." }, { "code": null, "e": 3464, "s": 3411, "text": "Example 2: Sorting the Data frame in Ascending order" }, { "code": null, "e": 3472, "s": 3464, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', 38, 74, 3428000], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', 40, 100, 4528000], ['J.Root', 33, 72, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) # Sorting by column 'Weight'df.sort_values(by=['Weight'])", "e": 4049, "s": 3472, "text": null }, { "code": null, "e": 4057, "s": 4049, "text": "Output:" }, { "code": null, "e": 4123, "s": 4057, "text": "In the above example, we sort the data frame by column ‘Weight”. " }, { "code": null, "e": 4159, "s": 4123, "text": "Case 4: Cleaning Pandas Data frame " }, { "code": null, "e": 4167, "s": 4159, "text": "Python3" }, { "code": "# importing pandas and Numpy librariesimport pandas as pdimport numpy as np # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], ['A.B.D Villers', np.nan, 74, np.nan], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], ['C.Gayle', np.nan, 100, np.nan], [np.nan, 33, np.nan, 7028000], ['K.Peterson', 42, 85, 2528000]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) df", "e": 4727, "s": 4167, "text": null }, { "code": null, "e": 4735, "s": 4727, "text": "Output:" }, { "code": null, "e": 4743, "s": 4735, "text": "Python3" }, { "code": "# Checking for missing valuesdf.isnull().sum()", "e": 4790, "s": 4743, "text": null }, { "code": null, "e": 4798, "s": 4790, "text": "Output:" }, { "code": null, "e": 4806, "s": 4798, "text": "Python3" }, { "code": "# dropping or cleaning the missing data df= df.dropna() df", "e": 4865, "s": 4806, "text": null }, { "code": null, "e": 4873, "s": 4865, "text": "Output:" }, { "code": null, "e": 4947, "s": 4873, "text": "In the above example, we clean all the missing values from the data set. " }, { "code": null, "e": 4971, "s": 4947, "text": "Python pandas-dataFrame" }, { "code": null, "e": 4985, "s": 4971, "text": "Python-pandas" }, { "code": null, "e": 4992, "s": 4985, "text": "Python" } ]
How to Setup Handlebars View Engine in Node.js ?
27 Apr, 2020 Handlebars is a template engine that is widely used and easy to use. The pages contain .hbs extension and there are many other template engines in the market like EJS, Mustache, etc. Installation of hbs module: You can visit the link Install hbs module. You can install this package by using this command.npm install hbsAfter installing hbs module, you can check your hbs version in command prompt using the command.npm version hbsAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.jsTo setup hbs view engine, you need to write this middleware in your index.js as follow:app.set('views', path.join(__dirname)) app.set('view engine', 'hbs')Now create the file and run the code. It will display the result. You can visit the link Install hbs module. You can install this package by using this command.npm install hbs npm install hbs After installing hbs module, you can check your hbs version in command prompt using the command.npm version hbs npm version hbs After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js node index.js To setup hbs view engine, you need to write this middleware in your index.js as follow:app.set('views', path.join(__dirname)) app.set('view engine', 'hbs') app.set('views', path.join(__dirname)) app.set('view engine', 'hbs') Now create the file and run the code. It will display the result. Filename: Home.hbs <!DOCTYPE html><html><head> <title>Handlebars Demo</title></head><body> <!-- For loop demo --> {{#each array}} <h4>{{this}}</h4> {{/each}} <h4>{{message}}</h4></body></html> Filename: index.js const express = require('express')const path = require('path')const hbs = require('hbs')const app = express() // View Engine Setupapp.set('views', path.join(__dirname))app.set('view engine', 'hbs') app.get('/', function(req, res){ res.render('Home', { array: ['One', 'Two', 'Three', 'Four'], message: 'Greetings from geekforgeeks' })}) app.listen(8080, function(error){ if(error) throw error console.log("Server created Successfully")}) Steps to run the program: The project structure will look like this:Make sure you have installed hbs and express module using the following commands:npm install hbs npm install expressRun index.js file using the following command:node index.jsOpen browser and type this URL: http://localhost:8080/. Then you will see the Home.hbs page as shown below: The project structure will look like this: Make sure you have installed hbs and express module using the following commands:npm install hbs npm install express npm install hbs npm install express Run index.js file using the following command:node index.js node index.js Open browser and type this URL: http://localhost:8080/. Then you will see the Home.hbs page as shown below: So this is how you can setup Handlebars (hbs) view engine in node.js. There are many other handlebars engines exist like EJS, Mustache, etc. Node.js-Misc Node.js Web Technologies Web technologies Questions Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Apr, 2020" }, { "code": null, "e": 237, "s": 54, "text": "Handlebars is a template engine that is widely used and easy to use. The pages contain .hbs extension and there are many other template engines in the market like EJS, Mustache, etc." }, { "code": null, "e": 265, "s": 237, "text": "Installation of hbs module:" }, { "code": null, "e": 852, "s": 265, "text": "You can visit the link Install hbs module. You can install this package by using this command.npm install hbsAfter installing hbs module, you can check your hbs version in command prompt using the command.npm version hbsAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.jsTo setup hbs view engine, you need to write this middleware in your index.js as follow:app.set('views', path.join(__dirname))\napp.set('view engine', 'hbs')Now create the file and run the code. It will display the result." }, { "code": null, "e": 962, "s": 852, "text": "You can visit the link Install hbs module. You can install this package by using this command.npm install hbs" }, { "code": null, "e": 978, "s": 962, "text": "npm install hbs" }, { "code": null, "e": 1090, "s": 978, "text": "After installing hbs module, you can check your hbs version in command prompt using the command.npm version hbs" }, { "code": null, "e": 1106, "s": 1090, "text": "npm version hbs" }, { "code": null, "e": 1253, "s": 1106, "text": "After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 1267, "s": 1253, "text": "node index.js" }, { "code": null, "e": 1423, "s": 1267, "text": "To setup hbs view engine, you need to write this middleware in your index.js as follow:app.set('views', path.join(__dirname))\napp.set('view engine', 'hbs')" }, { "code": null, "e": 1492, "s": 1423, "text": "app.set('views', path.join(__dirname))\napp.set('view engine', 'hbs')" }, { "code": null, "e": 1558, "s": 1492, "text": "Now create the file and run the code. It will display the result." }, { "code": null, "e": 1577, "s": 1558, "text": "Filename: Home.hbs" }, { "code": "<!DOCTYPE html><html><head> <title>Handlebars Demo</title></head><body> <!-- For loop demo --> {{#each array}} <h4>{{this}}</h4> {{/each}} <h4>{{message}}</h4></body></html>", "e": 1774, "s": 1577, "text": null }, { "code": null, "e": 1793, "s": 1774, "text": "Filename: index.js" }, { "code": "const express = require('express')const path = require('path')const hbs = require('hbs')const app = express() // View Engine Setupapp.set('views', path.join(__dirname))app.set('view engine', 'hbs') app.get('/', function(req, res){ res.render('Home', { array: ['One', 'Two', 'Three', 'Four'], message: 'Greetings from geekforgeeks' })}) app.listen(8080, function(error){ if(error) throw error console.log(\"Server created Successfully\")})", "e": 2257, "s": 1793, "text": null }, { "code": null, "e": 2283, "s": 2257, "text": "Steps to run the program:" }, { "code": null, "e": 2608, "s": 2283, "text": "The project structure will look like this:Make sure you have installed hbs and express module using the following commands:npm install hbs\nnpm install expressRun index.js file using the following command:node index.jsOpen browser and type this URL: http://localhost:8080/. Then you will see the Home.hbs page as shown below:" }, { "code": null, "e": 2651, "s": 2608, "text": "The project structure will look like this:" }, { "code": null, "e": 2768, "s": 2651, "text": "Make sure you have installed hbs and express module using the following commands:npm install hbs\nnpm install express" }, { "code": null, "e": 2804, "s": 2768, "text": "npm install hbs\nnpm install express" }, { "code": null, "e": 2864, "s": 2804, "text": "Run index.js file using the following command:node index.js" }, { "code": null, "e": 2878, "s": 2864, "text": "node index.js" }, { "code": null, "e": 2986, "s": 2878, "text": "Open browser and type this URL: http://localhost:8080/. Then you will see the Home.hbs page as shown below:" }, { "code": null, "e": 3127, "s": 2986, "text": "So this is how you can setup Handlebars (hbs) view engine in node.js. There are many other handlebars engines exist like EJS, Mustache, etc." }, { "code": null, "e": 3140, "s": 3127, "text": "Node.js-Misc" }, { "code": null, "e": 3148, "s": 3140, "text": "Node.js" }, { "code": null, "e": 3165, "s": 3148, "text": "Web Technologies" }, { "code": null, "e": 3192, "s": 3165, "text": "Web technologies Questions" }, { "code": null, "e": 3208, "s": 3192, "text": "Write From Home" } ]
Setup Terraform On Linux and Windows Machine
30 Jun, 2020 Before learning about Multicloud, we must know what is a cloud?. Cloud is a name given to groups of different kinds of services provided by the server and is available over the internet. Example: Compute Units, Storage Units (like google drive).Different companies have built their own data centers to provide these cloud services. Example: AWS, GCP, Azure, etc. When a company decides to use different cloud platforms (mentioned above) to develop and use in an architecture it is called Multicloud. Terraform is a tool or software program that helps to work with different cloud platforms at a time. Each cloud platform has its own set of rules, syntax, and commands to work with, Terraform makes it easy for us to work with all such clouds at the same time. Terraform uses different plugins for different cloud platforms. So if you use terraform you do not need to learn the different syntax, commands, or rules required by the platforms. Terraform will automatically connect to platforms without you being worry. 1. Download the Zip file sudo wget https://releases.hashicorp.com/terraform/0.12.2/terraform_0.12.2_linux_amd64.zip 2. UnZip the Downloaded file and add this to the path sudo unzip ./terraform_0.12.2_linux_amd64.zip –d /usr/local/bin/ 3. if above command show error, first install wget and unzip, To install wget and unzip command enter the following commands as per your package managerFor yum package manager yum install wget unzip For apt package manager sudo apt install wget unzip 4. Now terraform is installed and can be checked by seeing the version terraform -v 1. Terraform is a product of a company hashicorp, so to download it for windows visit terraform download. 2. After Download put the terraform.exe at C:\Program Files\terraform 3. Also add this C:\Program Files\terraform path to the environment variables 4. Now you can check terraform version in cmd Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2020" }, { "code": null, "e": 528, "s": 28, "text": "Before learning about Multicloud, we must know what is a cloud?. Cloud is a name given to groups of different kinds of services provided by the server and is available over the internet. Example: Compute Units, Storage Units (like google drive).Different companies have built their own data centers to provide these cloud services. Example: AWS, GCP, Azure, etc. When a company decides to use different cloud platforms (mentioned above) to develop and use in an architecture it is called Multicloud." }, { "code": null, "e": 1044, "s": 528, "text": "Terraform is a tool or software program that helps to work with different cloud platforms at a time. Each cloud platform has its own set of rules, syntax, and commands to work with, Terraform makes it easy for us to work with all such clouds at the same time. Terraform uses different plugins for different cloud platforms. So if you use terraform you do not need to learn the different syntax, commands, or rules required by the platforms. Terraform will automatically connect to platforms without you being worry." }, { "code": null, "e": 1069, "s": 1044, "text": "1. Download the Zip file" }, { "code": null, "e": 1160, "s": 1069, "text": "sudo wget https://releases.hashicorp.com/terraform/0.12.2/terraform_0.12.2_linux_amd64.zip" }, { "code": null, "e": 1214, "s": 1160, "text": "2. UnZip the Downloaded file and add this to the path" }, { "code": null, "e": 1279, "s": 1214, "text": "sudo unzip ./terraform_0.12.2_linux_amd64.zip –d /usr/local/bin/" }, { "code": null, "e": 1455, "s": 1279, "text": "3. if above command show error, first install wget and unzip, To install wget and unzip command enter the following commands as per your package managerFor yum package manager" }, { "code": null, "e": 1478, "s": 1455, "text": "yum install wget unzip" }, { "code": null, "e": 1502, "s": 1478, "text": "For apt package manager" }, { "code": null, "e": 1530, "s": 1502, "text": "sudo apt install wget unzip" }, { "code": null, "e": 1601, "s": 1530, "text": "4. Now terraform is installed and can be checked by seeing the version" }, { "code": null, "e": 1614, "s": 1601, "text": "terraform -v" }, { "code": null, "e": 1720, "s": 1614, "text": "1. Terraform is a product of a company hashicorp, so to download it for windows visit terraform download." }, { "code": null, "e": 1790, "s": 1720, "text": "2. After Download put the terraform.exe at C:\\Program Files\\terraform" }, { "code": null, "e": 1868, "s": 1790, "text": "3. Also add this C:\\Program Files\\terraform path to the environment variables" }, { "code": null, "e": 1914, "s": 1868, "text": "4. Now you can check terraform version in cmd" }, { "code": null, "e": 1925, "s": 1914, "text": "Linux-Unix" } ]
How to use ngIf without an extra element in Angular2?
29 Jul, 2020 In order to use *ngIf without an extra element in Angular 2+, we can use either <ng-container> or <ng-template>But in many cases, <ng-container> is recommended.The best scenario regarding the usage of with *ngIf without an extra element is mentioned below. app.component.ts: import { Component } from '@angular/core';@Component({ selector: 'my-app-table', template: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { India=[{city:'Hyderabad'}, {city:'Mumbai'}] } app.component.html : <h1>ng-container example</h1> <div *ngFor="let state of India"> <ng-container *ngIf="state.city"> <p> {{ state.city }} </p> </ng-container> </div> Illustration of above code for ng-container If we inspect it then we can see there is no extra element added after <div> tag and before <p> tag. AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to setup 404 page in angular routing ? 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": "\n29 Jul, 2020" }, { "code": null, "e": 285, "s": 28, "text": "In order to use *ngIf without an extra element in Angular 2+, we can use either <ng-container> or <ng-template>But in many cases, <ng-container> is recommended.The best scenario regarding the usage of with *ngIf without an extra element is mentioned below." }, { "code": null, "e": 303, "s": 285, "text": "app.component.ts:" }, { "code": "import { Component } from '@angular/core';@Component({ selector: 'my-app-table', template: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { India=[{city:'Hyderabad'}, {city:'Mumbai'}] }", "e": 536, "s": 303, "text": null }, { "code": null, "e": 557, "s": 536, "text": "app.component.html :" }, { "code": "<h1>ng-container example</h1> <div *ngFor=\"let state of India\"> <ng-container *ngIf=\"state.city\"> <p> {{ state.city }} </p> </ng-container> </div>", "e": 716, "s": 557, "text": null }, { "code": null, "e": 760, "s": 716, "text": "Illustration of above code for ng-container" }, { "code": null, "e": 862, "s": 760, "text": "If we inspect it then we can see there is no extra element added after <div> tag and before <p> tag." }, { "code": null, "e": 877, "s": 862, "text": "AngularJS-Misc" }, { "code": null, "e": 884, "s": 877, "text": "Picked" }, { "code": null, "e": 894, "s": 884, "text": "AngularJS" }, { "code": null, "e": 911, "s": 894, "text": "Web Technologies" }, { "code": null, "e": 1009, "s": 911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1033, "s": 1009, "text": "Routing in Angular 9/10" }, { "code": null, "e": 1068, "s": 1033, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 1092, "s": 1068, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 1145, "s": 1092, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 1188, "s": 1145, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 1221, "s": 1188, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1283, "s": 1221, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1344, "s": 1283, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1394, "s": 1344, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
memcpy() in C/C++
06 Sep, 2021 memcpy() is used to copy a block of memory from a location to another. It is declared in string.h // Copies "numBytes" bytes from address "from" to address "to" void * memcpy(void *to, const void *from, size_t numBytes); Below is a sample C program to show working of memcpy(). C /* A C program to demonstrate working of memcpy */#include <stdio.h>#include <string.h> int main (){ char str1[] = "Geeks"; char str2[] = "Quiz"; puts("str1 before memcpy "); puts(str1); /* Copies contents of str2 to str1 */ memcpy (str1, str2, sizeof(str2)); puts("\nstr1 after memcpy "); puts(str1); return 0;} Output: str1 before memcpy Geeks str1 after memcpy Quiz Notes: 1) memcpy() doesn’t check for overflow or \0 2) memcpy() leads to problems when source and destination addresses overlap. memmove() is another library function that handles overlapping well.Write your own memcpy() and memmove()Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrinathsswami CPP-Library C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Sep, 2021" }, { "code": null, "e": 151, "s": 53, "text": "memcpy() is used to copy a block of memory from a location to another. It is declared in string.h" }, { "code": null, "e": 274, "s": 151, "text": "// Copies \"numBytes\" bytes from address \"from\" to address \"to\"\nvoid * memcpy(void *to, const void *from, size_t numBytes);" }, { "code": null, "e": 331, "s": 274, "text": "Below is a sample C program to show working of memcpy()." }, { "code": null, "e": 333, "s": 331, "text": "C" }, { "code": "/* A C program to demonstrate working of memcpy */#include <stdio.h>#include <string.h> int main (){ char str1[] = \"Geeks\"; char str2[] = \"Quiz\"; puts(\"str1 before memcpy \"); puts(str1); /* Copies contents of str2 to str1 */ memcpy (str1, str2, sizeof(str2)); puts(\"\\nstr1 after memcpy \"); puts(str1); return 0;}", "e": 661, "s": 333, "text": null }, { "code": null, "e": 670, "s": 661, "text": "Output: " }, { "code": null, "e": 721, "s": 670, "text": "str1 before memcpy \nGeeks\n\nstr1 after memcpy \nQuiz" }, { "code": null, "e": 851, "s": 721, "text": "Notes: 1) memcpy() doesn’t check for overflow or \\0 2) memcpy() leads to problems when source and destination addresses overlap. " }, { "code": null, "e": 1081, "s": 851, "text": "memmove() is another library function that handles overlapping well.Write your own memcpy() and memmove()Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 1096, "s": 1081, "text": "shrinathsswami" }, { "code": null, "e": 1108, "s": 1096, "text": "CPP-Library" }, { "code": null, "e": 1112, "s": 1108, "text": "C++" }, { "code": null, "e": 1116, "s": 1112, "text": "CPP" } ]
C | Data Types | Question 7
12 Dec, 2018 Assume that the size of char is 1 byte and negatives are stored in 2’s complement form #include<stdio.h>int main(){ char c = 125; c = c+10; printf("%d", c); return 0;} (A) 135(B) +INF(C) -121(D) -8Answer: (C)Explanation: 125 is represented as 01111101 in binary and when we add 10 i.e 1010 in binary it becomes : 10000111. Now what does this number represent?Firstly, you should know that char can store numbers only -128 to 127 since the most significant bit is kept for sign bit. Therefore 10000111 represents a negative number. To check which number it represents we find the 2’s complement of it and get 01111001 which is = 121 in decimal system. Hence, the number 10000111 represents -121.Quiz of this Question shaztri C-Data Types Data Types C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C | Dynamic Memory Allocation | Question 7 C | Dynamic Memory Allocation | Question 5 C | Advanced Pointer | Question 1 C | File Handling | Question 5 C | Advanced Pointer | Question 9 C | File Handling | Question 2 C | Pointer Basics | Question 17 C | Pointer Basics | Question 4 C | Advanced Pointer | Question 2 C | Input and Output | Question 2
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Dec, 2018" }, { "code": null, "e": 139, "s": 52, "text": "Assume that the size of char is 1 byte and negatives are stored in 2’s complement form" }, { "code": "#include<stdio.h>int main(){ char c = 125; c = c+10; printf(\"%d\", c); return 0;}", "e": 232, "s": 139, "text": null }, { "code": null, "e": 780, "s": 232, "text": "(A) 135(B) +INF(C) -121(D) -8Answer: (C)Explanation: 125 is represented as 01111101 in binary and when we add 10 i.e 1010 in binary it becomes : 10000111. Now what does this number represent?Firstly, you should know that char can store numbers only -128 to 127 since the most significant bit is kept for sign bit. Therefore 10000111 represents a negative number. To check which number it represents we find the 2’s complement of it and get 01111001 which is = 121 in decimal system. Hence, the number 10000111 represents -121.Quiz of this Question" }, { "code": null, "e": 788, "s": 780, "text": "shaztri" }, { "code": null, "e": 801, "s": 788, "text": "C-Data Types" }, { "code": null, "e": 812, "s": 801, "text": "Data Types" }, { "code": null, "e": 819, "s": 812, "text": "C Quiz" }, { "code": null, "e": 917, "s": 819, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 960, "s": 917, "text": "C | Dynamic Memory Allocation | Question 7" }, { "code": null, "e": 1003, "s": 960, "text": "C | Dynamic Memory Allocation | Question 5" }, { "code": null, "e": 1037, "s": 1003, "text": "C | Advanced Pointer | Question 1" }, { "code": null, "e": 1068, "s": 1037, "text": "C | File Handling | Question 5" }, { "code": null, "e": 1102, "s": 1068, "text": "C | Advanced Pointer | Question 9" }, { "code": null, "e": 1133, "s": 1102, "text": "C | File Handling | Question 2" }, { "code": null, "e": 1166, "s": 1133, "text": "C | Pointer Basics | Question 17" }, { "code": null, "e": 1198, "s": 1166, "text": "C | Pointer Basics | Question 4" }, { "code": null, "e": 1232, "s": 1198, "text": "C | Advanced Pointer | Question 2" } ]
UUID and Timeuuid functions in Cassandra
19 May, 2021 Prerequisite – Cassandra In this article, we are going to discuss uuid() function which is very important to insert value and to uniquely generates “guaranteed unique” UID value Universally. One of the reason of using uuid() function to generate Unique ID which helps in avoiding collisions. The uuid() function is suitable for use in insert or update statements and uuid() function takes no parameter value to generate a unique random Type 4 UUID value which is guaranteed unique value. Let’s take an example to understand the uuid() function. Create table function4(Id uuid primary key, name text); This CQL query is NOT correct to insert Id value using uuid() function. Insert into function4 (Id, name) values (1, ‘Ashish’); // fails Output: This CQL query is correct to insert Id value using uuid() function. Insert into function4(Id, name) values (now(), ‘Ashish’); //correct Output: Some additional timeuuid() functions: dateof() : This function returns the extracted timestamp as a date.now() : In Cassandra Query Language now() function can be used for UTC (Universal Time) standard. Now() method is useful to insert value which is guaranteed to be unique. To insert the current time as a value then we can use timeuuid functions now() and dateof(). dateof() : This function returns the extracted timestamp as a date. now() : In Cassandra Query Language now() function can be used for UTC (Universal Time) standard. Now() method is useful to insert value which is guaranteed to be unique. To insert the current time as a value then we can use timeuuid functions now() and dateof(). To insert the current time as a value then we can use timeuuid functions now() and dateof(). CREATE TABLE function_test1(Id uuid primary key, name text, modified_date timestamp ); INSERT INTO function_test1(Id, name, modified_date) VALUES (now(), 'Rana', '2019-10-29 00:05+0000'); INSERT INTO function_test1(Id, name, modified_date) VALUES (now(), 'Rana', '2019-10-30 00:05+0000'); select * from function_test1; Output: Output: Output: Now, let’s check how todate() function works. Now, let’s check how todate() function works. Now, let’s check how todate() function works. select todate(modified_date) from function_test1; Output: Output: Output: For later version >2.2.0 in Cassandra we can used toTimestamp(now()) function. For later version >2.2.0 in Cassandra we can used toTimestamp(now()) function. For later version >2.2.0 in Cassandra we can used toTimestamp(now()) function. CREATE TABLE function_test2(Id uuid primary key, name text, modified_date timestamp ); INSERT INTO function_test2 (Id, name, modified_date) VALUES (now(), 'Rana', toTimestamp(now())); Select * from function_test2; Output: Output: Output: minTimeuuid() and maxTimeuuid() : Both function is used to find minimum and maximum timeuuid respectively. minTimeuuid() function returns minimumm Timeuuid value and maxTimeuuid() function returns maximum Timeuuid value. unixTimestampOf() : In Cassandra Query Language unixTimestampOf() functions the timestamp in ms(milliseconds)of a timeuuid column in a result set. unixTimestampOf() functions returns 64 bit integer timestamp. minTimeuuid() and maxTimeuuid() : Both function is used to find minimum and maximum timeuuid respectively. minTimeuuid() function returns minimumm Timeuuid value and maxTimeuuid() function returns maximum Timeuuid value. unixTimestampOf() : In Cassandra Query Language unixTimestampOf() functions the timestamp in ms(milliseconds)of a timeuuid column in a result set. unixTimestampOf() functions returns 64 bit integer timestamp. In the new version of Cassandra to manipulate date support some additional timeuuid and timestamp functions. It can be used for insert, update, and select statements. Let’s understand with an example, CREATE TABLE function3( Col1 int, Col2 timestamp, Col3 timeuuid, Col4 bigint, PRIMARY KEY(Col1, Col2, Col3, Col4)); Insert into function3(Col1, Col2, Col3, Col4) Values (9, toUnixTimestamp(now()), 49d59e61-961b-11e8-9854-134d5b3f9cf8, toTimestamp(now())); SELECT * from function3; Output: Figure – Output of function3 table nidhi_biet gabaa406 Apache DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 May, 2021" }, { "code": null, "e": 220, "s": 28, "text": "Prerequisite – Cassandra In this article, we are going to discuss uuid() function which is very important to insert value and to uniquely generates “guaranteed unique” UID value Universally. " }, { "code": null, "e": 576, "s": 220, "text": "One of the reason of using uuid() function to generate Unique ID which helps in avoiding collisions. The uuid() function is suitable for use in insert or update statements and uuid() function takes no parameter value to generate a unique random Type 4 UUID value which is guaranteed unique value. Let’s take an example to understand the uuid() function. " }, { "code": null, "e": 633, "s": 576, "text": "Create table function4(Id uuid primary key, name text); " }, { "code": null, "e": 707, "s": 633, "text": "This CQL query is NOT correct to insert Id value using uuid() function. " }, { "code": null, "e": 774, "s": 707, "text": "Insert into function4 (Id, name) \nvalues (1, ‘Ashish’); // fails " }, { "code": null, "e": 783, "s": 774, "text": "Output: " }, { "code": null, "e": 855, "s": 785, "text": "This CQL query is correct to insert Id value using uuid() function. " }, { "code": null, "e": 926, "s": 855, "text": "Insert into function4(Id, name) \nvalues (now(), ‘Ashish’); //correct " }, { "code": null, "e": 935, "s": 926, "text": "Output: " }, { "code": null, "e": 977, "s": 937, "text": "Some additional timeuuid() functions: " }, { "code": null, "e": 1310, "s": 977, "text": "dateof() : This function returns the extracted timestamp as a date.now() : In Cassandra Query Language now() function can be used for UTC (Universal Time) standard. Now() method is useful to insert value which is guaranteed to be unique. To insert the current time as a value then we can use timeuuid functions now() and dateof(). " }, { "code": null, "e": 1378, "s": 1310, "text": "dateof() : This function returns the extracted timestamp as a date." }, { "code": null, "e": 1644, "s": 1378, "text": "now() : In Cassandra Query Language now() function can be used for UTC (Universal Time) standard. Now() method is useful to insert value which is guaranteed to be unique. To insert the current time as a value then we can use timeuuid functions now() and dateof(). " }, { "code": null, "e": 1739, "s": 1644, "text": "To insert the current time as a value then we can use timeuuid functions now() and dateof(). " }, { "code": null, "e": 2145, "s": 1739, "text": "CREATE TABLE function_test1(Id uuid primary key,\n name text,\n modified_date timestamp );\n\nINSERT INTO function_test1(Id, name, modified_date) \n VALUES (now(), 'Rana', '2019-10-29 00:05+0000');\nINSERT INTO function_test1(Id, name, modified_date) \n VALUES (now(), 'Rana', '2019-10-30 00:05+0000');\n\nselect * \nfrom function_test1; " }, { "code": null, "e": 2155, "s": 2145, "text": "Output: " }, { "code": null, "e": 2165, "s": 2155, "text": "Output: " }, { "code": null, "e": 2174, "s": 2165, "text": "Output: " }, { "code": null, "e": 2224, "s": 2176, "text": "Now, let’s check how todate() function works. " }, { "code": null, "e": 2272, "s": 2224, "text": "Now, let’s check how todate() function works. " }, { "code": null, "e": 2320, "s": 2272, "text": "Now, let’s check how todate() function works. " }, { "code": null, "e": 2372, "s": 2320, "text": "select todate(modified_date) \nfrom function_test1; " }, { "code": null, "e": 2382, "s": 2372, "text": "Output: " }, { "code": null, "e": 2392, "s": 2382, "text": "Output: " }, { "code": null, "e": 2401, "s": 2392, "text": "Output: " }, { "code": null, "e": 2484, "s": 2403, "text": "For later version >2.2.0 in Cassandra we can used toTimestamp(now()) function. " }, { "code": null, "e": 2565, "s": 2484, "text": "For later version >2.2.0 in Cassandra we can used toTimestamp(now()) function. " }, { "code": null, "e": 2646, "s": 2565, "text": "For later version >2.2.0 in Cassandra we can used toTimestamp(now()) function. " }, { "code": null, "e": 2937, "s": 2646, "text": "CREATE TABLE function_test2(Id uuid primary key,\n name text,\n modified_date timestamp );\n\nINSERT INTO function_test2 (Id, name, modified_date) \n VALUES (now(), 'Rana', toTimestamp(now()));\n\nSelect * \nfrom function_test2; " }, { "code": null, "e": 2947, "s": 2937, "text": "Output: " }, { "code": null, "e": 2957, "s": 2947, "text": "Output: " }, { "code": null, "e": 2966, "s": 2957, "text": "Output: " }, { "code": null, "e": 3400, "s": 2968, "text": " minTimeuuid() and maxTimeuuid() : Both function is used to find minimum and maximum timeuuid respectively. minTimeuuid() function returns minimumm Timeuuid value and maxTimeuuid() function returns maximum Timeuuid value. unixTimestampOf() : In Cassandra Query Language unixTimestampOf() functions the timestamp in ms(milliseconds)of a timeuuid column in a result set. unixTimestampOf() functions returns 64 bit integer timestamp." }, { "code": null, "e": 3627, "s": 3404, "text": "minTimeuuid() and maxTimeuuid() : Both function is used to find minimum and maximum timeuuid respectively. minTimeuuid() function returns minimumm Timeuuid value and maxTimeuuid() function returns maximum Timeuuid value. " }, { "code": null, "e": 3836, "s": 3627, "text": "unixTimestampOf() : In Cassandra Query Language unixTimestampOf() functions the timestamp in ms(milliseconds)of a timeuuid column in a result set. unixTimestampOf() functions returns 64 bit integer timestamp." }, { "code": null, "e": 4004, "s": 3836, "text": "In the new version of Cassandra to manipulate date support some additional timeuuid and timestamp functions. It can be used for insert, update, and select statements. " }, { "code": null, "e": 4041, "s": 4006, "text": "Let’s understand with an example, " }, { "code": null, "e": 4209, "s": 4043, "text": "CREATE TABLE function3( Col1 int, Col2 timestamp, \n Col3 timeuuid, Col4 bigint, \n PRIMARY KEY(Col1, Col2, Col3, Col4)); " }, { "code": null, "e": 4412, "s": 4211, "text": "Insert into function3(Col1, Col2, Col3, Col4) \n Values (9, toUnixTimestamp(now()), \n 49d59e61-961b-11e8-9854-134d5b3f9cf8, \n toTimestamp(now())); " }, { "code": null, "e": 4441, "s": 4414, "text": "SELECT * \nfrom function3; " }, { "code": null, "e": 4450, "s": 4441, "text": "Output: " }, { "code": null, "e": 4488, "s": 4452, "text": "Figure – Output of function3 table " }, { "code": null, "e": 4499, "s": 4488, "text": "nidhi_biet" }, { "code": null, "e": 4508, "s": 4499, "text": "gabaa406" }, { "code": null, "e": 4515, "s": 4508, "text": "Apache" }, { "code": null, "e": 4520, "s": 4515, "text": "DBMS" }, { "code": null, "e": 4525, "s": 4520, "text": "DBMS" } ]
HTML <input type="hidden"> - GeeksforGeeks
29 May, 2019 The HTML <input type=”hidden”> is used to define a input Hidden field. A hidden field also includes those data that could not be seen or modified by the users when submitted the form. A hidden field only stores those database records that need to be updated when submitting the form. Syntax: <input type="hidden"> Example: <!DOCTYPE html> <html> <head> <title> HTML input type hidden </title> <style> h1 { color: green; } body { text-align: center; } </style> </head> <body> <h1> GeeksforGeeks </h1> <h3> HTML <input type = "hidden"> </h3> <form action="#"> <input type="hidden" id="myFile" value="1234"> Name: <input type="text"> <input type="submit" value="Submit"> </form></body> </html> Output: Supported Browsers: The browsers supported by <input type=”hidden”> are listed below: Google Chrome 1.0 Internet Explorer Firefox 1.0 Safari 1.0 Opera 1.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction) Types of CSS (Cascading Style Sheet) Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 25026, "s": 24998, "text": "\n29 May, 2019" }, { "code": null, "e": 25310, "s": 25026, "text": "The HTML <input type=”hidden”> is used to define a input Hidden field. A hidden field also includes those data that could not be seen or modified by the users when submitted the form. A hidden field only stores those database records that need to be updated when submitting the form." }, { "code": null, "e": 25318, "s": 25310, "text": "Syntax:" }, { "code": null, "e": 25341, "s": 25318, "text": "<input type=\"hidden\"> " }, { "code": null, "e": 25350, "s": 25341, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML input type hidden </title> <style> h1 { color: green; } body { text-align: center; } </style> </head> <body> <h1> GeeksforGeeks </h1> <h3> HTML <input type = \"hidden\"> </h3> <form action=\"#\"> <input type=\"hidden\" id=\"myFile\" value=\"1234\"> Name: <input type=\"text\"> <input type=\"submit\" value=\"Submit\"> </form></body> </html> ", "e": 25933, "s": 25350, "text": null }, { "code": null, "e": 25941, "s": 25933, "text": "Output:" }, { "code": null, "e": 26027, "s": 25941, "text": "Supported Browsers: The browsers supported by <input type=”hidden”> are listed below:" }, { "code": null, "e": 26045, "s": 26027, "text": "Google Chrome 1.0" }, { "code": null, "e": 26063, "s": 26045, "text": "Internet Explorer" }, { "code": null, "e": 26075, "s": 26063, "text": "Firefox 1.0" }, { "code": null, "e": 26086, "s": 26075, "text": "Safari 1.0" }, { "code": null, "e": 26096, "s": 26086, "text": "Opera 1.0" }, { "code": null, "e": 26233, "s": 26096, "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": 26249, "s": 26233, "text": "HTML-Attributes" }, { "code": null, "e": 26254, "s": 26249, "text": "HTML" }, { "code": null, "e": 26271, "s": 26254, "text": "Web Technologies" }, { "code": null, "e": 26276, "s": 26271, "text": "HTML" }, { "code": null, "e": 26374, "s": 26276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26383, "s": 26374, "text": "Comments" }, { "code": null, "e": 26396, "s": 26383, "text": "Old Comments" }, { "code": null, "e": 26444, "s": 26396, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26494, "s": 26444, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26544, "s": 26494, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26568, "s": 26544, "text": "REST API (Introduction)" }, { "code": null, "e": 26605, "s": 26568, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26647, "s": 26605, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26680, "s": 26647, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26723, "s": 26680, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26768, "s": 26723, "text": "Convert a string to an integer in JavaScript" } ]
How to display Y-axis with Euro sign using ggplot2 in R?
When we have a Euro currency column in an R data frame as a response variable then we might to display the Euro sign in the plot created by using ggplot2 package. For this purpose, we can use scales package and the scale for Y axis will be changed by using the command scale_y_continuous(labels=dollar_format(suffix="€",prefix="")) to the plot command. Consider the below data frame − Live Demo x<-rpois(20,5) y<-rpois(20,100) df<-data.frame(x,y) df x y 1 8 112 2 10 81 3 4 97 4 7 104 5 4 98 6 5 99 7 5 97 8 7 97 9 5 95 10 3 98 11 6 92 12 6 80 13 6 92 14 6 108 15 7 113 16 4 103 17 3 106 18 2 116 19 4 105 20 6 83 Loading ggplot2 package and creating a scatterplot between x and y − library(ggplot2) ggplot(df,aes(x,y))+geom_point() Loading scales package and creating the scatterplot with Euro sign displayed with Y-axis labels − library(scales) ggplot(df)+geom_point(aes(x,y))+scale_y_continuous(labels=dollar_format(suffix="€",prefix=""))
[ { "code": null, "e": 1415, "s": 1062, "text": "When we have a Euro currency column in an R data frame as a response variable then we might to display the Euro sign in the plot created by using ggplot2 package. For this purpose, we can use scales package and the scale for Y axis will be changed by using the command scale_y_continuous(labels=dollar_format(suffix=\"€\",prefix=\"\")) to the plot command." }, { "code": null, "e": 1447, "s": 1415, "text": "Consider the below data frame −" }, { "code": null, "e": 1458, "s": 1447, "text": " Live Demo" }, { "code": null, "e": 1513, "s": 1458, "text": "x<-rpois(20,5)\ny<-rpois(20,100)\ndf<-data.frame(x,y)\ndf" }, { "code": null, "e": 1723, "s": 1513, "text": " x y\n1 8 112\n2 10 81\n3 4 97\n4 7 104\n5 4 98\n6 5 99\n7 5 97\n8 7 97\n9 5 95\n10 3 98\n11 6 92\n12 6 80\n13 6 92\n14 6 108\n15 7 113\n16 4 103\n17 3 106\n18 2 116\n19 4 105\n20 6 83" }, { "code": null, "e": 1792, "s": 1723, "text": "Loading ggplot2 package and creating a scatterplot between x and y −" }, { "code": null, "e": 1842, "s": 1792, "text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_point()" }, { "code": null, "e": 1940, "s": 1842, "text": "Loading scales package and creating the scatterplot with Euro sign displayed with Y-axis labels −" }, { "code": null, "e": 2051, "s": 1940, "text": "library(scales)\nggplot(df)+geom_point(aes(x,y))+scale_y_continuous(labels=dollar_format(suffix=\"€\",prefix=\"\"))" } ]
SQL Tryit Editor v1.6
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 23, "s": 0, "text": "SELECT * FROM Products" }, { "code": null, "e": 54, "s": 23, "text": "WHERE Price BETWEEN 10 AND 20;" }, { "code": null, "e": 56, "s": 54, "text": "​" }, { "code": null, "e": 119, "s": 56, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 179, "s": 119, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 247, "s": 179, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 285, "s": 247, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 370, "s": 285, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 544, "s": 370, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 595, "s": 544, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 663, "s": 595, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 834, "s": 663, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 934, "s": 834, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 994, "s": 934, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
How to convert a class to another class type in C++?
In this tutorial, we will be discussing a program to understand how to convert a class to another class type in C/C++. Class conversion can be done with the help of operator overloading. This allows data of one class type to be assigned to the object of another class type. Live Demo #include <bits/stdc++.h> using namespace std; //type to which it will be converted class Class_type_one { string a = "TutorialsPoint"; public: string get_string(){ return (a); } void display(){ cout << a << endl; } }; //class to be converted class Class_type_two { string b; public: void operator=(Class_type_one a){ b = a.get_string(); } void display(){ cout << b << endl; } }; int main(){ //type one Class_type_one a; //type two Class_type_two b; //type conversion b = a; a.display(); b.display(); return 0; } TutorialsPoint TutorialsPoint
[ { "code": null, "e": 1181, "s": 1062, "text": "In this tutorial, we will be discussing a program to understand how to convert a class to another class type in C/C++." }, { "code": null, "e": 1336, "s": 1181, "text": "Class conversion can be done with the help of operator overloading. This allows data of one class type to be assigned to the object of another class type." }, { "code": null, "e": 1347, "s": 1336, "text": " Live Demo" }, { "code": null, "e": 1952, "s": 1347, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//type to which it will be converted\nclass Class_type_one {\n string a = \"TutorialsPoint\";\n public:\n string get_string(){\n return (a);\n }\n void display(){\n cout << a << endl;\n }\n};\n//class to be converted\nclass Class_type_two {\n string b;\n public:\n void operator=(Class_type_one a){\n b = a.get_string();\n }\n void display(){\n cout << b << endl;\n }\n};\nint main(){\n //type one\n Class_type_one a;\n //type two\n Class_type_two b;\n //type conversion\n b = a;\n a.display();\n b.display();\n return 0;\n}" }, { "code": null, "e": 1982, "s": 1952, "text": "TutorialsPoint\nTutorialsPoint" } ]
How to create a DataBlock for Multispectral Satellite Image Segmentation with the Fastai-v2 | by Maurício Cordeiro | Towards Data Science
For information about the course Introduction to Python for Scientists (available on YouTube) and other articles like this, please visit my website cordmaur.carrd.co. Fastai is an open source deep learning library that adds higher level functionalities to PyTorch and makes it easier to achieve state-of-the-art results with little coding. The vision module is really handy when we need to quickly create an image dataset, apply data augmentations, resize, crop or even overlay a segmentation mask (Figure 1). However, all this simplification comes with a cost. Most of these higher level APIs for computer vision are optimized to RGB images, and these image libraries don’t support multispectral or multichannel images. In recent years, due to an increase in data accessibility, Earth Observation researchers have been paying a lot of attention on deep learning techniques, like image recognition, image segmentation, object detection, among others. [1]. The problem is that satellite imagery, usually composed by many different spectral bands (wavelengths), doesn’t fit in most vision libraries used by the deep learning community. For that reason, I have been working directly with PyTorch to create the dataset (here) and train the “home-made” U-Net architecture (here). With the upcoming of Fastai-v2 (promised to be released in next weeks)[2], I would like to test if it was possible to use it’s Data Block structure to create a multispectral image dataset to train a U-Net model. That’s more advanced than my previous stories as we have to create some custom subclasses, but I tried to make it as simple as possible. The notebook with all the code is available in the GitHub project (notebook here). Before we start, it’s necessary to install fastai2 library, following the installation guide at https://dev.fast.ai. To continue, we will need some training patches as multispectral images. That could be a Kaggle dataset, as the 38-cloud dataset, used in this story, or a completely new one. In the story Creating training patches for Deep Learning Image Segmentation of Satellite (Sentinel 2) Imagery using the Google Earth Engine (GEE), I show how to create training patches from Google Earth Engine and consume them as NumPy arrays. For this tutorial, I made it available in the GitHub repository (https://github.com/cordmaur/Fastai2-Medium), under /data folder, a few sample patches from Orós reservoir in Brazil. Data is saved as NumPy’s arrays and separated in two folders /data/images for the multispectral patches and /data/labels for the target masks. Checking number of files - images:40 masks:40Checking shapes - image: (13, 366, 366) mask: (366, 366) As we can see from the output, the images were cropped in 366x366 pixels and the training patches have 13 channels. These are the 12 Sentinel-2 bands, in order, and I have added an additional band to indicate “no data” flag. Channels have been put in the first axis, as it is the standard for PyTorch and Fastai, differently from other image libraries. Mask values are 0-No water, 1-Water and 2-Water Shadow. We will check an image sample using Matplotlib. For this, we need to move the channels axes to the last position using Numpy.transpose and select the corresponding Red, Green and Blue axis. Now that we have checked our images, we need a way of opening them in Fastai. As Fastai uses the Python Imaging Library (PIL), it is not able to handle multispectral images like these. We will, then, inherit a new class called MSTensorImage from the original TensorImage that is capable of opening .npy extensions and showing it visually. Let’s get to the code. First, we define a function that opens Numpy arrays and returns it as a given class (open_npy function). Then, we define the MSTensorImage class with a create method that receives the filename (or the numpy array, or a tensor), the desired channels (if we wouldn’t want to load all 13 channels) and a flag indicating whether the channels are in the first axis or not. At last, we define a show method to correctly display this image. We can pass to the show method different channels to create false color composites and Matplotlib axes for multiple display. In the following example, we can see that the image was correctly loaded and displayed. To handle the mask, instead of creating a new class, as we did previously, we will use the TensorMask class already defined in Fastai2. The only difference, in this case, is that the TensorMask, doesn’t know how to open .npy extensions. In this case, we will create it passing the result of our newly defined open_npy function, like so. The DataBlock is an abstraction to provide transformations to your source data to fit your model. Remember that in order to train a neural net, we have to provide the model a set of inputs (Xs) and corresponding targets (Ys). The cost and the optimization functions will take care of the rest. More complex architectures could have multiple Xs as inputs and even multiple targets, so the DataBlock accepts multiple pipelines (Figure 2). In our case, that is the most common, we need to create a DataBlock that provides only two blocks, Xs and Ys. For each block we can create a TransformBlock (that’s like a processing pipe) that manipulates each group (Xs or Ys) until they reach the desired format for loading into the model. To create a DataBlock, besides the TransformBlocks, we have to provide a function responsible to get the items, given a source. In our example, as the files are already saved in disk, the get_items function will just read the directory and return the file_names. The list of files will be the starting point of our transformations pipes. If the mask is created from the same original file (for example, if the mask was the 14th channel), the X transformation pipeline would be responsible to exclude this channel and the Y transformation pipeline would be responsible to extract this information from the original image. As we have the files saved separately, we will provide a new function called get_lbl_fn that will receive the name of the image file and then return the name of the corresponding target file. Now that we have some understanding of the DataBlock, let’s go to the code. The last command, DataBlock.summary, will check if everything is working fine and give us a data sample: Setting-up type transforms pipelinesCollecting items from Data\imagesFound 40 items2 datasets of sizes 36,4Setting up Pipeline: partialSetting up Pipeline: get_lbl_fn -> partialBuilding one sample Pipeline: partial starting from Data\images\Oros_1_19.npy applying partial gives MSTensorImage of size 13x366x366 Pipeline: get_lbl_fn -> partial starting from Data\images\Oros_1_19.npy applying get_lbl_fn gives Data\labels\Oros_1_19.npy applying partial gives TensorMask of size 366x366Final sample: (MSTensorImage: torch.Size([13, 366, 366]), TensorMask([[0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.], ..., [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.]]))Setting up after_item: Pipeline: AddMaskCodes -> ToTensorSetting up before_batch: Pipeline: Setting up after_batch: Pipeline: Building one batchApplying item_tfms to the first sample: Pipeline: AddMaskCodes -> ToTensor starting from (MSTensorImage of size 13x366x366, TensorMask of size 366x366) applying AddMaskCodes gives (MSTensorImage of size 13x366x366, TensorMask of size 366x366) applying ToTensor gives (MSTensorImage of size 13x366x366, TensorMask of size 366x366)Adding the next 3 samplesNo before_batch transform to applyCollating items in a batchNo batch_tfms to apply As we can see in the results, the final sample, after processing all the transformations, is composed of a tuple with 2 items (X, Y). In our case the (MSTensorImage, TensorMask). Once we are done creating the DataBlock the creation of a DataSet or a DataLoader are very straightforward. The datasets will be splitted, considering the splitter function (in our case, a random splitter with 10% for validation), into training and validation datasets, and the data can be accessed directly by subscripting: The same is valid for DataLoaders. Additionally the show_batch method automatically understands that we are performing a segmentation task (because of the TensorMask class) and overlays Xs and Ys: In today’s story we saw the basic concepts and how to use the Fastai 2’s DataBlock to prepare the multispectral satellite data to fit a deep learning model. The subclassing of the TensorImage class and the use of the open_npy function were enough to handle the multiple channels. As one can note, the basic functionalities of Fastai to create a dataloader and show a batch sample were successfully preserved. The fact of using Fastai 2 for these Earth Observation tasks is really handy, as differently from Fastai 1 and other high level APIs, Fastai 2’s built-in vision architectures accepts input channels as a parameter. But that’s a subject for a next story. The notebook and sample data to follow this “how-to” is available at the GitHub repository https://github.com/cordmaur/Fastai2-Medium. See you in the next story. [1] Hoeser, T., Kuenzer, C., 2020. Object Detection and Image Segmentation with Deep Learning on Earth Observation Data: A Review-Part I: Evolution and Recent Trends. Remote Sensing 12, 1667. https://doi.org/10.3390/rs12101667 [2] Howard, J., Gugger, S., 2020. fastai: A Layered API for Deep Learning. Information 11, 108. https://doi.org/10.3390/info11020108
[ { "code": null, "e": 339, "s": 172, "text": "For information about the course Introduction to Python for Scientists (available on YouTube) and other articles like this, please visit my website cordmaur.carrd.co." }, { "code": null, "e": 512, "s": 339, "text": "Fastai is an open source deep learning library that adds higher level functionalities to PyTorch and makes it easier to achieve state-of-the-art results with little coding." }, { "code": null, "e": 893, "s": 512, "text": "The vision module is really handy when we need to quickly create an image dataset, apply data augmentations, resize, crop or even overlay a segmentation mask (Figure 1). However, all this simplification comes with a cost. Most of these higher level APIs for computer vision are optimized to RGB images, and these image libraries don’t support multispectral or multichannel images." }, { "code": null, "e": 1447, "s": 893, "text": "In recent years, due to an increase in data accessibility, Earth Observation researchers have been paying a lot of attention on deep learning techniques, like image recognition, image segmentation, object detection, among others. [1]. The problem is that satellite imagery, usually composed by many different spectral bands (wavelengths), doesn’t fit in most vision libraries used by the deep learning community. For that reason, I have been working directly with PyTorch to create the dataset (here) and train the “home-made” U-Net architecture (here)." }, { "code": null, "e": 1879, "s": 1447, "text": "With the upcoming of Fastai-v2 (promised to be released in next weeks)[2], I would like to test if it was possible to use it’s Data Block structure to create a multispectral image dataset to train a U-Net model. That’s more advanced than my previous stories as we have to create some custom subclasses, but I tried to make it as simple as possible. The notebook with all the code is available in the GitHub project (notebook here)." }, { "code": null, "e": 1996, "s": 1879, "text": "Before we start, it’s necessary to install fastai2 library, following the installation guide at https://dev.fast.ai." }, { "code": null, "e": 2415, "s": 1996, "text": "To continue, we will need some training patches as multispectral images. That could be a Kaggle dataset, as the 38-cloud dataset, used in this story, or a completely new one. In the story Creating training patches for Deep Learning Image Segmentation of Satellite (Sentinel 2) Imagery using the Google Earth Engine (GEE), I show how to create training patches from Google Earth Engine and consume them as NumPy arrays." }, { "code": null, "e": 2741, "s": 2415, "text": "For this tutorial, I made it available in the GitHub repository (https://github.com/cordmaur/Fastai2-Medium), under /data folder, a few sample patches from Orós reservoir in Brazil. Data is saved as NumPy’s arrays and separated in two folders /data/images for the multispectral patches and /data/labels for the target masks." }, { "code": null, "e": 2848, "s": 2741, "text": "Checking number of files - images:40 masks:40Checking shapes - image: (13, 366, 366) mask: (366, 366)" }, { "code": null, "e": 3447, "s": 2848, "text": "As we can see from the output, the images were cropped in 366x366 pixels and the training patches have 13 channels. These are the 12 Sentinel-2 bands, in order, and I have added an additional band to indicate “no data” flag. Channels have been put in the first axis, as it is the standard for PyTorch and Fastai, differently from other image libraries. Mask values are 0-No water, 1-Water and 2-Water Shadow. We will check an image sample using Matplotlib. For this, we need to move the channels axes to the last position using Numpy.transpose and select the corresponding Red, Green and Blue axis." }, { "code": null, "e": 3809, "s": 3447, "text": "Now that we have checked our images, we need a way of opening them in Fastai. As Fastai uses the Python Imaging Library (PIL), it is not able to handle multispectral images like these. We will, then, inherit a new class called MSTensorImage from the original TensorImage that is capable of opening .npy extensions and showing it visually. Let’s get to the code." }, { "code": null, "e": 3914, "s": 3809, "text": "First, we define a function that opens Numpy arrays and returns it as a given class (open_npy function)." }, { "code": null, "e": 4177, "s": 3914, "text": "Then, we define the MSTensorImage class with a create method that receives the filename (or the numpy array, or a tensor), the desired channels (if we wouldn’t want to load all 13 channels) and a flag indicating whether the channels are in the first axis or not." }, { "code": null, "e": 4456, "s": 4177, "text": "At last, we define a show method to correctly display this image. We can pass to the show method different channels to create false color composites and Matplotlib axes for multiple display. In the following example, we can see that the image was correctly loaded and displayed." }, { "code": null, "e": 4793, "s": 4456, "text": "To handle the mask, instead of creating a new class, as we did previously, we will use the TensorMask class already defined in Fastai2. The only difference, in this case, is that the TensorMask, doesn’t know how to open .npy extensions. In this case, we will create it passing the result of our newly defined open_npy function, like so." }, { "code": null, "e": 5230, "s": 4793, "text": "The DataBlock is an abstraction to provide transformations to your source data to fit your model. Remember that in order to train a neural net, we have to provide the model a set of inputs (Xs) and corresponding targets (Ys). The cost and the optimization functions will take care of the rest. More complex architectures could have multiple Xs as inputs and even multiple targets, so the DataBlock accepts multiple pipelines (Figure 2)." }, { "code": null, "e": 5521, "s": 5230, "text": "In our case, that is the most common, we need to create a DataBlock that provides only two blocks, Xs and Ys. For each block we can create a TransformBlock (that’s like a processing pipe) that manipulates each group (Xs or Ys) until they reach the desired format for loading into the model." }, { "code": null, "e": 5859, "s": 5521, "text": "To create a DataBlock, besides the TransformBlocks, we have to provide a function responsible to get the items, given a source. In our example, as the files are already saved in disk, the get_items function will just read the directory and return the file_names. The list of files will be the starting point of our transformations pipes." }, { "code": null, "e": 6410, "s": 5859, "text": "If the mask is created from the same original file (for example, if the mask was the 14th channel), the X transformation pipeline would be responsible to exclude this channel and the Y transformation pipeline would be responsible to extract this information from the original image. As we have the files saved separately, we will provide a new function called get_lbl_fn that will receive the name of the image file and then return the name of the corresponding target file. Now that we have some understanding of the DataBlock, let’s go to the code." }, { "code": null, "e": 6515, "s": 6410, "text": "The last command, DataBlock.summary, will check if everything is working fine and give us a data sample:" }, { "code": null, "e": 7957, "s": 6515, "text": "Setting-up type transforms pipelinesCollecting items from Data\\imagesFound 40 items2 datasets of sizes 36,4Setting up Pipeline: partialSetting up Pipeline: get_lbl_fn -> partialBuilding one sample Pipeline: partial starting from Data\\images\\Oros_1_19.npy applying partial gives MSTensorImage of size 13x366x366 Pipeline: get_lbl_fn -> partial starting from Data\\images\\Oros_1_19.npy applying get_lbl_fn gives Data\\labels\\Oros_1_19.npy applying partial gives TensorMask of size 366x366Final sample: (MSTensorImage: torch.Size([13, 366, 366]), TensorMask([[0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.], ..., [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 0.]]))Setting up after_item: Pipeline: AddMaskCodes -> ToTensorSetting up before_batch: Pipeline: Setting up after_batch: Pipeline: Building one batchApplying item_tfms to the first sample: Pipeline: AddMaskCodes -> ToTensor starting from (MSTensorImage of size 13x366x366, TensorMask of size 366x366) applying AddMaskCodes gives (MSTensorImage of size 13x366x366, TensorMask of size 366x366) applying ToTensor gives (MSTensorImage of size 13x366x366, TensorMask of size 366x366)Adding the next 3 samplesNo before_batch transform to applyCollating items in a batchNo batch_tfms to apply" }, { "code": null, "e": 8136, "s": 7957, "text": "As we can see in the results, the final sample, after processing all the transformations, is composed of a tuple with 2 items (X, Y). In our case the (MSTensorImage, TensorMask)." }, { "code": null, "e": 8461, "s": 8136, "text": "Once we are done creating the DataBlock the creation of a DataSet or a DataLoader are very straightforward. The datasets will be splitted, considering the splitter function (in our case, a random splitter with 10% for validation), into training and validation datasets, and the data can be accessed directly by subscripting:" }, { "code": null, "e": 8658, "s": 8461, "text": "The same is valid for DataLoaders. Additionally the show_batch method automatically understands that we are performing a segmentation task (because of the TensorMask class) and overlays Xs and Ys:" }, { "code": null, "e": 9067, "s": 8658, "text": "In today’s story we saw the basic concepts and how to use the Fastai 2’s DataBlock to prepare the multispectral satellite data to fit a deep learning model. The subclassing of the TensorImage class and the use of the open_npy function were enough to handle the multiple channels. As one can note, the basic functionalities of Fastai to create a dataloader and show a batch sample were successfully preserved." }, { "code": null, "e": 9320, "s": 9067, "text": "The fact of using Fastai 2 for these Earth Observation tasks is really handy, as differently from Fastai 1 and other high level APIs, Fastai 2’s built-in vision architectures accepts input channels as a parameter. But that’s a subject for a next story." }, { "code": null, "e": 9455, "s": 9320, "text": "The notebook and sample data to follow this “how-to” is available at the GitHub repository https://github.com/cordmaur/Fastai2-Medium." }, { "code": null, "e": 9482, "s": 9455, "text": "See you in the next story." }, { "code": null, "e": 9709, "s": 9482, "text": "[1] Hoeser, T., Kuenzer, C., 2020. Object Detection and Image Segmentation with Deep Learning on Earth Observation Data: A Review-Part I: Evolution and Recent Trends. Remote Sensing 12, 1667. https://doi.org/10.3390/rs12101667" } ]
Static NAT (on ASA) - GeeksforGeeks
25 Oct, 2021 Prerequisite – Adaptive security appliance (ASA), Network address translation (NAT)ASA is a Cisco security device which has classic firewall capabilities like static packet filtering, stateful packet filtering with VPN, antivirus and intrusion prevention capabilities.Network Address Translation (NAT) is a process in which a private IP address is translated to a public IP address. This hides the IP address of the original source device from the outside network. Static NAT –In this, a single unregistered (Private) IP address is mapped with a legally registered (Public) IP address i.e one-to-one mapping between local and global address.These are generally used in Web hosting and home networks. These are not used in organizations as there are many devices who will need Internet access and to provide Internet access, public IP addresses are needed. Suppose, if there are 3000 devices who needs access to Internet, the organization has to buy 3000 public addresses that will be very costly. Procedure – Step-1: Configure the access-list –Build the access-list stating the permit condition i.e who should be permit and what protocol should be permit. Step-2: Apply the access-list to an interface –The access-group command will be used to state the direction (out or in) in which the action (specified above) should be taken place. Step-3: Create network object –This will state the host on which NAT will be applied. Step-4: Create static NAT statement –This step will specify the direction in which NAT should take place and in what IP address the private IP address should be translated, e.g., NAT (DMZ, OUTSIDE) static 111.1.1.1 This states that the static NAT operation will take place when the traffic is going from DMZ to OUTSIDE and will translate the IP address (specified in network object command) to 111.1.1.1 Note –The access-list has been made to allow ICMP the traffic from OUTSIDE to DMZ or INSIDE because by default, the ICMP traffic is not allowed from lower security level to higher security level in ASA (Adaptive Security Appliance). Example – Three routers namely Router1 (IP address – 10.1.1.1/24), Router2 (IP address – 11.1.1.1/24) and Router3 (IP address – 101.1.1.1) are connected to ASA (IP address- 10.1.1.2/24, name – INSIDE and security level – 100 on Gi0/0, IP address – 11.1.1.2/24, name – DMZ and security level – 50 on Gi0/1, IP address – 101.1.1.2/24, name-OUTSIDE and security level – 0 on Gi0/2) as shown in the above figure. In this task, we will enable static NAT for the traffic generating from INSIDE to OUTSIDE and for the traffic going from DMZ to OUTSIDE.Configuring IP addresses on all routers and ASA.Configure IP address on Router1. Router1(config)#int fa0/0 Router1(config-if)#ip address 10.1.1.1 255.255.255.0 Router1(config-if)#no shut Configuring IP address on Router2. Router2(config)#int fa0/0 Router2(config-if)#ip address 11.1.1.1 255.255.255.0 Router2(config-if)#no shut Configuring IP address on Router3. Router3(config)#int fa0/0 Router3(config-if)#ip address 101.1.1.1 255.255.255.0 Router3(config-if)#no shut Configuring IP address, name and security level on the interface of ASA. asa(config)#int Gi0/0 asa(config-if)#no shut asa(config-if)#ip address 10.1.1.2 255.255.255.0 asa(config-if)#nameif INSIDE asa(config-if)#security level 100 asa(config-if)#exit asa(config)#int Gi0/1 asa(config-if)#no shut asa(config-if)#ip address 11.1.1.2 255.255.255.0 asa(config-if)#nameif DMZ asa(config-if)#security level 50 asa(config-if)#exit asa(config)#int Gi0/2 asa(config-if)#no shut asa(config-if)#ip address 101.1.1.2 255.255.255.0 asa(config-if)#nameif OUTSIDE asa(config-if)#security level 0 Now giving static routes to the routers.Configuring static route to Router1. Router1(config)#ip route 0.0.0.0 0.0.0.0 10.1.1.2 Configuring static route to Router2. Router2(config)#ip route 0.0.0.0 0.0.0.0 11.1.1.2 Configuring static route to Router3. Router3(config)#ip route 0.0.0.0 0.0.0.0 101.1.1.2 Now, at last configuring static route to ASA. asa(config)#route INSIDE 10.1.1.0 255.255.255.0 10.1.1.1 asa(config)#route OUTSIDE 101.1.1.0 255.255.255.0 101.1.1.1 asa(config)#route DMZ 11.1.1.0 255.255.255.0 10.1.1.1 Now, for ICMP, either we have to inspect or we have to use ACL to allow the ICMP echo reply from the lower security level to higher security level (This is to be done because by default, no traffic is allowed from lower security level to higher security level).In this scenario, we will use ACL. asa(config)#access-list traffic_out permit icmp any any asa(config)#access-list traffic_dmz permit icmp any any Here, two access-list has been made.First access-list name is traffic_out which will allow ICMP traffic from OUTSIDE to INSIDE (having an IP address any mask).Second access-list has been made named traffic_dmz which will allow ICMP traffic from OUTSIDE to DMZ (having an IP address any mask). Now, we have to apply these access-list to the ASA interfaces: asa(config)#access-group traffic_out in interface OUTSIDE asa(config)#access-group traffic_dmz in interface DMZ First statement states that the access-list traffic_out is applied in the inwards direction to the OUTSIDE interface. Second statement states that the access-list traffic_dmz is applied in the inwards direction to the DMZ interface.Now, INSIDE devices will be able to ping OUTSIDE and DMZ devices. Now, the task is to enable NAT on ASA whenever the traffic goes out from INSIDE to OUTSIDE and DMZ to OUTSIDE. asa(config)#object network INSIDE_OUTSIDE_NAT asa(config-network-object)#host 10.1.1.1 asa(config-network-object)#nat (INSIDE, OUTSIDE) static 110.1.1.1 Here, the host 10.1.1.1 will be translated to 110.1.1.1 when the traffic will go from INSIDE to OUTSIDE. asa(config)#object network DMZ_OUTSIDE_NAT asa(config-network-object)#host 11.1.1.1 asa(config-network-object)#exit asa(config)#nat (DMZ, OUTSIDE) static 111.1.1.1 Here, the host 11.1.1.1 will be translated to 111.1.1.1 when the traffic will go from DMZ to OUTSIDE. vaibhavsinghtanwar Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments UDP Server-Client implementation in C TCP 3-Way Handshake Process Error Detection in Computer Networks Socket Programming in Java Hamming Code in Computer Network Implementation of Diffie-Hellman Algorithm Differences between IPv4 and IPv6 Distance Vector Routing (DVR) Protocol Advanced Encryption Standard (AES) User Datagram Protocol (UDP)
[ { "code": null, "e": 24774, "s": 24746, "text": "\n25 Oct, 2021" }, { "code": null, "e": 25239, "s": 24774, "text": "Prerequisite – Adaptive security appliance (ASA), Network address translation (NAT)ASA is a Cisco security device which has classic firewall capabilities like static packet filtering, stateful packet filtering with VPN, antivirus and intrusion prevention capabilities.Network Address Translation (NAT) is a process in which a private IP address is translated to a public IP address. This hides the IP address of the original source device from the outside network." }, { "code": null, "e": 25474, "s": 25239, "text": "Static NAT –In this, a single unregistered (Private) IP address is mapped with a legally registered (Public) IP address i.e one-to-one mapping between local and global address.These are generally used in Web hosting and home networks." }, { "code": null, "e": 25771, "s": 25474, "text": "These are not used in organizations as there are many devices who will need Internet access and to provide Internet access, public IP addresses are needed. Suppose, if there are 3000 devices who needs access to Internet, the organization has to buy 3000 public addresses that will be very costly." }, { "code": null, "e": 25783, "s": 25771, "text": "Procedure –" }, { "code": null, "e": 25930, "s": 25783, "text": "Step-1: Configure the access-list –Build the access-list stating the permit condition i.e who should be permit and what protocol should be permit." }, { "code": null, "e": 26111, "s": 25930, "text": "Step-2: Apply the access-list to an interface –The access-group command will be used to state the direction (out or in) in which the action (specified above) should be taken place." }, { "code": null, "e": 26197, "s": 26111, "text": "Step-3: Create network object –This will state the host on which NAT will be applied." }, { "code": null, "e": 26601, "s": 26197, "text": "Step-4: Create static NAT statement –This step will specify the direction in which NAT should take place and in what IP address the private IP address should be translated, e.g., NAT (DMZ, OUTSIDE) static 111.1.1.1 This states that the static NAT operation will take place when the traffic is going from DMZ to OUTSIDE and will translate the IP address (specified in network object command) to 111.1.1.1" }, { "code": null, "e": 26834, "s": 26601, "text": "Note –The access-list has been made to allow ICMP the traffic from OUTSIDE to DMZ or INSIDE because by default, the ICMP traffic is not allowed from lower security level to higher security level in ASA (Adaptive Security Appliance)." }, { "code": null, "e": 26844, "s": 26834, "text": "Example –" }, { "code": null, "e": 27243, "s": 26844, "text": "Three routers namely Router1 (IP address – 10.1.1.1/24), Router2 (IP address – 11.1.1.1/24) and Router3 (IP address – 101.1.1.1) are connected to ASA (IP address- 10.1.1.2/24, name – INSIDE and security level – 100 on Gi0/0, IP address – 11.1.1.2/24, name – DMZ and security level – 50 on Gi0/1, IP address – 101.1.1.2/24, name-OUTSIDE and security level – 0 on Gi0/2) as shown in the above figure." }, { "code": null, "e": 27460, "s": 27243, "text": "In this task, we will enable static NAT for the traffic generating from INSIDE to OUTSIDE and for the traffic going from DMZ to OUTSIDE.Configuring IP addresses on all routers and ASA.Configure IP address on Router1." }, { "code": null, "e": 27567, "s": 27460, "text": "Router1(config)#int fa0/0\nRouter1(config-if)#ip address 10.1.1.1 255.255.255.0\nRouter1(config-if)#no shut " }, { "code": null, "e": 27602, "s": 27567, "text": "Configuring IP address on Router2." }, { "code": null, "e": 27709, "s": 27602, "text": "Router2(config)#int fa0/0\nRouter2(config-if)#ip address 11.1.1.1 255.255.255.0\nRouter2(config-if)#no shut " }, { "code": null, "e": 27744, "s": 27709, "text": "Configuring IP address on Router3." }, { "code": null, "e": 27852, "s": 27744, "text": "Router3(config)#int fa0/0\nRouter3(config-if)#ip address 101.1.1.1 255.255.255.0\nRouter3(config-if)#no shut " }, { "code": null, "e": 27925, "s": 27852, "text": "Configuring IP address, name and security level on the interface of ASA." }, { "code": null, "e": 28433, "s": 27925, "text": "asa(config)#int Gi0/0\nasa(config-if)#no shut\nasa(config-if)#ip address 10.1.1.2 255.255.255.0\nasa(config-if)#nameif INSIDE \nasa(config-if)#security level 100\nasa(config-if)#exit\nasa(config)#int Gi0/1\nasa(config-if)#no shut\nasa(config-if)#ip address 11.1.1.2 255.255.255.0\nasa(config-if)#nameif DMZ\nasa(config-if)#security level 50\nasa(config-if)#exit\nasa(config)#int Gi0/2\nasa(config-if)#no shut\nasa(config-if)#ip address 101.1.1.2 255.255.255.0\nasa(config-if)#nameif OUTSIDE\nasa(config-if)#security level 0" }, { "code": null, "e": 28510, "s": 28433, "text": "Now giving static routes to the routers.Configuring static route to Router1." }, { "code": null, "e": 28561, "s": 28510, "text": "Router1(config)#ip route 0.0.0.0 0.0.0.0 10.1.1.2 " }, { "code": null, "e": 28598, "s": 28561, "text": "Configuring static route to Router2." }, { "code": null, "e": 28649, "s": 28598, "text": "Router2(config)#ip route 0.0.0.0 0.0.0.0 11.1.1.2 " }, { "code": null, "e": 28686, "s": 28649, "text": "Configuring static route to Router3." }, { "code": null, "e": 28738, "s": 28686, "text": "Router3(config)#ip route 0.0.0.0 0.0.0.0 101.1.1.2 " }, { "code": null, "e": 28784, "s": 28738, "text": "Now, at last configuring static route to ASA." }, { "code": null, "e": 28956, "s": 28784, "text": "asa(config)#route INSIDE 10.1.1.0 255.255.255.0 10.1.1.1\nasa(config)#route OUTSIDE 101.1.1.0 255.255.255.0 101.1.1.1\nasa(config)#route DMZ 11.1.1.0 255.255.255.0 10.1.1.1\n" }, { "code": null, "e": 29252, "s": 28956, "text": "Now, for ICMP, either we have to inspect or we have to use ACL to allow the ICMP echo reply from the lower security level to higher security level (This is to be done because by default, no traffic is allowed from lower security level to higher security level).In this scenario, we will use ACL." }, { "code": null, "e": 29366, "s": 29252, "text": "asa(config)#access-list traffic_out permit icmp any any \nasa(config)#access-list traffic_dmz permit icmp any any " }, { "code": null, "e": 29659, "s": 29366, "text": "Here, two access-list has been made.First access-list name is traffic_out which will allow ICMP traffic from OUTSIDE to INSIDE (having an IP address any mask).Second access-list has been made named traffic_dmz which will allow ICMP traffic from OUTSIDE to DMZ (having an IP address any mask)." }, { "code": null, "e": 29722, "s": 29659, "text": "Now, we have to apply these access-list to the ASA interfaces:" }, { "code": null, "e": 29835, "s": 29722, "text": "asa(config)#access-group traffic_out in interface OUTSIDE \nasa(config)#access-group traffic_dmz in interface DMZ" }, { "code": null, "e": 30244, "s": 29835, "text": "First statement states that the access-list traffic_out is applied in the inwards direction to the OUTSIDE interface. Second statement states that the access-list traffic_dmz is applied in the inwards direction to the DMZ interface.Now, INSIDE devices will be able to ping OUTSIDE and DMZ devices. Now, the task is to enable NAT on ASA whenever the traffic goes out from INSIDE to OUTSIDE and DMZ to OUTSIDE." }, { "code": null, "e": 30398, "s": 30244, "text": "asa(config)#object network INSIDE_OUTSIDE_NAT\nasa(config-network-object)#host 10.1.1.1\nasa(config-network-object)#nat (INSIDE, OUTSIDE) static 110.1.1.1 " }, { "code": null, "e": 30503, "s": 30398, "text": "Here, the host 10.1.1.1 will be translated to 110.1.1.1 when the traffic will go from INSIDE to OUTSIDE." }, { "code": null, "e": 30668, "s": 30503, "text": "asa(config)#object network DMZ_OUTSIDE_NAT\nasa(config-network-object)#host 11.1.1.1\nasa(config-network-object)#exit\nasa(config)#nat (DMZ, OUTSIDE) static 111.1.1.1 " }, { "code": null, "e": 30770, "s": 30668, "text": "Here, the host 11.1.1.1 will be translated to 111.1.1.1 when the traffic will go from DMZ to OUTSIDE." }, { "code": null, "e": 30789, "s": 30770, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 30807, "s": 30789, "text": "Computer Networks" }, { "code": null, "e": 30825, "s": 30807, "text": "Computer Networks" }, { "code": null, "e": 30923, "s": 30825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30932, "s": 30923, "text": "Comments" }, { "code": null, "e": 30945, "s": 30932, "text": "Old Comments" }, { "code": null, "e": 30983, "s": 30945, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 31011, "s": 30983, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 31048, "s": 31011, "text": "Error Detection in Computer Networks" }, { "code": null, "e": 31075, "s": 31048, "text": "Socket Programming in Java" }, { "code": null, "e": 31108, "s": 31075, "text": "Hamming Code in Computer Network" }, { "code": null, "e": 31151, "s": 31108, "text": "Implementation of Diffie-Hellman Algorithm" }, { "code": null, "e": 31185, "s": 31151, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 31224, "s": 31185, "text": "Distance Vector Routing (DVR) Protocol" }, { "code": null, "e": 31259, "s": 31224, "text": "Advanced Encryption Standard (AES)" } ]
Check whether frequency of characters in a string makes Fibonacci Sequence - GeeksforGeeks
26 Nov, 2021 Given a string with lowercase English alphabets. The task is to check whether the frequency of the characters in the string can be arranged as a Fibonacci series. If yes, print “YES”, otherwise print “NO”.Note: Frequencies can be arranged in any way to form Fibonacci Series. The Fibonacci Series starts from 1. That is the series is 1,1,2,3,5,..... Examples: Input : str = "abeeedd" Output : YES Frequency of 'a' => 1 Frequency of 'b' => 1 Frequency of 'e' => 3 Frequency of 'd' => 2 These frequencies are first 4 terms of Fibonacci series => {1, 1, 2, 3} Input : str = "dzzddz" Output : NO Frequencies are not in Fibonacci series Approach: Store the frequencies of each character of the string in a map. Let the size of the map be after storing frequencies. Then, make a vector and insert first ‘n’ elements of the Fibonacci series in this vector. Then, compare each element of the vector with values of the map. If both elements of vector and values of the map are same, print ‘YES’, otherwise print ‘NO’. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check whether frequency of// characters in a string makes// Fibonacci Sequence #include <bits/stdc++.h>using namespace std; // Function to check if the frequencies// are in Fibonacci seriesstring isFibonacci(string s){ // map to store the // frequencies of character map<char, int> m; for (int i = 0; i < s.length(); i++) { m[s[i]]++; } // Vector to store first n // fibonacci numbers vector<int> v; // Get the size of the map int n = m.size(); // a and b are first and second terms of // fibonacci series int a = 1, b = 1; int c; v.push_back(a); v.push_back(b); // vector v contains elements of fibonacci series for (int i = 0; i < n - 2; i++) { v.push_back(a + b); c = a + b; a = b; b = c; } int flag = 1; int i = 0; // Compare vector elements with values in Map for (auto itr = m.begin(); itr != m.end(); itr++) { if (itr->second != v[i]) { flag = 0; break; } i++; } if (flag == 1) return "YES"; else return "NO";} // Driver codeint main(){ string s = "abeeedd"; cout << isFibonacci(s); return 0;} // Java program to check whether frequency of// characters in a string makes// Fibonacci Sequenceimport java.util.HashMap;import java.util.Vector; class GFG{ // Function to check if the frequencies // are in Fibonacci series static String isFibonacci(String s) { // map to store the // frequencies of character HashMap<Character, Integer> m = new HashMap<>(); for (int i = 0; i < s.length(); i++) m.put(s.charAt(i), m.get(s.charAt(i)) == null ? 1 : m.get(s.charAt(i)) + 1); // Vector to store first n // fibonacci numbers Vector<Integer> v = new Vector<>(); // Get the size of the map int n = m.size(); // a and b are first and second terms of // fibonacci series int a = 1, b = 1; int c; v.add(a); v.add(b); // vector v contains elements of // fibonacci series for (int i = 0; i < n - 2; i++) { v.add(a + b); c = a + b; a = b; b = c; } int flag = 1; int i = 0; // Compare vector elements with values in Map for (HashMap.Entry<Character, Integer> entry : m.entrySet()) { if (entry.getValue() != v.elementAt(i)) { flag = 1; break; } i++; } if (flag == 1) return "YES"; else return "NO"; } // Driver Code public static void main(String[] args) { String s = "abeeedd"; System.out.println(isFibonacci(s)); }} // This code is contributed by// sanjeev2552 # Python3 program to check whether the frequency# of characters in a string make Fibonacci Sequencefrom collections import defaultdict # Function to check if the frequencies# are in Fibonacci seriesdef isFibonacci(s): # map to store the frequencies of character m = defaultdict(lambda:0) for i in range(0, len(s)): m[s[i]] += 1 # Vector to store first n fibonacci numbers v = [] # Get the size of the map n = len(m) # a and b are first and second # terms of fibonacci series a = b = 1 v.append(a) v.append(b) # vector v contains elements of # fibonacci series for i in range(0, n - 2): v.append(a + b) c = a + b a, b = b, c flag, i = 1, 0 # Compare vector elements with values in Map for itr in sorted(m): if m[itr] != v[i]: flag = 0 break i += 1 if flag == 1: return "YES" else: return "NO" # Driver codeif __name__ == "__main__": s = "abeeedd" print(isFibonacci(s)) # This code is contributed by Rituraj Jain // C# program to check whether frequency of// characters in a string makes// Fibonacci Sequenceusing System;using System.Collections.Generic; class GFG{ // Function to check if the frequencies // are in Fibonacci series static String isFibonacci(String s) { // map to store the // frequencies of character int i = 0; Dictionary<int, int> mp = new Dictionary<int, int>(); for (i = 0; i < s.Length; i++) { if(mp.ContainsKey(s[i])) { var val = mp[s[i]]; mp.Remove(s[i]); mp.Add(s[i], val + 1); } else { mp.Add(s[i], 1); } } // List to store first n // fibonacci numbers List<int> v = new List<int>(); // Get the size of the map int n = mp.Count; // a and b are first and second terms of // fibonacci series int a = 1, b = 1; int c; v.Add(a); v.Add(b); // vector v contains elements of // fibonacci series for (i = 0; i < n - 2; i++) { v.Add(a + b); c = a + b; a = b; b = c; } int flag = 1; // Compare vector elements with values in Map foreach(KeyValuePair<int, int> entry in mp) { if (entry.Value != v[i]) { flag = 1; break; } i++; } if (flag == 1) return "YES"; else return "NO"; } // Driver Code public static void Main(String[] args) { String s = "abeeedd"; Console.WriteLine(isFibonacci(s)); }} // This code is contributed by 29AjayKumar <script> // Javascript program to check whether frequency of// characters in a string makes// Fibonacci Sequence // Function to check if the frequencies// are in Fibonacci seriesfunction isFibonacci(s){ // map to store the // frequencies of character var m = new Map(); for (var i = 0; i < s.length; i++) { if(m.has(s[i])) { m.set(s[i], m.get(s[i])); } else { m.set(s[i], 1); } } // Vector to store first n // fibonacci numbers var v = []; // Get the size of the map var n = m.length; // a and b are first and second terms of // fibonacci series var a = 1, b = 1; var c; v.push(a); v.push(b); // vector v contains elements of fibonacci series for (var i = 0; i < n - 2; i++) { v.push(a + b); c = a + b; a = b; b = c; } var flag = 1; var i = 0; // Compare vector elements with values in Map m.forEach((value, key) => { if (value != v[i]) { flag = 0; } }); if (flag == 1) return "YES"; else return "NO";} // Driver codevar s = "abeeedd";document.write( isFibonacci(s)); </script> YES Time Complexity: O(n), where n is the length of the given string. Auxiliary Space: O(n) rituraj_jain sanjeev2552 29AjayKumar noob2000 samim2000 cpp-map Fibonacci frequency-counting Strings Strings Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Minimum changes to a string to make all substrings distinct Hill Cipher Vigenère Cipher Naive algorithm for Pattern Searching How to Append a Character to a String in C Convert character array to string in C++ Converting Roman Numerals to Decimal lying between 1 to 3999 sprintf() in C Print all subsequences of a string
[ { "code": null, "e": 24828, "s": 24800, "text": "\n26 Nov, 2021" }, { "code": null, "e": 25041, "s": 24828, "text": "Given a string with lowercase English alphabets. The task is to check whether the frequency of the characters in the string can be arranged as a Fibonacci series. If yes, print “YES”, otherwise print “NO”.Note: " }, { "code": null, "e": 25106, "s": 25041, "text": "Frequencies can be arranged in any way to form Fibonacci Series." }, { "code": null, "e": 25180, "s": 25106, "text": "The Fibonacci Series starts from 1. That is the series is 1,1,2,3,5,....." }, { "code": null, "e": 25192, "s": 25180, "text": "Examples: " }, { "code": null, "e": 25466, "s": 25192, "text": "Input : str = \"abeeedd\"\nOutput : YES\nFrequency of 'a' => 1\nFrequency of 'b' => 1\nFrequency of 'e' => 3\nFrequency of 'd' => 2\nThese frequencies are first 4 terms of \nFibonacci series => {1, 1, 2, 3}\n\nInput : str = \"dzzddz\"\nOutput : NO\nFrequencies are not in Fibonacci series" }, { "code": null, "e": 25478, "s": 25466, "text": "Approach: " }, { "code": null, "e": 25596, "s": 25478, "text": "Store the frequencies of each character of the string in a map. Let the size of the map be after storing frequencies." }, { "code": null, "e": 25686, "s": 25596, "text": "Then, make a vector and insert first ‘n’ elements of the Fibonacci series in this vector." }, { "code": null, "e": 25845, "s": 25686, "text": "Then, compare each element of the vector with values of the map. If both elements of vector and values of the map are same, print ‘YES’, otherwise print ‘NO’." }, { "code": null, "e": 25897, "s": 25845, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25901, "s": 25897, "text": "C++" }, { "code": null, "e": 25906, "s": 25901, "text": "Java" }, { "code": null, "e": 25914, "s": 25906, "text": "Python3" }, { "code": null, "e": 25917, "s": 25914, "text": "C#" }, { "code": null, "e": 25928, "s": 25917, "text": "Javascript" }, { "code": "// C++ program to check whether frequency of// characters in a string makes// Fibonacci Sequence #include <bits/stdc++.h>using namespace std; // Function to check if the frequencies// are in Fibonacci seriesstring isFibonacci(string s){ // map to store the // frequencies of character map<char, int> m; for (int i = 0; i < s.length(); i++) { m[s[i]]++; } // Vector to store first n // fibonacci numbers vector<int> v; // Get the size of the map int n = m.size(); // a and b are first and second terms of // fibonacci series int a = 1, b = 1; int c; v.push_back(a); v.push_back(b); // vector v contains elements of fibonacci series for (int i = 0; i < n - 2; i++) { v.push_back(a + b); c = a + b; a = b; b = c; } int flag = 1; int i = 0; // Compare vector elements with values in Map for (auto itr = m.begin(); itr != m.end(); itr++) { if (itr->second != v[i]) { flag = 0; break; } i++; } if (flag == 1) return \"YES\"; else return \"NO\";} // Driver codeint main(){ string s = \"abeeedd\"; cout << isFibonacci(s); return 0;}", "e": 27138, "s": 25928, "text": null }, { "code": "// Java program to check whether frequency of// characters in a string makes// Fibonacci Sequenceimport java.util.HashMap;import java.util.Vector; class GFG{ // Function to check if the frequencies // are in Fibonacci series static String isFibonacci(String s) { // map to store the // frequencies of character HashMap<Character, Integer> m = new HashMap<>(); for (int i = 0; i < s.length(); i++) m.put(s.charAt(i), m.get(s.charAt(i)) == null ? 1 : m.get(s.charAt(i)) + 1); // Vector to store first n // fibonacci numbers Vector<Integer> v = new Vector<>(); // Get the size of the map int n = m.size(); // a and b are first and second terms of // fibonacci series int a = 1, b = 1; int c; v.add(a); v.add(b); // vector v contains elements of // fibonacci series for (int i = 0; i < n - 2; i++) { v.add(a + b); c = a + b; a = b; b = c; } int flag = 1; int i = 0; // Compare vector elements with values in Map for (HashMap.Entry<Character, Integer> entry : m.entrySet()) { if (entry.getValue() != v.elementAt(i)) { flag = 1; break; } i++; } if (flag == 1) return \"YES\"; else return \"NO\"; } // Driver Code public static void main(String[] args) { String s = \"abeeedd\"; System.out.println(isFibonacci(s)); }} // This code is contributed by// sanjeev2552", "e": 28859, "s": 27138, "text": null }, { "code": "# Python3 program to check whether the frequency# of characters in a string make Fibonacci Sequencefrom collections import defaultdict # Function to check if the frequencies# are in Fibonacci seriesdef isFibonacci(s): # map to store the frequencies of character m = defaultdict(lambda:0) for i in range(0, len(s)): m[s[i]] += 1 # Vector to store first n fibonacci numbers v = [] # Get the size of the map n = len(m) # a and b are first and second # terms of fibonacci series a = b = 1 v.append(a) v.append(b) # vector v contains elements of # fibonacci series for i in range(0, n - 2): v.append(a + b) c = a + b a, b = b, c flag, i = 1, 0 # Compare vector elements with values in Map for itr in sorted(m): if m[itr] != v[i]: flag = 0 break i += 1 if flag == 1: return \"YES\" else: return \"NO\" # Driver codeif __name__ == \"__main__\": s = \"abeeedd\" print(isFibonacci(s)) # This code is contributed by Rituraj Jain", "e": 29938, "s": 28859, "text": null }, { "code": "// C# program to check whether frequency of// characters in a string makes// Fibonacci Sequenceusing System;using System.Collections.Generic; class GFG{ // Function to check if the frequencies // are in Fibonacci series static String isFibonacci(String s) { // map to store the // frequencies of character int i = 0; Dictionary<int, int> mp = new Dictionary<int, int>(); for (i = 0; i < s.Length; i++) { if(mp.ContainsKey(s[i])) { var val = mp[s[i]]; mp.Remove(s[i]); mp.Add(s[i], val + 1); } else { mp.Add(s[i], 1); } } // List to store first n // fibonacci numbers List<int> v = new List<int>(); // Get the size of the map int n = mp.Count; // a and b are first and second terms of // fibonacci series int a = 1, b = 1; int c; v.Add(a); v.Add(b); // vector v contains elements of // fibonacci series for (i = 0; i < n - 2; i++) { v.Add(a + b); c = a + b; a = b; b = c; } int flag = 1; // Compare vector elements with values in Map foreach(KeyValuePair<int, int> entry in mp) { if (entry.Value != v[i]) { flag = 1; break; } i++; } if (flag == 1) return \"YES\"; else return \"NO\"; } // Driver Code public static void Main(String[] args) { String s = \"abeeedd\"; Console.WriteLine(isFibonacci(s)); }} // This code is contributed by 29AjayKumar", "e": 31799, "s": 29938, "text": null }, { "code": "<script> // Javascript program to check whether frequency of// characters in a string makes// Fibonacci Sequence // Function to check if the frequencies// are in Fibonacci seriesfunction isFibonacci(s){ // map to store the // frequencies of character var m = new Map(); for (var i = 0; i < s.length; i++) { if(m.has(s[i])) { m.set(s[i], m.get(s[i])); } else { m.set(s[i], 1); } } // Vector to store first n // fibonacci numbers var v = []; // Get the size of the map var n = m.length; // a and b are first and second terms of // fibonacci series var a = 1, b = 1; var c; v.push(a); v.push(b); // vector v contains elements of fibonacci series for (var i = 0; i < n - 2; i++) { v.push(a + b); c = a + b; a = b; b = c; } var flag = 1; var i = 0; // Compare vector elements with values in Map m.forEach((value, key) => { if (value != v[i]) { flag = 0; } }); if (flag == 1) return \"YES\"; else return \"NO\";} // Driver codevar s = \"abeeedd\";document.write( isFibonacci(s)); </script>", "e": 32996, "s": 31799, "text": null }, { "code": null, "e": 33000, "s": 32996, "text": "YES" }, { "code": null, "e": 33068, "s": 33002, "text": "Time Complexity: O(n), where n is the length of the given string." }, { "code": null, "e": 33090, "s": 33068, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 33103, "s": 33090, "text": "rituraj_jain" }, { "code": null, "e": 33115, "s": 33103, "text": "sanjeev2552" }, { "code": null, "e": 33127, "s": 33115, "text": "29AjayKumar" }, { "code": null, "e": 33136, "s": 33127, "text": "noob2000" }, { "code": null, "e": 33146, "s": 33136, "text": "samim2000" }, { "code": null, "e": 33154, "s": 33146, "text": "cpp-map" }, { "code": null, "e": 33164, "s": 33154, "text": "Fibonacci" }, { "code": null, "e": 33183, "s": 33164, "text": "frequency-counting" }, { "code": null, "e": 33191, "s": 33183, "text": "Strings" }, { "code": null, "e": 33199, "s": 33191, "text": "Strings" }, { "code": null, "e": 33209, "s": 33199, "text": "Fibonacci" }, { "code": null, "e": 33307, "s": 33209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33352, "s": 33307, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 33412, "s": 33352, "text": "Minimum changes to a string to make all substrings distinct" }, { "code": null, "e": 33424, "s": 33412, "text": "Hill Cipher" }, { "code": null, "e": 33441, "s": 33424, "text": "Vigenère Cipher" }, { "code": null, "e": 33479, "s": 33441, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 33522, "s": 33479, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 33563, "s": 33522, "text": "Convert character array to string in C++" }, { "code": null, "e": 33624, "s": 33563, "text": "Converting Roman Numerals to Decimal lying between 1 to 3999" }, { "code": null, "e": 33639, "s": 33624, "text": "sprintf() in C" } ]
C# | Get an enumerator that iterates through the List - GeeksforGeeks
01 Feb, 2019 List<T>.GetEnumerator Method is used to returns an enumerator that iterates through the List<T>. Syntax: public System.Collections.Generic.List<T>.Enumerator GetEnumerator (); Return Value: It returns an List<T>Enumerator for the List<T>. Below programs illustrate the use of List<T>.GetEnumerator Method: Example 1: // C# code to get an enumerator// that iterates through the List<T>.using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of int List<int> mylist = new List<int>(); // Inserting elements into List mylist.Add(45); mylist.Add(78); mylist.Add(32); mylist.Add(231); mylist.Add(123); mylist.Add(76); mylist.Add(726); mylist.Add(716); mylist.Add(876); // To get an Enumerator // for the List. List<int>.Enumerator em = mylist.GetEnumerator(); display(em); } // display method static void display(IEnumerator<int> em) { while (em.MoveNext()) { int val = em.Current; Console.WriteLine(val); } }} Output: 45 78 32 231 123 76 726 716 876 Example 2: // C# code to get an enumerator// that iterates through the List<T>.using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of string List<string> mylist = new List<string>(); // Inserting elements into List mylist.Add("C#"); mylist.Add("Java"); mylist.Add("C"); mylist.Add("C++"); // To get an Enumerator // for the List. List<string>.Enumerator em = mylist.GetEnumerator(); display(em); } // display method static void display(IEnumerator<string> em) { while (em.MoveNext()) { string val = em.Current; Console.WriteLine(val); } }} Output: C# Java C C++ Note: The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection. Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element. An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined. This method is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.getenumerator?view=netframework-4.7.2 CSharp-Generic-List CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Class and Object C# | Constructors Introduction to .NET Framework Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Abstract Classes C# | Delegates C# | Data Types Top 50 C# Interview Questions & Answers Common Language Runtime (CLR) in C#
[ { "code": null, "e": 24674, "s": 24646, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24771, "s": 24674, "text": "List<T>.GetEnumerator Method is used to returns an enumerator that iterates through the List<T>." }, { "code": null, "e": 24779, "s": 24771, "text": "Syntax:" }, { "code": null, "e": 24850, "s": 24779, "text": "public System.Collections.Generic.List<T>.Enumerator GetEnumerator ();" }, { "code": null, "e": 24913, "s": 24850, "text": "Return Value: It returns an List<T>Enumerator for the List<T>." }, { "code": null, "e": 24980, "s": 24913, "text": "Below programs illustrate the use of List<T>.GetEnumerator Method:" }, { "code": null, "e": 24991, "s": 24980, "text": "Example 1:" }, { "code": "// C# code to get an enumerator// that iterates through the List<T>.using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of int List<int> mylist = new List<int>(); // Inserting elements into List mylist.Add(45); mylist.Add(78); mylist.Add(32); mylist.Add(231); mylist.Add(123); mylist.Add(76); mylist.Add(726); mylist.Add(716); mylist.Add(876); // To get an Enumerator // for the List. List<int>.Enumerator em = mylist.GetEnumerator(); display(em); } // display method static void display(IEnumerator<int> em) { while (em.MoveNext()) { int val = em.Current; Console.WriteLine(val); } }}", "e": 25829, "s": 24991, "text": null }, { "code": null, "e": 25837, "s": 25829, "text": "Output:" }, { "code": null, "e": 25870, "s": 25837, "text": "45\n78\n32\n231\n123\n76\n726\n716\n876\n" }, { "code": null, "e": 25881, "s": 25870, "text": "Example 2:" }, { "code": "// C# code to get an enumerator// that iterates through the List<T>.using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of string List<string> mylist = new List<string>(); // Inserting elements into List mylist.Add(\"C#\"); mylist.Add(\"Java\"); mylist.Add(\"C\"); mylist.Add(\"C++\"); // To get an Enumerator // for the List. List<string>.Enumerator em = mylist.GetEnumerator(); display(em); } // display method static void display(IEnumerator<string> em) { while (em.MoveNext()) { string val = em.Current; Console.WriteLine(val); } }}", "e": 26627, "s": 25881, "text": null }, { "code": null, "e": 26635, "s": 26627, "text": "Output:" }, { "code": null, "e": 26650, "s": 26635, "text": "C#\nJava\nC\nC++\n" }, { "code": null, "e": 26656, "s": 26650, "text": "Note:" }, { "code": null, "e": 26828, "s": 26656, "text": "The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator." }, { "code": null, "e": 26949, "s": 26828, "text": "Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection." }, { "code": null, "e": 27066, "s": 26949, "text": "Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element." }, { "code": null, "e": 27302, "s": 27066, "text": "An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined." }, { "code": null, "e": 27336, "s": 27302, "text": "This method is an O(1) operation." }, { "code": null, "e": 27347, "s": 27336, "text": "Reference:" }, { "code": null, "e": 27463, "s": 27347, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.getenumerator?view=netframework-4.7.2" }, { "code": null, "e": 27483, "s": 27463, "text": "CSharp-Generic-List" }, { "code": null, "e": 27508, "s": 27483, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 27522, "s": 27508, "text": "CSharp-method" }, { "code": null, "e": 27525, "s": 27522, "text": "C#" }, { "code": null, "e": 27623, "s": 27525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27632, "s": 27623, "text": "Comments" }, { "code": null, "e": 27645, "s": 27632, "text": "Old Comments" }, { "code": null, "e": 27667, "s": 27645, "text": "C# | Class and Object" }, { "code": null, "e": 27685, "s": 27667, "text": "C# | Constructors" }, { "code": null, "e": 27716, "s": 27685, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27739, "s": 27716, "text": "Extension Method in C#" }, { "code": null, "e": 27779, "s": 27739, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27801, "s": 27779, "text": "C# | Abstract Classes" }, { "code": null, "e": 27816, "s": 27801, "text": "C# | Delegates" }, { "code": null, "e": 27832, "s": 27816, "text": "C# | Data Types" }, { "code": null, "e": 27872, "s": 27832, "text": "Top 50 C# Interview Questions & Answers" } ]
Java Concurrency - AtomicIntegerArray Class
A java.util.concurrent.atomic.AtomicIntegerArray class provides operations on underlying int array that can be read and written atomically, and also contains advanced atomic operations. AtomicIntegerArray supports atomic operations on underlying int array variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features. Following is the list of important methods available in the AtomicIntegerArray class. public int addAndGet(int i, int delta) Atomically adds the given value to the element at index i. public boolean compareAndSet(int i, int expect, int update) Atomically sets the element at position i to the given updated value if the current value == the expected value. public int decrementAndGet(int i) Atomically decrements by one the element at index i. public int get(int i) Gets the current value at position i. public int getAndAdd(int i, int delta) Atomically adds the given value to the element at index i. public int getAndDecrement(int i) Atomically decrements by one the element at index i. public int getAndIncrement(int i) Atomically increments by one the element at index i. public int getAndSet(int i, int newValue) Atomically sets the element at position i to the given value and returns the old value. public int incrementAndGet(int i) Atomically increments by one the element at index i. public void lazySet(int i, int newValue) Eventually sets the element at position i to the given value. public int length() Returns the length of the array. public void set(int i, int newValue) Sets the element at position i to the given value. public String toString() Returns the String representation of the current values of array. public boolean weakCompareAndSet(int i, int expect, int update) Atomically sets the element at position i to the given updated value if the current value == the expected value. The following TestThread program shows usage of AtomicIntegerArray variable in thread based environment. import java.util.concurrent.atomic.AtomicIntegerArray; public class TestThread { private static AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(10); public static void main(final String[] arguments) throws InterruptedException { for (int i = 0; i<atomicIntegerArray.length(); i++) { atomicIntegerArray.set(i, 1); } Thread t1 = new Thread(new Increment()); Thread t2 = new Thread(new Compare()); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Values: "); for (int i = 0; i<atomicIntegerArray.length(); i++) { System.out.print(atomicIntegerArray.get(i) + " "); } } static class Increment implements Runnable { public void run() { for(int i = 0; i<atomicIntegerArray.length(); i++) { int add = atomicIntegerArray.incrementAndGet(i); System.out.println("Thread " + Thread.currentThread().getId() + ", index " +i + ", value: "+ add); } } } static class Compare implements Runnable { public void run() { for(int i = 0; i<atomicIntegerArray.length(); i++) { boolean swapped = atomicIntegerArray.compareAndSet(i, 2, 3); if(swapped) { System.out.println("Thread " + Thread.currentThread().getId() + ", index " +i + ", value: 3"); } } } } } This will produce the following result. Thread 10, index 0, value: 2 Thread 10, index 1, value: 2 Thread 10, index 2, value: 2 Thread 11, index 0, value: 3 Thread 10, index 3, value: 2 Thread 11, index 1, value: 3 Thread 11, index 2, value: 3 Thread 10, index 4, value: 2 Thread 11, index 3, value: 3 Thread 10, index 5, value: 2 Thread 10, index 6, value: 2 Thread 11, index 4, value: 3 Thread 10, index 7, value: 2 Thread 11, index 5, value: 3 Thread 10, index 8, value: 2 Thread 11, index 6, value: 3 Thread 10, index 9, value: 2 Thread 11, index 7, value: 3 Thread 11, index 8, value: 3 Thread 11, index 9, value: 3 Values: 3 3 3 3 3 3 3 3 3 3 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 3177, "s": 2657, "text": "A java.util.concurrent.atomic.AtomicIntegerArray class provides operations on underlying int array that can be read and written atomically, and also contains advanced atomic operations. AtomicIntegerArray supports atomic operations on underlying int array variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features." }, { "code": null, "e": 3263, "s": 3177, "text": "Following is the list of important methods available in the AtomicIntegerArray class." }, { "code": null, "e": 3302, "s": 3263, "text": "public int addAndGet(int i, int delta)" }, { "code": null, "e": 3361, "s": 3302, "text": "Atomically adds the given value to the element at index i." }, { "code": null, "e": 3421, "s": 3361, "text": "public boolean compareAndSet(int i, int expect, int update)" }, { "code": null, "e": 3534, "s": 3421, "text": "Atomically sets the element at position i to the given updated value if the current value == the expected value." }, { "code": null, "e": 3568, "s": 3534, "text": "public int decrementAndGet(int i)" }, { "code": null, "e": 3621, "s": 3568, "text": "Atomically decrements by one the element at index i." }, { "code": null, "e": 3643, "s": 3621, "text": "public int get(int i)" }, { "code": null, "e": 3681, "s": 3643, "text": "Gets the current value at position i." }, { "code": null, "e": 3720, "s": 3681, "text": "public int getAndAdd(int i, int delta)" }, { "code": null, "e": 3779, "s": 3720, "text": "Atomically adds the given value to the element at index i." }, { "code": null, "e": 3813, "s": 3779, "text": "public int getAndDecrement(int i)" }, { "code": null, "e": 3866, "s": 3813, "text": "Atomically decrements by one the element at index i." }, { "code": null, "e": 3900, "s": 3866, "text": "public int getAndIncrement(int i)" }, { "code": null, "e": 3953, "s": 3900, "text": "Atomically increments by one the element at index i." }, { "code": null, "e": 3995, "s": 3953, "text": "public int getAndSet(int i, int newValue)" }, { "code": null, "e": 4083, "s": 3995, "text": "Atomically sets the element at position i to the given value and returns the old value." }, { "code": null, "e": 4117, "s": 4083, "text": "public int incrementAndGet(int i)" }, { "code": null, "e": 4170, "s": 4117, "text": "Atomically increments by one the element at index i." }, { "code": null, "e": 4211, "s": 4170, "text": "public void lazySet(int i, int newValue)" }, { "code": null, "e": 4273, "s": 4211, "text": "Eventually sets the element at position i to the given value." }, { "code": null, "e": 4293, "s": 4273, "text": "public int length()" }, { "code": null, "e": 4326, "s": 4293, "text": "Returns the length of the array." }, { "code": null, "e": 4363, "s": 4326, "text": "public void set(int i, int newValue)" }, { "code": null, "e": 4414, "s": 4363, "text": "Sets the element at position i to the given value." }, { "code": null, "e": 4439, "s": 4414, "text": "public String toString()" }, { "code": null, "e": 4505, "s": 4439, "text": "Returns the String representation of the current values of array." }, { "code": null, "e": 4569, "s": 4505, "text": "public boolean weakCompareAndSet(int i, int expect, int update)" }, { "code": null, "e": 4682, "s": 4569, "text": "Atomically sets the element at position i to the given updated value if the current value == the expected value." }, { "code": null, "e": 4787, "s": 4682, "text": "The following TestThread program shows usage of AtomicIntegerArray variable in thread based environment." }, { "code": null, "e": 6258, "s": 4787, "text": "import java.util.concurrent.atomic.AtomicIntegerArray;\n\npublic class TestThread {\n private static AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(10);\n\n public static void main(final String[] arguments) throws InterruptedException {\n \n for (int i = 0; i<atomicIntegerArray.length(); i++) {\n atomicIntegerArray.set(i, 1);\n }\n\n Thread t1 = new Thread(new Increment());\n Thread t2 = new Thread(new Compare());\n t1.start();\n t2.start();\n\n t1.join();\n t2.join();\n\n System.out.println(\"Values: \");\n\n for (int i = 0; i<atomicIntegerArray.length(); i++) {\n System.out.print(atomicIntegerArray.get(i) + \" \");\n }\n }\n\n static class Increment implements Runnable {\n\n public void run() {\n\n for(int i = 0; i<atomicIntegerArray.length(); i++) {\n int add = atomicIntegerArray.incrementAndGet(i);\n System.out.println(\"Thread \" + Thread.currentThread().getId() \n + \", index \" +i + \", value: \"+ add);\n }\n }\n }\n\n static class Compare implements Runnable {\n\n public void run() {\n\n for(int i = 0; i<atomicIntegerArray.length(); i++) {\n boolean swapped = atomicIntegerArray.compareAndSet(i, 2, 3);\n \n if(swapped) {\n System.out.println(\"Thread \" + Thread.currentThread().getId()\n + \", index \" +i + \", value: 3\");\n }\n }\n }\n }\n}" }, { "code": null, "e": 6298, "s": 6258, "text": "This will produce the following result." }, { "code": null, "e": 6907, "s": 6298, "text": "Thread 10, index 0, value: 2\nThread 10, index 1, value: 2\nThread 10, index 2, value: 2\nThread 11, index 0, value: 3\nThread 10, index 3, value: 2\nThread 11, index 1, value: 3\nThread 11, index 2, value: 3\nThread 10, index 4, value: 2\nThread 11, index 3, value: 3\nThread 10, index 5, value: 2\nThread 10, index 6, value: 2\nThread 11, index 4, value: 3\nThread 10, index 7, value: 2\nThread 11, index 5, value: 3\nThread 10, index 8, value: 2\nThread 11, index 6, value: 3\nThread 10, index 9, value: 2\nThread 11, index 7, value: 3\nThread 11, index 8, value: 3\nThread 11, index 9, value: 3\nValues:\n3 3 3 3 3 3 3 3 3 3\n" }, { "code": null, "e": 6940, "s": 6907, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6956, "s": 6940, "text": " Malhar Lathkar" }, { "code": null, "e": 6989, "s": 6956, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 7005, "s": 6989, "text": " Malhar Lathkar" }, { "code": null, "e": 7040, "s": 7005, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7054, "s": 7040, "text": " Anadi Sharma" }, { "code": null, "e": 7088, "s": 7054, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 7102, "s": 7088, "text": " Tushar Kale" }, { "code": null, "e": 7139, "s": 7102, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7154, "s": 7139, "text": " Monica Mittal" }, { "code": null, "e": 7187, "s": 7154, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 7206, "s": 7187, "text": " Arnab Chakraborty" }, { "code": null, "e": 7213, "s": 7206, "text": " Print" }, { "code": null, "e": 7224, "s": 7213, "text": " Add Notes" } ]
C# | Type.GetEnumValues() Method - GeeksforGeeks
27 Aug, 2021 Type.GetEnumValues() Method is used to return an array of the values of the constants in the current enumeration type.Syntax: public virtual Array GetEnumValues (); Return Value: This method returns an array which contains the values. The elements of the array are sorted by the binary values i.e. the unsigned values of the enumeration constants.Exception: This method will give ArgumentException if the current type is not an enumeration.Below programs illustrate the use of the above-discussed method:Example 1: csharp // C# program to demonstrate the// Type.GetEnumValues() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Defining enum ABC enum ABC { A, B, C, D, E, F } // Main Method public static void Main() { // try-catch block to // handle exceptions try { // Creating and initializing object // of ABC with instance of enum ABC ABC a = ABC.A; // Declaring and initializing // object of Type Type type = a.GetType(); // Getting an array of the values // of the constants // By using GetEnumValues() method Array obj = type.GetEnumValues(); // Display values of the constants Console.Write("Values of the constants is : {0} ", obj); } // catch ArgumentException here catch (ArgumentException e) { Console.WriteLine("The current type is not an enumeration."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} Values of the constants is : GFG+ABC[] Example 2: For ArgumentException csharp // C# program to demonstrate the// Type.GetEnumValues() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Defining enum ABC enum ABC { A, B, C, D, E, F } // Main Method public static void Main() { // try-catch block to // handle exceptions try { // Creating and initializing object // of ABC with instance of enum ABC ABC a = ABC.A; // Declaring and initializing // object of Type Type type = typeof(int); // Getting an array of the values // of the constants // By using GetEnumValues() method Array obj = type.GetEnumValues(); // Display values of the constants Console.Write("Values of the constants is : {0} ", obj); } // catch ArgumentException here catch (ArgumentException e) { Console.WriteLine("The current type is not an enumeration."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} The current type is not an enumeration. Exception Thrown: System.ArgumentException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.type.getenumvalues?view=netframework-4.8 rs1686740 CSharp-method CSharp-Type-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | Inheritance Partial Classes in C# C# | List Class Lambda Expressions in C# Difference between Hashtable and Dictionary in C# Convert String to Character Array in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n27 Aug, 2021" }, { "code": null, "e": 24429, "s": 24302, "text": "Type.GetEnumValues() Method is used to return an array of the values of the constants in the current enumeration type.Syntax: " }, { "code": null, "e": 24468, "s": 24429, "text": "public virtual Array GetEnumValues ();" }, { "code": null, "e": 24819, "s": 24468, "text": "Return Value: This method returns an array which contains the values. The elements of the array are sorted by the binary values i.e. the unsigned values of the enumeration constants.Exception: This method will give ArgumentException if the current type is not an enumeration.Below programs illustrate the use of the above-discussed method:Example 1: " }, { "code": null, "e": 24826, "s": 24819, "text": "csharp" }, { "code": "// C# program to demonstrate the// Type.GetEnumValues() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Defining enum ABC enum ABC { A, B, C, D, E, F } // Main Method public static void Main() { // try-catch block to // handle exceptions try { // Creating and initializing object // of ABC with instance of enum ABC ABC a = ABC.A; // Declaring and initializing // object of Type Type type = a.GetType(); // Getting an array of the values // of the constants // By using GetEnumValues() method Array obj = type.GetEnumValues(); // Display values of the constants Console.Write(\"Values of the constants is : {0} \", obj); } // catch ArgumentException here catch (ArgumentException e) { Console.WriteLine(\"The current type is not an enumeration.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 26014, "s": 24826, "text": null }, { "code": null, "e": 26054, "s": 26014, "text": "Values of the constants is : GFG+ABC[] " }, { "code": null, "e": 26089, "s": 26056, "text": "Example 2: For ArgumentException" }, { "code": null, "e": 26096, "s": 26089, "text": "csharp" }, { "code": "// C# program to demonstrate the// Type.GetEnumValues() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Defining enum ABC enum ABC { A, B, C, D, E, F } // Main Method public static void Main() { // try-catch block to // handle exceptions try { // Creating and initializing object // of ABC with instance of enum ABC ABC a = ABC.A; // Declaring and initializing // object of Type Type type = typeof(int); // Getting an array of the values // of the constants // By using GetEnumValues() method Array obj = type.GetEnumValues(); // Display values of the constants Console.Write(\"Values of the constants is : {0} \", obj); } // catch ArgumentException here catch (ArgumentException e) { Console.WriteLine(\"The current type is not an enumeration.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 27284, "s": 26096, "text": null }, { "code": null, "e": 27367, "s": 27284, "text": "The current type is not an enumeration.\nException Thrown: System.ArgumentException" }, { "code": null, "e": 27381, "s": 27369, "text": "Reference: " }, { "code": null, "e": 27473, "s": 27381, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.getenumvalues?view=netframework-4.8" }, { "code": null, "e": 27485, "s": 27475, "text": "rs1686740" }, { "code": null, "e": 27499, "s": 27485, "text": "CSharp-method" }, { "code": null, "e": 27517, "s": 27499, "text": "CSharp-Type-Class" }, { "code": null, "e": 27520, "s": 27517, "text": "C#" }, { "code": null, "e": 27618, "s": 27520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27627, "s": 27618, "text": "Comments" }, { "code": null, "e": 27640, "s": 27627, "text": "Old Comments" }, { "code": null, "e": 27663, "s": 27640, "text": "Extension Method in C#" }, { "code": null, "e": 27691, "s": 27663, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27731, "s": 27691, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27774, "s": 27731, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27791, "s": 27774, "text": "C# | Inheritance" }, { "code": null, "e": 27813, "s": 27791, "text": "Partial Classes in C#" }, { "code": null, "e": 27829, "s": 27813, "text": "C# | List Class" }, { "code": null, "e": 27854, "s": 27829, "text": "Lambda Expressions in C#" }, { "code": null, "e": 27904, "s": 27854, "text": "Difference between Hashtable and Dictionary in C#" } ]
Tryit Editor v3.7
CSS Grid Item Tryit: Using grid-area to name grid items
[ { "code": null, "e": 23, "s": 9, "text": "CSS Grid Item" } ]
Human Resource analytics — Can we predict Employee Turnover with caret in R? | by Hannah Roos | Towards Data Science
People are the key factors for success to every organization — nothing else produces such a big value like skilled minds in the right time and place. This is why organizations all over the world make tremendous efforts to find and — maybe even more importantly — to maintain valuable talents. In a world of data, HR managers do not only rely on their gut feelings anymore when it comes to designing strategies to develop their own workforce of high-calibre minds: They make use of analytics to improve their HR practices and to make business success as well as employee satisfaction truly measurable. In case of employee turnover, the use of predictive analytics is not only thought to benefit the people, but is also to save the company’s finances: When a skilled team member leaves voluntarily, it is always associated with a lot of time and money spent on finding and onboarding a suitable substitute. In addition, it can affect the firm’s overall productivity, customer loyalty and timely delivery of products (Hammermann & Thiele, 2019; Sexton et al., 2005). Among many other reasons, this is because a whole field emerged from the idea of using data to support human resources: HR analytics (also called people analytics) is about changing the way of recruiting and retaining talent based on data-driven insights (Isson & Harriot, 2016). This way data analytics are used to predict behavioural patterns (e.g., attrition rates, training costs, productivity) which are inherently informative to the respective management because it can guide their decision-making process. Based on the successful implementation of machine learning algorithms, some of the big players already apply predictive analytics to decrease attrition and increase retention of their profitable employees. For example, the (former) Senior Vice President of HR at Google argued that statistics were used to fully automate their job interview questions — based on their candidates’ profiles and actually use employee data to predict turnover (Laszlo Bock, 2016). Now as data enthusiasts, it is our task to support HR managers for sakes of their planning continuity while helping them to reduce the costs related to frequent turnover and facilitating successful growth on the market. “HR analytics (also called people analytics) is about changing the way of recruiting and retaining talent based on data-driven insights.” — Isson & Harriot, 2016 A quick search on Google scholar reveals that there are a bunch of research articles out there that demonstrate how different ML algorithms can predict employee turnover. Nevertheless, the focus is usually put on technical characteristics (e.g., model performance, feature selection etc.) while the practical context of these applications is more or less left to the reader’s interpretation. For example, Zhao and colleagues evaluated different supervised machine learning techniques to predict employee turnover on simulated and real HR datasets of small-, medium and large-sized organizations (Zhao et al., 2019). These machine learning algorithms are used to predict employee turnover range from decision tree and random forest methods, gradient boosting trees, extreme gradient boosting over logistic regression, support vector machines, neural networks, linear discriminant analysis, Naïve Bayes methods and K-nearest neighbours. Even if attempts to predict employee turnover with modern analytics seem to have a huge potential, there are some limitations which could make it challenging to transfer these scientific findings to real-world cases from the industry: Predicting or explaining behaviour are two different things. Predicting or explaining behaviour are two different things. When working with data, we can drive either of the following strategies: When it is our goal to predict relevant outcomes, we do not have to fully understand the mechanisms that are at play (Yarkoni & Westfall, 2017). Our strategy would be rather prediction-focused. In the case of our employee turnover problem, we maybe do not want to lose too much time racking our brains over the “why” when we can already forecast which employees are at risk to leave soon — after all, our chance to change something lies only in the future. A good machine learning model does not have to be based on theory to make accurate predictions because it inherently learns from data: the algorithm mimics the outputs of the data-generating process when feeding it with new observations (e.g., new employees) without explicitly “knowing” anything about the reasons. But if you have a strong academic background and ask a lot of “why”-questions, you would probably argue that we would also like to know why employees leave the organization in the first place. If we have no clue about the underlying mechanism that causes employees to churn, it will be even harder to design targeted interventions. Fortunately, there are studies highlighting the importance of regular pay raises, the role of business travel and job satisfaction to employee turnover. This makes it easier for us to pinpoint the actual “pain points” from inside of the organization and truly understand what drives the intention to go. 2. Statistics are not sufficient to deal with individuals. In such a complex world we live in, data are not a magic key to a world full of perfectly computed, valid decisions that make everybody’s lives easier. Still, it sounds so cool and advanced when people talk about the fact that they use data to make evidence-based decisions. But if a machine learning algorithm is later applied to strongly inform decisions on SINGLE employees (e.g., when applied to rank candidates from a set of applicants), this procedure can easily gain an unethical taste. When applied incorrectly, applicants are not reviewed individually as a person anymore but as a score that estimates their probability to perform well on the job. Using data mining techniques, historical and labelled employee data can be used to detect features which can be associated with high job performance to later predict a new hire’s likelihood to perform well on the job (Mahmoud et al., 2019). Consequently, other people’s performance data along with some key measures (e.g., IQ, personality tests, structured interview results) or their curriculum vitae serve as a basis to forecast a new employee’s performance (Kluemper, Rosen & Mossholder, 2012; Apatean, Szakacs & Tilca, 2017, Li, Lai & Kao, 2008). Hence, the algorithm is trained with data from the past to predict the future. Especially in such a high-stakes context like job applications, this seems pretty deterministic to me and should be viewed with caution: the model is only capable of capturing associations from a specific moment in time even if they will change dynamically from person to person as well as across the organization’s development across time. Moreover, the algorithms typically also replicate discriminatory biases that are inherently represented in the data (e.g., being female could be predictive of having difficulties to gain a leadership position), which makes the model’s actual deployment within an organization hard to justify. To avoid any backfiring from employees, organizations thus need to take the issue of adverse impact against certain groups or individuals (e.g., parents, black people, pregnant women etc.) very seriously. A first step is to measure these biases statistically and correct them to create a fair AI that is benefits employees as well as the organization as a whole. You can find more ideas to fight discriminatory biases in an article from Andrew Burt published 2020 in Harvard Business Review. This problem is strongly tied to the impression the organization makes towards external candidates: Candidates should have a reasonable chance to convince the team by means of their actual skills and knowledge, without any biases or expectations. If the application of machine learning algorithms for recruiting purposes were made transparent, it may feel strange to get a job thanks to the mere combination of features that have been proven to be success factors for some predecessors. A similar thought applies to the prediction of employee turnover: Even if there is a set of features considered to be key drivers of employee churn (last pay raise, business travel, person-job fit, distance from home etc.), it is pretty obvious that the intention to quit a job is highly personal. By means of data analytics tools, we can only describe general patterns from a pool of individuals. We can even try to predict behaviour based upon these general tendencies. But we can never really know for sure if they apply to everybody. If data-driven insights can affect people’s lives (e.g., hiring decisions, retention efforts...), we should stay very careful and constantly question the sanity of our procedures. 3. The use of analytics does not justify unethical practices. AI dystopia often involves machines making ethically sensitive decisions, turning computers into decision-makers. Even if the following examples are far from reaching this kind of scenario, we should be aware that even if data can inform decision makers with reasonable insights, they are not the decision makers themselves and should be used under proper data protection and privacy guidelines. When it comes to the use of HR analytics for recruiting purposes, it has been suggested to give candidates the opportunity to opt-in and have control over their data by deciding whether or not potential employers and recruiters can assess their digital footprint to address any ethical and legal concerns (Chamorro-Premuzic et al. 2013). Another suggestion touches upon more autonomy for the people affected by HR-analytics tools: Employees should not become passive recipients of algorithmic governance but have the chance to actually understand how the model makes predictions and to give critical feedback if needed. Another creepy application I have stumbled upon in the literature includes the use of social media profiles like LinkedIn or Xing with the aim to predict the character of candidates bases on sentiment analysis — both in order to assess the candidate’s fit for a job (Faliagka, 2012). All of the above procedures certainly uncover interesting insights for researchers and psychologists, but should not be applied when the individuals, whose data are being processed, have not given any consent. 4. The employee data sets available in industry are often noisy and sparse. If prediction is based on historical data, we always need to ask ourselves if these can really generalize to new, yet unknown observations. Now even if simulated HR data seem like a gift to any passionate data scientist, real HR data is often confidential, small, inconsistent and contains missing information. In case of medium-sized firms, not all of them can actually afford large-scale data storage, making it more difficult to store employee data in a consistent way. Moreover, it does typically include just a small proportion of employees who have actually left the company, making classes (stayed/left) imbalanced — a characteristic that needs special attention when evaluating machine learning models (but more on that later). Another data-related change in perspective refers to the quality vs. quantity of data: Yahia, Hlel and Colomo-Palacious (2021) argue for a shift from big data to what they call “deep data” — qualitative data that contains all the necessary features to practically predict turnover. Indeed, massive sets of employee data are neither available to medium-to-small-sized firms nor necessary if we can identify the key drivers of turnover. There are other voices from the literature who go a step further and propose that large unstructured data sets (often referred to as “big data”) are not always better because they can be so noisy that it “overwhelms” each model’s predictive capacity (Chamorro-Premuzic et al., 2013). This is just a gentle reminder to raise your awareness about the power of predictive analytics and its impact on the people — I highly recommend this paper from Dr. Michele Loi who has summarized ethical guidelines for the deployment of people analytics tools above and beyond the GDPR. Keeping these political issues in mind, we will now walk through a little case study to find out if the prediction of employee churn can be reasonably applied to a small fictive sample derived from the famous IBM employee dataset. I am curious to find out if it could potentially work for real-world cases, too! The dataset we will use for our case study is a simulated dataset created by IBM Watson Analytics which can be found on Kaggle. It contains 1470 employee entries and common 38 features (Monthly income, Job satisfaction, gender etc.) — one of which is our target variable (Employee) Attrition (YES/NO). Let’s take a look at our raw data. Disclaimer: All graphics are made by the author unless specified differently. We seem to have 26 numeric variables and 9 character variables which differ in their distinct levels. None of the observations are missing and the summary the skim function gives us shows some descriptive statistics including mean, standard deviation, percentiles as well as a histogram. I am a big fan of the skim function — look how practical it is to get such a concise and yet detailed overview of the data! It is pretty obvious that a payment that is perceived as unfair can influence a person’s intention to leave the job to look for better payment (Harden, Boakye & Ryan, 2018; Sarkar, 2018; Bryant & Allen, 2013). This is why we would like to create another variable that represents the payment competitiveness of each employee’s monthly income — the reasoning behind this is that employees may compare their income against those of their peers who share the same job level. Somebody who perceives his or her payment as fair should be less likely to leave the company compared to a person who gets considerably less for a similar position. To get there, we will use the data.table syntax to first calculate the median compensation by job level and store the appropriate value for each observation. Then we will divide each employee’s monthly income by the median income to get his or her compensation ratio: a measure that directly represents the person’s payment in respect to what would be expected by job level. Thus, a score of 1 means that the employee exactly matches the average payment for this position. A score of 1.2 means that the employee is paid 20% above the average pay and a score of 0.8 means that the person is paid 20% less than what would be expected by the usual payment per job level. To represent this at a factorial level, we will assign values To “average” which lie within 0.75 and 1.25 To “below” that lie within 0 and 0.74 and to “above” that lie within 1.25 and 2 of the CompensationRatio range. This is how our newly generates features look like on the first 10 observations: But how many employees actually left? Let’s calculate the turnover rate to learn something about the distribution of classes. So, it appears that 237 employees (16%) left the company in a given timeframe while a majority (almost 84%) stayed. As argued above, many HR mangers do not have access to huge datasets containing thousands of employees with complete records. Now what if we would like to advise a small-to-medium firm that includes 50 to 250 employees? Can we still train ML algorithms to predict turnover? To create an extra bit of a challenge and mimic a real-life sample that mimics a small-to-medium-sized company, we will randomly draw 126 observations from our full IBM Watson dataset. I will set a seed to make it more replicable for you. Let’s now take a closer look at the interplay between two key factors for employee churn: job satisfaction and compensation. A typical hypothesis derived from the literature proposes that higher job satisfaction is associated with a lower likelihood of employee turnover — unhappy employees usually have more reason to leave because they expect to be happier somewhere else and do not feel as emotionally committed to their current organization, making it more desirable and easier to leave as soon as attractive alternatives are found (Zimmermann, Swider & Boswell, 2018). It looks like the data generally support this hypothesis: even if the tails of the distribution demonstrate that a few employees who stayed are actually unsatisfied while some leavers are happy, the general tendency suggests that employees who leave are indeed on average less satisfied than the remaining employees in our sample. Okay — but how does the combination of monthly income and job satisfaction differ among in relation to employee churn? More specifically, could a lower income be the reason to leave for employees who are actually satisfied with their job? Of course, we cannot really fully tell if there is a cause-effect-relationship between income or job satisfaction and employee attrition — but it is still interesting to see if there is any hint about an association. Surprisingly, for very unsatisfied employees, monthly income is actually higher leavers compared to the remaining employees. This suggests that monthly income alone cannot really account for employee turnover in cases in which employees are not satisfied with their jobs — money is not everything! This is consistent with the observation that satisfaction with compensation is just one side of the same coin: To be truly happy with their jobs, employees do not only expect appropriate compensation for their hard work but rather a range of factors that contribute to their overall satisfaction with their work (e.g., non-monetary support from their supervisors, strong relationships to great colleagues, a sense of fulfilment from the work itself etc.) (Zimmermann et al., 2018). Intriguingly, the relationship seems to be vice versa for more satisfied employees: As could be expected, people who stayed are paid considerably better than leavers. This pattern even seems to be more pronounced the higher we climb the happiness ladder: The payment gap seems to increase linearly with each level of job satisfaction. We could speculate that the more satisfied employees have more resources to invest a lot of energy into their work, making them more resilient towards high-pressure job demands (Bakker & Demerouti, 2007). As compensation is often tied to performance, this could result in two scenarios: The boost in energy could result into an appropriate promotion for some employees, giving them even more incentive to stay with their current employer.But if they are not given any better compensation in return, this could be perceived as inequitable and yet another reason to leave the organization (Birtch, Chiang & Van Esch, 2016). Still, testing this assumption is a bit beyond the scope for this article and difficult to test such a simulated dataset which does not include longitudinal information to begin with. But we could argue that payment is certainly related to the employee’s job level as managers naturally earn more than junior consultants. Do the relationships hold if we swap the y-axis by the CompensationRatio variable we have created earlier? For example, are medium-to-highly satisfied employees who left paid less compared to what would be expected by their job level? Not quite. On average, leavers are often paid the average pay or even better compared to their peers. Even if it appears that the range of different degrees of pay competitiveness are a bit larger in the middle of the job satisfaction scale, suggesting that payment competitiveness of not-so-happy employees who have left can be very different. But we should be careful here and avoid any premature interpretation: there could be significantly more employees who show a medium degree of job satisfaction than those who lie at the more extreme levels (very happy/unhappy). If we have more employees at the middle of the satisfaction distribution, chances would be higher that each degree of pay competitiveness would be somewhat covered, right? On the other hand, larger samples often cause the distribution to appear more normally distributed and less flat while the density peaks around the average value as the central limit theorem states. Let’s calculate a quick sanity check to find it out how this applies to our sample: Wow — there are more satisfied than unsatisfied employees in our sample as they amount to about 65% of the observations. Thus, our second interpretation is more likely in this case and at first sight, there are no obvious interaction effects between job satisfaction and pay competitiveness that could contribute to employee attrition. Being a trained psychologist, I am particularly interested in the question how the psychological climate may affect employee’s intention to leave. For the modelling part in particular, we will use the caret package, short for Classification And REgression Training which was developed by Max Kuhn and various other smart contributors. Caret has a nice built-in function to quickly get an impression about the features we are interested in. Because the scale on which each of these variables are rated is ordinal in nature, a density plot looks cool but might not be the ideal choice here: The kurtosis of the curves is directly influenced by our class imbalance (a few who leave and a lot who stay) which could be misleading and we do not want to hallucinate any patterns here where there are none. Therefore, let’s try another technique: mosaic plots. Now what the mosaic function from the vcd-package does is to test whether the frequencies in our sample could have been generated by simple chance. This is done by calculating a Chi-squared-test behind the scenes. We can now analyse the results by looking at both the size of the rectangles and the colors: the area of the rectangle represents the proportion of cases for any given combination of levels and the color of the tiles indicate the degree relationship among the variables — the more the colour deviates from grey, the more we must question statistical independence between the different factor combinations (as represented by the pearson-residual scale on the right). Usually dark blue represents more cases than expected given random occurrence while dark red represents less cases than expected if they were generated by chance alone. Okay — in our case, every tile is coloured in grey which suggests that there are no strong deviations from statistical independence. Only in case of Environment Satisfaction we could wonder whether leavers are overly unsatisfied with their work environment compared to the remaining as indicated by the close-to-significant p-value and the shift between both distributions we can draw from the featureplot above. A limitation could be that the mosaic plot function is probably not sensitive enough to capture slight deviations from random frequency distributions — we still have a small sample size that gets further broken down by the combination of categorical levels we try to investigate. We now make our dataset ready for the actual modelling part. As a first step, we will remove all variables that are very unlikely to have any predictive power. For example, employee-ID won’t explain any meaningful variation in employee turnover, therefore it should be deleted for now among some other variables. Other examples include variables that share a lot with other features and therefore could lead to multicollinearity issues (e.g., hourly rate and monthly income). We will save the reduced dataset by properly converting all string variables (e.g., Department) to factors at the same time. To be pretty sure that we have not overlooked any highly intercorrelated variables, we will automatically detect and remove them. For this purpose, we first identify any numeric variables, compute a correlation matrix and find correlations that exceed 0.5. So, there are indeed some variables that were flagged by our code — we should take a closer look at: “YearsAtCompany”, “JobLevel”, “MonthlyIncome”,”YearsInCurrentRole” and “PercentSalaryHike”. It appears that YearsAtCompany is highly correlated with YearsInCurrentRole, YearsSinceLastPromotion and YearsWithCurrManager. Thus, just one of these time-related variables can stay: I would suggest to keep “Years since last Promotion” because this could explain some additional variance the others cannot: it relates not only to the time that has passed since the employee entered the company, but also the years that went by without promotion. As the literature suggests, regular pay raises that are often a consequence of a promotion play a crucial protective role against turnover (Das & Baruah, 2013). Joblevel is highly correlated with Age and with monthly income: It is plausible that the older employees get, the higher the chances they have already climbed the career ladder and earn significantly more compared to previous years. Because we have discussed the impact of monthly income, I would rather drop Job Level and Age than our income variable. PercentSalaryHike is highly correlated with PerformanceRating as a strong performance is rewarded with money. After analysing the interrelations of these variables, let us alter the list of variables which should be removed and create a new dataframe containing the selected variables: To make our machine learning algorithms work, we need to transform these factor variables into dummy variables. For each factor level, we will have a separate variable indicating whether or not the respective participant falls into this category (e.g. a person who travels rarely would get a 1 instead of a 0). Firstly, we will detect all categorical variables except for our target (attrition). Then, we will make use of caret’s dummyVars function, apply it to our dataset and create a brand new dataframe that contains our selected set of numeric variables, dummy variables and attrition (yes/no). Please note that the caret-function dummyVars transforms the variables into a complete set of dummy variables which means that all factor levels will be covered and none will be left out — a procedure that does not work for linear models for which the output is always compared against a reference level (e.g., if we want to compare the effect of being female against the intercept which represents male employees). Thus, our variables are one-hot encoded. Next, we will remove variables that do not provide any predictive value using carets nearZeroVar function. It applies to predictors that only have a single unique value (i.e. a “zero-variance predictor”). This would be the case if all our employees would be frequent travellers, leaving all other options (rare or none travel) blank which would create a constant in our statistical model. It also applies to predictors that only have a few unique values which occur in very low frequencies (e.g., if 1 out of 100 employees would be divorced). For many models (except for tree-based models), this may cause the model to crash or the fit to be unstable. As a final pre-processing step, we will make sure that we have ordered the target’s factor levels correctly: I have noticed that in the past, caret appears to just take the first level as the positive class (e.g., yes vs. no, win vs. lose etc.) which can sometimes “confuse” the confusion matrix later — for example, specificity and sensitivity can easily mixed up. Therefore, we want to make sure that an actual employee turnover is considered to positive class by explicitly assigning “yes” and then “no” as factor levels of our attrition variable. Our final dataset is now cleaned up and ready for modelling. Because we have a small sample, we could run into the problem to overly fit our model to our sample-specific data to an extent that we cannot apply it to new employee data later. A problem that is often referred to as overfitting — a phenomenon that could explain why we sometimes cannot replicate previously found effects anymore. For machine learning models, we often split our data into training and validation/test sets to overcome this issue. The training set is used to train the model and the validation/test set is used to validate it on data it has never seen before. If we would use a traditional 80/20-split to our use case, model performance would largely depend on chance because we it would differ each time the algorithm would randomly select 25 individuals for testing purposes. This problem becomes even more extreme in our case because we have an imbalance of classes: Remember that only roughly 20% of employees left the company — this means that our model would probably be tested on about 5 leavers and 20 remaining, leaving us with the question whether the algorithm would perform similarly on different cases. Also, if we would assess model performance by looking at the prediction accuracy, the result would easily overestimate its actual performance as there are many positive cases as a reference (e.g., employees who did not leave). You can find more on the question how to split the data from a small imbalanced dataset in this interesting Stackoverflow discussion. Fortunately, we have something from our statistical toolbox: cross-validation with various splits. We will apply our trained model(s) to a new set of observations and repeatedly adjust the parameters to reduce prediction error. For these “new observations”, we do not even need a new sample: we will recycle the dataset by training the model to a set of observations and use another part of the data to test model performance. We will repeat this 5 times and average the test performance to receive a final estimation of our model’s performance — a technique called 5-fold-cross-validation. Thus, we can make use of all of our data while the model is still tested on “new” cases. Now we will set up a reusable train Control object to build our machine learning models with the same settings: repeated cross-validation makes sure that we run our 5-fold-cross-validation process 5 times. Moreover, we ask caret to provide us with class probabilities in our model output as well as the final predictions and we want to see the progress of our modelling process (verbose = True). We will use caret’s built-in hyperparameter search with its standard settings. The models we will test against each other are the following: Logistic Regression: this is a widely used, traditional classification algorithm that is based on the linear regression you know from your statistics course and was originally proposed in 1958 by Cox. The primary prediction output is the observation’s estimated probability to belong to a certain class. Based on the value of the probability, the model creates a linear boundary separating the input space into two regions (e.g., more likely yes or more likely no). Random Forests: Basic decision trees are interpretable models that are built in a tree-like fashion: branches are combinations of features and leaves are the class labels of interest (e.g., yes or no). Random forests give us an edge over basic decision trees by combining the power of all multiple weak learners to come to a collective prediction. This makes more robust than simple decision trees because the final prediction is not dominated by a few influential predictors. Extreme Gradient Boosting (XGB): this modelling technique is another tree-based method introduced by Chen (2014) which is based on Gradient boosting trees which is an ensemble machine learning method proposed in 2001 by Friedman for regression and classification purposes. A key characteristic is that they learn sequentially — each tree attempts to correct the mistakes of the previous tree until no further enhancement can be achieved. XGB is often described as the faster, more scalable and memory efficient technique version compared to gradient boosting trees. GLMnet: this is a very flexible, efficient extension of glm models that is nicely implemented in R. It fits generalized linear models using penalized maximum likelihood estimation and thus reduces overfitting known from common regression models (e.g., basic logistic or linear regression) by using a lasso or elastic net penalty term. It is known for its ability to deal well with small samples, prefer simple over overly complex models and its built-in variable selection. Naïve Bayes: this model uses the famous Bayes Theorem as it estimates the occurrence probability of an event based on prior knowledge of related features. Classifiers first learn joint probability distribution of their inputs and produce an output (e.g., yes or no) based on the maximum posterior probability of the given each respective feature combination. Because we have imbalanced sample (more stayed than left), we won’t assess the model’s performance with accuracy later. As accuracy is the proportion of correctly classified cases out of all cases, it would be not a big deal for the algorithm to give us a high score even if it simply classified ALL cases as the majority class (e.g., no). It is a more appropriate metric if we would have more equally distributed classes which were similarly important to us. But in this case, we actually are about the positive cases: you could argue that it is more detrimental NOT to correctly identify leavers (e.g., sensitivity or true positive rate) than accidentally predict that an employee would leave if the person actually stayed (false positive rate or 1 — specificity). Therefore, I would like to use the F1-score as accuracy metric for training optimization as it assigns more importance to correctly classify positive cases (e.g., employee churn) and makes more sense for heavily imbalanced datasets. The F1-score is the harmonic mean of precision and recall: The precision is the amount of correctly classified positive cases divided by the number of all positive predictions (including the false positives, e.g. employees who were identified as leavers but did not go). It is also called positive predictive value. Recall, on the other hand, is the amount of true positive cases divided by the number of all samples that should have been identified as positive (e.g., all actual leavers, even if not all of them were correctly identified). It is also known as sensitivity in binary classification use cases. If you did not get it yet, no worries, it is not that intuitive as the simple accuracy metric. I hope that my visualizations may help you to wrap your head around it. In sum, the F1-score is associated with the algorithm’s ability to detect positive cases correctly. Because caret does not directly provide the f1 metric as an option to our train function, we will use a DIY-code found on Stackoverflow. You can find more on accuracy metrices here. By the way, it is not as easy to interpret whether other not our achieved F1-score is “good enough” because it heavily depends on the amount of truly positive cases in our sample. Therefore, we will later look for the model highest F1-score we have achieved on the same data. To have a good baseline model to compare the others with, we will create a logistic regression model: Based on the visualizations we have created earlier and the theories from the psychological literature, we would hypothesize that higher job satisfaction is protective against employee attrition. Also, we would assume that the lower monthly income, the higher the likelihood for employees to leave the company to get better payment. Moreover, we would think that the effect of monthly income on employee turnover gets amplified with each level of job satisfaction. For all other models, we will throw in all the variables we have selected before and make no further theoretical predictions. This way, we can see whether give us a predictive advantage. But before we dive into the actual model comparison, let’s see if our baseline model can actually explain employee attrition at a rudimentary stage. model_baselinesummary(model_baseline) As predicted by our hypothesis, can see that the estimates of the model suggest that the likelihood that an employee leaves the company decreases slightly with every additional dollar monthly income and every additional level of job satisfaction. Note that the estimates cannot be directly interpreted because they are scaled as log odds that fits our logistic regression formula. The interaction term (combination of monthly income and job satisfaction) also became statistically significant (p < .001). Can the other models with a larger set of predictors do a better job predicting employee turnover in our small sample? Let’s find it out. We will first make a list of all our model objects (random forest, glmnet etc.) and name them for future reference. Then we will use the resamples-function from caret to plot the models’ performance against each. It will give us the range of F1 values across all 5 folds, making it possible to select the model with the highest average performance. It appears that XGBoost outperformed all other models when it comes to its ability to correctly classify leavers and showed a pretty robust performance across all folds. Our baseline model showed pretty variable model performance depending on the folds that were used for testing, making it seem a bit unstable. However, we did some unfair comparison here by comparing apples with bananas: for our basic model, we used a theoretically plausible formula while we threw in all of the candidate-variables into the other models. In these cases, we tried to predict employee churn with EVERYTHING. This makes it hard to judge whether the model performance of let’s say the random forest algorithm is due to an overly complex formula or due to the kind of model itself. I could even imagine that a simpler model might be beneficial in our case because we do not have enough observations to justify such a large set of predictors used in our model. As Yarkoni and Westfall (2017) nicely pointed out, the higher the chance that a small set of predictors is applied to many observations, the smaller the likelihood of overfitting, represented in a low n to p ratio (sample size to predictors). If we however have a small dataset and many parameters that all make small contributions to an outcome X like in our first modelling round, the likelier we will get large prediction errors and the performance gap between training and test set will be substantial. Therefore, we will make a fairer comparison by demonstrating what happens if you tell caret to predict employee churn with job satisfaction, monthly income and the combination of these for all of the models: Now random forest now does not seem to show the worst performance anymore, but again XGB seems to be our winner. Interestingly, the F1-score encompasses very similar values like our complex models, suggesting that a more parsimonious model is preferable over too complex models. Let’s see if the confusion matrix can tell us a bit more about the XGB’s performance that includes our simple model formula compared to our baseline model. As a reminder, this is how such a confusion matrix translates to our problem. Wow — the direct comparison shows that XGBoost is much better in predicting employee churn than our baseline model! By looking at the raw confusion matrix we can see that the XGBoost correctly identified 17 out of 22 leavers whereas the baseline model only identified 3 of them. Our winner model’s precision is very good (0.94) which means that it did not mix up true leavers with fake leavers (false positives, i.e. employees who did not actually leave the company but stayed). On the other hand, the baseline model just predicted 4 positive cases from which 3 were correct, resulting in a rather poor precision of 0.75. The capacity to detect employee churn correctly becomes even more pronounced for the other metrices: Because the XGBoost algorithm also missed 5 true positive cases and incorrectly flagged them as negative, recall is not exceedingly high but still acceptable (0.77). As a reminder, recall is the amount of true positive cases divided by the number of all samples that should have been identified as positive (e.g., all actual leavers, even if not all of them were correctly identified) and is also known as sensitivity. In contrast, the baseline model was not sensitive enough to pick up the true leavers and accidentally flagged a majority of them as remaining employees. The gap in performance is also captured by the balanced accuracy score on the bottom which represents the balance between specificity and sensitivity of the respective model, suggesting that our baseline model underperformed when it comes to correctly identifying loyal employees as well. Apart from the F1-score, balanced accuracy has been suggested to be a better proxy of the model’s accuracy in imbalanced samples. All in all, XGBoost seems to give us a predictive edge over a simple generalized linear model even if we keep our predictors constant. As a next step, we would like to actually use the model to increase retention in our small company. For this purpose, we will first get the indices of employees that are still active and predict the likelihood for these employees to leave according to our model. Then we will save these probabilities as well as the actual employee data. Lastly, we will find the top 5 employees with the highest risk to leave the company. In order to give the company a chance to intervene, these are probably the people that should be recruited first to find out what they need to be happier and how they would like to develop in the future. This way, we can hopefully address any voluntary turnover. In the end, we will give the managers a full list of employees to talk to, ranked by their risk to leave — after all, it is good to give employees the chance to get rid of constructive feedback that may enhance the working climate. Do not use tibbles for modelling Before I have discovered the beauty of the data.table syntax, I have worked with tibbles because I think the %>% operator is such an intuitive tool. Unfortunately, caret does only take in dataframes (or data.tables), but not tibbles and it took a long time for me to work out why my code would not run through. Until I have discovered this comment on github and changed the whole data wrangling part to a DT-like structure. Make sure to transform tibbles into classic dataframes before modelling with caret or do not use dplyr-syntax in the first place. Appropriate accuracy metrices make such a huge difference Moreover, I have first used the AUC ROC score as the metric for optimization before I have discovered that you can also make it work with other metrices (e.g., the F1-score) as well. This resulted in a horrible model performance, with sensitivity scores under 0.1 — the algorithms did not really detect positive cases (e.g., actual employee churn) which might be due to our heavily imbalanced dataset. As predicted before, the model summary still demonstrated acceptable accuracy scores because it was not such a big deal for the models to identify those who stay as the majority of employees did not churn anyway. Using a more appropriate metric for optimization was really a game-changer and massively improved model performance. Our results are highly sample-specific Before I have set a seed for replication purposes when drawing random samples from our original IBM HR analytics dataset, I realized that results would largely differ from sample to sample. This was especially true for the psychological variables like environment or relationship satisfaction. Even if this may sound a bit obvious to you, think about what this means to cases in which you do not have any larger dataset available from which you can draw a subset from: your interpretation of the data-generating processes (e.g., which factors would explain employee turnover) would be heavily biased but you would not have any chance to validate it yet due to a lack of data. This should make us careful about drawing preliminary conclusions about general patterns in nature before we have the chance to prove them on a larger population. Also, please keep in mind that the dataset is fictious as it does not contain real HR employee data, so it should not be used as a single source to answer truly scientific questions. From a technical perspective, I would argue that we can indeed make use of machine learning to predict employee turnover, even in small samples if you have a complete, high-quality dataset. Also, we have seen that when it comes to the number of predictors, a simpler, more parsimonious model can perform at least as good as a complex model. Nevertheless, the type of machine learning model can make a huge difference to the accuracy of our prediction. From a broader perspective, we need to be aware of the fact that it seems to be inevitable that we capture some degree of sample-specific error that does not generalize to new employees. Therefore, it would not be recommended to let the algorithm decide over people’s jobs and lives alone — as human beings, being data scientists, managers or HR experts, we need to take responsibility for the decisions being made under our supervision. There are several ways to increase the transparency of our data-driven approach towards external parties: If we did not have strong hypothesis before evaluating data, it may be helpful to explicitly claim that our work is exploratory in nature because our explanations are somewhat post-hoc and therefore could be biased. This limitation also applies to our approach since we inspected the potential psychological reasons driving employee turnover visually before specifying our model formula. At the end of the day, it might be most fruitful to make use of both of the worlds: investigating the roots and causes behind the data, widening our view towards patterns within the data that we have actually not hypothesized in the first place and always test a model’s ability to predict out-of-sample behaviour to minimize overfitting. Thus, a mix of some degree of theoretical flexibility but mindful interpretation of the data could enable us to make good and reasonable predictions. When you really think about deploying HR analytics tools in your organization, the end-users of the model need to be educated about the its benefits as well as its limitations: Even if we understand the common roots which increase the likelihood of turnover, people as well as organizations are still pretty unique — and so are the reasons to leave. Consequently, the mixture personal and practical reasons that drive frequent turnover may vary from company to company and even change across time. Thus, when a predictive model is applied, it must be constantly evaluated before it is already outdated and makes profound mistakes. I am such a big fan of data-driven technologies and if we use them thoughtfully, machine learning techniques can be a powerful tool to improve the workplace for good. But if we use it mechanically, it can easily become the dangerous black-box AI-critics fear and which our society should not aim for. So, let’s stay mindful data-enthusiasts. [1] A. Hammermann & C. Thiele, People Analytics: Evidenzbasiert Entscheidungsfindung im Personalmanagement (2019), (No35/2019), IW-Report. [2] R. S. Sexton, S. McMurtrey, J. O. Michalopoulos & A. M., Employee turnover: a neural network solution (2005), Computers & Operations Research, 32(10), 2635–2651. [3] J. P. Isson & J. S. Harriott, People analytics in the era of big data: Changing the way you attract, acquire, develop, and retain talent (2016), John Wiley & Sons. [4] L. Bock, Work Rules!: Wie Google die Art und Weise, wie wir leben und arbeiten, verändert. (2016), Vahlen. [5] Y. Zhao, M. K. Hryniewicki, F. Cheng, B. Fu & X. Zhu, Employee turnover prediction with machine learning: A reliable approach (2018), In Proceedings of SAI intelligent systems conference (pp. 737–758). Springer, Cham. [6] T. Yarkoni & J. Westfall, Choosing prediction over explanation in psychology: Lessons from machine learning (2017), Perspectives on Psychological Science, 12(6), 1100–1122. [7] A. A. Mahmoud, T. A. Shawabkeh, W. A. Salameh & I. Al Amro, Performance predicting in hiring process and performance appraisals using machine learning (2019), In 2019 10th International Conference on Information and Communication Systems (ICICS) (pp. 110–115). IEEE. [8] D. H. Kluemper, P. A. Rosen & K. W. Mossholder, Social networking websites, personality ratings, and the organizational context: More than meets the eye? (2012),1. Journal of Applied Social Psychology, 42(5), 1143–1172. [9] A. Apatean, E. Szakacs & M. Tilca, Machine-learning based application for staff recruiting (2017), Acta Technica Napocensis, 58(4), 16–21. [10] Y. M. Li, C. Y. Lai, & C. P. Kao, Incorporate personality trait with support vector machine to acquire quality matching of personnel recruitment (2008), In 4th international conference on business and information (pp. 1–11). [11] T. Chamorro-Premuzic, D. Winsborough, R. A. Sherman & R. Hogan, New talent signals: shiny new objects or a brave new world (2013), Ind. Organ. Psychol. Perspect. Sci. Pract., 53:1689–1699. [12] E. Faliagka, K. Ramantas, A. Tsakalidis & G. Tzimas, Application of machine learning algorithms to an online recruitment system (2012), In Proc. International Conference on Internet and Web Applications and Services (pp. 215–220). [13] M. Loi, People Analytics must benefit the people. An ethical analysis of data-driven algorithmic systems in human resources management (2020), Algorithmwatch. [14] N. B. Yahia, J. Hlel & R. Colomo-Palacios, From Big Data to Deep Data to Support People Analytics for Employee Attrition Prediction (2021), IEEE Access, 9, 60447–60458. [15] G. Harden, K. G. Boakye & S. Ryan, Turnover intention of technology professionals: A social exchange theory perspective (2018), Journal of Computer Information Systems, 58(4), 291–300. [16] J. Sarkar, Linking Compensation and Turnover: Retrospection and Future Directions (2018), IUP Journal of Organizational Behavior, 17(1). [17] P.C. Bryant & D. G. Allen, Compensation, benefits and employee turnover: HR strategies for retaining top talent (2013), Compensation & Benefits Review, 45(3), 171–175. [18] R. D. Zimmerman, B. W. Swider & W. R. Boswell, Synthesizing content models of employee turnover (2019), Human Resource Management, 58(1), 99–114. [19] A. B. Bakker & E. Demerouti, The job demands‐resources model: State of the art (2007), Journal of managerial psychology. [20] T. A, Birtch, F. F. Chiang & E. Van Esch, A social exchange theory framework for understanding the job characteristics–job outcomes relationship: The mediating role of psychological contract fulfillment. (2016), The international journal of human resource management, 27(11), 1217–1236. [21] M. Kuhn, J. Wing, S. Weston, A. Williams, C. Keefer, A. Engelhardt., ... & M. Benesty, Package ‘caret’ (2020), The R Journal, 223. [22] B. L. Das & M. Baruah, Employee retention: A review of literature (2013), Journal of business and management, 14(2), 8–16. [23] T. Chen & Guestrin, Xgboost: A scalable tree boosting system (2016), In Proceedings of the 22nd acm sigkdd international conference on knowledge discovery and data mining (pp. 785–794).
[ { "code": null, "e": 773, "s": 172, "text": "People are the key factors for success to every organization — nothing else produces such a big value like skilled minds in the right time and place. This is why organizations all over the world make tremendous efforts to find and — maybe even more importantly — to maintain valuable talents. In a world of data, HR managers do not only rely on their gut feelings anymore when it comes to designing strategies to develop their own workforce of high-calibre minds: They make use of analytics to improve their HR practices and to make business success as well as employee satisfaction truly measurable." }, { "code": null, "e": 2430, "s": 773, "text": "In case of employee turnover, the use of predictive analytics is not only thought to benefit the people, but is also to save the company’s finances: When a skilled team member leaves voluntarily, it is always associated with a lot of time and money spent on finding and onboarding a suitable substitute. In addition, it can affect the firm’s overall productivity, customer loyalty and timely delivery of products (Hammermann & Thiele, 2019; Sexton et al., 2005). Among many other reasons, this is because a whole field emerged from the idea of using data to support human resources: HR analytics (also called people analytics) is about changing the way of recruiting and retaining talent based on data-driven insights (Isson & Harriot, 2016). This way data analytics are used to predict behavioural patterns (e.g., attrition rates, training costs, productivity) which are inherently informative to the respective management because it can guide their decision-making process. Based on the successful implementation of machine learning algorithms, some of the big players already apply predictive analytics to decrease attrition and increase retention of their profitable employees. For example, the (former) Senior Vice President of HR at Google argued that statistics were used to fully automate their job interview questions — based on their candidates’ profiles and actually use employee data to predict turnover (Laszlo Bock, 2016). Now as data enthusiasts, it is our task to support HR managers for sakes of their planning continuity while helping them to reduce the costs related to frequent turnover and facilitating successful growth on the market." }, { "code": null, "e": 2592, "s": 2430, "text": "“HR analytics (also called people analytics) is about changing the way of recruiting and retaining talent based on data-driven insights.” — Isson & Harriot, 2016" }, { "code": null, "e": 3528, "s": 2592, "text": "A quick search on Google scholar reveals that there are a bunch of research articles out there that demonstrate how different ML algorithms can predict employee turnover. Nevertheless, the focus is usually put on technical characteristics (e.g., model performance, feature selection etc.) while the practical context of these applications is more or less left to the reader’s interpretation. For example, Zhao and colleagues evaluated different supervised machine learning techniques to predict employee turnover on simulated and real HR datasets of small-, medium and large-sized organizations (Zhao et al., 2019). These machine learning algorithms are used to predict employee turnover range from decision tree and random forest methods, gradient boosting trees, extreme gradient boosting over logistic regression, support vector machines, neural networks, linear discriminant analysis, Naïve Bayes methods and K-nearest neighbours." }, { "code": null, "e": 3763, "s": 3528, "text": "Even if attempts to predict employee turnover with modern analytics seem to have a huge potential, there are some limitations which could make it challenging to transfer these scientific findings to real-world cases from the industry:" }, { "code": null, "e": 3824, "s": 3763, "text": "Predicting or explaining behaviour are two different things." }, { "code": null, "e": 3885, "s": 3824, "text": "Predicting or explaining behaviour are two different things." }, { "code": null, "e": 4731, "s": 3885, "text": "When working with data, we can drive either of the following strategies: When it is our goal to predict relevant outcomes, we do not have to fully understand the mechanisms that are at play (Yarkoni & Westfall, 2017). Our strategy would be rather prediction-focused. In the case of our employee turnover problem, we maybe do not want to lose too much time racking our brains over the “why” when we can already forecast which employees are at risk to leave soon — after all, our chance to change something lies only in the future. A good machine learning model does not have to be based on theory to make accurate predictions because it inherently learns from data: the algorithm mimics the outputs of the data-generating process when feeding it with new observations (e.g., new employees) without explicitly “knowing” anything about the reasons." }, { "code": null, "e": 5367, "s": 4731, "text": "But if you have a strong academic background and ask a lot of “why”-questions, you would probably argue that we would also like to know why employees leave the organization in the first place. If we have no clue about the underlying mechanism that causes employees to churn, it will be even harder to design targeted interventions. Fortunately, there are studies highlighting the importance of regular pay raises, the role of business travel and job satisfaction to employee turnover. This makes it easier for us to pinpoint the actual “pain points” from inside of the organization and truly understand what drives the intention to go." }, { "code": null, "e": 5426, "s": 5367, "text": "2. Statistics are not sufficient to deal with individuals." }, { "code": null, "e": 9044, "s": 5426, "text": "In such a complex world we live in, data are not a magic key to a world full of perfectly computed, valid decisions that make everybody’s lives easier. Still, it sounds so cool and advanced when people talk about the fact that they use data to make evidence-based decisions. But if a machine learning algorithm is later applied to strongly inform decisions on SINGLE employees (e.g., when applied to rank candidates from a set of applicants), this procedure can easily gain an unethical taste. When applied incorrectly, applicants are not reviewed individually as a person anymore but as a score that estimates their probability to perform well on the job. Using data mining techniques, historical and labelled employee data can be used to detect features which can be associated with high job performance to later predict a new hire’s likelihood to perform well on the job (Mahmoud et al., 2019). Consequently, other people’s performance data along with some key measures (e.g., IQ, personality tests, structured interview results) or their curriculum vitae serve as a basis to forecast a new employee’s performance (Kluemper, Rosen & Mossholder, 2012; Apatean, Szakacs & Tilca, 2017, Li, Lai & Kao, 2008). Hence, the algorithm is trained with data from the past to predict the future. Especially in such a high-stakes context like job applications, this seems pretty deterministic to me and should be viewed with caution: the model is only capable of capturing associations from a specific moment in time even if they will change dynamically from person to person as well as across the organization’s development across time. Moreover, the algorithms typically also replicate discriminatory biases that are inherently represented in the data (e.g., being female could be predictive of having difficulties to gain a leadership position), which makes the model’s actual deployment within an organization hard to justify. To avoid any backfiring from employees, organizations thus need to take the issue of adverse impact against certain groups or individuals (e.g., parents, black people, pregnant women etc.) very seriously. A first step is to measure these biases statistically and correct them to create a fair AI that is benefits employees as well as the organization as a whole. You can find more ideas to fight discriminatory biases in an article from Andrew Burt published 2020 in Harvard Business Review. This problem is strongly tied to the impression the organization makes towards external candidates: Candidates should have a reasonable chance to convince the team by means of their actual skills and knowledge, without any biases or expectations. If the application of machine learning algorithms for recruiting purposes were made transparent, it may feel strange to get a job thanks to the mere combination of features that have been proven to be success factors for some predecessors. A similar thought applies to the prediction of employee turnover: Even if there is a set of features considered to be key drivers of employee churn (last pay raise, business travel, person-job fit, distance from home etc.), it is pretty obvious that the intention to quit a job is highly personal. By means of data analytics tools, we can only describe general patterns from a pool of individuals. We can even try to predict behaviour based upon these general tendencies. But we can never really know for sure if they apply to everybody. If data-driven insights can affect people’s lives (e.g., hiring decisions, retention efforts...), we should stay very careful and constantly question the sanity of our procedures." }, { "code": null, "e": 9106, "s": 9044, "text": "3. The use of analytics does not justify unethical practices." }, { "code": null, "e": 10122, "s": 9106, "text": "AI dystopia often involves machines making ethically sensitive decisions, turning computers into decision-makers. Even if the following examples are far from reaching this kind of scenario, we should be aware that even if data can inform decision makers with reasonable insights, they are not the decision makers themselves and should be used under proper data protection and privacy guidelines. When it comes to the use of HR analytics for recruiting purposes, it has been suggested to give candidates the opportunity to opt-in and have control over their data by deciding whether or not potential employers and recruiters can assess their digital footprint to address any ethical and legal concerns (Chamorro-Premuzic et al. 2013). Another suggestion touches upon more autonomy for the people affected by HR-analytics tools: Employees should not become passive recipients of algorithmic governance but have the chance to actually understand how the model makes predictions and to give critical feedback if needed." }, { "code": null, "e": 10616, "s": 10122, "text": "Another creepy application I have stumbled upon in the literature includes the use of social media profiles like LinkedIn or Xing with the aim to predict the character of candidates bases on sentiment analysis — both in order to assess the candidate’s fit for a job (Faliagka, 2012). All of the above procedures certainly uncover interesting insights for researchers and psychologists, but should not be applied when the individuals, whose data are being processed, have not given any consent." }, { "code": null, "e": 10692, "s": 10616, "text": "4. The employee data sets available in industry are often noisy and sparse." }, { "code": null, "e": 11428, "s": 10692, "text": "If prediction is based on historical data, we always need to ask ourselves if these can really generalize to new, yet unknown observations. Now even if simulated HR data seem like a gift to any passionate data scientist, real HR data is often confidential, small, inconsistent and contains missing information. In case of medium-sized firms, not all of them can actually afford large-scale data storage, making it more difficult to store employee data in a consistent way. Moreover, it does typically include just a small proportion of employees who have actually left the company, making classes (stayed/left) imbalanced — a characteristic that needs special attention when evaluating machine learning models (but more on that later)." }, { "code": null, "e": 12147, "s": 11428, "text": "Another data-related change in perspective refers to the quality vs. quantity of data: Yahia, Hlel and Colomo-Palacious (2021) argue for a shift from big data to what they call “deep data” — qualitative data that contains all the necessary features to practically predict turnover. Indeed, massive sets of employee data are neither available to medium-to-small-sized firms nor necessary if we can identify the key drivers of turnover. There are other voices from the literature who go a step further and propose that large unstructured data sets (often referred to as “big data”) are not always better because they can be so noisy that it “overwhelms” each model’s predictive capacity (Chamorro-Premuzic et al., 2013)." }, { "code": null, "e": 12746, "s": 12147, "text": "This is just a gentle reminder to raise your awareness about the power of predictive analytics and its impact on the people — I highly recommend this paper from Dr. Michele Loi who has summarized ethical guidelines for the deployment of people analytics tools above and beyond the GDPR. Keeping these political issues in mind, we will now walk through a little case study to find out if the prediction of employee churn can be reasonably applied to a small fictive sample derived from the famous IBM employee dataset. I am curious to find out if it could potentially work for real-world cases, too!" }, { "code": null, "e": 13083, "s": 12746, "text": "The dataset we will use for our case study is a simulated dataset created by IBM Watson Analytics which can be found on Kaggle. It contains 1470 employee entries and common 38 features (Monthly income, Job satisfaction, gender etc.) — one of which is our target variable (Employee) Attrition (YES/NO). Let’s take a look at our raw data." }, { "code": null, "e": 13161, "s": 13083, "text": "Disclaimer: All graphics are made by the author unless specified differently." }, { "code": null, "e": 13573, "s": 13161, "text": "We seem to have 26 numeric variables and 9 character variables which differ in their distinct levels. None of the observations are missing and the summary the skim function gives us shows some descriptive statistics including mean, standard deviation, percentiles as well as a histogram. I am a big fan of the skim function — look how practical it is to get such a concise and yet detailed overview of the data!" }, { "code": null, "e": 14939, "s": 13573, "text": "It is pretty obvious that a payment that is perceived as unfair can influence a person’s intention to leave the job to look for better payment (Harden, Boakye & Ryan, 2018; Sarkar, 2018; Bryant & Allen, 2013). This is why we would like to create another variable that represents the payment competitiveness of each employee’s monthly income — the reasoning behind this is that employees may compare their income against those of their peers who share the same job level. Somebody who perceives his or her payment as fair should be less likely to leave the company compared to a person who gets considerably less for a similar position. To get there, we will use the data.table syntax to first calculate the median compensation by job level and store the appropriate value for each observation. Then we will divide each employee’s monthly income by the median income to get his or her compensation ratio: a measure that directly represents the person’s payment in respect to what would be expected by job level. Thus, a score of 1 means that the employee exactly matches the average payment for this position. A score of 1.2 means that the employee is paid 20% above the average pay and a score of 0.8 means that the person is paid 20% less than what would be expected by the usual payment per job level. To represent this at a factorial level, we will assign values" }, { "code": null, "e": 14983, "s": 14939, "text": "To “average” which lie within 0.75 and 1.25" }, { "code": null, "e": 15025, "s": 14983, "text": "To “below” that lie within 0 and 0.74 and" }, { "code": null, "e": 15095, "s": 15025, "text": "to “above” that lie within 1.25 and 2 of the CompensationRatio range." }, { "code": null, "e": 15176, "s": 15095, "text": "This is how our newly generates features look like on the first 10 observations:" }, { "code": null, "e": 15302, "s": 15176, "text": "But how many employees actually left? Let’s calculate the turnover rate to learn something about the distribution of classes." }, { "code": null, "e": 15692, "s": 15302, "text": "So, it appears that 237 employees (16%) left the company in a given timeframe while a majority (almost 84%) stayed. As argued above, many HR mangers do not have access to huge datasets containing thousands of employees with complete records. Now what if we would like to advise a small-to-medium firm that includes 50 to 250 employees? Can we still train ML algorithms to predict turnover?" }, { "code": null, "e": 15931, "s": 15692, "text": "To create an extra bit of a challenge and mimic a real-life sample that mimics a small-to-medium-sized company, we will randomly draw 126 observations from our full IBM Watson dataset. I will set a seed to make it more replicable for you." }, { "code": null, "e": 16505, "s": 15931, "text": "Let’s now take a closer look at the interplay between two key factors for employee churn: job satisfaction and compensation. A typical hypothesis derived from the literature proposes that higher job satisfaction is associated with a lower likelihood of employee turnover — unhappy employees usually have more reason to leave because they expect to be happier somewhere else and do not feel as emotionally committed to their current organization, making it more desirable and easier to leave as soon as attractive alternatives are found (Zimmermann, Swider & Boswell, 2018)." }, { "code": null, "e": 16836, "s": 16505, "text": "It looks like the data generally support this hypothesis: even if the tails of the distribution demonstrate that a few employees who stayed are actually unsatisfied while some leavers are happy, the general tendency suggests that employees who leave are indeed on average less satisfied than the remaining employees in our sample." }, { "code": null, "e": 17075, "s": 16836, "text": "Okay — but how does the combination of monthly income and job satisfaction differ among in relation to employee churn? More specifically, could a lower income be the reason to leave for employees who are actually satisfied with their job?" }, { "code": null, "e": 19213, "s": 17075, "text": "Of course, we cannot really fully tell if there is a cause-effect-relationship between income or job satisfaction and employee attrition — but it is still interesting to see if there is any hint about an association. Surprisingly, for very unsatisfied employees, monthly income is actually higher leavers compared to the remaining employees. This suggests that monthly income alone cannot really account for employee turnover in cases in which employees are not satisfied with their jobs — money is not everything! This is consistent with the observation that satisfaction with compensation is just one side of the same coin: To be truly happy with their jobs, employees do not only expect appropriate compensation for their hard work but rather a range of factors that contribute to their overall satisfaction with their work (e.g., non-monetary support from their supervisors, strong relationships to great colleagues, a sense of fulfilment from the work itself etc.) (Zimmermann et al., 2018). Intriguingly, the relationship seems to be vice versa for more satisfied employees: As could be expected, people who stayed are paid considerably better than leavers. This pattern even seems to be more pronounced the higher we climb the happiness ladder: The payment gap seems to increase linearly with each level of job satisfaction. We could speculate that the more satisfied employees have more resources to invest a lot of energy into their work, making them more resilient towards high-pressure job demands (Bakker & Demerouti, 2007). As compensation is often tied to performance, this could result in two scenarios: The boost in energy could result into an appropriate promotion for some employees, giving them even more incentive to stay with their current employer.But if they are not given any better compensation in return, this could be perceived as inequitable and yet another reason to leave the organization (Birtch, Chiang & Van Esch, 2016). Still, testing this assumption is a bit beyond the scope for this article and difficult to test such a simulated dataset which does not include longitudinal information to begin with." }, { "code": null, "e": 19586, "s": 19213, "text": "But we could argue that payment is certainly related to the employee’s job level as managers naturally earn more than junior consultants. Do the relationships hold if we swap the y-axis by the CompensationRatio variable we have created earlier? For example, are medium-to-highly satisfied employees who left paid less compared to what would be expected by their job level?" }, { "code": null, "e": 20613, "s": 19586, "text": "Not quite. On average, leavers are often paid the average pay or even better compared to their peers. Even if it appears that the range of different degrees of pay competitiveness are a bit larger in the middle of the job satisfaction scale, suggesting that payment competitiveness of not-so-happy employees who have left can be very different. But we should be careful here and avoid any premature interpretation: there could be significantly more employees who show a medium degree of job satisfaction than those who lie at the more extreme levels (very happy/unhappy). If we have more employees at the middle of the satisfaction distribution, chances would be higher that each degree of pay competitiveness would be somewhat covered, right? On the other hand, larger samples often cause the distribution to appear more normally distributed and less flat while the density peaks around the average value as the central limit theorem states. Let’s calculate a quick sanity check to find it out how this applies to our sample:" }, { "code": null, "e": 20949, "s": 20613, "text": "Wow — there are more satisfied than unsatisfied employees in our sample as they amount to about 65% of the observations. Thus, our second interpretation is more likely in this case and at first sight, there are no obvious interaction effects between job satisfaction and pay competitiveness that could contribute to employee attrition." }, { "code": null, "e": 21389, "s": 20949, "text": "Being a trained psychologist, I am particularly interested in the question how the psychological climate may affect employee’s intention to leave. For the modelling part in particular, we will use the caret package, short for Classification And REgression Training which was developed by Max Kuhn and various other smart contributors. Caret has a nice built-in function to quickly get an impression about the features we are interested in." }, { "code": null, "e": 21802, "s": 21389, "text": "Because the scale on which each of these variables are rated is ordinal in nature, a density plot looks cool but might not be the ideal choice here: The kurtosis of the curves is directly influenced by our class imbalance (a few who leave and a lot who stay) which could be misleading and we do not want to hallucinate any patterns here where there are none. Therefore, let’s try another technique: mosaic plots." }, { "code": null, "e": 22651, "s": 21802, "text": "Now what the mosaic function from the vcd-package does is to test whether the frequencies in our sample could have been generated by simple chance. This is done by calculating a Chi-squared-test behind the scenes. We can now analyse the results by looking at both the size of the rectangles and the colors: the area of the rectangle represents the proportion of cases for any given combination of levels and the color of the tiles indicate the degree relationship among the variables — the more the colour deviates from grey, the more we must question statistical independence between the different factor combinations (as represented by the pearson-residual scale on the right). Usually dark blue represents more cases than expected given random occurrence while dark red represents less cases than expected if they were generated by chance alone." }, { "code": null, "e": 23344, "s": 22651, "text": "Okay — in our case, every tile is coloured in grey which suggests that there are no strong deviations from statistical independence. Only in case of Environment Satisfaction we could wonder whether leavers are overly unsatisfied with their work environment compared to the remaining as indicated by the close-to-significant p-value and the shift between both distributions we can draw from the featureplot above. A limitation could be that the mosaic plot function is probably not sensitive enough to capture slight deviations from random frequency distributions — we still have a small sample size that gets further broken down by the combination of categorical levels we try to investigate." }, { "code": null, "e": 23945, "s": 23344, "text": "We now make our dataset ready for the actual modelling part. As a first step, we will remove all variables that are very unlikely to have any predictive power. For example, employee-ID won’t explain any meaningful variation in employee turnover, therefore it should be deleted for now among some other variables. Other examples include variables that share a lot with other features and therefore could lead to multicollinearity issues (e.g., hourly rate and monthly income). We will save the reduced dataset by properly converting all string variables (e.g., Department) to factors at the same time." }, { "code": null, "e": 24202, "s": 23945, "text": "To be pretty sure that we have not overlooked any highly intercorrelated variables, we will automatically detect and remove them. For this purpose, we first identify any numeric variables, compute a correlation matrix and find correlations that exceed 0.5." }, { "code": null, "e": 24395, "s": 24202, "text": "So, there are indeed some variables that were flagged by our code — we should take a closer look at: “YearsAtCompany”, “JobLevel”, “MonthlyIncome”,”YearsInCurrentRole” and “PercentSalaryHike”." }, { "code": null, "e": 25003, "s": 24395, "text": "It appears that YearsAtCompany is highly correlated with YearsInCurrentRole, YearsSinceLastPromotion and YearsWithCurrManager. Thus, just one of these time-related variables can stay: I would suggest to keep “Years since last Promotion” because this could explain some additional variance the others cannot: it relates not only to the time that has passed since the employee entered the company, but also the years that went by without promotion. As the literature suggests, regular pay raises that are often a consequence of a promotion play a crucial protective role against turnover (Das & Baruah, 2013)." }, { "code": null, "e": 25356, "s": 25003, "text": "Joblevel is highly correlated with Age and with monthly income: It is plausible that the older employees get, the higher the chances they have already climbed the career ladder and earn significantly more compared to previous years. Because we have discussed the impact of monthly income, I would rather drop Job Level and Age than our income variable." }, { "code": null, "e": 25466, "s": 25356, "text": "PercentSalaryHike is highly correlated with PerformanceRating as a strong performance is rewarded with money." }, { "code": null, "e": 25642, "s": 25466, "text": "After analysing the interrelations of these variables, let us alter the list of variables which should be removed and create a new dataframe containing the selected variables:" }, { "code": null, "e": 26699, "s": 25642, "text": "To make our machine learning algorithms work, we need to transform these factor variables into dummy variables. For each factor level, we will have a separate variable indicating whether or not the respective participant falls into this category (e.g. a person who travels rarely would get a 1 instead of a 0). Firstly, we will detect all categorical variables except for our target (attrition). Then, we will make use of caret’s dummyVars function, apply it to our dataset and create a brand new dataframe that contains our selected set of numeric variables, dummy variables and attrition (yes/no). Please note that the caret-function dummyVars transforms the variables into a complete set of dummy variables which means that all factor levels will be covered and none will be left out — a procedure that does not work for linear models for which the output is always compared against a reference level (e.g., if we want to compare the effect of being female against the intercept which represents male employees). Thus, our variables are one-hot encoded." }, { "code": null, "e": 27902, "s": 26699, "text": "Next, we will remove variables that do not provide any predictive value using carets nearZeroVar function. It applies to predictors that only have a single unique value (i.e. a “zero-variance predictor”). This would be the case if all our employees would be frequent travellers, leaving all other options (rare or none travel) blank which would create a constant in our statistical model. It also applies to predictors that only have a few unique values which occur in very low frequencies (e.g., if 1 out of 100 employees would be divorced). For many models (except for tree-based models), this may cause the model to crash or the fit to be unstable. As a final pre-processing step, we will make sure that we have ordered the target’s factor levels correctly: I have noticed that in the past, caret appears to just take the first level as the positive class (e.g., yes vs. no, win vs. lose etc.) which can sometimes “confuse” the confusion matrix later — for example, specificity and sensitivity can easily mixed up. Therefore, we want to make sure that an actual employee turnover is considered to positive class by explicitly assigning “yes” and then “no” as factor levels of our attrition variable." }, { "code": null, "e": 30137, "s": 27902, "text": "Our final dataset is now cleaned up and ready for modelling. Because we have a small sample, we could run into the problem to overly fit our model to our sample-specific data to an extent that we cannot apply it to new employee data later. A problem that is often referred to as overfitting — a phenomenon that could explain why we sometimes cannot replicate previously found effects anymore. For machine learning models, we often split our data into training and validation/test sets to overcome this issue. The training set is used to train the model and the validation/test set is used to validate it on data it has never seen before. If we would use a traditional 80/20-split to our use case, model performance would largely depend on chance because we it would differ each time the algorithm would randomly select 25 individuals for testing purposes. This problem becomes even more extreme in our case because we have an imbalance of classes: Remember that only roughly 20% of employees left the company — this means that our model would probably be tested on about 5 leavers and 20 remaining, leaving us with the question whether the algorithm would perform similarly on different cases. Also, if we would assess model performance by looking at the prediction accuracy, the result would easily overestimate its actual performance as there are many positive cases as a reference (e.g., employees who did not leave). You can find more on the question how to split the data from a small imbalanced dataset in this interesting Stackoverflow discussion. Fortunately, we have something from our statistical toolbox: cross-validation with various splits. We will apply our trained model(s) to a new set of observations and repeatedly adjust the parameters to reduce prediction error. For these “new observations”, we do not even need a new sample: we will recycle the dataset by training the model to a set of observations and use another part of the data to test model performance. We will repeat this 5 times and average the test performance to receive a final estimation of our model’s performance — a technique called 5-fold-cross-validation. Thus, we can make use of all of our data while the model is still tested on “new” cases." }, { "code": null, "e": 30612, "s": 30137, "text": "Now we will set up a reusable train Control object to build our machine learning models with the same settings: repeated cross-validation makes sure that we run our 5-fold-cross-validation process 5 times. Moreover, we ask caret to provide us with class probabilities in our model output as well as the final predictions and we want to see the progress of our modelling process (verbose = True). We will use caret’s built-in hyperparameter search with its standard settings." }, { "code": null, "e": 30674, "s": 30612, "text": "The models we will test against each other are the following:" }, { "code": null, "e": 31140, "s": 30674, "text": "Logistic Regression: this is a widely used, traditional classification algorithm that is based on the linear regression you know from your statistics course and was originally proposed in 1958 by Cox. The primary prediction output is the observation’s estimated probability to belong to a certain class. Based on the value of the probability, the model creates a linear boundary separating the input space into two regions (e.g., more likely yes or more likely no)." }, { "code": null, "e": 31617, "s": 31140, "text": "Random Forests: Basic decision trees are interpretable models that are built in a tree-like fashion: branches are combinations of features and leaves are the class labels of interest (e.g., yes or no). Random forests give us an edge over basic decision trees by combining the power of all multiple weak learners to come to a collective prediction. This makes more robust than simple decision trees because the final prediction is not dominated by a few influential predictors." }, { "code": null, "e": 32183, "s": 31617, "text": "Extreme Gradient Boosting (XGB): this modelling technique is another tree-based method introduced by Chen (2014) which is based on Gradient boosting trees which is an ensemble machine learning method proposed in 2001 by Friedman for regression and classification purposes. A key characteristic is that they learn sequentially — each tree attempts to correct the mistakes of the previous tree until no further enhancement can be achieved. XGB is often described as the faster, more scalable and memory efficient technique version compared to gradient boosting trees." }, { "code": null, "e": 32657, "s": 32183, "text": "GLMnet: this is a very flexible, efficient extension of glm models that is nicely implemented in R. It fits generalized linear models using penalized maximum likelihood estimation and thus reduces overfitting known from common regression models (e.g., basic logistic or linear regression) by using a lasso or elastic net penalty term. It is known for its ability to deal well with small samples, prefer simple over overly complex models and its built-in variable selection." }, { "code": null, "e": 33017, "s": 32657, "text": "Naïve Bayes: this model uses the famous Bayes Theorem as it estimates the occurrence probability of an event based on prior knowledge of related features. Classifiers first learn joint probability distribution of their inputs and produce an output (e.g., yes or no) based on the maximum posterior probability of the given each respective feature combination." }, { "code": null, "e": 34017, "s": 33017, "text": "Because we have imbalanced sample (more stayed than left), we won’t assess the model’s performance with accuracy later. As accuracy is the proportion of correctly classified cases out of all cases, it would be not a big deal for the algorithm to give us a high score even if it simply classified ALL cases as the majority class (e.g., no). It is a more appropriate metric if we would have more equally distributed classes which were similarly important to us. But in this case, we actually are about the positive cases: you could argue that it is more detrimental NOT to correctly identify leavers (e.g., sensitivity or true positive rate) than accidentally predict that an employee would leave if the person actually stayed (false positive rate or 1 — specificity). Therefore, I would like to use the F1-score as accuracy metric for training optimization as it assigns more importance to correctly classify positive cases (e.g., employee churn) and makes more sense for heavily imbalanced datasets." }, { "code": null, "e": 34076, "s": 34017, "text": "The F1-score is the harmonic mean of precision and recall:" }, { "code": null, "e": 34333, "s": 34076, "text": "The precision is the amount of correctly classified positive cases divided by the number of all positive predictions (including the false positives, e.g. employees who were identified as leavers but did not go). It is also called positive predictive value." }, { "code": null, "e": 34893, "s": 34333, "text": "Recall, on the other hand, is the amount of true positive cases divided by the number of all samples that should have been identified as positive (e.g., all actual leavers, even if not all of them were correctly identified). It is also known as sensitivity in binary classification use cases. If you did not get it yet, no worries, it is not that intuitive as the simple accuracy metric. I hope that my visualizations may help you to wrap your head around it. In sum, the F1-score is associated with the algorithm’s ability to detect positive cases correctly." }, { "code": null, "e": 35351, "s": 34893, "text": "Because caret does not directly provide the f1 metric as an option to our train function, we will use a DIY-code found on Stackoverflow. You can find more on accuracy metrices here. By the way, it is not as easy to interpret whether other not our achieved F1-score is “good enough” because it heavily depends on the amount of truly positive cases in our sample. Therefore, we will later look for the model highest F1-score we have achieved on the same data." }, { "code": null, "e": 36105, "s": 35351, "text": "To have a good baseline model to compare the others with, we will create a logistic regression model: Based on the visualizations we have created earlier and the theories from the psychological literature, we would hypothesize that higher job satisfaction is protective against employee attrition. Also, we would assume that the lower monthly income, the higher the likelihood for employees to leave the company to get better payment. Moreover, we would think that the effect of monthly income on employee turnover gets amplified with each level of job satisfaction. For all other models, we will throw in all the variables we have selected before and make no further theoretical predictions. This way, we can see whether give us a predictive advantage." }, { "code": null, "e": 36254, "s": 36105, "text": "But before we dive into the actual model comparison, let’s see if our baseline model can actually explain employee attrition at a rudimentary stage." }, { "code": null, "e": 36292, "s": 36254, "text": "model_baselinesummary(model_baseline)" }, { "code": null, "e": 36797, "s": 36292, "text": "As predicted by our hypothesis, can see that the estimates of the model suggest that the likelihood that an employee leaves the company decreases slightly with every additional dollar monthly income and every additional level of job satisfaction. Note that the estimates cannot be directly interpreted because they are scaled as log odds that fits our logistic regression formula. The interaction term (combination of monthly income and job satisfaction) also became statistically significant (p < .001)." }, { "code": null, "e": 37284, "s": 36797, "text": "Can the other models with a larger set of predictors do a better job predicting employee turnover in our small sample? Let’s find it out. We will first make a list of all our model objects (random forest, glmnet etc.) and name them for future reference. Then we will use the resamples-function from caret to plot the models’ performance against each. It will give us the range of F1 values across all 5 folds, making it possible to select the model with the highest average performance." }, { "code": null, "e": 38733, "s": 37284, "text": "It appears that XGBoost outperformed all other models when it comes to its ability to correctly classify leavers and showed a pretty robust performance across all folds. Our baseline model showed pretty variable model performance depending on the folds that were used for testing, making it seem a bit unstable. However, we did some unfair comparison here by comparing apples with bananas: for our basic model, we used a theoretically plausible formula while we threw in all of the candidate-variables into the other models. In these cases, we tried to predict employee churn with EVERYTHING. This makes it hard to judge whether the model performance of let’s say the random forest algorithm is due to an overly complex formula or due to the kind of model itself. I could even imagine that a simpler model might be beneficial in our case because we do not have enough observations to justify such a large set of predictors used in our model. As Yarkoni and Westfall (2017) nicely pointed out, the higher the chance that a small set of predictors is applied to many observations, the smaller the likelihood of overfitting, represented in a low n to p ratio (sample size to predictors). If we however have a small dataset and many parameters that all make small contributions to an outcome X like in our first modelling round, the likelier we will get large prediction errors and the performance gap between training and test set will be substantial." }, { "code": null, "e": 38941, "s": 38733, "text": "Therefore, we will make a fairer comparison by demonstrating what happens if you tell caret to predict employee churn with job satisfaction, monthly income and the combination of these for all of the models:" }, { "code": null, "e": 39454, "s": 38941, "text": "Now random forest now does not seem to show the worst performance anymore, but again XGB seems to be our winner. Interestingly, the F1-score encompasses very similar values like our complex models, suggesting that a more parsimonious model is preferable over too complex models. Let’s see if the confusion matrix can tell us a bit more about the XGB’s performance that includes our simple model formula compared to our baseline model. As a reminder, this is how such a confusion matrix translates to our problem." }, { "code": null, "e": 40749, "s": 39454, "text": "Wow — the direct comparison shows that XGBoost is much better in predicting employee churn than our baseline model! By looking at the raw confusion matrix we can see that the XGBoost correctly identified 17 out of 22 leavers whereas the baseline model only identified 3 of them. Our winner model’s precision is very good (0.94) which means that it did not mix up true leavers with fake leavers (false positives, i.e. employees who did not actually leave the company but stayed). On the other hand, the baseline model just predicted 4 positive cases from which 3 were correct, resulting in a rather poor precision of 0.75. The capacity to detect employee churn correctly becomes even more pronounced for the other metrices: Because the XGBoost algorithm also missed 5 true positive cases and incorrectly flagged them as negative, recall is not exceedingly high but still acceptable (0.77). As a reminder, recall is the amount of true positive cases divided by the number of all samples that should have been identified as positive (e.g., all actual leavers, even if not all of them were correctly identified) and is also known as sensitivity. In contrast, the baseline model was not sensitive enough to pick up the true leavers and accidentally flagged a majority of them as remaining employees." }, { "code": null, "e": 41168, "s": 40749, "text": "The gap in performance is also captured by the balanced accuracy score on the bottom which represents the balance between specificity and sensitivity of the respective model, suggesting that our baseline model underperformed when it comes to correctly identifying loyal employees as well. Apart from the F1-score, balanced accuracy has been suggested to be a better proxy of the model’s accuracy in imbalanced samples." }, { "code": null, "e": 41303, "s": 41168, "text": "All in all, XGBoost seems to give us a predictive edge over a simple generalized linear model even if we keep our predictors constant." }, { "code": null, "e": 42221, "s": 41303, "text": "As a next step, we would like to actually use the model to increase retention in our small company. For this purpose, we will first get the indices of employees that are still active and predict the likelihood for these employees to leave according to our model. Then we will save these probabilities as well as the actual employee data. Lastly, we will find the top 5 employees with the highest risk to leave the company. In order to give the company a chance to intervene, these are probably the people that should be recruited first to find out what they need to be happier and how they would like to develop in the future. This way, we can hopefully address any voluntary turnover. In the end, we will give the managers a full list of employees to talk to, ranked by their risk to leave — after all, it is good to give employees the chance to get rid of constructive feedback that may enhance the working climate." }, { "code": null, "e": 42254, "s": 42221, "text": "Do not use tibbles for modelling" }, { "code": null, "e": 42808, "s": 42254, "text": "Before I have discovered the beauty of the data.table syntax, I have worked with tibbles because I think the %>% operator is such an intuitive tool. Unfortunately, caret does only take in dataframes (or data.tables), but not tibbles and it took a long time for me to work out why my code would not run through. Until I have discovered this comment on github and changed the whole data wrangling part to a DT-like structure. Make sure to transform tibbles into classic dataframes before modelling with caret or do not use dplyr-syntax in the first place." }, { "code": null, "e": 42866, "s": 42808, "text": "Appropriate accuracy metrices make such a huge difference" }, { "code": null, "e": 43598, "s": 42866, "text": "Moreover, I have first used the AUC ROC score as the metric for optimization before I have discovered that you can also make it work with other metrices (e.g., the F1-score) as well. This resulted in a horrible model performance, with sensitivity scores under 0.1 — the algorithms did not really detect positive cases (e.g., actual employee churn) which might be due to our heavily imbalanced dataset. As predicted before, the model summary still demonstrated acceptable accuracy scores because it was not such a big deal for the models to identify those who stay as the majority of employees did not churn anyway. Using a more appropriate metric for optimization was really a game-changer and massively improved model performance." }, { "code": null, "e": 43637, "s": 43598, "text": "Our results are highly sample-specific" }, { "code": null, "e": 44659, "s": 43637, "text": "Before I have set a seed for replication purposes when drawing random samples from our original IBM HR analytics dataset, I realized that results would largely differ from sample to sample. This was especially true for the psychological variables like environment or relationship satisfaction. Even if this may sound a bit obvious to you, think about what this means to cases in which you do not have any larger dataset available from which you can draw a subset from: your interpretation of the data-generating processes (e.g., which factors would explain employee turnover) would be heavily biased but you would not have any chance to validate it yet due to a lack of data. This should make us careful about drawing preliminary conclusions about general patterns in nature before we have the chance to prove them on a larger population. Also, please keep in mind that the dataset is fictious as it does not contain real HR employee data, so it should not be used as a single source to answer truly scientific questions." }, { "code": null, "e": 45549, "s": 44659, "text": "From a technical perspective, I would argue that we can indeed make use of machine learning to predict employee turnover, even in small samples if you have a complete, high-quality dataset. Also, we have seen that when it comes to the number of predictors, a simpler, more parsimonious model can perform at least as good as a complex model. Nevertheless, the type of machine learning model can make a huge difference to the accuracy of our prediction. From a broader perspective, we need to be aware of the fact that it seems to be inevitable that we capture some degree of sample-specific error that does not generalize to new employees. Therefore, it would not be recommended to let the algorithm decide over people’s jobs and lives alone — as human beings, being data scientists, managers or HR experts, we need to take responsibility for the decisions being made under our supervision." }, { "code": null, "e": 46532, "s": 45549, "text": "There are several ways to increase the transparency of our data-driven approach towards external parties: If we did not have strong hypothesis before evaluating data, it may be helpful to explicitly claim that our work is exploratory in nature because our explanations are somewhat post-hoc and therefore could be biased. This limitation also applies to our approach since we inspected the potential psychological reasons driving employee turnover visually before specifying our model formula. At the end of the day, it might be most fruitful to make use of both of the worlds: investigating the roots and causes behind the data, widening our view towards patterns within the data that we have actually not hypothesized in the first place and always test a model’s ability to predict out-of-sample behaviour to minimize overfitting. Thus, a mix of some degree of theoretical flexibility but mindful interpretation of the data could enable us to make good and reasonable predictions." }, { "code": null, "e": 47505, "s": 46532, "text": "When you really think about deploying HR analytics tools in your organization, the end-users of the model need to be educated about the its benefits as well as its limitations: Even if we understand the common roots which increase the likelihood of turnover, people as well as organizations are still pretty unique — and so are the reasons to leave. Consequently, the mixture personal and practical reasons that drive frequent turnover may vary from company to company and even change across time. Thus, when a predictive model is applied, it must be constantly evaluated before it is already outdated and makes profound mistakes. I am such a big fan of data-driven technologies and if we use them thoughtfully, machine learning techniques can be a powerful tool to improve the workplace for good. But if we use it mechanically, it can easily become the dangerous black-box AI-critics fear and which our society should not aim for. So, let’s stay mindful data-enthusiasts." }, { "code": null, "e": 47644, "s": 47505, "text": "[1] A. Hammermann & C. Thiele, People Analytics: Evidenzbasiert Entscheidungsfindung im Personalmanagement (2019), (No35/2019), IW-Report." }, { "code": null, "e": 47810, "s": 47644, "text": "[2] R. S. Sexton, S. McMurtrey, J. O. Michalopoulos & A. M., Employee turnover: a neural network solution (2005), Computers & Operations Research, 32(10), 2635–2651." }, { "code": null, "e": 47978, "s": 47810, "text": "[3] J. P. Isson & J. S. Harriott, People analytics in the era of big data: Changing the way you attract, acquire, develop, and retain talent (2016), John Wiley & Sons." }, { "code": null, "e": 48090, "s": 47978, "text": "[4] L. Bock, Work Rules!: Wie Google die Art und Weise, wie wir leben und arbeiten, verändert. (2016), Vahlen." }, { "code": null, "e": 48312, "s": 48090, "text": "[5] Y. Zhao, M. K. Hryniewicki, F. Cheng, B. Fu & X. Zhu, Employee turnover prediction with machine learning: A reliable approach (2018), In Proceedings of SAI intelligent systems conference (pp. 737–758). Springer, Cham." }, { "code": null, "e": 48489, "s": 48312, "text": "[6] T. Yarkoni & J. Westfall, Choosing prediction over explanation in psychology: Lessons from machine learning (2017), Perspectives on Psychological Science, 12(6), 1100–1122." }, { "code": null, "e": 48760, "s": 48489, "text": "[7] A. A. Mahmoud, T. A. Shawabkeh, W. A. Salameh & I. Al Amro, Performance predicting in hiring process and performance appraisals using machine learning (2019), In 2019 10th International Conference on Information and Communication Systems (ICICS) (pp. 110–115). IEEE." }, { "code": null, "e": 48984, "s": 48760, "text": "[8] D. H. Kluemper, P. A. Rosen & K. W. Mossholder, Social networking websites, personality ratings, and the organizational context: More than meets the eye? (2012),1. Journal of Applied Social Psychology, 42(5), 1143–1172." }, { "code": null, "e": 49127, "s": 48984, "text": "[9] A. Apatean, E. Szakacs & M. Tilca, Machine-learning based application for staff recruiting (2017), Acta Technica Napocensis, 58(4), 16–21." }, { "code": null, "e": 49357, "s": 49127, "text": "[10] Y. M. Li, C. Y. Lai, & C. P. Kao, Incorporate personality trait with support vector machine to acquire quality matching of personnel recruitment (2008), In 4th international conference on business and information (pp. 1–11)." }, { "code": null, "e": 49551, "s": 49357, "text": "[11] T. Chamorro-Premuzic, D. Winsborough, R. A. Sherman & R. Hogan, New talent signals: shiny new objects or a brave new world (2013), Ind. Organ. Psychol. Perspect. Sci. Pract., 53:1689–1699." }, { "code": null, "e": 49787, "s": 49551, "text": "[12] E. Faliagka, K. Ramantas, A. Tsakalidis & G. Tzimas, Application of machine learning algorithms to an online recruitment system (2012), In Proc. International Conference on Internet and Web Applications and Services (pp. 215–220)." }, { "code": null, "e": 49951, "s": 49787, "text": "[13] M. Loi, People Analytics must benefit the people. An ethical analysis of data-driven algorithmic systems in human resources management (2020), Algorithmwatch." }, { "code": null, "e": 50125, "s": 49951, "text": "[14] N. B. Yahia, J. Hlel & R. Colomo-Palacios, From Big Data to Deep Data to Support People Analytics for Employee Attrition Prediction (2021), IEEE Access, 9, 60447–60458." }, { "code": null, "e": 50315, "s": 50125, "text": "[15] G. Harden, K. G. Boakye & S. Ryan, Turnover intention of technology professionals: A social exchange theory perspective (2018), Journal of Computer Information Systems, 58(4), 291–300." }, { "code": null, "e": 50457, "s": 50315, "text": "[16] J. Sarkar, Linking Compensation and Turnover: Retrospection and Future Directions (2018), IUP Journal of Organizational Behavior, 17(1)." }, { "code": null, "e": 50630, "s": 50457, "text": "[17] P.C. Bryant & D. G. Allen, Compensation, benefits and employee turnover: HR strategies for retaining top talent (2013), Compensation & Benefits Review, 45(3), 171–175." }, { "code": null, "e": 50781, "s": 50630, "text": "[18] R. D. Zimmerman, B. W. Swider & W. R. Boswell, Synthesizing content models of employee turnover (2019), Human Resource Management, 58(1), 99–114." }, { "code": null, "e": 50907, "s": 50781, "text": "[19] A. B. Bakker & E. Demerouti, The job demands‐resources model: State of the art (2007), Journal of managerial psychology." }, { "code": null, "e": 51199, "s": 50907, "text": "[20] T. A, Birtch, F. F. Chiang & E. Van Esch, A social exchange theory framework for understanding the job characteristics–job outcomes relationship: The mediating role of psychological contract fulfillment. (2016), The international journal of human resource management, 27(11), 1217–1236." }, { "code": null, "e": 51335, "s": 51199, "text": "[21] M. Kuhn, J. Wing, S. Weston, A. Williams, C. Keefer, A. Engelhardt., ... & M. Benesty, Package ‘caret’ (2020), The R Journal, 223." }, { "code": null, "e": 51463, "s": 51335, "text": "[22] B. L. Das & M. Baruah, Employee retention: A review of literature (2013), Journal of business and management, 14(2), 8–16." } ]
Dart Programming - Collection
Dart, unlike other programming languages, doesn’t support arrays. Dart collections can be used to replicate data structures like an array. The dart:core library and other classes enable Collection support in Dart scripts. Dart collections can be basically classified as − A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists. Fixed Length List − The list’s length cannot change at run-time. Fixed Length List − The list’s length cannot change at run-time. Growable List − The list’s length can change at run-time. Growable List − The list’s length can change at run-time. Set represents a collection of objects in which each object can occur only once. The dart:core library provides the Set class to implement the same. The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection. In other words, Maps can grow and shrink at runtime. The Map class in the dart:core library provides support for the same. A Queue is a collection that can be manipulated at both ends. Queues are useful when you want to build a first-in, first-out collection. Simply put, a queue inserts data from one end and deletes from another end. The values are removed / read in the order of their insertion. The Iterator class from the dart:core library enables easy collection traversal. Every collection has an iterator property. This property returns an iterator that points to the objects in the collection. The following example illustrates traversing a collection using an iterator object. import 'dart:collection'; void main() { Queue numQ = new Queue(); numQ.addAll([100,200,300]); Iterator i= numQ.iterator; while(i.moveNext()) { print(i.current); } } The moveNext() function returns a Boolean value indicating whether there is a subsequent entry. The current property of the iterator object returns the value of the object that the iterator currently points to. This program should produce the following output − 100 200 300 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2748, "s": 2525, "text": "Dart, unlike other programming languages, doesn’t support arrays. Dart collections can be used to replicate data structures like an array. The dart:core library and other classes enable Collection support in Dart scripts." }, { "code": null, "e": 2798, "s": 2748, "text": "Dart collections can be basically classified as −" }, { "code": null, "e": 2939, "s": 2798, "text": "A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists." }, { "code": null, "e": 3004, "s": 2939, "text": "Fixed Length List − The list’s length cannot change at run-time." }, { "code": null, "e": 3069, "s": 3004, "text": "Fixed Length List − The list’s length cannot change at run-time." }, { "code": null, "e": 3127, "s": 3069, "text": "Growable List − The list’s length can change at run-time." }, { "code": null, "e": 3185, "s": 3127, "text": "Growable List − The list’s length can change at run-time." }, { "code": null, "e": 3334, "s": 3185, "text": "Set represents a collection of objects in which each object can occur only once. The dart:core library provides the Set class to implement the same." }, { "code": null, "e": 3577, "s": 3334, "text": "The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection. In other words, Maps can grow and shrink at runtime. The Map class in the dart:core library provides support for the same." }, { "code": null, "e": 3853, "s": 3577, "text": "A Queue is a collection that can be manipulated at both ends. Queues are useful when you want to build a first-in, first-out collection. Simply put, a queue inserts data from one end and deletes from another end. The values are removed / read in the order of their insertion." }, { "code": null, "e": 4057, "s": 3853, "text": "The Iterator class from the dart:core library enables easy collection traversal. Every collection has an iterator property. This property returns an iterator that points to the objects in the collection." }, { "code": null, "e": 4141, "s": 4057, "text": "The following example illustrates traversing a collection using an iterator object." }, { "code": null, "e": 4340, "s": 4141, "text": "import 'dart:collection'; \nvoid main() { \n Queue numQ = new Queue(); \n numQ.addAll([100,200,300]); \n Iterator i= numQ.iterator; \n \n while(i.moveNext()) { \n print(i.current); \n } \n}" }, { "code": null, "e": 4551, "s": 4340, "text": "The moveNext() function returns a Boolean value indicating whether there is a subsequent entry. The current property of the iterator object returns the value of the object that the iterator currently points to." }, { "code": null, "e": 4602, "s": 4551, "text": "This program should produce the following output −" }, { "code": null, "e": 4617, "s": 4602, "text": "100 \n200 \n300\n" }, { "code": null, "e": 4652, "s": 4617, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4672, "s": 4652, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4705, "s": 4672, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4725, "s": 4705, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4758, "s": 4725, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 4775, "s": 4758, "text": " Frahaan Hussain" }, { "code": null, "e": 4810, "s": 4775, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 4827, "s": 4810, "text": " Frahaan Hussain" }, { "code": null, "e": 4862, "s": 4827, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4882, "s": 4862, "text": " Pranjal Srivastava" }, { "code": null, "e": 4915, "s": 4882, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 4935, "s": 4915, "text": " Pranjal Srivastava" }, { "code": null, "e": 4942, "s": 4935, "text": " Print" }, { "code": null, "e": 4953, "s": 4942, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML paragraphs ignore spaces
[]
Tryit Editor v3.6 - Show Python
c = camelcase.CamelCase() ​ txt = "lorem ipsum dolor sit amet" ​ print(c.hump(txt)) ​ #This method capitalizes the first letter of each word.
[ { "code": null, "e": 45, "s": 19, "text": "c = camelcase.CamelCase()" }, { "code": null, "e": 47, "s": 45, "text": "​" }, { "code": null, "e": 82, "s": 47, "text": "txt = \"lorem ipsum dolor sit amet\"" }, { "code": null, "e": 84, "s": 82, "text": "​" }, { "code": null, "e": 103, "s": 84, "text": "print(c.hump(txt))" }, { "code": null, "e": 105, "s": 103, "text": "​" } ]
Linked List Program in C
A linked list is a sequence of data structures, which are connected together via links. Linked List is a sequence of links which contains items. Each link contains a connection to another link. Linked list is the second most-used data structure after array. #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> struct node { int data; int key; struct node *next; }; struct node *head = NULL; struct node *current = NULL; //display the list void printList() { struct node *ptr = head; printf("\n[ "); //start from the beginning while(ptr != NULL) { printf("(%d,%d) ",ptr->key,ptr->data); ptr = ptr->next; } printf(" ]"); } //insert link at the first location void insertFirst(int key, int data) { //create a link struct node *link = (struct node*) malloc(sizeof(struct node)); link->key = key; link->data = data; //point it to old first node link->next = head; //point first to new first node head = link; } //delete first item struct node* deleteFirst() { //save reference to first link struct node *tempLink = head; //mark next to first link as first head = head->next; //return the deleted link return tempLink; } //is list empty bool isEmpty() { return head == NULL; } int length() { int length = 0; struct node *current; for(current = head; current != NULL; current = current->next) { length++; } return length; } //find a link with given key struct node* find(int key) { //start from the first link struct node* current = head; //if list is empty if(head == NULL) { return NULL; } //navigate through list while(current->key != key) { //if it is last node if(current->next == NULL) { return NULL; } else { //go to next link current = current->next; } } //if data found, return the current Link return current; } //delete a link with given key struct node* delete(int key) { //start from the first link struct node* current = head; struct node* previous = NULL; //if list is empty if(head == NULL) { return NULL; } //navigate through list while(current->key != key) { //if it is last node if(current->next == NULL) { return NULL; } else { //store reference to current link previous = current; //move to next link current = current->next; } } //found a match, update the link if(current == head) { //change first to point to next link head = head->next; } else { //bypass the current link previous->next = current->next; } return current; } void sort() { int i, j, k, tempKey, tempData; struct node *current; struct node *next; int size = length(); k = size ; for ( i = 0 ; i < size - 1 ; i++, k-- ) { current = head; next = head->next; for ( j = 1 ; j < k ; j++ ) { if ( current->data > next->data ) { tempData = current->data; current->data = next->data; next->data = tempData; tempKey = current->key; current->key = next->key; next->key = tempKey; } current = current->next; next = next->next; } } } void reverse(struct node** head_ref) { struct node* prev = NULL; struct node* current = *head_ref; struct node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; } void main() { insertFirst(1,10); insertFirst(2,20); insertFirst(3,30); insertFirst(4,1); insertFirst(5,40); insertFirst(6,56); printf("Original List: "); //print list printList(); while(!isEmpty()) { struct node *temp = deleteFirst(); printf("\nDeleted value:"); printf("(%d,%d) ",temp->key,temp->data); } printf("\nList after deleting all items: "); printList(); insertFirst(1,10); insertFirst(2,20); insertFirst(3,30); insertFirst(4,1); insertFirst(5,40); insertFirst(6,56); printf("\nRestored List: "); printList(); printf("\n"); struct node *foundLink = find(4); if(foundLink != NULL) { printf("Element found: "); printf("(%d,%d) ",foundLink->key,foundLink->data); printf("\n"); } else { printf("Element not found."); } delete(4); printf("List after deleting an item: "); printList(); printf("\n"); foundLink = find(4); if(foundLink != NULL) { printf("Element found: "); printf("(%d,%d) ",foundLink->key,foundLink->data); printf("\n"); } else { printf("Element not found."); } printf("\n"); sort(); printf("List after sorting the data: "); printList(); reverse(&head); printf("\nList after reversing the data: "); printList(); } If we compile and run the above program, it will produce the following result − Original List: [ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ] Deleted value:(6,56) Deleted value:(5,40) Deleted value:(4,1) Deleted value:(3,30) Deleted value:(2,20) Deleted value:(1,10) List after deleting all items: [ ] Restored List: [ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ] Element found: (4,1) List after deleting an item: [ (6,56) (5,40) (3,30) (2,20) (1,10) ] Element not found. List after sorting the data: [ (1,10) (2,20) (3,30) (5,40) (6,56) ] List after reversing the data: [ (6,56) (5,40) (3,30) (2,20) (1,10) ] 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2838, "s": 2580, "text": "A linked list is a sequence of data structures, which are connected together via links. Linked List is a sequence of links which contains items. Each link contains a connection to another link. Linked list is the second most-used data structure after array." }, { "code": null, "e": 7633, "s": 2838, "text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nstruct node {\n int data;\n int key;\n struct node *next;\n};\n\nstruct node *head = NULL;\nstruct node *current = NULL;\n\n//display the list\nvoid printList() {\n struct node *ptr = head;\n printf(\"\\n[ \");\n\t\n //start from the beginning\n while(ptr != NULL) {\n printf(\"(%d,%d) \",ptr->key,ptr->data);\n ptr = ptr->next;\n }\n\t\n printf(\" ]\");\n}\n\n//insert link at the first location\nvoid insertFirst(int key, int data) {\n //create a link\n struct node *link = (struct node*) malloc(sizeof(struct node));\n\t\n link->key = key;\n link->data = data;\n\t\n //point it to old first node\n link->next = head;\n\t\n //point first to new first node\n head = link;\n}\n\n//delete first item\nstruct node* deleteFirst() {\n\n //save reference to first link\n struct node *tempLink = head;\n\t\n //mark next to first link as first \n head = head->next;\n\t\n //return the deleted link\n return tempLink;\n}\n\n//is list empty\nbool isEmpty() {\n return head == NULL;\n}\n\nint length() {\n int length = 0;\n struct node *current;\n\t\n for(current = head; current != NULL; current = current->next) {\n length++;\n }\n\t\n return length;\n}\n\n//find a link with given key\nstruct node* find(int key) {\n\n //start from the first link\n struct node* current = head;\n\n //if list is empty\n if(head == NULL) {\n return NULL;\n }\n\n //navigate through list\n while(current->key != key) {\n\t\n //if it is last node\n if(current->next == NULL) {\n return NULL;\n } else {\n //go to next link\n current = current->next;\n }\n } \n\t\n //if data found, return the current Link\n return current;\n}\n\n//delete a link with given key\nstruct node* delete(int key) {\n\n //start from the first link\n struct node* current = head;\n struct node* previous = NULL;\n\t\n //if list is empty\n if(head == NULL) {\n return NULL;\n }\n\n //navigate through list\n while(current->key != key) {\n\n //if it is last node\n if(current->next == NULL) {\n return NULL;\n } else {\n //store reference to current link\n previous = current;\n //move to next link\n current = current->next;\n }\n }\n\n //found a match, update the link\n if(current == head) {\n //change first to point to next link\n head = head->next;\n } else {\n //bypass the current link\n previous->next = current->next;\n } \n\t\n return current;\n}\n\nvoid sort() {\n\n int i, j, k, tempKey, tempData;\n struct node *current;\n struct node *next;\n\t\n int size = length();\n k = size ;\n\t\n for ( i = 0 ; i < size - 1 ; i++, k-- ) {\n current = head;\n next = head->next;\n\t\t\n for ( j = 1 ; j < k ; j++ ) { \n\n if ( current->data > next->data ) {\n tempData = current->data;\n current->data = next->data;\n next->data = tempData;\n\n tempKey = current->key;\n current->key = next->key;\n next->key = tempKey;\n }\n\t\t\t\n current = current->next;\n next = next->next;\n }\n } \n}\n\nvoid reverse(struct node** head_ref) {\n struct node* prev = NULL;\n struct node* current = *head_ref;\n struct node* next;\n\t\n while (current != NULL) {\n next = current->next;\n current->next = prev; \n prev = current;\n current = next;\n }\n\t\n *head_ref = prev;\n}\n\nvoid main() {\n insertFirst(1,10);\n insertFirst(2,20);\n insertFirst(3,30);\n insertFirst(4,1);\n insertFirst(5,40);\n insertFirst(6,56); \n\n printf(\"Original List: \"); \n\t\n //print list\n printList();\n\n while(!isEmpty()) { \n struct node *temp = deleteFirst();\n printf(\"\\nDeleted value:\");\n printf(\"(%d,%d) \",temp->key,temp->data);\n } \n\t\n printf(\"\\nList after deleting all items: \");\n printList();\n insertFirst(1,10);\n insertFirst(2,20);\n insertFirst(3,30);\n insertFirst(4,1);\n insertFirst(5,40);\n insertFirst(6,56);\n \n printf(\"\\nRestored List: \");\n printList();\n printf(\"\\n\"); \n\n struct node *foundLink = find(4);\n\t\n if(foundLink != NULL) {\n printf(\"Element found: \");\n printf(\"(%d,%d) \",foundLink->key,foundLink->data);\n printf(\"\\n\"); \n } else {\n printf(\"Element not found.\");\n }\n\n delete(4);\n printf(\"List after deleting an item: \");\n printList();\n printf(\"\\n\");\n foundLink = find(4);\n\t\n if(foundLink != NULL) {\n printf(\"Element found: \");\n printf(\"(%d,%d) \",foundLink->key,foundLink->data);\n printf(\"\\n\");\n } else {\n printf(\"Element not found.\");\n }\n\t\n printf(\"\\n\");\n sort();\n\t\n printf(\"List after sorting the data: \");\n printList();\n\t\n reverse(&head);\n printf(\"\\nList after reversing the data: \");\n printList();\n}" }, { "code": null, "e": 7713, "s": 7633, "text": "If we compile and run the above program, it will produce the following result −" }, { "code": null, "e": 8253, "s": 7713, "text": "Original List: \n[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]\nDeleted value:(6,56) \nDeleted value:(5,40) \nDeleted value:(4,1) \nDeleted value:(3,30) \nDeleted value:(2,20) \nDeleted value:(1,10) \nList after deleting all items: \n[ ]\nRestored List: \n[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]\nElement found: (4,1) \nList after deleting an item: \n[ (6,56) (5,40) (3,30) (2,20) (1,10) ]\nElement not found.\nList after sorting the data: \n[ (1,10) (2,20) (3,30) (5,40) (6,56) ]\nList after reversing the data: \n[ (6,56) (5,40) (3,30) (2,20) (1,10) ]\n" }, { "code": null, "e": 8288, "s": 8253, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8300, "s": 8288, "text": " Ravi Kiran" }, { "code": null, "e": 8335, "s": 8300, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 8354, "s": 8335, "text": " Arnab Chakraborty" }, { "code": null, "e": 8389, "s": 8354, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 8404, "s": 8389, "text": " Parth Panjabi" }, { "code": null, "e": 8437, "s": 8404, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 8456, "s": 8437, "text": " Arnab Chakraborty" }, { "code": null, "e": 8490, "s": 8456, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 8518, "s": 8490, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8554, "s": 8518, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 8582, "s": 8554, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8589, "s": 8582, "text": " Print" }, { "code": null, "e": 8600, "s": 8589, "text": " Add Notes" } ]
Maximum triplet sum in array - GeeksforGeeks
05 Nov, 2021 Given an array, the task is to find the maximum triplet sum in the array.Examples : Input : arr[] = {1, 2, 3, 0, -1, 8, 10} Output : 21 10 + 8 + 3 = 21 Input : arr[] = {9, 8, 20, 3, 4, -1, 0} Output : 37 20 + 9 + 8 = 37 Naive approach: In this method, we simply run three-loop and one by one add three-element and compare with the previous sum if the sum of three-element is greater than store in the previous sum. C++ Java Python3 C# PHP Javascript // C++ code to find maximum triplet sum#include <bits/stdc++.h>using namespace std; int maxTripletSum(int arr[], int n){ // Initialize sum with INT_MIN int sum = INT_MIN; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) if (sum < arr[i] + arr[j] + arr[k]) sum = arr[i] + arr[j] + arr[k]; return sum; } // Driven codeint main(){ int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxTripletSum(arr, n); return 0;} // Java code to find maximum triplet sumimport java.io.*; class GFG { static int maxTripletSum(int arr[], int n) { // Initialize sum with INT_MIN int sum = -1000000; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) if (sum < arr[i] + arr[j] + arr[k]) sum = arr[i] + arr[j] + arr[k]; return sum; } // Driven code public static void main(String args[]) { int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = arr.length; System.out.println(maxTripletSum(arr, n)); }} // This code is contributed by Nikita Tiwari. # Python 3 code to find# maximum triplet sum def maxTripletSum(arr, n) : # Initialize sum with # INT_MIN sm = -1000000 for i in range(0, n) : for j in range(i + 1, n) : for k in range(j + 1, n) : if (sm < (arr[i] + arr[j] + arr[k])) : sm = arr[i] + arr[j] + arr[k] return sm # Driven codearr = [ 1, 0, 8, 6, 4, 2 ]n = len(arr) print(maxTripletSum(arr, n)) # This code is contributed by Nikita Tiwari. // C# code to find maximum triplet sumusing System; class GFG { static int maxTripletSum(int[] arr, int n) { // Initialize sum with INT_MIN int sum = -1000000; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) if (sum < arr[i] + arr[j] + arr[k]) sum = arr[i] + arr[j] + arr[k]; return sum; } // Driven code public static void Main() { int[] arr = { 1, 0, 8, 6, 4, 2 }; int n = arr.Length; Console.WriteLine(maxTripletSum(arr, n)); }} // This code is contributed by vt_m. <?php// PHP code to find maximum triplet sum function maxTripletSum( $arr, $n){ // Initialize sum with INT_MIN $sum = PHP_INT_MIN; for($i = 0; $i < $n; $i++) for($j = $i + 1; $j < $n; $j++) for($k = $j + 1; $k < $n; $k++) if ($sum < $arr[$i] + $arr[$j] + $arr[$k]) $sum = $arr[$i] + $arr[$j] + $arr[$k]; return $sum; } // Driver Code $arr = array(1, 0, 8, 6, 4, 2); $n = count($arr); echo maxTripletSum($arr, $n); // This code is contributed by anuj_67.?> <script> // JavaScript Program to find maximum triplet sum function maxTripletSum(arr, n) { // Initialize sum with INT_MIN let sum = -1000000; for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) for (let k = j + 1; k < n; k++) if (sum < arr[i] + arr[j] + arr[k]) sum = arr[i] + arr[j] + arr[k]; return sum; } // Driver code let arr = [ 1, 0, 8, 6, 4, 2 ]; let n = arr.length; document.write(maxTripletSum(arr, n)); </script> // This code is contributed by sanjoy_62. Output: 18 Time complexity : O(n^3) Space complexity : O(1)Another approach: In this, we first need to sort the whole array and after that when we add the last three-element of the array then we find the maximum sum of triplets. C++ Java Python3 C# PHP Javascript // C++ code to find maximum triplet sum#include <bits/stdc++.h>using namespace std; // This function assumes that there are at least// three elements in arr[].int maxTripletSum(int arr[], int n){ // sort the given array sort(arr, arr + n); // After sorting the array. // Add last three element of the given array return arr[n - 1] + arr[n - 2] + arr[n - 3];} // Driven codeint main(){ int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxTripletSum(arr, n); return 0;} // Java code to find maximum triplet sumimport java.io.*;import java.util.*; class GFG { // This function assumes that there are // at least three elements in arr[]. static int maxTripletSum(int arr[], int n) { // sort the given array Arrays.sort(arr); // After sorting the array. // Add last three element // of the given array return arr[n - 1] + arr[n - 2] + arr[n - 3]; } // Driven code public static void main(String args[]) { int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = arr.length; System.out.println(maxTripletSum(arr, n)); }} // This code is contributed by Nikita Tiwari. # Python 3 code to find# maximum triplet sum # This function assumes# that there are at least# three elements in arr[].def maxTripletSum(arr, n) : # sort the given array arr.sort() # After sorting the array. # Add last three element # of the given array return (arr[n - 1] + arr[n - 2] + arr[n - 3]) # Driven codearr = [ 1, 0, 8, 6, 4, 2 ]n = len(arr) print(maxTripletSum(arr, n)) # This code is contributed by Nikita Tiwari. // C# code to find maximum triplet sumusing System; class GFG { // This function assumes that there are // at least three elements in arr[]. static int maxTripletSum(int[] arr, int n) { // sort the given array Array.Sort(arr); // After sorting the array. // Add last three element // of the given array return arr[n - 1] + arr[n - 2] + arr[n - 3]; } // Driven code public static void Main() { int[] arr = { 1, 0, 8, 6, 4, 2 }; int n = arr.Length; Console.WriteLine(maxTripletSum(arr, n)); }} // This code is contributed by vt_m. <?php// PHP code to find// maximum triplet sum // This function assumes that// there are at least// three elements in arr[].function maxTripletSum( $arr, $n){ // sort the given array sort($arr); // After sorting the array. // Add last three element // of the given array return $arr[$n - 1] + $arr[$n - 2] + $arr[$n - 3];} // Driver code$arr = array( 1, 0, 8, 6, 4, 2 );$n = count($arr);echo maxTripletSum($arr, $n); // This code is contributed by anuj_67.?> <script> //Javascript code to find maximum triplet sum // This function assumes that there are at least// three elements in arr[].function maxTripletSum(arr, n){ // sort the given array arr.sort(); // After sorting the array. // Add last three element of the given array return arr[n - 1] + arr[n - 2] + arr[n - 3];} // Driven code let arr = [ 1, 0, 8, 6, 4, 2 ]; let n = arr.length; document.write(maxTripletSum(arr, n)); // This code is contributed by Mayank Tyagi </script> Output: 18 Time complexity: O(nlogn) Space complexity: O(1)Efficient approach: Scan the array and compute the Maximum, second maximum, and third maximum element present in the array and return the sum of its and it would be maximum sum. C++ Java Python3 C# PHP Javascript // C++ code to find maximum triplet sum#include <bits/stdc++.h>using namespace std; // This function assumes that there are at least// three elements in arr[].int maxTripletSum(int arr[], int n){ // Initialize Maximum, second maximum and third // maximum element int maxA = INT_MIN, maxB = INT_MIN, maxC = INT_MIN; for (int i = 0; i < n; i++) { // Update Maximum, second maximum and third // maximum element if (arr[i] > maxA) { maxC = maxB; maxB = maxA; maxA = arr[i]; } // Update second maximum and third maximum // element else if (arr[i] > maxB) { maxC = maxB; maxB = arr[i]; } // Update third maximum element else if (arr[i] > maxC) maxC = arr[i]; } return (maxA + maxB + maxC);} // Driven codeint main(){ int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxTripletSum(arr, n); return 0;} // Java code to find maximum triplet sumimport java.io.*;import java.util.*; class GFG { // This function assumes that there // are at least three elements in arr[]. static int maxTripletSum(int arr[], int n) { // Initialize Maximum, second maximum and third // maximum element int maxA = -100000000, maxB = -100000000; int maxC = -100000000; for (int i = 0; i < n; i++) { // Update Maximum, second maximum // and third maximum element if (arr[i] > maxA) { maxC = maxB; maxB = maxA; maxA = arr[i]; } // Update second maximum and third maximum // element else if (arr[i] > maxB) { maxC = maxB; maxB = arr[i]; } // Update third maximum element else if (arr[i] > maxC) maxC = arr[i]; } return (maxA + maxB + maxC); } // Driven code public static void main(String args[]) { int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = arr.length; System.out.println(maxTripletSum(arr, n)); }} // This code is contributed by Nikita Tiwari. # Python 3 code to find# maximum triplet sum # This function assumes# that there are at least# three elements in arr[].def maxTripletSum(arr, n) : # Initialize Maximum, second # maximum and third maximum # element maxA = -100000000 maxB = -100000000 maxC = -100000000 for i in range(0, n) : # Update Maximum, second maximum # and third maximum element if (arr[i] > maxA) : maxC = maxB maxB = maxA maxA = arr[i] # Update second maximum and # third maximum element elif (arr[i] > maxB) : maxC = maxB maxB = arr[i] # Update third maximum element elif (arr[i] > maxC) : maxC = arr[i] return (maxA + maxB + maxC) # Driven codearr = [ 1, 0, 8, 6, 4, 2 ]n = len(arr) print(maxTripletSum(arr, n)) # This code is contributed by Nikita Tiwari. // C# code to find maximum triplet sumusing System; class GFG { // This function assumes that there // are at least three elements in arr[]. static int maxTripletSum(int[] arr, int n) { // Initialize Maximum, second maximum // and third maximum element int maxA = -100000000, maxB = -100000000; int maxC = -100000000; for (int i = 0; i < n; i++) { // Update Maximum, second maximum // and third maximum element if (arr[i] > maxA) { maxC = maxB; maxB = maxA; maxA = arr[i]; } // Update second maximum and third // maximum element else if (arr[i] > maxB) { maxC = maxB; maxB = arr[i]; } // Update third maximum element else if (arr[i] > maxC) maxC = arr[i]; } return (maxA + maxB + maxC); } // Driven code public static void Main() { int[] arr = { 1, 0, 8, 6, 4, 2 }; int n = arr.Length; Console.WriteLine(maxTripletSum(arr, n)); }} // This code is contributed by vt_m. <?php// PHP code to find// maximum triplet sum // This function assumes that// there are at least three// elements in arr[].function maxTripletSum($arr, $n){ // Initialize Maximum, // second maximum and // third maximum element $maxA = PHP_INT_MIN; $maxB = PHP_INT_MIN; $maxC = PHP_INT_MIN; for ( $i = 0; $i < $n; $i++) { // Update Maximum, // second maximum and // third maximum element if ($arr[$i] > $maxA) { $maxC = $maxB; $maxB = $maxA; $maxA = $arr[$i]; } // Update second maximum and // third maximum element else if ($arr[$i] > $maxB) { $maxC = $maxB; $maxB = $arr[$i]; } // Update third maximum element else if ($arr[$i] > $maxC) $maxC = $arr[$i]; } return ($maxA + $maxB + $maxC);} // Driven code$arr = array( 1, 0, 8, 6, 4, 2 );$n = count($arr);echo maxTripletSum($arr, $n); // This code is contributed by anuj_67.?> <script> // JavaScript code to find maximum triplet sum // This function assumes that there are at least// three elements in arr[].function maxTripletSum(arr, n){ // Initialize Maximum, second maximum and third // maximum element let maxA = Number.MIN_SAFE_INTEGER; let maxB = Number.MIN_SAFE_INTEGER; let maxC = Number.MIN_SAFE_INTEGER; for (let i = 0; i < n; i++) { // Update Maximum, second maximum and third // maximum element if (arr[i] > maxA) { maxC = maxB; maxB = maxA; maxA = arr[i]; } // Update second maximum and third maximum // element else if (arr[i] > maxB) { maxC = maxB; maxB = arr[i]; } // Update third maximum element else if (arr[i] > maxC) maxC = arr[i]; } return (maxA + maxB + maxC);} // Driven code let arr = [ 1, 0, 8, 6, 4, 2 ]; let n = arr.length; document.write(maxTripletSum(arr, n)); // This code is contributed by Surbhi Tyagi. </script> Output: 18 Time complexity : O(n) Space complexity : O(1) vt_m mayanktyagi1709 sanjoy_62 surbhityagi15 as5853535 abhishek0719kadiyan Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews
[ { "code": null, "e": 40884, "s": 40856, "text": "\n05 Nov, 2021" }, { "code": null, "e": 40970, "s": 40884, "text": "Given an array, the task is to find the maximum triplet sum in the array.Examples : " }, { "code": null, "e": 41108, "s": 40970, "text": "Input : arr[] = {1, 2, 3, 0, -1, 8, 10} \nOutput : 21\n10 + 8 + 3 = 21\n\nInput : arr[] = {9, 8, 20, 3, 4, -1, 0}\nOutput : 37\n20 + 9 + 8 = 37" }, { "code": null, "e": 41307, "s": 41110, "text": "Naive approach: In this method, we simply run three-loop and one by one add three-element and compare with the previous sum if the sum of three-element is greater than store in the previous sum. " }, { "code": null, "e": 41311, "s": 41307, "text": "C++" }, { "code": null, "e": 41316, "s": 41311, "text": "Java" }, { "code": null, "e": 41324, "s": 41316, "text": "Python3" }, { "code": null, "e": 41327, "s": 41324, "text": "C#" }, { "code": null, "e": 41331, "s": 41327, "text": "PHP" }, { "code": null, "e": 41342, "s": 41331, "text": "Javascript" }, { "code": "// C++ code to find maximum triplet sum#include <bits/stdc++.h>using namespace std; int maxTripletSum(int arr[], int n){ // Initialize sum with INT_MIN int sum = INT_MIN; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) if (sum < arr[i] + arr[j] + arr[k]) sum = arr[i] + arr[j] + arr[k]; return sum; } // Driven codeint main(){ int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxTripletSum(arr, n); return 0;}", "e": 41926, "s": 41342, "text": null }, { "code": "// Java code to find maximum triplet sumimport java.io.*; class GFG { static int maxTripletSum(int arr[], int n) { // Initialize sum with INT_MIN int sum = -1000000; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) if (sum < arr[i] + arr[j] + arr[k]) sum = arr[i] + arr[j] + arr[k]; return sum; } // Driven code public static void main(String args[]) { int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = arr.length; System.out.println(maxTripletSum(arr, n)); }} // This code is contributed by Nikita Tiwari.", "e": 42641, "s": 41926, "text": null }, { "code": "# Python 3 code to find# maximum triplet sum def maxTripletSum(arr, n) : # Initialize sum with # INT_MIN sm = -1000000 for i in range(0, n) : for j in range(i + 1, n) : for k in range(j + 1, n) : if (sm < (arr[i] + arr[j] + arr[k])) : sm = arr[i] + arr[j] + arr[k] return sm # Driven codearr = [ 1, 0, 8, 6, 4, 2 ]n = len(arr) print(maxTripletSum(arr, n)) # This code is contributed by Nikita Tiwari.", "e": 43132, "s": 42641, "text": null }, { "code": "// C# code to find maximum triplet sumusing System; class GFG { static int maxTripletSum(int[] arr, int n) { // Initialize sum with INT_MIN int sum = -1000000; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) if (sum < arr[i] + arr[j] + arr[k]) sum = arr[i] + arr[j] + arr[k]; return sum; } // Driven code public static void Main() { int[] arr = { 1, 0, 8, 6, 4, 2 }; int n = arr.Length; Console.WriteLine(maxTripletSum(arr, n)); }} // This code is contributed by vt_m.", "e": 43786, "s": 43132, "text": null }, { "code": "<?php// PHP code to find maximum triplet sum function maxTripletSum( $arr, $n){ // Initialize sum with INT_MIN $sum = PHP_INT_MIN; for($i = 0; $i < $n; $i++) for($j = $i + 1; $j < $n; $j++) for($k = $j + 1; $k < $n; $k++) if ($sum < $arr[$i] + $arr[$j] + $arr[$k]) $sum = $arr[$i] + $arr[$j] + $arr[$k]; return $sum; } // Driver Code $arr = array(1, 0, 8, 6, 4, 2); $n = count($arr); echo maxTripletSum($arr, $n); // This code is contributed by anuj_67.?>", "e": 44472, "s": 43786, "text": null }, { "code": "<script> // JavaScript Program to find maximum triplet sum function maxTripletSum(arr, n) { // Initialize sum with INT_MIN let sum = -1000000; for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) for (let k = j + 1; k < n; k++) if (sum < arr[i] + arr[j] + arr[k]) sum = arr[i] + arr[j] + arr[k]; return sum; } // Driver code let arr = [ 1, 0, 8, 6, 4, 2 ]; let n = arr.length; document.write(maxTripletSum(arr, n)); </script> // This code is contributed by sanjoy_62.", "e": 45127, "s": 44472, "text": null }, { "code": null, "e": 45137, "s": 45127, "text": "Output: " }, { "code": null, "e": 45140, "s": 45137, "text": "18" }, { "code": null, "e": 45360, "s": 45140, "text": "Time complexity : O(n^3) Space complexity : O(1)Another approach: In this, we first need to sort the whole array and after that when we add the last three-element of the array then we find the maximum sum of triplets. " }, { "code": null, "e": 45364, "s": 45360, "text": "C++" }, { "code": null, "e": 45369, "s": 45364, "text": "Java" }, { "code": null, "e": 45377, "s": 45369, "text": "Python3" }, { "code": null, "e": 45380, "s": 45377, "text": "C#" }, { "code": null, "e": 45384, "s": 45380, "text": "PHP" }, { "code": null, "e": 45395, "s": 45384, "text": "Javascript" }, { "code": "// C++ code to find maximum triplet sum#include <bits/stdc++.h>using namespace std; // This function assumes that there are at least// three elements in arr[].int maxTripletSum(int arr[], int n){ // sort the given array sort(arr, arr + n); // After sorting the array. // Add last three element of the given array return arr[n - 1] + arr[n - 2] + arr[n - 3];} // Driven codeint main(){ int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxTripletSum(arr, n); return 0;}", "e": 45922, "s": 45395, "text": null }, { "code": "// Java code to find maximum triplet sumimport java.io.*;import java.util.*; class GFG { // This function assumes that there are // at least three elements in arr[]. static int maxTripletSum(int arr[], int n) { // sort the given array Arrays.sort(arr); // After sorting the array. // Add last three element // of the given array return arr[n - 1] + arr[n - 2] + arr[n - 3]; } // Driven code public static void main(String args[]) { int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = arr.length; System.out.println(maxTripletSum(arr, n)); }} // This code is contributed by Nikita Tiwari.", "e": 46607, "s": 45922, "text": null }, { "code": "# Python 3 code to find# maximum triplet sum # This function assumes# that there are at least# three elements in arr[].def maxTripletSum(arr, n) : # sort the given array arr.sort() # After sorting the array. # Add last three element # of the given array return (arr[n - 1] + arr[n - 2] + arr[n - 3]) # Driven codearr = [ 1, 0, 8, 6, 4, 2 ]n = len(arr) print(maxTripletSum(arr, n)) # This code is contributed by Nikita Tiwari.", "e": 47062, "s": 46607, "text": null }, { "code": "// C# code to find maximum triplet sumusing System; class GFG { // This function assumes that there are // at least three elements in arr[]. static int maxTripletSum(int[] arr, int n) { // sort the given array Array.Sort(arr); // After sorting the array. // Add last three element // of the given array return arr[n - 1] + arr[n - 2] + arr[n - 3]; } // Driven code public static void Main() { int[] arr = { 1, 0, 8, 6, 4, 2 }; int n = arr.Length; Console.WriteLine(maxTripletSum(arr, n)); }} // This code is contributed by vt_m.", "e": 47684, "s": 47062, "text": null }, { "code": "<?php// PHP code to find// maximum triplet sum // This function assumes that// there are at least// three elements in arr[].function maxTripletSum( $arr, $n){ // sort the given array sort($arr); // After sorting the array. // Add last three element // of the given array return $arr[$n - 1] + $arr[$n - 2] + $arr[$n - 3];} // Driver code$arr = array( 1, 0, 8, 6, 4, 2 );$n = count($arr);echo maxTripletSum($arr, $n); // This code is contributed by anuj_67.?>", "e": 48187, "s": 47684, "text": null }, { "code": "<script> //Javascript code to find maximum triplet sum // This function assumes that there are at least// three elements in arr[].function maxTripletSum(arr, n){ // sort the given array arr.sort(); // After sorting the array. // Add last three element of the given array return arr[n - 1] + arr[n - 2] + arr[n - 3];} // Driven code let arr = [ 1, 0, 8, 6, 4, 2 ]; let n = arr.length; document.write(maxTripletSum(arr, n)); // This code is contributed by Mayank Tyagi </script>", "e": 48690, "s": 48187, "text": null }, { "code": null, "e": 48700, "s": 48690, "text": "Output: " }, { "code": null, "e": 48703, "s": 48700, "text": "18" }, { "code": null, "e": 48930, "s": 48703, "text": "Time complexity: O(nlogn) Space complexity: O(1)Efficient approach: Scan the array and compute the Maximum, second maximum, and third maximum element present in the array and return the sum of its and it would be maximum sum. " }, { "code": null, "e": 48934, "s": 48930, "text": "C++" }, { "code": null, "e": 48939, "s": 48934, "text": "Java" }, { "code": null, "e": 48947, "s": 48939, "text": "Python3" }, { "code": null, "e": 48950, "s": 48947, "text": "C#" }, { "code": null, "e": 48954, "s": 48950, "text": "PHP" }, { "code": null, "e": 48965, "s": 48954, "text": "Javascript" }, { "code": "// C++ code to find maximum triplet sum#include <bits/stdc++.h>using namespace std; // This function assumes that there are at least// three elements in arr[].int maxTripletSum(int arr[], int n){ // Initialize Maximum, second maximum and third // maximum element int maxA = INT_MIN, maxB = INT_MIN, maxC = INT_MIN; for (int i = 0; i < n; i++) { // Update Maximum, second maximum and third // maximum element if (arr[i] > maxA) { maxC = maxB; maxB = maxA; maxA = arr[i]; } // Update second maximum and third maximum // element else if (arr[i] > maxB) { maxC = maxB; maxB = arr[i]; } // Update third maximum element else if (arr[i] > maxC) maxC = arr[i]; } return (maxA + maxB + maxC);} // Driven codeint main(){ int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxTripletSum(arr, n); return 0;}", "e": 49961, "s": 48965, "text": null }, { "code": "// Java code to find maximum triplet sumimport java.io.*;import java.util.*; class GFG { // This function assumes that there // are at least three elements in arr[]. static int maxTripletSum(int arr[], int n) { // Initialize Maximum, second maximum and third // maximum element int maxA = -100000000, maxB = -100000000; int maxC = -100000000; for (int i = 0; i < n; i++) { // Update Maximum, second maximum // and third maximum element if (arr[i] > maxA) { maxC = maxB; maxB = maxA; maxA = arr[i]; } // Update second maximum and third maximum // element else if (arr[i] > maxB) { maxC = maxB; maxB = arr[i]; } // Update third maximum element else if (arr[i] > maxC) maxC = arr[i]; } return (maxA + maxB + maxC); } // Driven code public static void main(String args[]) { int arr[] = { 1, 0, 8, 6, 4, 2 }; int n = arr.length; System.out.println(maxTripletSum(arr, n)); }} // This code is contributed by Nikita Tiwari.", "e": 51230, "s": 49961, "text": null }, { "code": "# Python 3 code to find# maximum triplet sum # This function assumes# that there are at least# three elements in arr[].def maxTripletSum(arr, n) : # Initialize Maximum, second # maximum and third maximum # element maxA = -100000000 maxB = -100000000 maxC = -100000000 for i in range(0, n) : # Update Maximum, second maximum # and third maximum element if (arr[i] > maxA) : maxC = maxB maxB = maxA maxA = arr[i] # Update second maximum and # third maximum element elif (arr[i] > maxB) : maxC = maxB maxB = arr[i] # Update third maximum element elif (arr[i] > maxC) : maxC = arr[i] return (maxA + maxB + maxC) # Driven codearr = [ 1, 0, 8, 6, 4, 2 ]n = len(arr) print(maxTripletSum(arr, n)) # This code is contributed by Nikita Tiwari.", "e": 52145, "s": 51230, "text": null }, { "code": "// C# code to find maximum triplet sumusing System; class GFG { // This function assumes that there // are at least three elements in arr[]. static int maxTripletSum(int[] arr, int n) { // Initialize Maximum, second maximum // and third maximum element int maxA = -100000000, maxB = -100000000; int maxC = -100000000; for (int i = 0; i < n; i++) { // Update Maximum, second maximum // and third maximum element if (arr[i] > maxA) { maxC = maxB; maxB = maxA; maxA = arr[i]; } // Update second maximum and third // maximum element else if (arr[i] > maxB) { maxC = maxB; maxB = arr[i]; } // Update third maximum element else if (arr[i] > maxC) maxC = arr[i]; } return (maxA + maxB + maxC); } // Driven code public static void Main() { int[] arr = { 1, 0, 8, 6, 4, 2 }; int n = arr.Length; Console.WriteLine(maxTripletSum(arr, n)); }} // This code is contributed by vt_m.", "e": 53317, "s": 52145, "text": null }, { "code": "<?php// PHP code to find// maximum triplet sum // This function assumes that// there are at least three// elements in arr[].function maxTripletSum($arr, $n){ // Initialize Maximum, // second maximum and // third maximum element $maxA = PHP_INT_MIN; $maxB = PHP_INT_MIN; $maxC = PHP_INT_MIN; for ( $i = 0; $i < $n; $i++) { // Update Maximum, // second maximum and // third maximum element if ($arr[$i] > $maxA) { $maxC = $maxB; $maxB = $maxA; $maxA = $arr[$i]; } // Update second maximum and // third maximum element else if ($arr[$i] > $maxB) { $maxC = $maxB; $maxB = $arr[$i]; } // Update third maximum element else if ($arr[$i] > $maxC) $maxC = $arr[$i]; } return ($maxA + $maxB + $maxC);} // Driven code$arr = array( 1, 0, 8, 6, 4, 2 );$n = count($arr);echo maxTripletSum($arr, $n); // This code is contributed by anuj_67.?>", "e": 54337, "s": 53317, "text": null }, { "code": "<script> // JavaScript code to find maximum triplet sum // This function assumes that there are at least// three elements in arr[].function maxTripletSum(arr, n){ // Initialize Maximum, second maximum and third // maximum element let maxA = Number.MIN_SAFE_INTEGER; let maxB = Number.MIN_SAFE_INTEGER; let maxC = Number.MIN_SAFE_INTEGER; for (let i = 0; i < n; i++) { // Update Maximum, second maximum and third // maximum element if (arr[i] > maxA) { maxC = maxB; maxB = maxA; maxA = arr[i]; } // Update second maximum and third maximum // element else if (arr[i] > maxB) { maxC = maxB; maxB = arr[i]; } // Update third maximum element else if (arr[i] > maxC) maxC = arr[i]; } return (maxA + maxB + maxC);} // Driven code let arr = [ 1, 0, 8, 6, 4, 2 ]; let n = arr.length; document.write(maxTripletSum(arr, n)); // This code is contributed by Surbhi Tyagi. </script>", "e": 55381, "s": 54337, "text": null }, { "code": null, "e": 55391, "s": 55381, "text": "Output: " }, { "code": null, "e": 55394, "s": 55391, "text": "18" }, { "code": null, "e": 55442, "s": 55394, "text": "Time complexity : O(n) Space complexity : O(1) " }, { "code": null, "e": 55447, "s": 55442, "text": "vt_m" }, { "code": null, "e": 55463, "s": 55447, "text": "mayanktyagi1709" }, { "code": null, "e": 55473, "s": 55463, "text": "sanjoy_62" }, { "code": null, "e": 55487, "s": 55473, "text": "surbhityagi15" }, { "code": null, "e": 55497, "s": 55487, "text": "as5853535" }, { "code": null, "e": 55517, "s": 55497, "text": "abhishek0719kadiyan" }, { "code": null, "e": 55524, "s": 55517, "text": "Arrays" }, { "code": null, "e": 55532, "s": 55524, "text": "Sorting" }, { "code": null, "e": 55539, "s": 55532, "text": "Arrays" }, { "code": null, "e": 55547, "s": 55539, "text": "Sorting" }, { "code": null, "e": 55645, "s": 55547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55654, "s": 55645, "text": "Comments" }, { "code": null, "e": 55667, "s": 55654, "text": "Old Comments" }, { "code": null, "e": 55682, "s": 55667, "text": "Arrays in Java" }, { "code": null, "e": 55698, "s": 55682, "text": "Arrays in C/C++" }, { "code": null, "e": 55725, "s": 55698, "text": "Program for array rotation" }, { "code": null, "e": 55773, "s": 55725, "text": "Stack Data Structure (Introduction and Program)" } ]
Beautiful Soup - Souping the Page
In the previous code example, we parse the document through beautiful constructor using a string method. Another way is to pass the document through open filehandle. from bs4 import BeautifulSoup with open("example.html") as fp: soup = BeautifulSoup(fp) soup = BeautifulSoup("<html>data</html>") First the document is converted to Unicode, and HTML entities are converted to Unicode characters:</p> import bs4 html = '''<b>tutorialspoint</b>, <i>&web scraping &data science;</i>''' soup = bs4.BeautifulSoup(html, 'lxml') print(soup) <html><body><b>tutorialspoint</b>, <i>&web scraping &data science;</i></body></html> BeautifulSoup then parses the data using HTML parser or you explicitly tell it to parse using an XML parser. Before we look into different components of a HTML page, let us first understand the HTML tree structure. The root element in the document tree is the html, which can have parents, children and siblings and this determines by its position in the tree structure. To move among HTML elements, attributes and text, you have to move among nodes in your tree structure. Let us suppose the webpage is as shown below − Which translates to an html document as follows − <html><head><title>TutorialsPoint</title></head><h1>Tutorialspoint Online Library</h1><p<<b>It's all Free</b></p></body></html> Which simply means, for above html document, we have a html tree structure as follows − 38 Lectures 3.5 hours Chandramouli Jayendran 22 Lectures 1 hours TELCOMA Global 6 Lectures 1 hours AlexanderSchlee 6 Lectures 1 hours AlexanderSchlee 6 Lectures 1 hours AlexanderSchlee 22 Lectures 4 hours AlexanderSchlee Print Add Notes Bookmark this page
[ { "code": null, "e": 2151, "s": 1985, "text": "In the previous code example, we parse the document through beautiful constructor using a string method. Another way is to pass the document through open filehandle." }, { "code": null, "e": 2284, "s": 2151, "text": "from bs4 import BeautifulSoup\nwith open(\"example.html\") as fp:\n soup = BeautifulSoup(fp)\nsoup = BeautifulSoup(\"<html>data</html>\")" }, { "code": null, "e": 2388, "s": 2284, "text": "First the document is converted to Unicode, and HTML entities are converted to Unicode characters:</p>\n" }, { "code": null, "e": 2522, "s": 2388, "text": "import bs4\nhtml = '''<b>tutorialspoint</b>, <i>&web scraping &data science;</i>'''\nsoup = bs4.BeautifulSoup(html, 'lxml')\nprint(soup)" }, { "code": null, "e": 2608, "s": 2522, "text": "<html><body><b>tutorialspoint</b>, <i>&web scraping &data science;</i></body></html>\n" }, { "code": null, "e": 2717, "s": 2608, "text": "BeautifulSoup then parses the data using HTML parser or you explicitly tell it to parse using an XML parser." }, { "code": null, "e": 2823, "s": 2717, "text": "Before we look into different components of a HTML page, let us first understand the HTML tree structure." }, { "code": null, "e": 3082, "s": 2823, "text": "The root element in the document tree is the html, which can have parents, children and siblings and this determines by its position in the tree structure. To move among HTML elements, attributes and text, you have to move among nodes in your tree structure." }, { "code": null, "e": 3129, "s": 3082, "text": "Let us suppose the webpage is as shown below −" }, { "code": null, "e": 3179, "s": 3129, "text": "Which translates to an html document as follows −" }, { "code": null, "e": 3307, "s": 3179, "text": "<html><head><title>TutorialsPoint</title></head><h1>Tutorialspoint Online Library</h1><p<<b>It's all Free</b></p></body></html>" }, { "code": null, "e": 3395, "s": 3307, "text": "Which simply means, for above html document, we have a html tree structure as follows −" }, { "code": null, "e": 3430, "s": 3395, "text": "\n 38 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3454, "s": 3430, "text": " Chandramouli Jayendran" }, { "code": null, "e": 3487, "s": 3454, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 3503, "s": 3487, "text": " TELCOMA Global" }, { "code": null, "e": 3535, "s": 3503, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 3552, "s": 3535, "text": " AlexanderSchlee" }, { "code": null, "e": 3584, "s": 3552, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 3601, "s": 3584, "text": " AlexanderSchlee" }, { "code": null, "e": 3633, "s": 3601, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 3650, "s": 3633, "text": " AlexanderSchlee" }, { "code": null, "e": 3683, "s": 3650, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 3700, "s": 3683, "text": " AlexanderSchlee" }, { "code": null, "e": 3707, "s": 3700, "text": " Print" }, { "code": null, "e": 3718, "s": 3707, "text": " Add Notes" } ]
What happens if try to access an element with an index greater than the size of the array in Java?
An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation. The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on. Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets. For example, if an array of 6 elements is created with name myArray, you can access the element of the array at index 3 as − System.out.println(myArray[3]); //25 In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as − int myArray[] = new int[7]; myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524; Or, you can directly assign values with in flower braces separating them with commas (,) as − int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524}; Though, you can refer the elements of an array by using the name and index as − myArray[5]; You cannot access the elements that are greater to the size of the array. i.e. If you create an array with 7 elements, as you observe in the diagram you can access up to myArray[6]. If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception. public class AccessingElements { public static void main(String[] args) { //Creating an integer array with size 5 int inpuArray[] = new int[5]; //Populating the array inpuArray[0] = 41; inpuArray[1] = 98; inpuArray[2] = 43; inpuArray[3] = 26; inpuArray[4] = 79; //Accessing index greater than the size of the array System.out.println( inpuArray[6]); } } Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at myPackage.AccessingElements.main(AccessingElements.java:17)
[ { "code": null, "e": 1253, "s": 1062, "text": "An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation." }, { "code": null, "e": 1437, "s": 1253, "text": "The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on." }, { "code": null, "e": 1597, "s": 1437, "text": "Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets." }, { "code": null, "e": 1722, "s": 1597, "text": "For example, if an array of 6 elements is created with name myArray, you can access the element of the array at index 3 as −" }, { "code": null, "e": 1759, "s": 1722, "text": "System.out.println(myArray[3]);\n//25" }, { "code": null, "e": 1911, "s": 1759, "text": "In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −" }, { "code": null, "e": 2072, "s": 1911, "text": "int myArray[] = new int[7];\nmyArray[0] = 1254;\nmyArray[1] = 1458;\nmyArray[2] = 5687;\nmyArray[3] = 1457;\nmyArray[4] = 4554;\nmyArray[5] = 5445;\nmyArray[6] = 7524;" }, { "code": null, "e": 2166, "s": 2072, "text": "Or, you can directly assign values with in flower braces separating them with commas (,) as −" }, { "code": null, "e": 2225, "s": 2166, "text": "int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524};" }, { "code": null, "e": 2305, "s": 2225, "text": "Though, you can refer the elements of an array by using the name and index as −" }, { "code": null, "e": 2317, "s": 2305, "text": "myArray[5];" }, { "code": null, "e": 2499, "s": 2317, "text": "You cannot access the elements that are greater to the size of the array. i.e. If you create an array with 7 elements, as you observe in the diagram you can access up to myArray[6]." }, { "code": null, "e": 2697, "s": 2499, "text": "If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception." }, { "code": null, "e": 3117, "s": 2697, "text": "public class AccessingElements {\n public static void main(String[] args) {\n //Creating an integer array with size 5\n int inpuArray[] = new int[5];\n //Populating the array\n inpuArray[0] = 41;\n inpuArray[1] = 98;\n inpuArray[2] = 43;\n inpuArray[3] = 26;\n inpuArray[4] = 79;\n //Accessing index greater than the size of the array\n System.out.println( inpuArray[6]);\n }\n}" }, { "code": null, "e": 3254, "s": 3117, "text": "Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 6\n at myPackage.AccessingElements.main(AccessingElements.java:17)" } ]
LISP - If Construct
The if macro is followed by a test clause that evaluates to t or nil. If the test clause is evaluated to the t, then the action following the test clause is executed. If it is nil, then the next clause is evaluated. Syntax for if − (if (test-clause) (action1) (action2)) Create a new source code file named main.lisp and type the following code in it. (setq a 10) (if (> a 20) (format t "~% a is less than 20")) (format t "~% value of a is ~d " a) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − value of a is 10 The if clause can be followed by an optional then clause. Create a new source code file named main.lisp and type the following code in it. (setq a 10) (if (> a 20) then (format t "~% a is less than 20")) (format t "~% value of a is ~d " a) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − a is less than 20 value of a is 10 You can also create an if-then-else type statement using the if clause. Create a new source code file named main.lisp and type the following code in it. (setq a 100) (if (> a 20) (format t "~% a is greater than 20") (format t "~% a is less than 20")) (format t "~% value of a is ~d " a) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − a is greater than 20 value of a is 100 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2276, "s": 2060, "text": "The if macro is followed by a test clause that evaluates to t or nil. If the test clause is evaluated to the t, then the action following the test clause is executed. If it is nil, then the next clause is evaluated." }, { "code": null, "e": 2292, "s": 2276, "text": "Syntax for if −" }, { "code": null, "e": 2332, "s": 2292, "text": "(if (test-clause) (action1) (action2))\n" }, { "code": null, "e": 2413, "s": 2332, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 2512, "s": 2413, "text": "(setq a 10)\n(if (> a 20)\n (format t \"~% a is less than 20\"))\n(format t \"~% value of a is ~d \" a)" }, { "code": null, "e": 2621, "s": 2512, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 2639, "s": 2621, "text": "value of a is 10\n" }, { "code": null, "e": 2697, "s": 2639, "text": "The if clause can be followed by an optional then clause." }, { "code": null, "e": 2778, "s": 2697, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 2882, "s": 2778, "text": "(setq a 10)\n(if (> a 20)\n then (format t \"~% a is less than 20\"))\n(format t \"~% value of a is ~d \" a)" }, { "code": null, "e": 2991, "s": 2882, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 3028, "s": 2991, "text": "a is less than 20\nvalue of a is 10 \n" }, { "code": null, "e": 3100, "s": 3028, "text": "You can also create an if-then-else type statement using the if clause." }, { "code": null, "e": 3181, "s": 3100, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 3322, "s": 3181, "text": "(setq a 100)\n(if (> a 20)\n (format t \"~% a is greater than 20\") \n (format t \"~% a is less than 20\"))\n(format t \"~% value of a is ~d \" a)" }, { "code": null, "e": 3431, "s": 3322, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 3473, "s": 3431, "text": "a is greater than 20\nvalue of a is 100 \n" }, { "code": null, "e": 3506, "s": 3473, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 3521, "s": 3506, "text": " Arnold Higuit" }, { "code": null, "e": 3528, "s": 3521, "text": " Print" }, { "code": null, "e": 3539, "s": 3528, "text": " Add Notes" } ]
PHP File Handling
File handling is an important part of any web application. You often need to open and process a file for different tasks. PHP has several functions for creating, reading, uploading, and editing files. Be careful when manipulating files! You can do a lot of damage if you do something wrong. Common errors are: editing the wrong file, filling a hard-drive with garbage data, and deleting the content of a file by accident. The readfile() function reads a file and writes it to the output buffer. Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this: The PHP code to read the file and write it to the output buffer is as follows (the readfile() function returns the number of bytes read on success): The readfile() function is useful if all you want to do is open up a file and read its contents. The next chapters will teach you more about file handling. Assume we have a file named "webdict.txt", write the correct syntax to open and read the file content. echo ; We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 123, "s": 0, "text": "File handling is an important part of any web application. You \noften need to open and process a file for different tasks." }, { "code": null, "e": 202, "s": 123, "text": "PHP has several functions for creating, reading, uploading, and editing files." }, { "code": null, "e": 240, "s": 204, "text": "Be careful when manipulating files!" }, { "code": null, "e": 428, "s": 240, "text": "You can do a \nlot of damage if you do something wrong. Common errors are: editing the wrong \nfile, filling a hard-drive with garbage data, and deleting the content of a file \nby accident." }, { "code": null, "e": 501, "s": 428, "text": "The readfile() function reads a file and writes it to the output buffer." }, { "code": null, "e": 601, "s": 501, "text": "Assume we have a text file called \"webdictionary.txt\", stored on the \nserver, that looks like this:" }, { "code": null, "e": 751, "s": 601, "text": "The PHP code to read the file and write it to the output buffer is as follows \n(the readfile() function returns the number of bytes read on success):" }, { "code": null, "e": 848, "s": 751, "text": "The readfile() function is useful if all you want to do is open up a file and read its contents." }, { "code": null, "e": 907, "s": 848, "text": "The next chapters will teach you more about file handling." }, { "code": null, "e": 1010, "s": 907, "text": "Assume we have a file named \"webdict.txt\", write the correct syntax to open and read the file content." }, { "code": null, "e": 1018, "s": 1010, "text": "echo ;\n" }, { "code": null, "e": 1051, "s": 1018, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1093, "s": 1051, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1200, "s": 1093, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1219, "s": 1200, "text": "help@w3schools.com" } ]
JavaScript String - substring() Method
This method returns a subset of a String object. The syntax to use substr() is as follows − string.substring(indexA, [indexB]) indexA − An integer between 0 and one less than the length of the string. indexA − An integer between 0 and one less than the length of the string. indexB − (optional) An integer between 0 and the length of the string. indexB − (optional) An integer between 0 and the length of the string. The substring method returns the new sub-string based on given parameters. Try the following example. <html> <head> <title>JavaScript String substring() Method</title> </head> <body> <script type = "text/javascript"> var str = "Apples are round, and apples are juicy."; document.write("(1,2): " + str.substring(1,2)); document.write("<br />(0,10): " + str.substring(0, 10)); document.write("<br />(5): " + str.substring(5)); </script> </body> </html> (1,2): p (0,10): Apples are (5): s are round, and apples are juicy. 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2515, "s": 2466, "text": "This method returns a subset of a String object." }, { "code": null, "e": 2558, "s": 2515, "text": "The syntax to use substr() is as follows −" }, { "code": null, "e": 2594, "s": 2558, "text": "string.substring(indexA, [indexB])\n" }, { "code": null, "e": 2668, "s": 2594, "text": "indexA − An integer between 0 and one less than the length of the string." }, { "code": null, "e": 2742, "s": 2668, "text": "indexA − An integer between 0 and one less than the length of the string." }, { "code": null, "e": 2813, "s": 2742, "text": "indexB − (optional) An integer between 0 and the length of the string." }, { "code": null, "e": 2884, "s": 2813, "text": "indexB − (optional) An integer between 0 and the length of the string." }, { "code": null, "e": 2959, "s": 2884, "text": "The substring method returns the new sub-string based on given parameters." }, { "code": null, "e": 2986, "s": 2959, "text": "Try the following example." }, { "code": null, "e": 3433, "s": 2986, "text": "<html>\n <head>\n <title>JavaScript String substring() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str = \"Apples are round, and apples are juicy.\"; \n document.write(\"(1,2): \" + str.substring(1,2));\n document.write(\"<br />(0,10): \" + str.substring(0, 10));\n document.write(\"<br />(5): \" + str.substring(5));\n </script> \n </body>\n</html>" }, { "code": null, "e": 3503, "s": 3433, "text": "(1,2): p\n(0,10): Apples are\n(5): s are round, and apples are juicy. \n" }, { "code": null, "e": 3538, "s": 3503, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3552, "s": 3538, "text": " Anadi Sharma" }, { "code": null, "e": 3586, "s": 3552, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3600, "s": 3586, "text": " Lets Kode It" }, { "code": null, "e": 3635, "s": 3600, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3652, "s": 3635, "text": " Frahaan Hussain" }, { "code": null, "e": 3687, "s": 3652, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3704, "s": 3687, "text": " Frahaan Hussain" }, { "code": null, "e": 3737, "s": 3704, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3765, "s": 3737, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3799, "s": 3765, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3827, "s": 3799, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3834, "s": 3827, "text": " Print" }, { "code": null, "e": 3845, "s": 3834, "text": " Add Notes" } ]
How to sort an ArrayList in Ascending Order in Java
To sort an ArrayList in ascending order, the easiest way is to the Collections.sort() method. With this method, you just need to set the ArrayList as the parameter as shown below − Collections.sort(ArrayList) Let us now see an example to sort an ArrayList un ascending order. Here, we are sorting ArrayList with integer elements − Live Demo import java.util.ArrayList; import java.util.Collections; public class Demo { public static void main(String args[]) { ArrayList<Integer> myList = new ArrayList<Integer>(); myList.add(50); myList.add(29); myList.add(35); myList.add(11); myList.add(78); myList.add(64); myList.add(89); myList.add(67); System.out.println("Points\n"+ myList); Collections.sort(myList); System.out.println("Points (ascending order)\n"+ myList); } } Points [50, 29, 35, 11, 78, 64, 89, 67] Points (ascending) [11, 29, 35, 50, 64, 67, 78, 89] Following is another code to sort an ArrayList in ascending order in Java. Here, we are sorting ArrayList with string values − Live Demo import java.util.ArrayList; import java.util.Collections; public class Demo { public static void main(String args[]) { ArrayList<String> myList = new ArrayList<String>(); myList.add("Tim"); myList.add("John"); myList.add("Steve"); myList.add("Andy"); myList.add("Devillers"); myList.add("Jacob"); myList.add("Franco"); myList.add("Amy"); System.out.println("Student Names\n"+ myList); Collections.sort(myList); System.out.println("Student Names (ascending)\n"+ myList); } } Student Names [Tim, John, Steve, Andy, Devillers, Jacob, Franco, Amy] Student Names (ascending) [Amy, Andy, Devillers, Franco, Jacob, John, Steve, Tim]
[ { "code": null, "e": 1243, "s": 1062, "text": "To sort an ArrayList in ascending order, the easiest way is to the Collections.sort() method. With this method, you just need to set the ArrayList as the parameter as shown below −" }, { "code": null, "e": 1271, "s": 1243, "text": "Collections.sort(ArrayList)" }, { "code": null, "e": 1393, "s": 1271, "text": "Let us now see an example to sort an ArrayList un ascending order. Here, we are sorting ArrayList with integer elements −" }, { "code": null, "e": 1404, "s": 1393, "text": " Live Demo" }, { "code": null, "e": 1911, "s": 1404, "text": "import java.util.ArrayList;\nimport java.util.Collections;\npublic class Demo {\n public static void main(String args[]) {\n ArrayList<Integer> myList = new ArrayList<Integer>();\n myList.add(50);\n myList.add(29);\n myList.add(35);\n myList.add(11);\n myList.add(78);\n myList.add(64);\n myList.add(89);\n myList.add(67);\n System.out.println(\"Points\\n\"+ myList);\n Collections.sort(myList);\n System.out.println(\"Points (ascending order)\\n\"+ myList);\n }\n}" }, { "code": null, "e": 2003, "s": 1911, "text": "Points\n[50, 29, 35, 11, 78, 64, 89, 67]\nPoints (ascending)\n[11, 29, 35, 50, 64, 67, 78, 89]" }, { "code": null, "e": 2130, "s": 2003, "text": "Following is another code to sort an ArrayList in ascending order in Java. Here, we are sorting ArrayList with string values −" }, { "code": null, "e": 2141, "s": 2130, "text": " Live Demo" }, { "code": null, "e": 2693, "s": 2141, "text": "import java.util.ArrayList;\nimport java.util.Collections;\npublic class Demo {\n public static void main(String args[]) {\n ArrayList<String> myList = new ArrayList<String>();\n myList.add(\"Tim\");\n myList.add(\"John\");\n myList.add(\"Steve\");\n myList.add(\"Andy\");\n myList.add(\"Devillers\");\n myList.add(\"Jacob\");\n myList.add(\"Franco\");\n myList.add(\"Amy\");\n System.out.println(\"Student Names\\n\"+ myList);\n Collections.sort(myList);\n System.out.println(\"Student Names (ascending)\\n\"+ myList);\n }\n}" }, { "code": null, "e": 2845, "s": 2693, "text": "Student Names\n[Tim, John, Steve, Andy, Devillers, Jacob, Franco, Amy]\nStudent Names (ascending)\n[Amy, Andy, Devillers, Franco, Jacob, John, Steve, Tim]" } ]
Exception propagation in Java
Exception propagation in Java occurs when an exception thrown from the top of the stack. When it is not caught, the exception drops down the call stack of the preceding method. If it is not caught there, it further drops down to the previous method. This continues until the method reaches the bottom of the call stack or is caught somewhere in between. Let us see an example which illustrates exception propagation in Java − Live Demo public class Example { void method1() // generates an exception { int arr[] = {10,20,30}; System.out.println(arr[7]); } void method2() // doesn't catch the exception { method1(); } // method1 drops down the call stack void method3() // method3 catches the exception { try { method2(); } catch(ArrayIndexOutOfBoundsException ae) { System.out.println("Exception is caught"); } } public static void main(String args[]) { Example obj = new Example(); obj.method3(); } } The output is as follows − Exception is caught
[ { "code": null, "e": 1416, "s": 1062, "text": "Exception propagation in Java occurs when an exception thrown from the top of the stack. When it is not caught, the exception drops down the call stack of the preceding method. If it is not caught there, it further drops down to the previous method. This continues until the method reaches the bottom of the call stack or is caught somewhere in between." }, { "code": null, "e": 1488, "s": 1416, "text": "Let us see an example which illustrates exception propagation in Java −" }, { "code": null, "e": 1499, "s": 1488, "text": " Live Demo" }, { "code": null, "e": 2058, "s": 1499, "text": "public class Example {\n void method1() // generates an exception {\n int arr[] = {10,20,30};\n System.out.println(arr[7]);\n }\n void method2() // doesn't catch the exception {\n method1();\n }\n // method1 drops down the call stack\n void method3() // method3 catches the exception {\n try {\n method2();\n } catch(ArrayIndexOutOfBoundsException ae) {\n System.out.println(\"Exception is caught\");\n }\n }\n public static void main(String args[]) {\n Example obj = new Example();\n obj.method3();\n }\n}" }, { "code": null, "e": 2085, "s": 2058, "text": "The output is as follows −" }, { "code": null, "e": 2105, "s": 2085, "text": "Exception is caught" } ]
C Program to insert an array element using pointers.
Write a C program to insert the elements into an array at runtime by the user and the result to be displayed on the screen after insertion. If the inserted element is greater than the size of an array, then, we need to display Invalid Input. An array is used to hold the group of common elements under one name. The array operations are as follows − Insert Delete Search Refer an algorithm to insert the elements into an array with the help of pointers. Step 1: Declare and read the number of elements. Step 2: Declare and read the array size at runtime. Step 3: Input the array elements. Step 4: Declare a pointer variable. Step 5: Allocate the memory dynamically at runtime. Step 6: Input the position, where an element should be inserted. Step 7: Insert the new element at that position and of the elements to right are to be shifted by one position. Size of array is: 5 Array elements are as follows − 1 2 3 4 5 Insert new element: 9 At position: 4 The output is as follows − After insertion the array elements are: 1 2 3 9 4 5 Following is the C program to insert the elements into an array with the help of pointers − Live Demo #include<stdio.h> #include<stdlib.h> void insert(int n1, int *a, int len, int ele){ int i; printf("Array elements after insertion is:\n"); for(i=0;i<len-1;i++){ printf("%d\n",*(a+i)); } printf("%d\n",ele); for(i=len-1;i<n1;i++){ printf("%d\n",*(a+i)); } } int main(){ int *a,n1,i,len,ele; printf("enter size of array elements:"); scanf("%d",&n1); a=(int*)malloc(n1*sizeof(int)); printf("enter the elements:\n"); for(i=0;i<n1;i++){ scanf("%d",a+i); } printf("enter the position where the element need to be insert:\n"); scanf("%d",&len); if(len<=n1){ printf("enter the new element that to be inserted:"); scanf("%d",&ele); insert(n1,a,len,ele); } else { printf("Invalid Input"); } return 0; } When the above program is executed, it produces the following output − enter size of array elements:5 enter the elements: 1 3 5 7 2 enter the position where the element need to be insert: 5 enter the new element that to be inserted:9 Array elements after insertion are: 1 3 5 7 9 2
[ { "code": null, "e": 1304, "s": 1062, "text": "Write a C program to insert the elements into an array at runtime by the user and the result to be displayed on the screen after insertion. If the inserted element is greater than the size of an array, then, we need to display Invalid Input." }, { "code": null, "e": 1374, "s": 1304, "text": "An array is used to hold the group of common elements under one name." }, { "code": null, "e": 1412, "s": 1374, "text": "The array operations are as follows −" }, { "code": null, "e": 1419, "s": 1412, "text": "Insert" }, { "code": null, "e": 1426, "s": 1419, "text": "Delete" }, { "code": null, "e": 1433, "s": 1426, "text": "Search" }, { "code": null, "e": 1516, "s": 1433, "text": "Refer an algorithm to insert the elements into an array with the help of pointers." }, { "code": null, "e": 1565, "s": 1516, "text": "Step 1: Declare and read the number of elements." }, { "code": null, "e": 1617, "s": 1565, "text": "Step 2: Declare and read the array size at runtime." }, { "code": null, "e": 1651, "s": 1617, "text": "Step 3: Input the array elements." }, { "code": null, "e": 1687, "s": 1651, "text": "Step 4: Declare a pointer variable." }, { "code": null, "e": 1739, "s": 1687, "text": "Step 5: Allocate the memory dynamically at runtime." }, { "code": null, "e": 1804, "s": 1739, "text": "Step 6: Input the position, where an element should be inserted." }, { "code": null, "e": 1916, "s": 1804, "text": "Step 7: Insert the new element at that position and of the elements to right are to be shifted by one position." }, { "code": null, "e": 1936, "s": 1916, "text": "Size of array is: 5" }, { "code": null, "e": 1968, "s": 1936, "text": "Array elements are as follows −" }, { "code": null, "e": 1978, "s": 1968, "text": "1 2 3 4 5" }, { "code": null, "e": 2000, "s": 1978, "text": "Insert new element: 9" }, { "code": null, "e": 2015, "s": 2000, "text": "At position: 4" }, { "code": null, "e": 2042, "s": 2015, "text": "The output is as follows −" }, { "code": null, "e": 2094, "s": 2042, "text": "After insertion the array elements are:\n1 2 3 9 4 5" }, { "code": null, "e": 2186, "s": 2094, "text": "Following is the C program to insert the elements into an array with the help of pointers −" }, { "code": null, "e": 2197, "s": 2186, "text": " Live Demo" }, { "code": null, "e": 2991, "s": 2197, "text": "#include<stdio.h>\n#include<stdlib.h>\nvoid insert(int n1, int *a, int len, int ele){\n int i;\n printf(\"Array elements after insertion is:\\n\");\n for(i=0;i<len-1;i++){\n printf(\"%d\\n\",*(a+i));\n }\n printf(\"%d\\n\",ele);\n for(i=len-1;i<n1;i++){\n printf(\"%d\\n\",*(a+i));\n }\n}\nint main(){\n int *a,n1,i,len,ele;\n printf(\"enter size of array elements:\");\n scanf(\"%d\",&n1);\n a=(int*)malloc(n1*sizeof(int));\n printf(\"enter the elements:\\n\");\n for(i=0;i<n1;i++){\n scanf(\"%d\",a+i);\n }\n printf(\"enter the position where the element need to be insert:\\n\");\n scanf(\"%d\",&len);\n if(len<=n1){\n printf(\"enter the new element that to be inserted:\");\n scanf(\"%d\",&ele);\n insert(n1,a,len,ele);\n } else {\n printf(\"Invalid Input\");\n }\n return 0;\n}" }, { "code": null, "e": 3062, "s": 2991, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 3273, "s": 3062, "text": "enter size of array elements:5\nenter the elements:\n1\n3\n5\n7\n2\nenter the position where the element need to be insert:\n5\nenter the new element that to be inserted:9\nArray elements after insertion are:\n1\n3\n5\n7\n9\n2" } ]
XPath - Attribute Node
This attribute can be easily retrieved and checked by using the @attribute-name of the element. @name − get the value of attribute "name". <td><xsl:value-of select = "@rollno"/></td> Attribute can be used to compared using operators. @rollno = 493 − get the text value of attribute "rollno" and compare with a value. <xsl:if test = "@rollno = 493"> In this example, we've created a sample XML document students.xml and its stylesheet document students.xsl which uses the XPath expressions. Following is the sample XML used. <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/"> <html> <body> <h3>Details of each Students. Xpath expression = "/class/student"</h3> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> </tr> <xsl:for-each select = "/class/student"> <tr> <td><xsl:value-of select = "@rollno"/></td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td> </tr> </xsl:for-each> </table> <h3>Details of Student whose roll no is 493. Xpath expression = "@rollno = 493"</h3> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> </tr> <xsl:for-each select = "//student"> <xsl:if test = "@rollno = 493"> <tr> <td><xsl:value-of select = "@rollno"/></td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td> </tr> </xsl:if> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> 90 Lectures 20 hours Arun Motoori 23 Lectures 8 hours Sanjay Kumar 13 Lectures 1.5 hours Sanjay Kumar 24 Lectures 1.5 hours Sanjay Kumar 47 Lectures 3 hours Krishna Sakinala Print Add Notes Bookmark this page
[ { "code": null, "e": 1825, "s": 1729, "text": "This attribute can be easily retrieved and checked by using the @attribute-name of the element." }, { "code": null, "e": 1868, "s": 1825, "text": "@name − get the value of attribute \"name\"." }, { "code": null, "e": 1912, "s": 1868, "text": "<td><xsl:value-of select = \"@rollno\"/></td>" }, { "code": null, "e": 1963, "s": 1912, "text": "Attribute can be used to compared using operators." }, { "code": null, "e": 2046, "s": 1963, "text": "@rollno = 493 − get the text value of attribute \"rollno\" and compare with a value." }, { "code": null, "e": 2078, "s": 2046, "text": "<xsl:if test = \"@rollno = 493\">" }, { "code": null, "e": 2219, "s": 2078, "text": "In this example, we've created a sample XML document students.xml and its stylesheet document students.xsl which uses the XPath expressions." }, { "code": null, "e": 2253, "s": 2219, "text": "Following is the sample XML used." }, { "code": null, "e": 2855, "s": 2253, "text": "<?xml version = \"1.0\"?>\n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?>\n<class>\n <student rollno = \"393\">\n <firstname>Dinkar</firstname>\n <lastname>Kad</lastname>\n <nickname>Dinkar</nickname>\n <marks>85</marks>\n </student>\n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>Vinni</nickname>\n <marks>95</marks>\n </student>\n <student rollno = \"593\">\n <firstname>Jasvir</firstname>\n <lastname>Singh</lastname>\n <nickname>Jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 4935, "s": 2855, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<xsl:stylesheet version = \"1.0\"\n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\">\n\t\n <xsl:template match = \"/\">\n <html>\n <body>\n <h3>Details of each Students. Xpath expression = \"/class/student\"</h3>\n\t\t\t\t\n <table border = \"1\">\n <tr bgcolor = \"#9acd32\">\n <th>Roll No</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Nick Name</th>\n <th>Marks</th>\n </tr>\n\t\t\t\t\t\n <xsl:for-each select = \"/class/student\">\n <tr>\n <td><xsl:value-of select = \"@rollno\"/></td>\n <td><xsl:value-of select = \"firstname\"/></td>\n <td><xsl:value-of select = \"lastname\"/></td>\n <td><xsl:value-of select = \"nickname\"/></td>\n <td><xsl:value-of select = \"marks\"/></td>\n </tr>\n </xsl:for-each>\n </table> \n\t\t\t\t\n <h3>Details of Student whose roll no is 493. Xpath expression = \"@rollno = 493\"</h3>\n\t\t\t\t\n <table border = \"1\">\n <tr bgcolor = \"#9acd32\">\n <th>Roll No</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Nick Name</th>\n <th>Marks</th>\n </tr>\n\t\t\t\t\t\n <xsl:for-each select = \"//student\">\n\t\t\t\t\t\n <xsl:if test = \"@rollno = 493\">\n <tr>\n <td><xsl:value-of select = \"@rollno\"/></td>\n <td><xsl:value-of select = \"firstname\"/></td>\n <td><xsl:value-of select = \"lastname\"/></td>\n <td><xsl:value-of select = \"nickname\"/></td>\n <td><xsl:value-of select = \"marks\"/></td>\n </tr>\n </xsl:if>\n </xsl:for-each>\n </table> \n </body>\n </html>\n </xsl:template>\n</xsl:stylesheet>" }, { "code": null, "e": 4969, "s": 4935, "text": "\n 90 Lectures \n 20 hours \n" }, { "code": null, "e": 4983, "s": 4969, "text": " Arun Motoori" }, { "code": null, "e": 5016, "s": 4983, "text": "\n 23 Lectures \n 8 hours \n" }, { "code": null, "e": 5030, "s": 5016, "text": " Sanjay Kumar" }, { "code": null, "e": 5065, "s": 5030, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5079, "s": 5065, "text": " Sanjay Kumar" }, { "code": null, "e": 5114, "s": 5079, "text": "\n 24 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5128, "s": 5114, "text": " Sanjay Kumar" }, { "code": null, "e": 5161, "s": 5128, "text": "\n 47 Lectures \n 3 hours \n" }, { "code": null, "e": 5179, "s": 5161, "text": " Krishna Sakinala" }, { "code": null, "e": 5186, "s": 5179, "text": " Print" }, { "code": null, "e": 5197, "s": 5186, "text": " Add Notes" } ]
Classification of Signature and Text images using CNN and Deploying the model on Google Cloud ML Engine | by Krishna Parekh | Towards Data Science
As we know for any document of legal importance, may it be a contract, a consignment or a simple form, signature is a substantial part. Signature provides an identification as well as a confirmation. Currently, the model that identifies signature from printed text data is not available. So the work here presented is about classification of signature and text data. The classification model is built using Keras, a high level API of TensorFlow which is an open-source library for machine learning. This classification model can also help in building the Signature Detection model for the document images. The dataset has been generated by extracting the text from the documents and capturing the signature samples from different documents. Data consists of two classes: Signature (class label 0) and Text(class label 1). Data of text images contains images of independent words with different backgrounds, height, width and stroke thickness. Images of text are not restricted to a unique language but also involves multilingual text. The data contains around 2000 different images. Data of signature images contains around 1300 different images of signatures with different backgrounds, height, width and stroke thickness. The data has been stored on Google Cloud Storage. The preliminary step of data cleaning involved dropping of blurred images and realignment of the text with appropriate padding and margins. To increase the size of data, some run time data augmentations like rotations, rescaling and zooming manipulations were performed. Dataset is split into 70% for training and 30% for validation. Apart from this, there is a separate unseen dataset on which the model is tested for accuracy. The blog is organised as: Part I: Independent classification model that can be run on individual system. Part II: Making the model public by deploying the model on GCP ML-Engine. Deep Convolution Neural Network is built by using sequential model. There are three convolution layers along with a fully connected layer followed by an output layer. The CNN parameters like max pooling size is set to (2, 2) and kernel size to (3, 3). Initially the number of filters are set to 32. The number of filters doubles in the subsequent convolution layer. The activation function used is ReLU and the final layer activation function is Sigmoid. A dropout layer is added with dropout probability 0.5. The architecture of the model is as follows: The summary of model gives the detailed picture of each layer with total number of parameters in each layer. The model summary is as below: Next, the model is compiled with evaluation metric as accuracy and loss as binary_crossentropy and optimizer as adam optimizer. As the training data size is limited, run time image augmentations are added with the help of ImageDataGenerator() function. Image augmentations like rotation, rescaling and zooming are added in the training dataset. To predict the the output of the model for test dataset, predict method is used. Then the precision, recall and test accuracy are calculated from the predictions using sklearn.metrics. The final test accuracy after adding image augmentations and dropout layer is 94.29%. The precision for signature images is 96.55% and recall is 97.22%. The table below gives insight into the result upgradations by adding augmentations and dropout layer. Cloud ML Engine helps to train your machine learning models at scale, to host the trained model in the cloud, and to use the model to make predictions about new data. The data has been prepared by taking the signature images and text images in different languages and with different backgrounds. As mentioned earlier, the same preprocessing is done on the data. There are two classes, signature and text. The package architecture of the model ready to be deployed on ML engine is shown below. The setup.py file contains the dependencies along with versions to be installed for the model to run on cloud ML engine. Cloud ML engine has built-in tensorflow support. All other requirements are needed to be installed. The task.py file is the entry point of the model. It contains the list of arguments that needs to be parsed while running the model. It also invokes the model and other dependent files if there are any. The trained model is saved in .hdf5 format. The code for task.py file is depicted here: Note: The saved model is in .hdf5 format. To deploy the model, we need .pb format of the model. For this we need to export the model with TensorFlow serving. The model.py contains the actual model to be trained. It returns the compiled model to the calling function. The code of model function is shown below. This file contains the code for the data preprocessing. The location of the directory containing image files is passed and labelled data is generated that can be fed to model. Data is saved in .npy file, which is then used for model training. a) Training Locally To train the model on local machine, there are two ways: using python command and using gcloud command. $ export JOB_DIR=/path/to/job/dir$ export TRAIN_DIR=/path/to/training/data/dir #either local or GCS#Train using pythonpython -m trainer.task \ --train-dir=$TRAIN_DIR \ --job-dir=$JOB_DIR#Train using gcloud command line tool$ gcloud ml-engine local train --module-name=trainer.task \ --package-path=trainer/ \ --train-dir=$TRAIN_DIR \ --job-dir=$JOB_DIR b) Submitting the job to Google Cloud After the successful training of the model locally, next step is to submit the job to cloud ml-engine. Run the command given below from the directory where your trainer package is located. $ export BUCKET_NAME="your GCS bucket name"$ export JOB_NAME="name of your job"$ export OUTPUT_PATH=gs://$BUCKET_NAME/$JOB_NAME$ export TRAIN_DATA=/path/to/dataset#gcloud command line$ gcloud ml-engine jobs submit training $JOB_NAME \ --job-dir $OUTPUT_PATH \ --runtime-version 1.10 \ --module-name trainer.task \ --package-path trainer/ \ --region $REGION \ -- \ --train-dir $TRAIN_DATA \ --verbosity DEBUG The logs can be checked from the dashboard of Google cloud ML engine. After the job gets submitted successfully, you can find a folder export in the OUTPUT_PATH of your GCS bucket. After training, its time for deploying the model for production. The first step is to convert the saved model from .hdf5 format to .pb (tensorflow model format). The step wise guide along with necessary code and shell commands for it can be found in this notebook. The gcloud command for creating the model is as below. $ export MODEL_NAME=<Name of the model>$ export MODEL_PATH=/gcs/path/to/the/model#CREATE MODEL$ gcloud ml-engine models create $MODEL_NAME Run the below command to create version version_1 of the model. $ gcloud ml-engine versions create "version_1" --model $MODEL_NAME \ --origin $MODEL_PATH \--python-version 3.5 --runtime-version 1.10 The prediction request to the model can be sent as test.json. For this you need to convert your image in a .json format request as shown below. The online prediction can be done with the help of following gcloud command. $ gcloud ml-engine predict — model $MODEL_NAME — version version_3 — json-instances test_data.json You can find the code files here. Hope you found this reading helpful and it provided some meaningful insights to you! Your valuable feedbacks are most welcomed. Happy Learning !!! Originally published at medium.com on January 9, 2019.
[ { "code": null, "e": 539, "s": 172, "text": "As we know for any document of legal importance, may it be a contract, a consignment or a simple form, signature is a substantial part. Signature provides an identification as well as a confirmation. Currently, the model that identifies signature from printed text data is not available. So the work here presented is about classification of signature and text data." }, { "code": null, "e": 778, "s": 539, "text": "The classification model is built using Keras, a high level API of TensorFlow which is an open-source library for machine learning. This classification model can also help in building the Signature Detection model for the document images." }, { "code": null, "e": 994, "s": 778, "text": "The dataset has been generated by extracting the text from the documents and capturing the signature samples from different documents. Data consists of two classes: Signature (class label 0) and Text(class label 1)." }, { "code": null, "e": 1255, "s": 994, "text": "Data of text images contains images of independent words with different backgrounds, height, width and stroke thickness. Images of text are not restricted to a unique language but also involves multilingual text. The data contains around 2000 different images." }, { "code": null, "e": 1396, "s": 1255, "text": "Data of signature images contains around 1300 different images of signatures with different backgrounds, height, width and stroke thickness." }, { "code": null, "e": 1875, "s": 1396, "text": "The data has been stored on Google Cloud Storage. The preliminary step of data cleaning involved dropping of blurred images and realignment of the text with appropriate padding and margins. To increase the size of data, some run time data augmentations like rotations, rescaling and zooming manipulations were performed. Dataset is split into 70% for training and 30% for validation. Apart from this, there is a separate unseen dataset on which the model is tested for accuracy." }, { "code": null, "e": 1901, "s": 1875, "text": "The blog is organised as:" }, { "code": null, "e": 1980, "s": 1901, "text": "Part I: Independent classification model that can be run on individual system." }, { "code": null, "e": 2054, "s": 1980, "text": "Part II: Making the model public by deploying the model on GCP ML-Engine." }, { "code": null, "e": 2420, "s": 2054, "text": "Deep Convolution Neural Network is built by using sequential model. There are three convolution layers along with a fully connected layer followed by an output layer. The CNN parameters like max pooling size is set to (2, 2) and kernel size to (3, 3). Initially the number of filters are set to 32. The number of filters doubles in the subsequent convolution layer." }, { "code": null, "e": 2609, "s": 2420, "text": "The activation function used is ReLU and the final layer activation function is Sigmoid. A dropout layer is added with dropout probability 0.5. The architecture of the model is as follows:" }, { "code": null, "e": 2749, "s": 2609, "text": "The summary of model gives the detailed picture of each layer with total number of parameters in each layer. The model summary is as below:" }, { "code": null, "e": 2877, "s": 2749, "text": "Next, the model is compiled with evaluation metric as accuracy and loss as binary_crossentropy and optimizer as adam optimizer." }, { "code": null, "e": 3094, "s": 2877, "text": "As the training data size is limited, run time image augmentations are added with the help of ImageDataGenerator() function. Image augmentations like rotation, rescaling and zooming are added in the training dataset." }, { "code": null, "e": 3279, "s": 3094, "text": "To predict the the output of the model for test dataset, predict method is used. Then the precision, recall and test accuracy are calculated from the predictions using sklearn.metrics." }, { "code": null, "e": 3534, "s": 3279, "text": "The final test accuracy after adding image augmentations and dropout layer is 94.29%. The precision for signature images is 96.55% and recall is 97.22%. The table below gives insight into the result upgradations by adding augmentations and dropout layer." }, { "code": null, "e": 3701, "s": 3534, "text": "Cloud ML Engine helps to train your machine learning models at scale, to host the trained model in the cloud, and to use the model to make predictions about new data." }, { "code": null, "e": 3939, "s": 3701, "text": "The data has been prepared by taking the signature images and text images in different languages and with different backgrounds. As mentioned earlier, the same preprocessing is done on the data. There are two classes, signature and text." }, { "code": null, "e": 4027, "s": 3939, "text": "The package architecture of the model ready to be deployed on ML engine is shown below." }, { "code": null, "e": 4248, "s": 4027, "text": "The setup.py file contains the dependencies along with versions to be installed for the model to run on cloud ML engine. Cloud ML engine has built-in tensorflow support. All other requirements are needed to be installed." }, { "code": null, "e": 4539, "s": 4248, "text": "The task.py file is the entry point of the model. It contains the list of arguments that needs to be parsed while running the model. It also invokes the model and other dependent files if there are any. The trained model is saved in .hdf5 format. The code for task.py file is depicted here:" }, { "code": null, "e": 4697, "s": 4539, "text": "Note: The saved model is in .hdf5 format. To deploy the model, we need .pb format of the model. For this we need to export the model with TensorFlow serving." }, { "code": null, "e": 4849, "s": 4697, "text": "The model.py contains the actual model to be trained. It returns the compiled model to the calling function. The code of model function is shown below." }, { "code": null, "e": 5092, "s": 4849, "text": "This file contains the code for the data preprocessing. The location of the directory containing image files is passed and labelled data is generated that can be fed to model. Data is saved in .npy file, which is then used for model training." }, { "code": null, "e": 5112, "s": 5092, "text": "a) Training Locally" }, { "code": null, "e": 5216, "s": 5112, "text": "To train the model on local machine, there are two ways: using python command and using gcloud command." }, { "code": null, "e": 5577, "s": 5216, "text": "$ export JOB_DIR=/path/to/job/dir$ export TRAIN_DIR=/path/to/training/data/dir #either local or GCS#Train using pythonpython -m trainer.task \\ --train-dir=$TRAIN_DIR \\ --job-dir=$JOB_DIR#Train using gcloud command line tool$ gcloud ml-engine local train --module-name=trainer.task \\ --package-path=trainer/ \\ --train-dir=$TRAIN_DIR \\ --job-dir=$JOB_DIR" }, { "code": null, "e": 5615, "s": 5577, "text": "b) Submitting the job to Google Cloud" }, { "code": null, "e": 5804, "s": 5615, "text": "After the successful training of the model locally, next step is to submit the job to cloud ml-engine. Run the command given below from the directory where your trainer package is located." }, { "code": null, "e": 6236, "s": 5804, "text": "$ export BUCKET_NAME=\"your GCS bucket name\"$ export JOB_NAME=\"name of your job\"$ export OUTPUT_PATH=gs://$BUCKET_NAME/$JOB_NAME$ export TRAIN_DATA=/path/to/dataset#gcloud command line$ gcloud ml-engine jobs submit training $JOB_NAME \\ --job-dir $OUTPUT_PATH \\ --runtime-version 1.10 \\ --module-name trainer.task \\ --package-path trainer/ \\ --region $REGION \\ -- \\ --train-dir $TRAIN_DATA \\ --verbosity DEBUG" }, { "code": null, "e": 6417, "s": 6236, "text": "The logs can be checked from the dashboard of Google cloud ML engine. After the job gets submitted successfully, you can find a folder export in the OUTPUT_PATH of your GCS bucket." }, { "code": null, "e": 6682, "s": 6417, "text": "After training, its time for deploying the model for production. The first step is to convert the saved model from .hdf5 format to .pb (tensorflow model format). The step wise guide along with necessary code and shell commands for it can be found in this notebook." }, { "code": null, "e": 6737, "s": 6682, "text": "The gcloud command for creating the model is as below." }, { "code": null, "e": 6876, "s": 6737, "text": "$ export MODEL_NAME=<Name of the model>$ export MODEL_PATH=/gcs/path/to/the/model#CREATE MODEL$ gcloud ml-engine models create $MODEL_NAME" }, { "code": null, "e": 6940, "s": 6876, "text": "Run the below command to create version version_1 of the model." }, { "code": null, "e": 7075, "s": 6940, "text": "$ gcloud ml-engine versions create \"version_1\" --model $MODEL_NAME \\ --origin $MODEL_PATH \\--python-version 3.5 --runtime-version 1.10" }, { "code": null, "e": 7219, "s": 7075, "text": "The prediction request to the model can be sent as test.json. For this you need to convert your image in a .json format request as shown below." }, { "code": null, "e": 7296, "s": 7219, "text": "The online prediction can be done with the help of following gcloud command." }, { "code": null, "e": 7395, "s": 7296, "text": "$ gcloud ml-engine predict — model $MODEL_NAME — version version_3 — json-instances test_data.json" }, { "code": null, "e": 7576, "s": 7395, "text": "You can find the code files here. Hope you found this reading helpful and it provided some meaningful insights to you! Your valuable feedbacks are most welcomed. Happy Learning !!!" } ]
Create and display a one-dimensional array-like object using Pandas in Python - GeeksforGeeks
18 Aug, 2020 Series() is a function present in the Pandas library that creates a one-dimensional array and can hold any type of objects or data in it. In this article, let us learn the syntax, create and display one-dimensional array-like object containing an array of data using Pandas library. Syntax : pandas.Series(parameters)Parameters : data : Contains data stored in Series. index : Values must be hashable and have the same length as data. dtype : Data type for the output Series. name : The name to give to the Series. copy : Copy input data. Returns : An object of class Series Example 1 : Creating Series from a list # import the libraryimport pandas as pd # create the one-dimensional arraydata = [1, 2, 3, 4, 5] # create the Seriesex1 = pd.Series(data) # displaying the Seriesprint(ex1) Output : Example 2 :Creating a Series from a NumPy array. # import the pandas and numpy libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array(['a', 'b', 'c', 'd']) # create one-dimensional datas = pd.Series(data) # display the Seriesprint(s) Output : Example 3: Creating a Series from a dictionary. # import the pandas libraryimport pandas as pd # create dictionarydict = {'a' : 0.1, 'b' : 0.2, 'c' : 0.3} # create one-dimensional datas = pd.Series(dict) # display the Seriesprint(s) Output : Example 4 :Creating a Series from list of lists. # importing the moduleimport pandas as pd # creating the datadata = [['g', 'e', 'e', 'k', 's'], ['f', 'o', 'r'], ['g', 'e', 'e', 'k', 's']] # creating a Pandas series of listss = pd.Series(data) # displaying the Seriesprint(s) Output : Python Pandas-exercise Python pandas-series Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python
[ { "code": null, "e": 24621, "s": 24593, "text": "\n18 Aug, 2020" }, { "code": null, "e": 24904, "s": 24621, "text": "Series() is a function present in the Pandas library that creates a one-dimensional array and can hold any type of objects or data in it. In this article, let us learn the syntax, create and display one-dimensional array-like object containing an array of data using Pandas library." }, { "code": null, "e": 24951, "s": 24904, "text": "Syntax : pandas.Series(parameters)Parameters :" }, { "code": null, "e": 24990, "s": 24951, "text": "data : Contains data stored in Series." }, { "code": null, "e": 25056, "s": 24990, "text": "index : Values must be hashable and have the same length as data." }, { "code": null, "e": 25097, "s": 25056, "text": "dtype : Data type for the output Series." }, { "code": null, "e": 25136, "s": 25097, "text": "name : The name to give to the Series." }, { "code": null, "e": 25160, "s": 25136, "text": "copy : Copy input data." }, { "code": null, "e": 25196, "s": 25160, "text": "Returns : An object of class Series" }, { "code": null, "e": 25236, "s": 25196, "text": "Example 1 : Creating Series from a list" }, { "code": "# import the libraryimport pandas as pd # create the one-dimensional arraydata = [1, 2, 3, 4, 5] # create the Seriesex1 = pd.Series(data) # displaying the Seriesprint(ex1)", "e": 25411, "s": 25236, "text": null }, { "code": null, "e": 25420, "s": 25411, "text": "Output :" }, { "code": null, "e": 25469, "s": 25420, "text": "Example 2 :Creating a Series from a NumPy array." }, { "code": "# import the pandas and numpy libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array(['a', 'b', 'c', 'd']) # create one-dimensional datas = pd.Series(data) # display the Seriesprint(s)", "e": 25683, "s": 25469, "text": null }, { "code": null, "e": 25692, "s": 25683, "text": "Output :" }, { "code": null, "e": 25740, "s": 25692, "text": "Example 3: Creating a Series from a dictionary." }, { "code": "# import the pandas libraryimport pandas as pd # create dictionarydict = {'a' : 0.1, 'b' : 0.2, 'c' : 0.3} # create one-dimensional datas = pd.Series(dict) # display the Seriesprint(s)", "e": 25928, "s": 25740, "text": null }, { "code": null, "e": 25937, "s": 25928, "text": "Output :" }, { "code": null, "e": 25986, "s": 25937, "text": "Example 4 :Creating a Series from list of lists." }, { "code": "# importing the moduleimport pandas as pd # creating the datadata = [['g', 'e', 'e', 'k', 's'], ['f', 'o', 'r'], ['g', 'e', 'e', 'k', 's']] # creating a Pandas series of listss = pd.Series(data) # displaying the Seriesprint(s)", "e": 26230, "s": 25986, "text": null }, { "code": null, "e": 26239, "s": 26230, "text": "Output :" }, { "code": null, "e": 26262, "s": 26239, "text": "Python Pandas-exercise" }, { "code": null, "e": 26283, "s": 26262, "text": "Python pandas-series" }, { "code": null, "e": 26297, "s": 26283, "text": "Python-pandas" }, { "code": null, "e": 26304, "s": 26297, "text": "Python" }, { "code": null, "e": 26402, "s": 26304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26411, "s": 26402, "text": "Comments" }, { "code": null, "e": 26424, "s": 26411, "text": "Old Comments" }, { "code": null, "e": 26442, "s": 26424, "text": "Python Dictionary" }, { "code": null, "e": 26477, "s": 26442, "text": "Read a file line by line in Python" }, { "code": null, "e": 26499, "s": 26477, "text": "Enumerate() in Python" }, { "code": null, "e": 26531, "s": 26499, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26573, "s": 26531, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26617, "s": 26573, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26642, "s": 26617, "text": "sum() function in Python" }, { "code": null, "e": 26679, "s": 26642, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26735, "s": 26679, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Pandas Sidetable: A Smarter Way of Using Pandas | by Soner Yıldırım | Towards Data Science
Pandas is a very powerful and versatile Python data analysis library that expedites the preprocessing steps of data science projects. It provides numerous functions and methods that are quite useful in data analysis. Although the built-in functions of Pandas are capable of performing efficient data analysis, custom made functions or libraries add value to Pandas. Sidetable is one of these add-ons which makes it easier to create summaries of dataframes. It can be considered as a combination of value counts and cross tab functions. In some cases, sidetable can work as the groupby function. It can also be combined with the groupby function to produce more informative results. Sidetable was created by Chris Moffitt. It has been quite useful for me in my daily analyses. In this post, I will walk you through examples to show how to best make use of the sidetable. Once installed, sidetable can be used as an accessor on dataframes just like dt and str accessors. Installation is straightforward. $ python -m pip install -U sidetable #from terminal!pip install sidetable #jupyter notebook We can import it along with pandas and start using. import pandas as pdimport sidetable I will be using direct marketing and US elections datasets for examples. Both datasets are available on Kaggle. Sidetable provides functions that are used with the stb accessor. The functions we will cover are: Freq function Counts function Missing function Subtotal function Freq function returns a dataframe that conveys 3 pieces of information. The number of observations (i.e. rows) for each category (value_counts()). The percentage of each category in the entire column (value_counts(normalize=True)). The cumulative versions of the two above. Here is an example. marketing.stb.freq(['Age']) The “Age” column has three categories (Middle, Young, Old). For each category, we see the number of rows and percentage. The rows in cumulative columns contain these values up to that row. For instance, the second row of cumulative columns shows the count and percentage of the middle and young categories. The freq function counts the number of rows by default. If we pass another column using the value parameter, it will return the sum of values in that column. Let’s do an example. marketing.stb.freq(['Age'], value='AmountSpent') As you can see, the name of the column changed from “count” to the name of the column passed to the value parameter. What we see in the returned table is the sum of the “AmountSpent” column for each category. The other columns contain the data (percentage, cumulative) based on the values in the “AmountSpent” column. The freq function can also take multiple columns as argument. It is similar to the groupby function with the count method. marketing.stb.freq(['Age','Gender']) We have have 6 categories which are the combinations of categories in the “Age”and “Gender” columns. Another useful feature of sidetable is that the values are sorted by default. We can achieve the same result (except for the cumulative part) with the groupby function. marketing[['Age','Gender','Salary']]\.groupby(['Age','Gender'], as_index=False)\.count().sort_values(by='Salary', ascending=False)\.rename(columns={'Salary':'count'}) It is clear that sidetable provides a much simpler syntax. One advantage of having cumulative values is that we can only display the larger categories. Let’s do an example on the elections dataset. We want to see the total number of votes in the states that constitute the %40 of all votes. elections.stb.freq(['state'], value='total_votes', thresh=40) The states are sorted based on the total number of votes. When the cumulative percent reach 0.40, remaining states are represented in one row and labelled as “others”. We can change the label name by using the other_label parameter. Another highly useful function of sidetable is the count function. It returns the number of unique values in each column along with some other measures. The number of non-missing values in each column The number of unique categories in each column The most and least frequent categories in each column The number of values that belong the most and least frequent columns Let’s apply it on the marketing dataframe. marketing.stb.counts() It is a quite informative table. We can see the number of unique values, the most and least frequent categories. As you can see, the table includes all the features. We can select a specific data type using the exclude or include parameters. For instance, the following syntax will exclude the numeric columns. marketing.stb.counts(exclude='number') The missing function is pretty simple. It returns the count and percentage of missing values in each column. marketing.stb.missing() This dataframe does not have many missing values. However, it comes in handy when we work with dataframes that contain missing values in most columns. The subtotal function is best used with the groupby function of Pandas. It adds a subtotal for levels of the grouping. Let’s first do a groupby example without the subtotal function of sidetable. marketing[['Age','OwnHome','AmountSpent']]\.groupby(['Age','OwnHome']).sum() We have 2 levels and 6 categories as the result of grouping. The levels are the “Age” and “OwnHome” columns. For each category, the sum of the “AmountSpent” column is shown. In some cases, it would be better to also see the sub total for the levels. Adding subtotals of levels are pretty simple with the sidetable. marketing[['Age','OwnHome','AmountSpent']]\.groupby(['Age','OwnHome']).sum()\.stb.subtotal() In addition to the subtotals, we also see the grand total for the aggregated columns. If we have more than two levels, the subtotals will be added to each level except for the last one. However, it can be changed using the sub_level parameter. Let’s assume we have 3 levels (Age, OwnHome, Gender) in the groupby function: sub_level = 1 : Subtotals for categories in Age column are shown sub_level = 2 : Subtotals for categories in OwnHome column are shown sub_level = [1,2] : All subtotals are shown. Sidetable is a great tool to create summary tables which are quite useful in exploratory data analysis. We can also use them to deliver analyses results. What sidetable offers can also be created using the Pandas own functions and methods. However, the syntax and simplicity of sidetable makes it the first choice for me in many cases. Thank you for reading. Please let me know if you have feedback.
[ { "code": null, "e": 388, "s": 171, "text": "Pandas is a very powerful and versatile Python data analysis library that expedites the preprocessing steps of data science projects. It provides numerous functions and methods that are quite useful in data analysis." }, { "code": null, "e": 537, "s": 388, "text": "Although the built-in functions of Pandas are capable of performing efficient data analysis, custom made functions or libraries add value to Pandas." }, { "code": null, "e": 707, "s": 537, "text": "Sidetable is one of these add-ons which makes it easier to create summaries of dataframes. It can be considered as a combination of value counts and cross tab functions." }, { "code": null, "e": 853, "s": 707, "text": "In some cases, sidetable can work as the groupby function. It can also be combined with the groupby function to produce more informative results." }, { "code": null, "e": 1041, "s": 853, "text": "Sidetable was created by Chris Moffitt. It has been quite useful for me in my daily analyses. In this post, I will walk you through examples to show how to best make use of the sidetable." }, { "code": null, "e": 1173, "s": 1041, "text": "Once installed, sidetable can be used as an accessor on dataframes just like dt and str accessors. Installation is straightforward." }, { "code": null, "e": 1266, "s": 1173, "text": "$ python -m pip install -U sidetable #from terminal!pip install sidetable #jupyter notebook" }, { "code": null, "e": 1318, "s": 1266, "text": "We can import it along with pandas and start using." }, { "code": null, "e": 1354, "s": 1318, "text": "import pandas as pdimport sidetable" }, { "code": null, "e": 1466, "s": 1354, "text": "I will be using direct marketing and US elections datasets for examples. Both datasets are available on Kaggle." }, { "code": null, "e": 1565, "s": 1466, "text": "Sidetable provides functions that are used with the stb accessor. The functions we will cover are:" }, { "code": null, "e": 1579, "s": 1565, "text": "Freq function" }, { "code": null, "e": 1595, "s": 1579, "text": "Counts function" }, { "code": null, "e": 1612, "s": 1595, "text": "Missing function" }, { "code": null, "e": 1630, "s": 1612, "text": "Subtotal function" }, { "code": null, "e": 1702, "s": 1630, "text": "Freq function returns a dataframe that conveys 3 pieces of information." }, { "code": null, "e": 1777, "s": 1702, "text": "The number of observations (i.e. rows) for each category (value_counts())." }, { "code": null, "e": 1862, "s": 1777, "text": "The percentage of each category in the entire column (value_counts(normalize=True))." }, { "code": null, "e": 1904, "s": 1862, "text": "The cumulative versions of the two above." }, { "code": null, "e": 1924, "s": 1904, "text": "Here is an example." }, { "code": null, "e": 1952, "s": 1924, "text": "marketing.stb.freq(['Age'])" }, { "code": null, "e": 2259, "s": 1952, "text": "The “Age” column has three categories (Middle, Young, Old). For each category, we see the number of rows and percentage. The rows in cumulative columns contain these values up to that row. For instance, the second row of cumulative columns shows the count and percentage of the middle and young categories." }, { "code": null, "e": 2438, "s": 2259, "text": "The freq function counts the number of rows by default. If we pass another column using the value parameter, it will return the sum of values in that column. Let’s do an example." }, { "code": null, "e": 2487, "s": 2438, "text": "marketing.stb.freq(['Age'], value='AmountSpent')" }, { "code": null, "e": 2805, "s": 2487, "text": "As you can see, the name of the column changed from “count” to the name of the column passed to the value parameter. What we see in the returned table is the sum of the “AmountSpent” column for each category. The other columns contain the data (percentage, cumulative) based on the values in the “AmountSpent” column." }, { "code": null, "e": 2928, "s": 2805, "text": "The freq function can also take multiple columns as argument. It is similar to the groupby function with the count method." }, { "code": null, "e": 2965, "s": 2928, "text": "marketing.stb.freq(['Age','Gender'])" }, { "code": null, "e": 3144, "s": 2965, "text": "We have have 6 categories which are the combinations of categories in the “Age”and “Gender” columns. Another useful feature of sidetable is that the values are sorted by default." }, { "code": null, "e": 3235, "s": 3144, "text": "We can achieve the same result (except for the cumulative part) with the groupby function." }, { "code": null, "e": 3402, "s": 3235, "text": "marketing[['Age','Gender','Salary']]\\.groupby(['Age','Gender'], as_index=False)\\.count().sort_values(by='Salary', ascending=False)\\.rename(columns={'Salary':'count'})" }, { "code": null, "e": 3461, "s": 3402, "text": "It is clear that sidetable provides a much simpler syntax." }, { "code": null, "e": 3554, "s": 3461, "text": "One advantage of having cumulative values is that we can only display the larger categories." }, { "code": null, "e": 3693, "s": 3554, "text": "Let’s do an example on the elections dataset. We want to see the total number of votes in the states that constitute the %40 of all votes." }, { "code": null, "e": 3755, "s": 3693, "text": "elections.stb.freq(['state'], value='total_votes', thresh=40)" }, { "code": null, "e": 3988, "s": 3755, "text": "The states are sorted based on the total number of votes. When the cumulative percent reach 0.40, remaining states are represented in one row and labelled as “others”. We can change the label name by using the other_label parameter." }, { "code": null, "e": 4141, "s": 3988, "text": "Another highly useful function of sidetable is the count function. It returns the number of unique values in each column along with some other measures." }, { "code": null, "e": 4189, "s": 4141, "text": "The number of non-missing values in each column" }, { "code": null, "e": 4236, "s": 4189, "text": "The number of unique categories in each column" }, { "code": null, "e": 4290, "s": 4236, "text": "The most and least frequent categories in each column" }, { "code": null, "e": 4359, "s": 4290, "text": "The number of values that belong the most and least frequent columns" }, { "code": null, "e": 4402, "s": 4359, "text": "Let’s apply it on the marketing dataframe." }, { "code": null, "e": 4425, "s": 4402, "text": "marketing.stb.counts()" }, { "code": null, "e": 4538, "s": 4425, "text": "It is a quite informative table. We can see the number of unique values, the most and least frequent categories." }, { "code": null, "e": 4736, "s": 4538, "text": "As you can see, the table includes all the features. We can select a specific data type using the exclude or include parameters. For instance, the following syntax will exclude the numeric columns." }, { "code": null, "e": 4775, "s": 4736, "text": "marketing.stb.counts(exclude='number')" }, { "code": null, "e": 4884, "s": 4775, "text": "The missing function is pretty simple. It returns the count and percentage of missing values in each column." }, { "code": null, "e": 4908, "s": 4884, "text": "marketing.stb.missing()" }, { "code": null, "e": 5059, "s": 4908, "text": "This dataframe does not have many missing values. However, it comes in handy when we work with dataframes that contain missing values in most columns." }, { "code": null, "e": 5178, "s": 5059, "text": "The subtotal function is best used with the groupby function of Pandas. It adds a subtotal for levels of the grouping." }, { "code": null, "e": 5255, "s": 5178, "text": "Let’s first do a groupby example without the subtotal function of sidetable." }, { "code": null, "e": 5332, "s": 5255, "text": "marketing[['Age','OwnHome','AmountSpent']]\\.groupby(['Age','OwnHome']).sum()" }, { "code": null, "e": 5582, "s": 5332, "text": "We have 2 levels and 6 categories as the result of grouping. The levels are the “Age” and “OwnHome” columns. For each category, the sum of the “AmountSpent” column is shown. In some cases, it would be better to also see the sub total for the levels." }, { "code": null, "e": 5647, "s": 5582, "text": "Adding subtotals of levels are pretty simple with the sidetable." }, { "code": null, "e": 5740, "s": 5647, "text": "marketing[['Age','OwnHome','AmountSpent']]\\.groupby(['Age','OwnHome']).sum()\\.stb.subtotal()" }, { "code": null, "e": 5826, "s": 5740, "text": "In addition to the subtotals, we also see the grand total for the aggregated columns." }, { "code": null, "e": 5984, "s": 5826, "text": "If we have more than two levels, the subtotals will be added to each level except for the last one. However, it can be changed using the sub_level parameter." }, { "code": null, "e": 6062, "s": 5984, "text": "Let’s assume we have 3 levels (Age, OwnHome, Gender) in the groupby function:" }, { "code": null, "e": 6127, "s": 6062, "text": "sub_level = 1 : Subtotals for categories in Age column are shown" }, { "code": null, "e": 6196, "s": 6127, "text": "sub_level = 2 : Subtotals for categories in OwnHome column are shown" }, { "code": null, "e": 6241, "s": 6196, "text": "sub_level = [1,2] : All subtotals are shown." }, { "code": null, "e": 6395, "s": 6241, "text": "Sidetable is a great tool to create summary tables which are quite useful in exploratory data analysis. We can also use them to deliver analyses results." }, { "code": null, "e": 6577, "s": 6395, "text": "What sidetable offers can also be created using the Pandas own functions and methods. However, the syntax and simplicity of sidetable makes it the first choice for me in many cases." } ]
QlikView - Rank Function
The Rank() function in QlikView is used to display the rank of the values in a field as well as return rows with specific rank value. So it is used in two scenarios. First scenario is in QlikView charts to display the ranks of the values in the field and second is in Aggregate function to display only the rows, which have a specific rank value. The data used in the examples describing Rank function is given below. You can save this as a .csv file in a path in your system where it is accessible by QlikView. Product_Id,Product_Line,Product_category,Quantity,Value 1,Sporting Goods,Outdoor Recreation,12,5642 2,Food, Beverages & Tobacco,38,2514 3,Apparel & Accessories,Clothing,54,2365 4,Apparel & Accessories,Costumes & Accessories,29,4487 5,Sporting Goods,Athletics,11,812 6,Health & Beauty,Personal Care,21,6912 7,Arts & Entertainment,Hobbies & Creative Arts,58,5201 8,Arts & Entertainment,Paintings,73,8451 9,Arts & Entertainment,Musical Instruments,41,1245 10,Hardware,Tool Accessories,2,456 11,Home & Garden,Bathroom Accessories,36,241 12,Food,Drinks,54,1247 13,Home & Garden,Lawn & Garden,29,5462 14,Office Supplies,Presentation Supplies,22,577 15,Hardware,Blocks,53,548 16,Baby & Toddler,Diapering,19,1247 17,Baby & Toddler,Toys,9,257 18,Home & Garden,Pipes,81,1241 19,Office Supplies,Display Board,29,2177 The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into QlikView's memory. Next, we follow the steps given below to create a chart, which shows the rank of the filed Value described with respect to the dimension Product_Line. Click on the Chart wizard and choose the option straight table as the chart type. Click Next. From the First Dimension drop down list, choose Product_Line as dimension. Click Next. In the custom expression field, mention the rank expression as shown below. Here we are considering the numeric field named Value, which represents the Sales value for each category under each Product Line. Click Next. On clicking Finish in the above step, the following chart appears which shows the rank of the sales value of each Product Line. The aggregate functions like − max, min etc. can take rank as an argument to return rows satisfying certain rank values. We consider the following expression to be out in the script editor, which will give the rows containing highest sales under each Product line. # Load the records with highest sales value for each product line. LOAD Product_Line, max(Value,1) FROM [E:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq) group by Product_Line; Let us create a Table Box sheet object to show the data generated by the above given script. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3267, "s": 2920, "text": "The Rank() function in QlikView is used to display the rank of the values in a field as well as return rows with specific rank value. So it is used in two scenarios. First scenario is in QlikView charts to display the ranks of the values in the field and second is in Aggregate function to display only the rows, which have a specific rank value." }, { "code": null, "e": 3432, "s": 3267, "text": "The data used in the examples describing Rank function is given below. You can save this as a .csv file in a path in your system where it is accessible by QlikView." }, { "code": null, "e": 4239, "s": 3432, "text": "Product_Id,Product_Line,Product_category,Quantity,Value\n1,Sporting Goods,Outdoor Recreation,12,5642\n2,Food, Beverages & Tobacco,38,2514\n3,Apparel & Accessories,Clothing,54,2365\n4,Apparel & Accessories,Costumes & Accessories,29,4487\n5,Sporting Goods,Athletics,11,812\n6,Health & Beauty,Personal Care,21,6912\n7,Arts & Entertainment,Hobbies & Creative Arts,58,5201\n8,Arts & Entertainment,Paintings,73,8451\n9,Arts & Entertainment,Musical Instruments,41,1245\n10,Hardware,Tool Accessories,2,456\n11,Home & Garden,Bathroom Accessories,36,241\n12,Food,Drinks,54,1247\n13,Home & Garden,Lawn & Garden,29,5462\n14,Office Supplies,Presentation Supplies,22,577\n15,Hardware,Blocks,53,548\n16,Baby & Toddler,Diapering,19,1247\n17,Baby & Toddler,Toys,9,257\n18,Home & Garden,Pipes,81,1241\n19,Office Supplies,Display Board,29,2177\n" }, { "code": null, "e": 4557, "s": 4239, "text": "The above data is loaded to the QlikView memory by using the script editor. Open the\nScript editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into QlikView's memory." }, { "code": null, "e": 4708, "s": 4557, "text": "Next, we follow the steps given below to create a chart, which shows the rank of the filed Value described with respect to the dimension Product_Line." }, { "code": null, "e": 4802, "s": 4708, "text": "Click on the Chart wizard and choose the option straight table as the chart type. Click Next." }, { "code": null, "e": 4889, "s": 4802, "text": "From the First Dimension drop down list, choose Product_Line as dimension. Click Next." }, { "code": null, "e": 5108, "s": 4889, "text": "In the custom expression field, mention the rank expression as shown below. Here we are considering the numeric field named Value, which represents the Sales value for each category under each Product Line. Click Next." }, { "code": null, "e": 5236, "s": 5108, "text": "On clicking Finish in the above step, the following chart appears which shows the rank of\nthe sales value of each Product Line." }, { "code": null, "e": 5501, "s": 5236, "text": "The aggregate functions like − max, min etc. can take rank as an argument to return rows satisfying certain rank values. We consider the following expression to be out in the script editor, which will give the rows containing highest sales under each Product line." }, { "code": null, "e": 5735, "s": 5501, "text": "# Load the records with highest sales value for each product line.\nLOAD Product_Line, \n max(Value,1)\nFROM\n[E:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq)\ngroup by Product_Line;" }, { "code": null, "e": 6092, "s": 5735, "text": "Let us create a Table Box sheet object to show the data generated by the above given\nscript. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below." }, { "code": null, "e": 6125, "s": 6092, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 6138, "s": 6125, "text": " Arthur Fong" }, { "code": null, "e": 6145, "s": 6138, "text": " Print" }, { "code": null, "e": 6156, "s": 6145, "text": " Add Notes" } ]
25 Questions to Ask as You Clean Data | by Rose Day | Towards Data Science
I work as a software engineer and data scientist with my code both in notebooks and software packages. If you haven’t heard it yet, you should stop and think before you code, and the same concept applies to data cleaning. It has been valuable to step back from the initial work and begin to think about the problem at hand and the data you will be cleaning. It is also a great idea to consider the end-use case for the data. Do you need it in a report or dashboard? Will the data be used by many or by one? How often will you need to clean this data? With that, I would like to introduce to you 25 common questions I consider before tackling data cleaning. When I start a project, the first consideration I have to make is how I will ingest the data for this project before I start cleaning it. Depending on where I am getting the data from, I may need to perform different data cleaning steps. Suppose the data had already come from another team. In that case, there is a possibility the data is clean before I ingest it, making it easier for me to preprocess the data before working with it. 1. Do you need to ingest the data and then clean it, or is it cleaned at the source? 2. If you are reading in files that contain your data, can you clean and overwrite the file, or will you need to save it somewhere else to keep the raw file separate? 3. Do you need to save your cleaned data or keep it in a dataframe and save your analysis's output?4. Do you need a backup of the data somewhere? 5. What happens if the files become corrupted as you are cleaning it? Are you prepared to start over? After I have received the data, the next step is to understand how to handle empty or NULL values. It is rarely that easy to have empty or NULL appear in your dataset. Instead, users will add obscure large values like -9999 or 9999, other characters, or words. It is good to take a step back and understand how users add empty values into the dataset and take action to look at how you will clean out these values. Once you know how these values are represented in your dataset, you can begin cleaning them out or impute values where needed. 6. Are there values that you can remove as empty or NULL values such as -1, -9999, 9999, or other characters? 7. Will these values be imputed as a string, numeric, or category? 8. Will you drop values that are empty or NULL? 9. Can these values be empty or NULL, and still have the data make sense to provide valuable action? If this value is missing, can you provide actionable insights? 10. Can work with those who created the data to develop a standard for what is considered empty or NULL? The next thing I look for is text fields. When I use text fields, I either use them as categories, discussed next, or as plain text that will be displayed or used for additional information. But what happens if you are using your text fields for modeling? You may need to consider different types of cleaning or natural language processing techniques to work with your data, such as stemming, lemmatization, or removing filler words. I find it harder to work with text fields as there can be variations in the spelling, acronyms, mistypes information, and more. 11. Are there spelling mistakes in the column that you need to consider? 12. Can a word or abbreviation be spelled multiple ways? 13. Could there be more than one abbreviation for the same thing? 14. Do you need to extract data from the text field? If so, will you use regular expressions, stemming, lemmatization, remove filler words, white space, etc.? 15. Do you have timestamp or other numeric data type columns that read as strings but should be another data type? Categories and booleans are the most accessible two data types to deal with when cleaning data as they tend to have less variation in their columns. For categories, I tend to look at the unique categories listed for a given column to understand better what I am working with for different values. Then I can bring that information back to a subject matter expert (SME) as needed to get definitions for categories that may be unclear, such as numeric numbers or single letter values that map to a definition. 16. Will you keep your categories in a human-readable format or convert them using one-hot encoding? 17. Do you have too many or too little categories? 18. Do you have duplicate categories? Duplication can appear due to misspellings or added white space such as 'R' and 'R '. 19. Should you add another category if there are items that do not fit into the rest? 20. How will you represent boolean values? 0 and 1, True and False. Pick a schema and use it for all boolean columns to have consistency. Lastly, there are numeric fields. A common task I have done when looking over numeric fields is to understand the summary statistics and data distribution in these columns. This quick analysis helps understand how the data is structured and if any noticeable outliers could exist. After looking at this data, you may also need to consider any units associated with your numeric points. Did you assume the units of specific columns, but something seems wrong? Double-checking this can help before you move forward with your work. 21. Does the data columns' distribution seem appropriate, or do you need to investigate an issue?22. Do you need to know what metrics the data stands for, such as feet vs. inches or Celcius vs. Fahrenheit? Will the difference matter to your end calculations?23. Is the column all numeric, or are there other values to clean out from the data?24. Have you converted the column to the same data type, such as int or float? Will this conversion affect your end-use case for the data? 25. Is your data continuous or categorical? How will that data be used? Data cleaning and preprocessing can take up much of the time during data science projects. As you ingest the data, consider how much work may have already been done to clean the data before receiving it and how much work you will need to do to clean it. As you look at your data, the first thing to consider is how you will handle null or empty data values. Can you clean them out, or will you need to impute a value in its place? Once you have made that determination, you can begin to look at the actual data points in each column and construct a plan to clean those columns as you see fit. Columns can include things like categories, booleans, numeric, and text fields. Each will require different considerations as you clean and preprocess the data before modeling. What types of questions do you ask as you clean data? If you would like to read more, check out some of my other articles below!
[ { "code": null, "e": 829, "s": 172, "text": "I work as a software engineer and data scientist with my code both in notebooks and software packages. If you haven’t heard it yet, you should stop and think before you code, and the same concept applies to data cleaning. It has been valuable to step back from the initial work and begin to think about the problem at hand and the data you will be cleaning. It is also a great idea to consider the end-use case for the data. Do you need it in a report or dashboard? Will the data be used by many or by one? How often will you need to clean this data? With that, I would like to introduce to you 25 common questions I consider before tackling data cleaning." }, { "code": null, "e": 1266, "s": 829, "text": "When I start a project, the first consideration I have to make is how I will ingest the data for this project before I start cleaning it. Depending on where I am getting the data from, I may need to perform different data cleaning steps. Suppose the data had already come from another team. In that case, there is a possibility the data is clean before I ingest it, making it easier for me to preprocess the data before working with it." }, { "code": null, "e": 1766, "s": 1266, "text": "1. Do you need to ingest the data and then clean it, or is it cleaned at the source? 2. If you are reading in files that contain your data, can you clean and overwrite the file, or will you need to save it somewhere else to keep the raw file separate? 3. Do you need to save your cleaned data or keep it in a dataframe and save your analysis's output?4. Do you need a backup of the data somewhere? 5. What happens if the files become corrupted as you are cleaning it? Are you prepared to start over?" }, { "code": null, "e": 2308, "s": 1766, "text": "After I have received the data, the next step is to understand how to handle empty or NULL values. It is rarely that easy to have empty or NULL appear in your dataset. Instead, users will add obscure large values like -9999 or 9999, other characters, or words. It is good to take a step back and understand how users add empty values into the dataset and take action to look at how you will clean out these values. Once you know how these values are represented in your dataset, you can begin cleaning them out or impute values where needed." }, { "code": null, "e": 2802, "s": 2308, "text": "6. Are there values that you can remove as empty or NULL values such as -1, -9999, 9999, or other characters? 7. Will these values be imputed as a string, numeric, or category? 8. Will you drop values that are empty or NULL? 9. Can these values be empty or NULL, and still have the data make sense to provide valuable action? If this value is missing, can you provide actionable insights? 10. Can work with those who created the data to develop a standard for what is considered empty or NULL?" }, { "code": null, "e": 3364, "s": 2802, "text": "The next thing I look for is text fields. When I use text fields, I either use them as categories, discussed next, or as plain text that will be displayed or used for additional information. But what happens if you are using your text fields for modeling? You may need to consider different types of cleaning or natural language processing techniques to work with your data, such as stemming, lemmatization, or removing filler words. I find it harder to work with text fields as there can be variations in the spelling, acronyms, mistypes information, and more." }, { "code": null, "e": 3834, "s": 3364, "text": "11. Are there spelling mistakes in the column that you need to consider? 12. Can a word or abbreviation be spelled multiple ways? 13. Could there be more than one abbreviation for the same thing? 14. Do you need to extract data from the text field? If so, will you use regular expressions, stemming, lemmatization, remove filler words, white space, etc.? 15. Do you have timestamp or other numeric data type columns that read as strings but should be another data type?" }, { "code": null, "e": 4342, "s": 3834, "text": "Categories and booleans are the most accessible two data types to deal with when cleaning data as they tend to have less variation in their columns. For categories, I tend to look at the unique categories listed for a given column to understand better what I am working with for different values. Then I can bring that information back to a subject matter expert (SME) as needed to get definitions for categories that may be unclear, such as numeric numbers or single letter values that map to a definition." }, { "code": null, "e": 4842, "s": 4342, "text": "16. Will you keep your categories in a human-readable format or convert them using one-hot encoding? 17. Do you have too many or too little categories? 18. Do you have duplicate categories? Duplication can appear due to misspellings or added white space such as 'R' and 'R '. 19. Should you add another category if there are items that do not fit into the rest? 20. How will you represent boolean values? 0 and 1, True and False. Pick a schema and use it for all boolean columns to have consistency." }, { "code": null, "e": 5371, "s": 4842, "text": "Lastly, there are numeric fields. A common task I have done when looking over numeric fields is to understand the summary statistics and data distribution in these columns. This quick analysis helps understand how the data is structured and if any noticeable outliers could exist. After looking at this data, you may also need to consider any units associated with your numeric points. Did you assume the units of specific columns, but something seems wrong? Double-checking this can help before you move forward with your work." }, { "code": null, "e": 5924, "s": 5371, "text": "21. Does the data columns' distribution seem appropriate, or do you need to investigate an issue?22. Do you need to know what metrics the data stands for, such as feet vs. inches or Celcius vs. Fahrenheit? Will the difference matter to your end calculations?23. Is the column all numeric, or are there other values to clean out from the data?24. Have you converted the column to the same data type, such as int or float? Will this conversion affect your end-use case for the data? 25. Is your data continuous or categorical? How will that data be used?" }, { "code": null, "e": 6694, "s": 5924, "text": "Data cleaning and preprocessing can take up much of the time during data science projects. As you ingest the data, consider how much work may have already been done to clean the data before receiving it and how much work you will need to do to clean it. As you look at your data, the first thing to consider is how you will handle null or empty data values. Can you clean them out, or will you need to impute a value in its place? Once you have made that determination, you can begin to look at the actual data points in each column and construct a plan to clean those columns as you see fit. Columns can include things like categories, booleans, numeric, and text fields. Each will require different considerations as you clean and preprocess the data before modeling." }, { "code": null, "e": 6748, "s": 6694, "text": "What types of questions do you ask as you clean data?" } ]
Modeling, Visualizing, and Navigating a Transportation Network with Memgraph | by Barbara Prkacin | Towards Data Science
If riding a bike or walking is not an option, using public transport is the most eco-friendly way to travel around a city. Navigating a public transportation system can be confusing and complicated. As a passenger, you usually want to know how to get from one station to another and where to change lines to make your journey as optimal as possible. In essence, the problem is finding the shortest path in the complex network of stations and lines. This type of problem is a typical graph use-case. Graphs are used for modeling and navigating complex network problems across a variety of domains including transportation, cybersecurity, fraud detection, and many more. In this tutorial, you will explore how to use graphs to model and navigate a transportation network. You will learn how to import the London Tube dataset into Memgraph and visualize it on a map using Memgraph Lab. Next, you will learn how to use the Cypher query language and graph algorithms to help you explore the London Tube network and find your way around the city without getting lost or wasting hours being stuck in traffic. To complete this tutorial, you will need: An installation of Memgraph DB: a native, in-memory graph database. To install Memgraph DB and set it up, please follow the Docker Installation instructions on the Installation guide. An installation of Memgraph Lab: an integrated development environment used to import data, develop, debug and profile database queries and visualize query results. The London Tube network dataset which you can download here. For this tutorial, you will be using the London Tube network dataset published by Nicola Greco. It contains 302 Stations (nodes) and 812 Connection (edges). The node lat and lng properties represent the coordinates of a station and will also be important to visualize the data on a map. Two stations are connected with an edge of the type :Connection if they are adjacent. Since trains travel both ways, there is an edge for each direction. Every edge has a time property that represents the time (in minutes) needed to travel between two stations and a line property which will make more sense after you add a name property later in this tutorial. Now that you have defined your schema, you’re ready to import your dataset. The first step is loading data into Memgraph. Memgraph comes with tools for importing data into the database. For this tutorial, you will be using the CSV Import Tool. The CSV import tool should be used for the initial bulk ingestion of data into Memgraph. Upon ingestion, the CSV importer creates a snapshot that will be used by the database to recover its state on the next startup. You can learn about snapshots here. Each row of a CSV file represents a single entry that should be imported into the database. Both nodes and relationships can be imported into the database using CSV files. To get all relevant data you will need three files. The first one contains data about nodes (stations.csv), the other two contain data about relationships (connections.csv and connections-reverse.csv). Each CSV file must have a header that describes the data.stations.csv has the following header: id:ID(STATION),lat:double,lng:double,name:string,display_name:string,zone:int,total_lines:int,rail:int The ID field type sets the internal ID that will be used for the node when creating relationships. It is optional and nodes that don’t have an ID value specified will be imported, but can’t be connected to any relationships. When importing relationships, the START_ID field type sets the start node that should be connected with the relationship to the end node with END_ID. The field must be specified and the node ID must be one of the node IDs that were specified in the node CSV files. The files connections.csv and connections-reverse.csv are identical except for the header. That’s because we need connections in both directions so, rather than creating missing relationships after importing the data, you can import the second file with a header where you switch START_ID and END_ID. As a result, you get a copy of every relationship from the first file, only in the opposite direction. :END_ID(STATION),:START_ID(STATION),line:int,time:int:START_ID(STATION),:END_ID(STATION),line:int,time:int [NOTE] If your Memgraph database instance is running, you need to stop it before continuing to the next step. First you need to copy the CSV files where the Docker image can see them. Navigate to the folder that contains the data files and run the following commands: docker container create --name mg_import_helper -v mg_import:/import-data busyboxdocker cp connections.csv mg_import_helper:/import-datadocker cp connections-reverse.csv mg_import_helper:/import-datadocker cp stations.csv mg_import_helper:/import-datadocker rm mg_import_helper The two main flags that are used to specify the input CSV files are --nodes and --relationships.Labels for nodes (Station) and type for relationships (:Connection) need to be set on import because the CSV files don’t contain this information. You can run the importer with the following command: docker run -v mg_lib:/var/lib/memgraph -v mg_etc:/etc/memgraph -v mg_import:/import-data --entrypoint=mg_import_csv memgraph --nodes Station=/import-data/stations.csv --relationships Connection=/import-data/connections.csv --relationships Connection=/import-data/connections-reverse.csv --data-directory /var/lib/memgraph true --storage-properties-on-edges true You can now start Memgraph by running the following command: docker run -v mg_lib:/var/lib/memgraph -p 7687:7687 memgraph:latest --data-directory /var/lib/memgraph If you have additional questions about the CSV Import Tool, take a look at our documentation: CSV Import Tool. Once you have the data in Memgraph, visualizing it with Memgraph Lab is pretty easy. Memgraph Lab automatically detects nodes that have numerical lat and lng properties. To get your graph, run the following Cypher query: MATCH (n)-[r]-(m)RETURN n,r,m; If everything works properly, you should get a visualization similar to the one below. The line property doesn’t make much sense because we usually recognize London Tube lines by their names or colors. The map will be more confusing than helpful unless you add a name property to the edges. The following Cypher query uses the CASE expression which allows multiple predicates to be listed. The first one that evaluates to true is matched, and the result of the expression provided after the THEN keyword is used to set the value of the name property on a relationship. MATCH (n)-[r]-(m)SET r.name = CASEWHEN r.line = 1 THEN "Bakerloo Line"WHEN r.line = 2 THEN "Central Line"WHEN r.line = 3 THEN "Circle Line"WHEN r.line = 4 THEN "District Line"WHEN r.line = 5 THEN "East London Line"WHEN r.line = 6 THEN "Hammersmith & City Line"WHEN r.line = 7 THEN "Jubilee Line"WHEN r.line = 8 THEN "Metropolitan Line"WHEN r.line = 9 THEN "Northern Line"WHEN r.line = 10 THEN "Piccadilly Line"WHEN r.line = 11 THEN "Victoria Line"WHEN r.line = 12 THEN "Waterloo & City Line"WHEN r.line = 13 THEN "Docklands Light Railway"END; While the dataset makes much more sense now, the styling of the map is still a bit too uniform. You can style the map to your liking by using the Style editor in Memgraph Lab. You can read more about the style editor in this tutorial. First, let’s make stations smaller and shaped like squares. A white circle with a black border is reserved for interchange stations (where you can switch between lines). To accomplish this, you will use the following styling script: @NodeStyle HasLabel?(node, "Station") { size: 15 color: black shape: "square" color-hover: red color-selected: Darker(red)}@NodeStyle Greater?(Property(node, "total_lines"), 1) { size: 30 shape: "dot" border-width: 2 border-color: black color: white color-hover: red color-selected: Darker(red)}@NodeStyle HasProperty?(node, "name") { label: AsText(Property(node, "name"))} Now you can add the most important thing, the iconic line colors! To do this, you will use the following script: @EdgeStyle HasProperty?(edge, "name") { label: AsText(Property(edge, "name")) width: 10}@EdgeStyle Equals?(Property(edge, "line"),1) {color: #AE6017}@EdgeStyle Equals?(Property(edge, "line"),2) {color: #F15B2E}@EdgeStyle Equals?(Property(edge, "line"),3) {color: #FFE02B}@EdgeStyle Equals?(Property(edge, "line"),4) {color: #00A166} @EdgeStyle Equals?(Property(edge, "line"),5) {color: #FBAE34}@EdgeStyle Equals?(Property(edge, "line"),6) {color: #F491A8}@EdgeStyle Equals?(Property(edge, "line"),7) {color: #949699}@EdgeStyle Equals?(Property(edge, "line"),8) {color: #91005A}@EdgeStyle Equals?(Property(edge, "line"),9) {color: #000000}@EdgeStyle Equals?(Property(edge, "line"),10) {color: #094FA3}@EdgeStyle Equals?(Property(edge, "line"),11) {color: #0A9CDA}@EdgeStyle Equals?(Property(edge, "line"),12) {color: #88D0C4}@EdgeStyle Equals?(Property(edge, "line"),13) {color: #00A77E} Your graph should now look like this: Now that you have your graph data loaded into Memgraph and visualizations set up in Memgraph Lab, you are ready to start exploring the London Tube network by using graph traversals and algorithms. Let’s say you’re planning a trip and want to find a hotel near a well-connected station. By using the following Cypher query, you will find which stations have the most connections to other stations: MATCH (s1:Station)-[:Connection]->(s2:Station)WITH DISTINCT s2.name as adjacent, s1.name as nameRETURN name AS Station_name, COUNT(adjacent) AS Total_connectionsORDER BY Total_connections DESC LIMIT 10; For every station, the first part of the query matches all stations that are one degree apart. The second part counts connections and returns a list of the 10 most connected stations. Now that you have your list, King’s Cross St. Pancras is the obvious choice. You can easily check what Tube lines you can access from King’s Cross St. Pancras by running the following query: MATCH (:Station {name:"King's Cross St. Pancras"})-[r]-(:Station)WITH DISTINCT r.name AS lineRETURN line; Let’s say you’re traveling on a budget and you want to stay in the first fare zone to keep your transportation cost low. In this case, you can use the Breadth-First algorithm to find out what stations you can get to from St. Pancras while staying in the first fare zone: MATCH p = (s1:Station {name:"King's Cross St. Pancras"}) -[:Connection * bfs (e, n | n.zone = 1)]- (s2:Station) UNWIND (nodes(p)) as rowsWITH DISTINCT rows.name as Station RETURN Station LIMIT 10; (e, n | n.zone = 1) is called a filter lambda. It’s a function that takes an edge symbol e and a node symbol n and decides whether this edge and node pair should be considered valid in breadth-first expansion by returning true or false. In this example, the lambda is returning true if station is in the first fare zone. Or if you are more of a visual person, you can visualize your results by running the following query: MATCH p = (:Station {name:"King's Cross St. Pancras"}) -[:Connection * bfs (e, n | n.zone = 1)]- (:Station)RETURN p; Let’s say you have just arrived at London Heathrow airport. You are probably tired and in desperate need of a shower and nap but you’d love to stop by Big Ben, which is located at the Westminster tube station, on your way to your hotel. Lucky for you, Memgraph can help you find the quickest route in no time! Pathfinding algorithms are one of the classical graph problems and have been researched since the 19th century. The Shortest Path algorithm calculates a path between two nodes in a graph such that the total sum of the edge weights is minimized.The syntax here is similar to breadth-first search syntax. Instead of a filter lambda, we need to provide a weight lambda and the total weight symbol. Given an edge and node pair, weight lambda must return the cost (time) of expanding to the given node using the given edge. MATCH p = (s1:Station {name: "Heathrow Terminal 4"}) -[edge_list:Connection *wShortest (e, n | e.time) time]- (s2:Station {name: "Westminster"})RETURN *; This route will get you from Heathrow to Westminster in 43 minutes, but there are delays on Circle and District lines, so you want exclude them from the search. You can combine weight and filter lambdas in the shortest-path query: MATCH p = (s1:Station {name: "Heathrow Terminal 4"}) -[edge_list:Connection *wShortest (e, n | e.time) time (e, n | e.name != "Circle Line" AND e.name != "District Line")]- (s2:Station {name: "Westminster"})RETURN *; The new route is only 3 minutes longer, but you’ll avoid delays. And the shortest route from Westminster will get you to the hotel in 10 minutes (with Circle and District lines excluded). MATCH p = (s1:Station {name: "Westminster"}) -[edge_list:Connection *wShortest (e, n | e.time) time (e, n | e.name != "Circle Line" AND e.name != "District Line")]- (s2:Station {name: "King's Cross St. Pancras"})RETURN *; It is surprising how many of London’s museums and galleries are free to visit. The British Museum should definitely be your first choice! Although you can spend hours there, you want to see a little bit of everything so let’s add a few more options. Tottenham Court Road station is nearest to the British Museum and it will be your first stop. South Kensington station is within walking distance of three amazing museums: Science Museum, Natural History Museum, and Victoria and Albert Museum. To find the optimal route for your trip, you can use the following Cypher query: MATCH p = (:Station {name: "King's Cross St. Pancras"}) -[:Connection *wShortest (e, n | e.time) time1]- (:Station {name: "Tottenham Court Road"}) -[:Connection *wShortest (e, n | e.time) time2]- (:Station {name: "South Kensington"})RETURN p, time1 + time2 AS total_time; In this tutorial, you learned how to use Memgraph and Cypher to model and navigate a complex transportation network. With the help of graph algorithms, you found the optimal routes and learned how to visualize data using Memgraph Lab to get the most out of it. If you are interested in exploring another graph route planning tutorial, you can check out the Exploring the European Road Network demo on Memgraph Playground. A friend once told me: “You can never get lost in London, you just have to find a Tube station and you’ll know where you are.” I would say: “You can never get lost in London, you just have to use Memgraph and find the shortest path!” Remember, always stand on the right, and don’t forget to mind the gap!
[ { "code": null, "e": 371, "s": 172, "text": "If riding a bike or walking is not an option, using public transport is the most eco-friendly way to travel around a city. Navigating a public transportation system can be confusing and complicated." }, { "code": null, "e": 841, "s": 371, "text": "As a passenger, you usually want to know how to get from one station to another and where to change lines to make your journey as optimal as possible. In essence, the problem is finding the shortest path in the complex network of stations and lines. This type of problem is a typical graph use-case. Graphs are used for modeling and navigating complex network problems across a variety of domains including transportation, cybersecurity, fraud detection, and many more." }, { "code": null, "e": 1274, "s": 841, "text": "In this tutorial, you will explore how to use graphs to model and navigate a transportation network. You will learn how to import the London Tube dataset into Memgraph and visualize it on a map using Memgraph Lab. Next, you will learn how to use the Cypher query language and graph algorithms to help you explore the London Tube network and find your way around the city without getting lost or wasting hours being stuck in traffic." }, { "code": null, "e": 1316, "s": 1274, "text": "To complete this tutorial, you will need:" }, { "code": null, "e": 1500, "s": 1316, "text": "An installation of Memgraph DB: a native, in-memory graph database. To install Memgraph DB and set it up, please follow the Docker Installation instructions on the Installation guide." }, { "code": null, "e": 1665, "s": 1500, "text": "An installation of Memgraph Lab: an integrated development environment used to import data, develop, debug and profile database queries and visualize query results." }, { "code": null, "e": 1726, "s": 1665, "text": "The London Tube network dataset which you can download here." }, { "code": null, "e": 2013, "s": 1726, "text": "For this tutorial, you will be using the London Tube network dataset published by Nicola Greco. It contains 302 Stations (nodes) and 812 Connection (edges). The node lat and lng properties represent the coordinates of a station and will also be important to visualize the data on a map." }, { "code": null, "e": 2167, "s": 2013, "text": "Two stations are connected with an edge of the type :Connection if they are adjacent. Since trains travel both ways, there is an edge for each direction." }, { "code": null, "e": 2375, "s": 2167, "text": "Every edge has a time property that represents the time (in minutes) needed to travel between two stations and a line property which will make more sense after you add a name property later in this tutorial." }, { "code": null, "e": 2451, "s": 2375, "text": "Now that you have defined your schema, you’re ready to import your dataset." }, { "code": null, "e": 2619, "s": 2451, "text": "The first step is loading data into Memgraph. Memgraph comes with tools for importing data into the database. For this tutorial, you will be using the CSV Import Tool." }, { "code": null, "e": 2872, "s": 2619, "text": "The CSV import tool should be used for the initial bulk ingestion of data into Memgraph. Upon ingestion, the CSV importer creates a snapshot that will be used by the database to recover its state on the next startup. You can learn about snapshots here." }, { "code": null, "e": 3044, "s": 2872, "text": "Each row of a CSV file represents a single entry that should be imported into the database. Both nodes and relationships can be imported into the database using CSV files." }, { "code": null, "e": 3342, "s": 3044, "text": "To get all relevant data you will need three files. The first one contains data about nodes (stations.csv), the other two contain data about relationships (connections.csv and connections-reverse.csv). Each CSV file must have a header that describes the data.stations.csv has the following header:" }, { "code": null, "e": 3445, "s": 3342, "text": "id:ID(STATION),lat:double,lng:double,name:string,display_name:string,zone:int,total_lines:int,rail:int" }, { "code": null, "e": 3670, "s": 3445, "text": "The ID field type sets the internal ID that will be used for the node when creating relationships. It is optional and nodes that don’t have an ID value specified will be imported, but can’t be connected to any relationships." }, { "code": null, "e": 3935, "s": 3670, "text": "When importing relationships, the START_ID field type sets the start node that should be connected with the relationship to the end node with END_ID. The field must be specified and the node ID must be one of the node IDs that were specified in the node CSV files." }, { "code": null, "e": 4339, "s": 3935, "text": "The files connections.csv and connections-reverse.csv are identical except for the header. That’s because we need connections in both directions so, rather than creating missing relationships after importing the data, you can import the second file with a header where you switch START_ID and END_ID. As a result, you get a copy of every relationship from the first file, only in the opposite direction." }, { "code": null, "e": 4446, "s": 4339, "text": ":END_ID(STATION),:START_ID(STATION),line:int,time:int:START_ID(STATION),:END_ID(STATION),line:int,time:int" }, { "code": null, "e": 4556, "s": 4446, "text": "[NOTE] If your Memgraph database instance is running, you need to stop it before continuing to the next step." }, { "code": null, "e": 4714, "s": 4556, "text": "First you need to copy the CSV files where the Docker image can see them. Navigate to the folder that contains the data files and run the following commands:" }, { "code": null, "e": 4992, "s": 4714, "text": "docker container create --name mg_import_helper -v mg_import:/import-data busyboxdocker cp connections.csv mg_import_helper:/import-datadocker cp connections-reverse.csv mg_import_helper:/import-datadocker cp stations.csv mg_import_helper:/import-datadocker rm mg_import_helper" }, { "code": null, "e": 5235, "s": 4992, "text": "The two main flags that are used to specify the input CSV files are --nodes and --relationships.Labels for nodes (Station) and type for relationships (:Connection) need to be set on import because the CSV files don’t contain this information." }, { "code": null, "e": 5288, "s": 5235, "text": "You can run the importer with the following command:" }, { "code": null, "e": 5650, "s": 5288, "text": "docker run -v mg_lib:/var/lib/memgraph -v mg_etc:/etc/memgraph -v mg_import:/import-data --entrypoint=mg_import_csv memgraph --nodes Station=/import-data/stations.csv --relationships Connection=/import-data/connections.csv --relationships Connection=/import-data/connections-reverse.csv --data-directory /var/lib/memgraph true --storage-properties-on-edges true" }, { "code": null, "e": 5711, "s": 5650, "text": "You can now start Memgraph by running the following command:" }, { "code": null, "e": 5814, "s": 5711, "text": "docker run -v mg_lib:/var/lib/memgraph -p 7687:7687 memgraph:latest --data-directory /var/lib/memgraph" }, { "code": null, "e": 5925, "s": 5814, "text": "If you have additional questions about the CSV Import Tool, take a look at our documentation: CSV Import Tool." }, { "code": null, "e": 6146, "s": 5925, "text": "Once you have the data in Memgraph, visualizing it with Memgraph Lab is pretty easy. Memgraph Lab automatically detects nodes that have numerical lat and lng properties. To get your graph, run the following Cypher query:" }, { "code": null, "e": 6177, "s": 6146, "text": "MATCH (n)-[r]-(m)RETURN n,r,m;" }, { "code": null, "e": 6264, "s": 6177, "text": "If everything works properly, you should get a visualization similar to the one below." }, { "code": null, "e": 6468, "s": 6264, "text": "The line property doesn’t make much sense because we usually recognize London Tube lines by their names or colors. The map will be more confusing than helpful unless you add a name property to the edges." }, { "code": null, "e": 6746, "s": 6468, "text": "The following Cypher query uses the CASE expression which allows multiple predicates to be listed. The first one that evaluates to true is matched, and the result of the expression provided after the THEN keyword is used to set the value of the name property on a relationship." }, { "code": null, "e": 7298, "s": 6746, "text": "MATCH (n)-[r]-(m)SET r.name = CASEWHEN r.line = 1 THEN \"Bakerloo Line\"WHEN r.line = 2 THEN \"Central Line\"WHEN r.line = 3 THEN \"Circle Line\"WHEN r.line = 4 THEN \"District Line\"WHEN r.line = 5 THEN \"East London Line\"WHEN r.line = 6 THEN \"Hammersmith & City Line\"WHEN r.line = 7 THEN \"Jubilee Line\"WHEN r.line = 8 THEN \"Metropolitan Line\"WHEN r.line = 9 THEN \"Northern Line\"WHEN r.line = 10 THEN \"Piccadilly Line\"WHEN r.line = 11 THEN \"Victoria Line\"WHEN r.line = 12 THEN \"Waterloo & City Line\"WHEN r.line = 13 THEN \"Docklands Light Railway\"END;" }, { "code": null, "e": 7533, "s": 7298, "text": "While the dataset makes much more sense now, the styling of the map is still a bit too uniform. You can style the map to your liking by using the Style editor in Memgraph Lab. You can read more about the style editor in this tutorial." }, { "code": null, "e": 7766, "s": 7533, "text": "First, let’s make stations smaller and shaped like squares. A white circle with a black border is reserved for interchange stations (where you can switch between lines). To accomplish this, you will use the following styling script:" }, { "code": null, "e": 8179, "s": 7766, "text": "@NodeStyle HasLabel?(node, \"Station\") { size: 15 color: black shape: \"square\" color-hover: red color-selected: Darker(red)}@NodeStyle Greater?(Property(node, \"total_lines\"), 1) { size: 30 shape: \"dot\" border-width: 2 border-color: black color: white color-hover: red color-selected: Darker(red)}@NodeStyle HasProperty?(node, \"name\") { label: AsText(Property(node, \"name\"))}" }, { "code": null, "e": 8292, "s": 8179, "text": "Now you can add the most important thing, the iconic line colors! To do this, you will use the following script:" }, { "code": null, "e": 9190, "s": 8292, "text": "@EdgeStyle HasProperty?(edge, \"name\") { label: AsText(Property(edge, \"name\")) width: 10}@EdgeStyle Equals?(Property(edge, \"line\"),1) {color: #AE6017}@EdgeStyle Equals?(Property(edge, \"line\"),2) {color: #F15B2E}@EdgeStyle Equals?(Property(edge, \"line\"),3) {color: #FFE02B}@EdgeStyle Equals?(Property(edge, \"line\"),4) {color: #00A166} @EdgeStyle Equals?(Property(edge, \"line\"),5) {color: #FBAE34}@EdgeStyle Equals?(Property(edge, \"line\"),6) {color: #F491A8}@EdgeStyle Equals?(Property(edge, \"line\"),7) {color: #949699}@EdgeStyle Equals?(Property(edge, \"line\"),8) {color: #91005A}@EdgeStyle Equals?(Property(edge, \"line\"),9) {color: #000000}@EdgeStyle Equals?(Property(edge, \"line\"),10) {color: #094FA3}@EdgeStyle Equals?(Property(edge, \"line\"),11) {color: #0A9CDA}@EdgeStyle Equals?(Property(edge, \"line\"),12) {color: #88D0C4}@EdgeStyle Equals?(Property(edge, \"line\"),13) {color: #00A77E}" }, { "code": null, "e": 9228, "s": 9190, "text": "Your graph should now look like this:" }, { "code": null, "e": 9425, "s": 9228, "text": "Now that you have your graph data loaded into Memgraph and visualizations set up in Memgraph Lab, you are ready to start exploring the London Tube network by using graph traversals and algorithms." }, { "code": null, "e": 9514, "s": 9425, "text": "Let’s say you’re planning a trip and want to find a hotel near a well-connected station." }, { "code": null, "e": 9625, "s": 9514, "text": "By using the following Cypher query, you will find which stations have the most connections to other stations:" }, { "code": null, "e": 9828, "s": 9625, "text": "MATCH (s1:Station)-[:Connection]->(s2:Station)WITH DISTINCT s2.name as adjacent, s1.name as nameRETURN name AS Station_name, COUNT(adjacent) AS Total_connectionsORDER BY Total_connections DESC LIMIT 10;" }, { "code": null, "e": 10012, "s": 9828, "text": "For every station, the first part of the query matches all stations that are one degree apart. The second part counts connections and returns a list of the 10 most connected stations." }, { "code": null, "e": 10203, "s": 10012, "text": "Now that you have your list, King’s Cross St. Pancras is the obvious choice. You can easily check what Tube lines you can access from King’s Cross St. Pancras by running the following query:" }, { "code": null, "e": 10309, "s": 10203, "text": "MATCH (:Station {name:\"King's Cross St. Pancras\"})-[r]-(:Station)WITH DISTINCT r.name AS lineRETURN line;" }, { "code": null, "e": 10580, "s": 10309, "text": "Let’s say you’re traveling on a budget and you want to stay in the first fare zone to keep your transportation cost low. In this case, you can use the Breadth-First algorithm to find out what stations you can get to from St. Pancras while staying in the first fare zone:" }, { "code": null, "e": 10798, "s": 10580, "text": "MATCH p = (s1:Station {name:\"King's Cross St. Pancras\"}) -[:Connection * bfs (e, n | n.zone = 1)]- (s2:Station) UNWIND (nodes(p)) as rowsWITH DISTINCT rows.name as Station RETURN Station LIMIT 10;" }, { "code": null, "e": 11119, "s": 10798, "text": "(e, n | n.zone = 1) is called a filter lambda. It’s a function that takes an edge symbol e and a node symbol n and decides whether this edge and node pair should be considered valid in breadth-first expansion by returning true or false. In this example, the lambda is returning true if station is in the first fare zone." }, { "code": null, "e": 11221, "s": 11119, "text": "Or if you are more of a visual person, you can visualize your results by running the following query:" }, { "code": null, "e": 11356, "s": 11221, "text": "MATCH p = (:Station {name:\"King's Cross St. Pancras\"}) -[:Connection * bfs (e, n | n.zone = 1)]- (:Station)RETURN p;" }, { "code": null, "e": 11593, "s": 11356, "text": "Let’s say you have just arrived at London Heathrow airport. You are probably tired and in desperate need of a shower and nap but you’d love to stop by Big Ben, which is located at the Westminster tube station, on your way to your hotel." }, { "code": null, "e": 11666, "s": 11593, "text": "Lucky for you, Memgraph can help you find the quickest route in no time!" }, { "code": null, "e": 12185, "s": 11666, "text": "Pathfinding algorithms are one of the classical graph problems and have been researched since the 19th century. The Shortest Path algorithm calculates a path between two nodes in a graph such that the total sum of the edge weights is minimized.The syntax here is similar to breadth-first search syntax. Instead of a filter lambda, we need to provide a weight lambda and the total weight symbol. Given an edge and node pair, weight lambda must return the cost (time) of expanding to the given node using the given edge." }, { "code": null, "e": 12357, "s": 12185, "text": "MATCH p = (s1:Station {name: \"Heathrow Terminal 4\"}) -[edge_list:Connection *wShortest (e, n | e.time) time]- (s2:Station {name: \"Westminster\"})RETURN *;" }, { "code": null, "e": 12588, "s": 12357, "text": "This route will get you from Heathrow to Westminster in 43 minutes, but there are delays on Circle and District lines, so you want exclude them from the search. You can combine weight and filter lambdas in the shortest-path query:" }, { "code": null, "e": 12823, "s": 12588, "text": "MATCH p = (s1:Station {name: \"Heathrow Terminal 4\"}) -[edge_list:Connection *wShortest (e, n | e.time) time (e, n | e.name != \"Circle Line\" AND e.name != \"District Line\")]- (s2:Station {name: \"Westminster\"})RETURN *;" }, { "code": null, "e": 12888, "s": 12823, "text": "The new route is only 3 minutes longer, but you’ll avoid delays." }, { "code": null, "e": 13011, "s": 12888, "text": "And the shortest route from Westminster will get you to the hotel in 10 minutes (with Circle and District lines excluded)." }, { "code": null, "e": 13251, "s": 13011, "text": "MATCH p = (s1:Station {name: \"Westminster\"}) -[edge_list:Connection *wShortest (e, n | e.time) time (e, n | e.name != \"Circle Line\" AND e.name != \"District Line\")]- (s2:Station {name: \"King's Cross St. Pancras\"})RETURN *;" }, { "code": null, "e": 13501, "s": 13251, "text": "It is surprising how many of London’s museums and galleries are free to visit. The British Museum should definitely be your first choice! Although you can spend hours there, you want to see a little bit of everything so let’s add a few more options." }, { "code": null, "e": 13826, "s": 13501, "text": "Tottenham Court Road station is nearest to the British Museum and it will be your first stop. South Kensington station is within walking distance of three amazing museums: Science Museum, Natural History Museum, and Victoria and Albert Museum. To find the optimal route for your trip, you can use the following Cypher query:" }, { "code": null, "e": 14134, "s": 13826, "text": "MATCH p = (:Station {name: \"King's Cross St. Pancras\"}) -[:Connection *wShortest (e, n | e.time) time1]- (:Station {name: \"Tottenham Court Road\"}) -[:Connection *wShortest (e, n | e.time) time2]- (:Station {name: \"South Kensington\"})RETURN p, time1 + time2 AS total_time;" }, { "code": null, "e": 14556, "s": 14134, "text": "In this tutorial, you learned how to use Memgraph and Cypher to model and navigate a complex transportation network. With the help of graph algorithms, you found the optimal routes and learned how to visualize data using Memgraph Lab to get the most out of it. If you are interested in exploring another graph route planning tutorial, you can check out the Exploring the European Road Network demo on Memgraph Playground." }, { "code": null, "e": 14579, "s": 14556, "text": "A friend once told me:" }, { "code": null, "e": 14683, "s": 14579, "text": "“You can never get lost in London, you just have to find a Tube station and you’ll know where you are.”" }, { "code": null, "e": 14696, "s": 14683, "text": "I would say:" }, { "code": null, "e": 14790, "s": 14696, "text": "“You can never get lost in London, you just have to use Memgraph and find the shortest path!”" } ]
Prophet-able Forecasting. Getting started with Prophet... | by Werlindo Mangrobang | Towards Data Science
If you google “time-series forecasting”, most of the first search results you’ll get will involve autoregressive integrated moving average modeling (ARIMA) or exponential smoothing (ETS). And with good reason! There are popular options available for performing applying these time-series forecasting methods, both in R and Python. One of the first forecasting tools I started playing around with are the ARIMA and ETS models in the forecast package in R, led by the influential Rob Hyndman. One of the most gee-whiz options in forecast is to use auto.arima. The name says it all; it will 'automatically' determine a best-fit ARIMA model, based on the selected information criterion (AIC, BIC, or AICc). Time-series forecasting made easy! These days, though, I prefer to use Python. And with another quick google search, I spot a potential Python analog. But for this post, I’d like to spend our time getting to know another forecasting Python library: Prophet. Introduced in 2017, Prophet is a forecasting library developed by Facebook, with implementations in R and Python. It was developed with two goals in mind: First, to create scalable, high-quality forecasts for the business, and second, to have a rigorous methodology behind the scenes, but have its parameter levers be intuitive enough for traditional business analysts to adjust. For this post we will be doing a brisk stream-of-consciousness-esque quick-start tutorial: Installing in Python Setting up the data Fitting the model and predicting Inspecting the results Let’s do this! If some of the following is a little terse for your taste, I simply followed directions on Prophet’s installation guide. Also, I’m on a Mac, so YMMV with the following if you’re on Windows, etc. I went to the Installation page on the project’s github.io site and followed the directions for Python. As mentioned there, the library has a major dependency on pystan. On my first attempt, I actually missed the part where it says to pip install pystan first before pip installing fbprophet (the actual name of the Python library). Of course, I DID THE EXACT OPPOSITE, and things were NOT HAPPY. BUT: I’m also on the Anaconda distribution of Python, so I was able to eventually get everything working by simply following the Anaconda instructions: In terminal: conda install gcc ...and then following any prompts accordingly. Once that’s done, do the following:install -c conda-forge fbprophet Phew! That was close. I was afraid this post was going to end right here. The project site also provides a very clear Quick Start that I ran through to sniff-test that everything worked as intended. I’ll leave it up to you, dear reader, to do the same, and highly encourage it. One can never get enough reps. What I will walk through, though, is another dataset of my choosing, to start getting used to the API. For this first dataset, we are looking at a dataset on bike share trips in Los Angeles. I pulled down a .csv from Kaggle. Don't tell anyone, but I believe I'm the first person to have ever thought of that. Just kidding! Seriously though, I would have loved to have scraped something, but ran out of time. So Kaggle it is. You can find the data here. If you have the Kaggle API installed you can just download directly to your folder of choice by copying the API command: and then pasting into terminal and running it, like so:kaggle datasets download -d cityofLA/los-angeles-metro-bike-share-trip-data Another YMMV-type blocker: I then had issues with the downloaded file’s permissions when I tried to unzip it. But I resolved it by:chmod 600 los-angeles-metro-bike-share-trip-data.zip ..which gave me full read/write permissions on the file. Then I was able to unzip it:unzip los-angeles-metro-bike-share-trip-data.zip OK! Let’s set up the dataframe for running through the Prophet object. Note that the model is expecting very specific column names and types; to quote: The input to Prophet is always a dataframe with two columns: ds and y. The ds (datestamp) column should be of a format expected by Pandas, ideally YYYY-MM-DD for a date or YYYY-MM-DD HH:MM:SS for a timestamp. The y column must be numeric, and represents the measurement we wish to forecast. Full Jupyter notebook of all the code is available at this GitHub repository (complete with all my false starts!) but a cleaned up version is as follows: import pandas as pd # Dataframes. import plotly_express as px # Plotting.# Get datasetbikes = pd.read_csv('./data/metro-bike-share-trip-data.csv')# Start time is string, convert to databikes['ds'] = pd.to_datetime( bikes['Start Time'].apply(lambda st : st[:10]) , format='%Y-%m-%d')# Aggregate by trip start datetrips = bikes.groupby(['ds']).agg( {'Trip ID': 'count'}).reset_index()# Rename columnstrips.columns = ['ds', 'y'] # Column names required by fbprophet API# Plot: reasonability check px.scatter(trips ,x='ds' ,y='y' ,title='LA Daily Bike Share Trips - Jul 16 to Apr 17' ,labels={'y':'Trips','ds':'Day'}) Next, we’ll run through an example of running a forecast: Fitting the model Predicting on our model First, let’s instantiate our model and fit it on our dataset: from fbprophet import Prophet #Importing here for visibility# Create Prophet object and fitm_bikes = Prophet(yearly_seasonality=True , weekly_seasonality=True) #All defaultsm_bikes.fit(trips) The object Prophet has many parameters that can be set to tune the model. For example, seasonality settings such as daily_seasonality, weekly_seasonality, and yearly_seasonality are just some of the options that can be tuned. For example, I think there might be some weekly and/or yearly patterns for bike-share rentals. For fun, let’s see what happens if we set weekly_seasonality and yearly_seasonalityto True. Next, we can then perform predictions using the model. the Prophet object has a handy method calledmake_future_dataframe that can create a dataframe with a specified number of future dates, relative to the training data (days is the default periods). For example, below we tack on 60 days after our training data’s last day. # Create dataframe with appended future datesfuture = m_bikes.make_future_dataframe(periods=60) #Days is defaultfuture.tail() Once, that dataframe is set up, we can then run predictions on that ‘test’ set: # Forecast on future dates forecast = m_bikes.predict(future)# Look at prediction and prediction intervalforecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail() We already got a sneak preview into the predictions by looking at the tail of the forecast dataframe we created. Let’s visualize it though to get the big picture. It just so happens that our Prophet object also includes a plot method to do just that! Here’s the plot of the fit/forecast (line (y_hat) and shaded area (prediction interval)) versus the actuals (scatter): # Plot the forecast vs actualsm_bikes.plot(forecast) In addition, there are plots for the forecast components as well! For example, since we explicitly set weekly_seasonality and yearly_seasonalityto True, there will be component plots specifically for them: We could definitely use more historical data, but if we take these plots at face value, it appears there is a late summer spike in trips, and then it gradually dips over the fall. Furthermore, during the week, peak riding seemed to happen mid to late weekdays. That might not completely pass the sniff-test of my anecdotal observations if these were Seattle bike-shares, but hey, L.A. is probably a completely different market. The point is though we were able to create some decent forecasts in a short amount of time! If we had more time to dive in more we could start looking at the aforementioned parameters to further tune the forecasts. These include not only seasonality for different periods, but specific holiday effects, providing specific changepoints for trend (e.g.you don’t have a perfectly linear baseline trend, such as in the example above), accounting for saturation points, and more. Again, details can be found in the documentation, and I would highly encourage reading the white paper to gain a deeper understanding of the underlying methodologies. That’s all we have time for, I hope this has been useful. Thanks for reading! Work files here. Please feel free to reach out! | LinkedIn | GitHub Sources: https://facebook.github.io/prophet/ Taylor SJ, Letham B. 2017. Forecasting at scale. PeerJ Preprints 5:e3190v2 https://doi.org/10.7287/peerj.preprints.3190v2
[ { "code": null, "e": 663, "s": 172, "text": "If you google “time-series forecasting”, most of the first search results you’ll get will involve autoregressive integrated moving average modeling (ARIMA) or exponential smoothing (ETS). And with good reason! There are popular options available for performing applying these time-series forecasting methods, both in R and Python. One of the first forecasting tools I started playing around with are the ARIMA and ETS models in the forecast package in R, led by the influential Rob Hyndman." }, { "code": null, "e": 910, "s": 663, "text": "One of the most gee-whiz options in forecast is to use auto.arima. The name says it all; it will 'automatically' determine a best-fit ARIMA model, based on the selected information criterion (AIC, BIC, or AICc). Time-series forecasting made easy!" }, { "code": null, "e": 1133, "s": 910, "text": "These days, though, I prefer to use Python. And with another quick google search, I spot a potential Python analog. But for this post, I’d like to spend our time getting to know another forecasting Python library: Prophet." }, { "code": null, "e": 1513, "s": 1133, "text": "Introduced in 2017, Prophet is a forecasting library developed by Facebook, with implementations in R and Python. It was developed with two goals in mind: First, to create scalable, high-quality forecasts for the business, and second, to have a rigorous methodology behind the scenes, but have its parameter levers be intuitive enough for traditional business analysts to adjust." }, { "code": null, "e": 1604, "s": 1513, "text": "For this post we will be doing a brisk stream-of-consciousness-esque quick-start tutorial:" }, { "code": null, "e": 1625, "s": 1604, "text": "Installing in Python" }, { "code": null, "e": 1645, "s": 1625, "text": "Setting up the data" }, { "code": null, "e": 1678, "s": 1645, "text": "Fitting the model and predicting" }, { "code": null, "e": 1701, "s": 1678, "text": "Inspecting the results" }, { "code": null, "e": 1716, "s": 1701, "text": "Let’s do this!" }, { "code": null, "e": 1911, "s": 1716, "text": "If some of the following is a little terse for your taste, I simply followed directions on Prophet’s installation guide. Also, I’m on a Mac, so YMMV with the following if you’re on Windows, etc." }, { "code": null, "e": 2308, "s": 1911, "text": "I went to the Installation page on the project’s github.io site and followed the directions for Python. As mentioned there, the library has a major dependency on pystan. On my first attempt, I actually missed the part where it says to pip install pystan first before pip installing fbprophet (the actual name of the Python library). Of course, I DID THE EXACT OPPOSITE, and things were NOT HAPPY." }, { "code": null, "e": 2313, "s": 2308, "text": "BUT:" }, { "code": null, "e": 2460, "s": 2313, "text": "I’m also on the Anaconda distribution of Python, so I was able to eventually get everything working by simply following the Anaconda instructions:" }, { "code": null, "e": 2473, "s": 2460, "text": "In terminal:" }, { "code": null, "e": 2491, "s": 2473, "text": "conda install gcc" }, { "code": null, "e": 2538, "s": 2491, "text": "...and then following any prompts accordingly." }, { "code": null, "e": 2606, "s": 2538, "text": "Once that’s done, do the following:install -c conda-forge fbprophet" }, { "code": null, "e": 2680, "s": 2606, "text": "Phew! That was close. I was afraid this post was going to end right here." }, { "code": null, "e": 3018, "s": 2680, "text": "The project site also provides a very clear Quick Start that I ran through to sniff-test that everything worked as intended. I’ll leave it up to you, dear reader, to do the same, and highly encourage it. One can never get enough reps. What I will walk through, though, is another dataset of my choosing, to start getting used to the API." }, { "code": null, "e": 3340, "s": 3018, "text": "For this first dataset, we are looking at a dataset on bike share trips in Los Angeles. I pulled down a .csv from Kaggle. Don't tell anyone, but I believe I'm the first person to have ever thought of that. Just kidding! Seriously though, I would have loved to have scraped something, but ran out of time. So Kaggle it is." }, { "code": null, "e": 3368, "s": 3340, "text": "You can find the data here." }, { "code": null, "e": 3489, "s": 3368, "text": "If you have the Kaggle API installed you can just download directly to your folder of choice by copying the API command:" }, { "code": null, "e": 3620, "s": 3489, "text": "and then pasting into terminal and running it, like so:kaggle datasets download -d cityofLA/los-angeles-metro-bike-share-trip-data" }, { "code": null, "e": 3804, "s": 3620, "text": "Another YMMV-type blocker: I then had issues with the downloaded file’s permissions when I tried to unzip it. But I resolved it by:chmod 600 los-angeles-metro-bike-share-trip-data.zip" }, { "code": null, "e": 3938, "s": 3804, "text": "..which gave me full read/write permissions on the file. Then I was able to unzip it:unzip los-angeles-metro-bike-share-trip-data.zip" }, { "code": null, "e": 4090, "s": 3938, "text": "OK! Let’s set up the dataframe for running through the Prophet object. Note that the model is expecting very specific column names and types; to quote:" }, { "code": null, "e": 4381, "s": 4090, "text": "The input to Prophet is always a dataframe with two columns: ds and y. The ds (datestamp) column should be of a format expected by Pandas, ideally YYYY-MM-DD for a date or YYYY-MM-DD HH:MM:SS for a timestamp. The y column must be numeric, and represents the measurement we wish to forecast." }, { "code": null, "e": 4535, "s": 4381, "text": "Full Jupyter notebook of all the code is available at this GitHub repository (complete with all my false starts!) but a cleaned up version is as follows:" }, { "code": null, "e": 5285, "s": 4535, "text": "import pandas as pd # Dataframes. import plotly_express as px # Plotting.# Get datasetbikes = pd.read_csv('./data/metro-bike-share-trip-data.csv')# Start time is string, convert to databikes['ds'] = pd.to_datetime( bikes['Start Time'].apply(lambda st : st[:10]) , format='%Y-%m-%d')# Aggregate by trip start datetrips = bikes.groupby(['ds']).agg( {'Trip ID': 'count'}).reset_index()# Rename columnstrips.columns = ['ds', 'y'] # Column names required by fbprophet API# Plot: reasonability check px.scatter(trips ,x='ds' ,y='y' ,title='LA Daily Bike Share Trips - Jul 16 to Apr 17' ,labels={'y':'Trips','ds':'Day'})" }, { "code": null, "e": 5343, "s": 5285, "text": "Next, we’ll run through an example of running a forecast:" }, { "code": null, "e": 5361, "s": 5343, "text": "Fitting the model" }, { "code": null, "e": 5385, "s": 5361, "text": "Predicting on our model" }, { "code": null, "e": 5447, "s": 5385, "text": "First, let’s instantiate our model and fit it on our dataset:" }, { "code": null, "e": 5673, "s": 5447, "text": "from fbprophet import Prophet #Importing here for visibility# Create Prophet object and fitm_bikes = Prophet(yearly_seasonality=True , weekly_seasonality=True) #All defaultsm_bikes.fit(trips)" }, { "code": null, "e": 6086, "s": 5673, "text": "The object Prophet has many parameters that can be set to tune the model. For example, seasonality settings such as daily_seasonality, weekly_seasonality, and yearly_seasonality are just some of the options that can be tuned. For example, I think there might be some weekly and/or yearly patterns for bike-share rentals. For fun, let’s see what happens if we set weekly_seasonality and yearly_seasonalityto True." }, { "code": null, "e": 6411, "s": 6086, "text": "Next, we can then perform predictions using the model. the Prophet object has a handy method calledmake_future_dataframe that can create a dataframe with a specified number of future dates, relative to the training data (days is the default periods). For example, below we tack on 60 days after our training data’s last day." }, { "code": null, "e": 6537, "s": 6411, "text": "# Create dataframe with appended future datesfuture = m_bikes.make_future_dataframe(periods=60) #Days is defaultfuture.tail()" }, { "code": null, "e": 6617, "s": 6537, "text": "Once, that dataframe is set up, we can then run predictions on that ‘test’ set:" }, { "code": null, "e": 6782, "s": 6617, "text": "# Forecast on future dates forecast = m_bikes.predict(future)# Look at prediction and prediction intervalforecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()" }, { "code": null, "e": 6945, "s": 6782, "text": "We already got a sneak preview into the predictions by looking at the tail of the forecast dataframe we created. Let’s visualize it though to get the big picture." }, { "code": null, "e": 7152, "s": 6945, "text": "It just so happens that our Prophet object also includes a plot method to do just that! Here’s the plot of the fit/forecast (line (y_hat) and shaded area (prediction interval)) versus the actuals (scatter):" }, { "code": null, "e": 7205, "s": 7152, "text": "# Plot the forecast vs actualsm_bikes.plot(forecast)" }, { "code": null, "e": 7411, "s": 7205, "text": "In addition, there are plots for the forecast components as well! For example, since we explicitly set weekly_seasonality and yearly_seasonalityto True, there will be component plots specifically for them:" }, { "code": null, "e": 7931, "s": 7411, "text": "We could definitely use more historical data, but if we take these plots at face value, it appears there is a late summer spike in trips, and then it gradually dips over the fall. Furthermore, during the week, peak riding seemed to happen mid to late weekdays. That might not completely pass the sniff-test of my anecdotal observations if these were Seattle bike-shares, but hey, L.A. is probably a completely different market. The point is though we were able to create some decent forecasts in a short amount of time!" }, { "code": null, "e": 8481, "s": 7931, "text": "If we had more time to dive in more we could start looking at the aforementioned parameters to further tune the forecasts. These include not only seasonality for different periods, but specific holiday effects, providing specific changepoints for trend (e.g.you don’t have a perfectly linear baseline trend, such as in the example above), accounting for saturation points, and more. Again, details can be found in the documentation, and I would highly encourage reading the white paper to gain a deeper understanding of the underlying methodologies." }, { "code": null, "e": 8559, "s": 8481, "text": "That’s all we have time for, I hope this has been useful. Thanks for reading!" }, { "code": null, "e": 8576, "s": 8559, "text": "Work files here." }, { "code": null, "e": 8627, "s": 8576, "text": "Please feel free to reach out! | LinkedIn | GitHub" }, { "code": null, "e": 8636, "s": 8627, "text": "Sources:" }, { "code": null, "e": 8672, "s": 8636, "text": "https://facebook.github.io/prophet/" } ]
Hands-on guide to Python Optimal Transport toolbox: Part 1 | by Aurelie Boisbunon | Towards Data Science
As a follow-up of the introductory article on optimal transport by Ievgen Redko, I will present below how you can solve Optimal Transport (OT) in practice using the Python Optimal Transport (POT) toolbox. To start with, let us install POT using pip from the terminal by simply running pip3 install pot Or with conda conda install -c conda-forge pot If everything went well, you now have POT installed and ready to use on your computer. import numpy as np # always need itimport scipy as sp # often use itimport pylab as pl # do the plotsimport ot # ot The online documentation of POT is available at http://pot.readthedocs.io, or you can check the inline help help(ot.dist) . We are now ready to start our example. We will solve the Bakery/Cafés problem of transporting croissants from a number of Bakeries to Cafés in a City (in this case Manhattan). We did a quick google map search in Manhattan for bakeries and Cafés: We extracted from this search their positions and generated fictional production and sale number (that both sum to the same value). We have access to the position of Bakeries bakery_pos and their respective production bakery_prod which describe the source distribution. The Cafés where the croissants are sold are defined also by their position cafe_pos and cafe_prod, and describe the target distribution. Now we load the data data = np.load('https://github.com/PythonOT/POT/raw/master/data/manhattan.npz')bakery_pos = data['bakery_pos']bakery_prod = data['bakery_prod']cafe_pos = data['cafe_pos']cafe_prod = data['cafe_prod']Imap = data['Imap']print('Bakery production: {}'.format(bakery_prod))print('Cafe sale: {}'.format(cafe_prod))print('Total croissants : {}'.format(cafe_prod.sum())) This gives: Bakery production: [31. 48. 82. 30. 40. 48. 89. 73.]Cafe sale: [82. 88. 92. 88. 91.]Total croissants : 441.0 Next, we plot the position of the bakeries and cafés on the map. The size of the circle is proportional to their production. We can now compute a cost matrix between the bakeries and the cafés, which will be the transport cost matrix. This can be done using the ot.dist function that defaults to squared Euclidean distance but can return other things such as cityblock (or Manhattan distance). M = ot.dist(bakery_pos, cafe_pos) The red cells in the matrix image show the bakeries and cafés that are further away, and thus more costly to transport from one to the other, while the blue ones show those that are very close to each other, with respect to the squared Euclidean distance. We now come to the problem itself, which is to find an optimal solution to the problem of transporting croissants from bakeries to cafés. In order to do that, let’s see a little bit of maths. The aim is to find the transport matrix gamma such that where M is the cost matrix, and a and b are respectively the sample weights for source and target. So, what it means, is that we take into account the cost of transporting croissants from a bakery to a café through M, and we want the sum of each line of gamma to be the number of croissants the corresponding bakery has to sell, and the sum of each column to be the number of croissants the corresponding cafés needs. Hence, each element of the transport matrix will correspond to the number of croissants that a bakery has to send to a café. This problem is called Earth Mover’s distance, or EMD, also known as discrete Wasserstein distance. Let’s see what it gives on our example. gamma_emd = ot.emd(bakery_prod, cafe_prod, M) The graph below (left) show the transport from a bakery to a café, with the width of the line proportional to the number of croissants to be transported. On the right, we can see the transport matrix with the exact values. We can see that the bakeries only need to transport croissants to one or two cafés, the transport matrix being very sparse. One issue with EMD is that its algorithmic complexity is in O(n3log(n)), n being the largest dimension between source and target. In our example, n is small, so it is OK to use EMD, but for larger values of n we might want to look into other options. As is often the case when an algorithm is long to compute, we can regularize it in order to obtain a solution to a simpler or faster problem. The Sinkhorn algorithm does that by adding an entropic regularization term and thus solves the following problem. where reg is an hyperparameter and Omega is the entropic regularization term defined by: The Sinkhorn algorithm is very simple to code. You can implement it directly using the following pseudo-code: Be careful of numerical problems. A good pre-processing for Sinkhorn is to divide the cost matrix M by its maximum value. reg = 0.1K = np.exp(-M / M.max() / reg)nit = 100u = np.ones((len(bakery_prod), ))for i in range(1, nit): v = cafe_prod / np.dot(K.T, u) u = bakery_prod / (np.dot(K, v))gamma_sink_algo = np.atleast_2d(u).T * (K * v.T) # Equivalent to np.dot(np.diag(u), np.dot(K, np.diag(v))) An alternative is to use the POT toolbox with ot.sinkhorn: gamma_sinkhorn = ot.sinkhorn(bakery_prod, cafe_prod, reg=reg, M=M/M.max()) When plotting the resulting transport matrix, we notice right away that it is not sparse at all with Sinkhorn, each bakery delivering croissants to all 5 cafés with that solution. Also, this solution gives a transport with fractions, which does not make sense in the case of croissants. This was not the case with EMD. Obviously, the regularization hyperparameter reg of Sinkhorn plays an important role. Let’s see with the following graphs how it impacts the transport matrix by looking at different values. This series of graphs shows that the solution of Sinkhorn starts with something very similar to EMD (although not sparse) for very small values of the regularization parameter reg, and tends to a more uniform solution as reg increases. This first part showed a simple example for applying Optimal Transport with POT library. Optimal Transport is a powerful tool that can be applied in many ways, as discussed in Part 2 by Ievgen Redko.
[ { "code": null, "e": 377, "s": 172, "text": "As a follow-up of the introductory article on optimal transport by Ievgen Redko, I will present below how you can solve Optimal Transport (OT) in practice using the Python Optimal Transport (POT) toolbox." }, { "code": null, "e": 457, "s": 377, "text": "To start with, let us install POT using pip from the terminal by simply running" }, { "code": null, "e": 474, "s": 457, "text": "pip3 install pot" }, { "code": null, "e": 488, "s": 474, "text": "Or with conda" }, { "code": null, "e": 521, "s": 488, "text": "conda install -c conda-forge pot" }, { "code": null, "e": 608, "s": 521, "text": "If everything went well, you now have POT installed and ready to use on your computer." }, { "code": null, "e": 724, "s": 608, "text": "import numpy as np # always need itimport scipy as sp # often use itimport pylab as pl # do the plotsimport ot # ot" }, { "code": null, "e": 848, "s": 724, "text": "The online documentation of POT is available at http://pot.readthedocs.io, or you can check the inline help help(ot.dist) ." }, { "code": null, "e": 887, "s": 848, "text": "We are now ready to start our example." }, { "code": null, "e": 1097, "s": 887, "text": "We will solve the Bakery/Cafés problem of transporting croissants from a number of Bakeries to Cafés in a City (in this case Manhattan). We did a quick google map search in Manhattan for bakeries and Cafés:" }, { "code": null, "e": 1229, "s": 1097, "text": "We extracted from this search their positions and generated fictional production and sale number (that both sum to the same value)." }, { "code": null, "e": 1505, "s": 1229, "text": "We have access to the position of Bakeries bakery_pos and their respective production bakery_prod which describe the source distribution. The Cafés where the croissants are sold are defined also by their position cafe_pos and cafe_prod, and describe the target distribution." }, { "code": null, "e": 1526, "s": 1505, "text": "Now we load the data" }, { "code": null, "e": 1889, "s": 1526, "text": "data = np.load('https://github.com/PythonOT/POT/raw/master/data/manhattan.npz')bakery_pos = data['bakery_pos']bakery_prod = data['bakery_prod']cafe_pos = data['cafe_pos']cafe_prod = data['cafe_prod']Imap = data['Imap']print('Bakery production: {}'.format(bakery_prod))print('Cafe sale: {}'.format(cafe_prod))print('Total croissants : {}'.format(cafe_prod.sum()))" }, { "code": null, "e": 1901, "s": 1889, "text": "This gives:" }, { "code": null, "e": 2010, "s": 1901, "text": "Bakery production: [31. 48. 82. 30. 40. 48. 89. 73.]Cafe sale: [82. 88. 92. 88. 91.]Total croissants : 441.0" }, { "code": null, "e": 2136, "s": 2010, "text": "Next, we plot the position of the bakeries and cafés on the map. The size of the circle is proportional to their production." }, { "code": null, "e": 2406, "s": 2136, "text": "We can now compute a cost matrix between the bakeries and the cafés, which will be the transport cost matrix. This can be done using the ot.dist function that defaults to squared Euclidean distance but can return other things such as cityblock (or Manhattan distance)." }, { "code": null, "e": 2440, "s": 2406, "text": "M = ot.dist(bakery_pos, cafe_pos)" }, { "code": null, "e": 2697, "s": 2440, "text": "The red cells in the matrix image show the bakeries and cafés that are further away, and thus more costly to transport from one to the other, while the blue ones show those that are very close to each other, with respect to the squared Euclidean distance." }, { "code": null, "e": 2890, "s": 2697, "text": "We now come to the problem itself, which is to find an optimal solution to the problem of transporting croissants from bakeries to cafés. In order to do that, let’s see a little bit of maths." }, { "code": null, "e": 2946, "s": 2890, "text": "The aim is to find the transport matrix gamma such that" }, { "code": null, "e": 3045, "s": 2946, "text": "where M is the cost matrix, and a and b are respectively the sample weights for source and target." }, { "code": null, "e": 3492, "s": 3045, "text": "So, what it means, is that we take into account the cost of transporting croissants from a bakery to a café through M, and we want the sum of each line of gamma to be the number of croissants the corresponding bakery has to sell, and the sum of each column to be the number of croissants the corresponding cafés needs. Hence, each element of the transport matrix will correspond to the number of croissants that a bakery has to send to a café." }, { "code": null, "e": 3592, "s": 3492, "text": "This problem is called Earth Mover’s distance, or EMD, also known as discrete Wasserstein distance." }, { "code": null, "e": 3632, "s": 3592, "text": "Let’s see what it gives on our example." }, { "code": null, "e": 3678, "s": 3632, "text": "gamma_emd = ot.emd(bakery_prod, cafe_prod, M)" }, { "code": null, "e": 4027, "s": 3678, "text": "The graph below (left) show the transport from a bakery to a café, with the width of the line proportional to the number of croissants to be transported. On the right, we can see the transport matrix with the exact values. We can see that the bakeries only need to transport croissants to one or two cafés, the transport matrix being very sparse." }, { "code": null, "e": 4278, "s": 4027, "text": "One issue with EMD is that its algorithmic complexity is in O(n3log(n)), n being the largest dimension between source and target. In our example, n is small, so it is OK to use EMD, but for larger values of n we might want to look into other options." }, { "code": null, "e": 4534, "s": 4278, "text": "As is often the case when an algorithm is long to compute, we can regularize it in order to obtain a solution to a simpler or faster problem. The Sinkhorn algorithm does that by adding an entropic regularization term and thus solves the following problem." }, { "code": null, "e": 4623, "s": 4534, "text": "where reg is an hyperparameter and Omega is the entropic regularization term defined by:" }, { "code": null, "e": 4733, "s": 4623, "text": "The Sinkhorn algorithm is very simple to code. You can implement it directly using the following pseudo-code:" }, { "code": null, "e": 4855, "s": 4733, "text": "Be careful of numerical problems. A good pre-processing for Sinkhorn is to divide the cost matrix M by its maximum value." }, { "code": null, "e": 5137, "s": 4855, "text": "reg = 0.1K = np.exp(-M / M.max() / reg)nit = 100u = np.ones((len(bakery_prod), ))for i in range(1, nit): v = cafe_prod / np.dot(K.T, u) u = bakery_prod / (np.dot(K, v))gamma_sink_algo = np.atleast_2d(u).T * (K * v.T) # Equivalent to np.dot(np.diag(u), np.dot(K, np.diag(v)))" }, { "code": null, "e": 5196, "s": 5137, "text": "An alternative is to use the POT toolbox with ot.sinkhorn:" }, { "code": null, "e": 5271, "s": 5196, "text": "gamma_sinkhorn = ot.sinkhorn(bakery_prod, cafe_prod, reg=reg, M=M/M.max())" }, { "code": null, "e": 5591, "s": 5271, "text": "When plotting the resulting transport matrix, we notice right away that it is not sparse at all with Sinkhorn, each bakery delivering croissants to all 5 cafés with that solution. Also, this solution gives a transport with fractions, which does not make sense in the case of croissants. This was not the case with EMD." }, { "code": null, "e": 5781, "s": 5591, "text": "Obviously, the regularization hyperparameter reg of Sinkhorn plays an important role. Let’s see with the following graphs how it impacts the transport matrix by looking at different values." }, { "code": null, "e": 6017, "s": 5781, "text": "This series of graphs shows that the solution of Sinkhorn starts with something very similar to EMD (although not sparse) for very small values of the regularization parameter reg, and tends to a more uniform solution as reg increases." } ]
The Most Awesome Loss Function. Paper Review: General and Adaptive... | by Saptashwa Bhattacharyya | Towards Data Science
Recently, I came across the amazing paper presented in CVPR 2019 by Jon Barron about developing a robust and adaptive loss function for Machine Learning problems. This post is a review of that paper along with some necessary concepts and, it will also contain an implementation of the loss function on a simple regression problem. Consider one of the most used errors in machine learning problems- Mean Squared Error (MSE). As you know it is of the form (y-x)2. One of the key characteristics of the MSE is that its high sensitivity towards large errors compared to small ones. A model trained with MSE will be biased towards reducing the largest errors. For example, a single error of 3 units will be given same importance to 9 errors of 1 unit. I created an example using Scikit-Learn to demonstrate how the fit varies in a simple data-set with and without taking the effect of outliers. As you can see the fit line including the outliers get heavily influenced by the outliers but, the optimization problem should require the model to get more influenced by the inliers. At this point you can already think about Mean Absolute Error (MAE) as better choice than MSE, due to less sensitivity to large errors. There are various types of robust losses (like MAE) and for a particular problem we may need to test various losses. Wouldn’t it be amazing to test various loss functions on the fly while training a network? The main idea of the paper is to introduce a generalized loss function where the robustness of the loss function can be varied and, this hyperparameter can be trained while training the network, to improve performance. It is way less time consuming than finding the best loss say, by performing grid-search cross-validation. Let’s get started with the definition below — The general form of the robust and adaptive loss is as below — α controls the robustness of the loss function. c can be considered as a scale parameter which controls the size of the bowl near x=0. Since α acts as hyperparameter, we can see that for different values of α the loss function takes familiar forms. Let’s see below — The loss function is undefined at α = 0 and 2, but taking the limit we can make approximations. From α =2 to α =1 the loss smoothly makes a transition from L2 loss to L1 loss. For different values of α we can plot the loss function to see how it behaves (fig. 2). We can also spend some time with the first derivative of this loss function because the derivative is needed for gradient-based optimization. For various values of α the derivatives w.r.t x are shown below. In figure 2, I have also plotted the derivatives along with the loss function for different α. The figure below is very important to understand the behaviour of this loss function and its derivative. For the plots below, I have fixed the scale parameter c to 1.1. When x = 6.6, we can consider this as like x = 6× c. We can draw the following inferences about the loss and its derivative — The loss function is smooth for x, α and c>0 and thus suited for gradient based optimization.The loss is always zero at origin and increases monotonically for |x|>0. Monotonic nature of the loss can also be compared with taking log of a loss.The loss is also monotonically increasing with increasing α. This property is important for the robust nature of loss function because we can start with a higher value of α and then gradually reduce (smoothly) during optimization to enable robust estimation avoiding local minima.We see that when |x|<c, the derivatives are almost linear for different values of α. This implies that the derivatives are proportional to residual’s magnitude when they are small.For α = 2 the derivative is throughout proportional to the residual’s magnitude. This is in general the property of MSE (L2) loss.For α = 1 (gives us L1 Loss), we see that the derivative’s magnitude saturates to a constant value (exactly 1/c) beyond |x|>c. This implies that effect of residuals never exceeds a fixed amount.For α < 1, the derivative’s magnitude decreases as |x|>c. This implies that when residual increases it has less effect on the gradient, thus the outliers will have less effect during gradient descent. The loss function is smooth for x, α and c>0 and thus suited for gradient based optimization. The loss is always zero at origin and increases monotonically for |x|>0. Monotonic nature of the loss can also be compared with taking log of a loss. The loss is also monotonically increasing with increasing α. This property is important for the robust nature of loss function because we can start with a higher value of α and then gradually reduce (smoothly) during optimization to enable robust estimation avoiding local minima. We see that when |x|<c, the derivatives are almost linear for different values of α. This implies that the derivatives are proportional to residual’s magnitude when they are small. For α = 2 the derivative is throughout proportional to the residual’s magnitude. This is in general the property of MSE (L2) loss. For α = 1 (gives us L1 Loss), we see that the derivative’s magnitude saturates to a constant value (exactly 1/c) beyond |x|>c. This implies that effect of residuals never exceeds a fixed amount. For α < 1, the derivative’s magnitude decreases as |x|>c. This implies that when residual increases it has less effect on the gradient, thus the outliers will have less effect during gradient descent. I have also plotted below the surface plots of robust loss and its derivative for different values of α. Since we have gone through the basics and properties of the robust and adaptive loss function, let us put this into action. Codes used below are just slightly modified from what can be found in Jon Barron’s GitHub repository. I have also created an animation to depict how the adaptive loss finds the best-fit line as the number of iteration increases. Rather than cloning the repository and working with it, we can install it locally using pip in Colab. !pip install git+https://github.com/jonbarron/robust_loss_pytorchimport robust_loss_pytorch We create a simple linear dataset including normally distributed noise and also outliers. Since the library uses pytorch, we convert the numpy arrays of x, y to tensors using torch. import numpy as npimport torch scale_true = 0.7shift_true = 0.15x = np.random.uniform(size=n)y = scale_true * x + shift_truey = y + np.random.normal(scale=0.025, size=n) # add noise flip_mask = np.random.uniform(size=n) > 0.9 y = np.where(flip_mask, 0.05 + 0.4 * (1. — np.sign(y — 0.5)), y) # include outliersx = torch.Tensor(x)y = torch.Tensor(y) Next we define a Linear regression class using pytorch modules as below- class RegressionModel(torch.nn.Module): def __init__(self): super(RegressionModel, self).__init__() self.linear = torch.nn.Linear(1, 1) ## applies the linear transformation. def forward(self, x): return self.linear(x[:,None])[:,0] # returns the forward pass Next, we fit a linear regression model to our data but, first the general form of the loss function is used. Here we use a fixed value of α (α = 2.0) and it remains constant throughout the optimization procedure. As we have seen for α = 2.0 the loss function replicates L2 loss and this as we know is not optimal for problems including outliers. For optimization we use the Adam optimizer with a learning rate of 0.01. regression = RegressionModel()params = regression.parameters()optimizer = torch.optim.Adam(params, lr = 0.01)for epoch in range(2000): y_i = regression(x) # Use general loss to compute MSE, fixed alpha, fixed scale. loss = torch.mean(robust_loss_pytorch.general.lossfun( y_i — y, alpha=torch.Tensor([2.]), scale=torch.Tensor([0.1]))) optimizer.zero_grad() loss.backward() optimizer.step() Using the general form of the robust loss function and a fixed value of α, we can obtain the fit line. The original data, true line (line with the same slope and bias used to generate data-points excluding the outliers) and fit line are plotted below in fig. 4. The general form of the loss function doesn’t allow α to change and thus we have to fine tune the α parameter by hand or by performing a grid-search. Also, as the figure above suggests that the fit is affected by the outliers because we used L2 loss. This is the general scenario but, what happens if we use the adaptive version of the loss function ? We call the adaptive loss module and just initialize α and let it adapt itself at each iteration step. regression = RegressionModel()adaptive = robust_loss_pytorch.adaptive.AdaptiveLossFunction( num_dims = 1, float_dtype=np.float32)params = list(regression.parameters()) + list(adaptive.parameters())optimizer = torch.optim.Adam(params, lr = 0.01)for epoch in range(2000): y_i = regression(x) loss = torch.mean(adaptive.lossfun((y_i — y)[:,None])) # (y_i - y)[:, None] # numpy array or tensor optimizer.zero_grad() loss.backward() optimizer.step() Using this, and also some extra bit of code using Celluloid module, I created the animation below (figure 5). Here, you clearly see, how with increasing iterations adaptive loss finds the best fit line. This is close to the true line and it is negligibly affected by the outliers. We have seen how the robust loss including an hyperparameter α can be used to find the best loss-function on the fly. The paper also demonstrates how the robustness of the loss-function with α as continuous hyperparameter can be introduced to classic computer vision algorithms. Examples of implementing adaptive loss for Variational Autoencoder and Monocular depth estimations are shown in the paper and these codes are also available in Jon’s GitHub. However, the most fascinating part for me was the motivation and step by step derivation of the loss function as described in the paper. It’s easy to read so, I suggest to take a look at the paper! Stay strong and cheers!! [1] “A General and Adaptive Robust Loss Function”; J. Barron, Google Research. [2] Robust-Loss: Linear regression example; Jon Barron’s GitHub. [3] Surface plot of robust loss and animation: GitHub Link.
[ { "code": null, "e": 503, "s": 172, "text": "Recently, I came across the amazing paper presented in CVPR 2019 by Jon Barron about developing a robust and adaptive loss function for Machine Learning problems. This post is a review of that paper along with some necessary concepts and, it will also contain an implementation of the loss function on a simple regression problem." }, { "code": null, "e": 919, "s": 503, "text": "Consider one of the most used errors in machine learning problems- Mean Squared Error (MSE). As you know it is of the form (y-x)2. One of the key characteristics of the MSE is that its high sensitivity towards large errors compared to small ones. A model trained with MSE will be biased towards reducing the largest errors. For example, a single error of 3 units will be given same importance to 9 errors of 1 unit." }, { "code": null, "e": 1062, "s": 919, "text": "I created an example using Scikit-Learn to demonstrate how the fit varies in a simple data-set with and without taking the effect of outliers." }, { "code": null, "e": 1961, "s": 1062, "text": "As you can see the fit line including the outliers get heavily influenced by the outliers but, the optimization problem should require the model to get more influenced by the inliers. At this point you can already think about Mean Absolute Error (MAE) as better choice than MSE, due to less sensitivity to large errors. There are various types of robust losses (like MAE) and for a particular problem we may need to test various losses. Wouldn’t it be amazing to test various loss functions on the fly while training a network? The main idea of the paper is to introduce a generalized loss function where the robustness of the loss function can be varied and, this hyperparameter can be trained while training the network, to improve performance. It is way less time consuming than finding the best loss say, by performing grid-search cross-validation. Let’s get started with the definition below —" }, { "code": null, "e": 2024, "s": 1961, "text": "The general form of the robust and adaptive loss is as below —" }, { "code": null, "e": 2291, "s": 2024, "text": "α controls the robustness of the loss function. c can be considered as a scale parameter which controls the size of the bowl near x=0. Since α acts as hyperparameter, we can see that for different values of α the loss function takes familiar forms. Let’s see below —" }, { "code": null, "e": 2555, "s": 2291, "text": "The loss function is undefined at α = 0 and 2, but taking the limit we can make approximations. From α =2 to α =1 the loss smoothly makes a transition from L2 loss to L1 loss. For different values of α we can plot the loss function to see how it behaves (fig. 2)." }, { "code": null, "e": 2857, "s": 2555, "text": "We can also spend some time with the first derivative of this loss function because the derivative is needed for gradient-based optimization. For various values of α the derivatives w.r.t x are shown below. In figure 2, I have also plotted the derivatives along with the loss function for different α." }, { "code": null, "e": 3152, "s": 2857, "text": "The figure below is very important to understand the behaviour of this loss function and its derivative. For the plots below, I have fixed the scale parameter c to 1.1. When x = 6.6, we can consider this as like x = 6× c. We can draw the following inferences about the loss and its derivative —" }, { "code": null, "e": 4379, "s": 3152, "text": "The loss function is smooth for x, α and c>0 and thus suited for gradient based optimization.The loss is always zero at origin and increases monotonically for |x|>0. Monotonic nature of the loss can also be compared with taking log of a loss.The loss is also monotonically increasing with increasing α. This property is important for the robust nature of loss function because we can start with a higher value of α and then gradually reduce (smoothly) during optimization to enable robust estimation avoiding local minima.We see that when |x|<c, the derivatives are almost linear for different values of α. This implies that the derivatives are proportional to residual’s magnitude when they are small.For α = 2 the derivative is throughout proportional to the residual’s magnitude. This is in general the property of MSE (L2) loss.For α = 1 (gives us L1 Loss), we see that the derivative’s magnitude saturates to a constant value (exactly 1/c) beyond |x|>c. This implies that effect of residuals never exceeds a fixed amount.For α < 1, the derivative’s magnitude decreases as |x|>c. This implies that when residual increases it has less effect on the gradient, thus the outliers will have less effect during gradient descent." }, { "code": null, "e": 4473, "s": 4379, "text": "The loss function is smooth for x, α and c>0 and thus suited for gradient based optimization." }, { "code": null, "e": 4623, "s": 4473, "text": "The loss is always zero at origin and increases monotonically for |x|>0. Monotonic nature of the loss can also be compared with taking log of a loss." }, { "code": null, "e": 4904, "s": 4623, "text": "The loss is also monotonically increasing with increasing α. This property is important for the robust nature of loss function because we can start with a higher value of α and then gradually reduce (smoothly) during optimization to enable robust estimation avoiding local minima." }, { "code": null, "e": 5085, "s": 4904, "text": "We see that when |x|<c, the derivatives are almost linear for different values of α. This implies that the derivatives are proportional to residual’s magnitude when they are small." }, { "code": null, "e": 5216, "s": 5085, "text": "For α = 2 the derivative is throughout proportional to the residual’s magnitude. This is in general the property of MSE (L2) loss." }, { "code": null, "e": 5411, "s": 5216, "text": "For α = 1 (gives us L1 Loss), we see that the derivative’s magnitude saturates to a constant value (exactly 1/c) beyond |x|>c. This implies that effect of residuals never exceeds a fixed amount." }, { "code": null, "e": 5612, "s": 5411, "text": "For α < 1, the derivative’s magnitude decreases as |x|>c. This implies that when residual increases it has less effect on the gradient, thus the outliers will have less effect during gradient descent." }, { "code": null, "e": 5717, "s": 5612, "text": "I have also plotted below the surface plots of robust loss and its derivative for different values of α." }, { "code": null, "e": 6070, "s": 5717, "text": "Since we have gone through the basics and properties of the robust and adaptive loss function, let us put this into action. Codes used below are just slightly modified from what can be found in Jon Barron’s GitHub repository. I have also created an animation to depict how the adaptive loss finds the best-fit line as the number of iteration increases." }, { "code": null, "e": 6172, "s": 6070, "text": "Rather than cloning the repository and working with it, we can install it locally using pip in Colab." }, { "code": null, "e": 6265, "s": 6172, "text": "!pip install git+https://github.com/jonbarron/robust_loss_pytorchimport robust_loss_pytorch " }, { "code": null, "e": 6447, "s": 6265, "text": "We create a simple linear dataset including normally distributed noise and also outliers. Since the library uses pytorch, we convert the numpy arrays of x, y to tensors using torch." }, { "code": null, "e": 6795, "s": 6447, "text": "import numpy as npimport torch scale_true = 0.7shift_true = 0.15x = np.random.uniform(size=n)y = scale_true * x + shift_truey = y + np.random.normal(scale=0.025, size=n) # add noise flip_mask = np.random.uniform(size=n) > 0.9 y = np.where(flip_mask, 0.05 + 0.4 * (1. — np.sign(y — 0.5)), y) # include outliersx = torch.Tensor(x)y = torch.Tensor(y)" }, { "code": null, "e": 6868, "s": 6795, "text": "Next we define a Linear regression class using pytorch modules as below-" }, { "code": null, "e": 7151, "s": 6868, "text": "class RegressionModel(torch.nn.Module): def __init__(self): super(RegressionModel, self).__init__() self.linear = torch.nn.Linear(1, 1) ## applies the linear transformation. def forward(self, x): return self.linear(x[:,None])[:,0] # returns the forward pass" }, { "code": null, "e": 7570, "s": 7151, "text": "Next, we fit a linear regression model to our data but, first the general form of the loss function is used. Here we use a fixed value of α (α = 2.0) and it remains constant throughout the optimization procedure. As we have seen for α = 2.0 the loss function replicates L2 loss and this as we know is not optimal for problems including outliers. For optimization we use the Adam optimizer with a learning rate of 0.01." }, { "code": null, "e": 7975, "s": 7570, "text": "regression = RegressionModel()params = regression.parameters()optimizer = torch.optim.Adam(params, lr = 0.01)for epoch in range(2000): y_i = regression(x) # Use general loss to compute MSE, fixed alpha, fixed scale. loss = torch.mean(robust_loss_pytorch.general.lossfun( y_i — y, alpha=torch.Tensor([2.]), scale=torch.Tensor([0.1]))) optimizer.zero_grad() loss.backward() optimizer.step()" }, { "code": null, "e": 8237, "s": 7975, "text": "Using the general form of the robust loss function and a fixed value of α, we can obtain the fit line. The original data, true line (line with the same slope and bias used to generate data-points excluding the outliers) and fit line are plotted below in fig. 4." }, { "code": null, "e": 8692, "s": 8237, "text": "The general form of the loss function doesn’t allow α to change and thus we have to fine tune the α parameter by hand or by performing a grid-search. Also, as the figure above suggests that the fit is affected by the outliers because we used L2 loss. This is the general scenario but, what happens if we use the adaptive version of the loss function ? We call the adaptive loss module and just initialize α and let it adapt itself at each iteration step." }, { "code": null, "e": 9159, "s": 8692, "text": "regression = RegressionModel()adaptive = robust_loss_pytorch.adaptive.AdaptiveLossFunction( num_dims = 1, float_dtype=np.float32)params = list(regression.parameters()) + list(adaptive.parameters())optimizer = torch.optim.Adam(params, lr = 0.01)for epoch in range(2000): y_i = regression(x) loss = torch.mean(adaptive.lossfun((y_i — y)[:,None])) # (y_i - y)[:, None] # numpy array or tensor optimizer.zero_grad() loss.backward() optimizer.step()" }, { "code": null, "e": 9440, "s": 9159, "text": "Using this, and also some extra bit of code using Celluloid module, I created the animation below (figure 5). Here, you clearly see, how with increasing iterations adaptive loss finds the best fit line. This is close to the true line and it is negligibly affected by the outliers." }, { "code": null, "e": 10091, "s": 9440, "text": "We have seen how the robust loss including an hyperparameter α can be used to find the best loss-function on the fly. The paper also demonstrates how the robustness of the loss-function with α as continuous hyperparameter can be introduced to classic computer vision algorithms. Examples of implementing adaptive loss for Variational Autoencoder and Monocular depth estimations are shown in the paper and these codes are also available in Jon’s GitHub. However, the most fascinating part for me was the motivation and step by step derivation of the loss function as described in the paper. It’s easy to read so, I suggest to take a look at the paper!" }, { "code": null, "e": 10116, "s": 10091, "text": "Stay strong and cheers!!" }, { "code": null, "e": 10195, "s": 10116, "text": "[1] “A General and Adaptive Robust Loss Function”; J. Barron, Google Research." }, { "code": null, "e": 10260, "s": 10195, "text": "[2] Robust-Loss: Linear regression example; Jon Barron’s GitHub." } ]
Power BI Connects to Azure Databricks | Towards Data Science
Microsoft PowerBI is becoming more and more popular recently as a Data Analytics tool. Also, It is ubiquitous for a company to have a whole bucket of Microsoft products that include Azure. Azure Databricks is one of the most popular services in the Azure platform. It leverages Apache Spark to process data in a distributed environment, which can expedite the performance dramatically. Azure Databricks also support Delta Lake that is an open-sourced storage layer in a distributed environment. It can be used very similarly to most of the traditional database management systems because it supports ACID transactions. https://delta.io This article will be demonstrated how to connect to Azure Databricks tables (Delta Lake) from PowerBI using its built-in connector. The tricky part is going to be the “Spark URL” which will be emphasised later on. Since the purpose of this tutorial is to introduce the steps of connecting PowerBI to Azure Databricks only, a sample data table will be created for testing purposes. To begin with, let’s create a table with a few columns. A date column can be used as a “filter”, and another column with integers as the values for each date. Let’s firstly create a notebook in Azure Databricks, and I would like to call it “PowerBI_Test”. Create a database for testing purposes. %sqlCREATE DATABASE TEST_DB; Then, import necessary libraries, create a Python function to generate a Pandas Dataframe with the columns above-mentioned. from datetime import datetime, timedeltaimport numpy as npimport pandas as pd# Create date df in pandasdef create_date_table(start='2020-01-01', end='2020-03-01'): df = pd.DataFrame({"date": pd.date_range(start, end)}) df['day'] = df['date'].dt.weekday_name df['date'] = df['date'].dt.date df['value'] = np.random.randint(100, size=df.shape[0]) return df Now, we can generate the Spark Dataframe from the Pandas Dataframe and save it into Delta Lake. date_pdf = create_date_table()sample_table = spark.createDataFrame(date_pdf)sample_table.write.format('delta').mode("overwrite").saveAsTable('TEST_DB.sample_table') Here is the preview of the table: To connect to Azure Databricks from PowerBI, we need two important “keys”, which are the URL and the User Token. From the left navigation, go to the “Cluster” tab.From the cluster list, click to select the cluster you want to use. This will navigate the page to the Cluster Edit page.In the Cluster Edit page, click “Advanced Options” to expand the section.Select “JDBC/ODBC” tab. There will be a lot of information here, but we only need to focus on the “JDBC URL”. From the left navigation, go to the “Cluster” tab. From the cluster list, click to select the cluster you want to use. This will navigate the page to the Cluster Edit page. In the Cluster Edit page, click “Advanced Options” to expand the section. Select “JDBC/ODBC” tab. There will be a lot of information here, but we only need to focus on the “JDBC URL”. 5. Copy the whole URL to some text editor. This URL CANNOT be directly used, and we need to “derive” the correct URL from it. Here is the URL I copied from the “JDBC URL” text field: jdbc:spark://australiasoutheast.azuredatabricks.net:443/default;transportMode=http;ssl=1;httpPath=sql/protocolv1/o/***************/****-******-*******;AuthMech=3;UID=token;PWD=<personal-access-token> The components we need from this URL is shown in the square brackets: jdbc:spark[://australiasoutheast.azuredatabricks.net:443/]default;transportMode=http;ssl=1;httpPath=[sql/protocolv1/o/***************/****-******-*******];AuthMech=3;UID=token;PWD=<personal-access-token> We also need to add a protocol at the front, which is HTTPS. So, the final URL will become as follows: https://australiasoutheast.azuredatabricks.net:443/sql/protocolv1/o/***************/****-******-******* We need to create a user token for authentication. Firstly, find the user icon in the top right corner. Click the icon, and then select “User Settings” in the dropdown menu. In the “User Setting” page, click the button “Generate New Token”. In the pop-up window, input the comment field which will be used to remind yourself in the future what is this token used for. The “Lifetime” will determine after how many days the token will be revoked automatically. Please be noted that if the token lifespan is unspecified, the token will live indefinitely. After clicked the “Generate” button, a token will be generated. **IMPORTANT** You will not be able to retrieve the token once you have clicked the “Done” button. So, please make sure you copy the token and save it to a secured place now. Now, we can get data from Databricks in PowerBI. In PowerBI, click “Get Data” > search “Spark” > Select “Spark” in the list > click “Connect” button. In the pop-up window, fill the URL https://australiasoutheast.azuredatabricks.net:443/sql/protocolv1/o/***************/****-******-******* into the “Server” text field. Then, select “HTTP” for the protocol. For the “Data Connectivity mode”, we choose “DirectQuery”. This is because we are very likely to deal with a large dataset when we need Azure Databricks in practice, so importing all the data into PowerBI will not be a good idea in that scenario. After clicking the “OK” button, we will be able to see all the tables in the current Azure Databricks Cluster. If there are many tables in the cluster, we can search the table in the navigator. Then, click the “Load” button to add the table as a data source. Of course, you can import multiple tables at one time in practice. Now, we can create visualisations from Delta Lake. This article has demonstrated how to connect to Azure Databricks from Microsoft PowerBI. The most critical steps are getting the Spark URL and User Token from Azure Databricks. Hopefully, this article can help Data Scientists/Engineers to create visualisations from Azure Databricks directly. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 360, "s": 171, "text": "Microsoft PowerBI is becoming more and more popular recently as a Data Analytics tool. Also, It is ubiquitous for a company to have a whole bucket of Microsoft products that include Azure." }, { "code": null, "e": 790, "s": 360, "text": "Azure Databricks is one of the most popular services in the Azure platform. It leverages Apache Spark to process data in a distributed environment, which can expedite the performance dramatically. Azure Databricks also support Delta Lake that is an open-sourced storage layer in a distributed environment. It can be used very similarly to most of the traditional database management systems because it supports ACID transactions." }, { "code": null, "e": 807, "s": 790, "text": "https://delta.io" }, { "code": null, "e": 1021, "s": 807, "text": "This article will be demonstrated how to connect to Azure Databricks tables (Delta Lake) from PowerBI using its built-in connector. The tricky part is going to be the “Spark URL” which will be emphasised later on." }, { "code": null, "e": 1347, "s": 1021, "text": "Since the purpose of this tutorial is to introduce the steps of connecting PowerBI to Azure Databricks only, a sample data table will be created for testing purposes. To begin with, let’s create a table with a few columns. A date column can be used as a “filter”, and another column with integers as the values for each date." }, { "code": null, "e": 1444, "s": 1347, "text": "Let’s firstly create a notebook in Azure Databricks, and I would like to call it “PowerBI_Test”." }, { "code": null, "e": 1484, "s": 1444, "text": "Create a database for testing purposes." }, { "code": null, "e": 1513, "s": 1484, "text": "%sqlCREATE DATABASE TEST_DB;" }, { "code": null, "e": 1637, "s": 1513, "text": "Then, import necessary libraries, create a Python function to generate a Pandas Dataframe with the columns above-mentioned." }, { "code": null, "e": 1997, "s": 1637, "text": "from datetime import datetime, timedeltaimport numpy as npimport pandas as pd# Create date df in pandasdef create_date_table(start='2020-01-01', end='2020-03-01'): df = pd.DataFrame({\"date\": pd.date_range(start, end)}) df['day'] = df['date'].dt.weekday_name df['date'] = df['date'].dt.date df['value'] = np.random.randint(100, size=df.shape[0]) return df" }, { "code": null, "e": 2093, "s": 1997, "text": "Now, we can generate the Spark Dataframe from the Pandas Dataframe and save it into Delta Lake." }, { "code": null, "e": 2258, "s": 2093, "text": "date_pdf = create_date_table()sample_table = spark.createDataFrame(date_pdf)sample_table.write.format('delta').mode(\"overwrite\").saveAsTable('TEST_DB.sample_table')" }, { "code": null, "e": 2292, "s": 2258, "text": "Here is the preview of the table:" }, { "code": null, "e": 2405, "s": 2292, "text": "To connect to Azure Databricks from PowerBI, we need two important “keys”, which are the URL and the User Token." }, { "code": null, "e": 2759, "s": 2405, "text": "From the left navigation, go to the “Cluster” tab.From the cluster list, click to select the cluster you want to use. This will navigate the page to the Cluster Edit page.In the Cluster Edit page, click “Advanced Options” to expand the section.Select “JDBC/ODBC” tab. There will be a lot of information here, but we only need to focus on the “JDBC URL”." }, { "code": null, "e": 2810, "s": 2759, "text": "From the left navigation, go to the “Cluster” tab." }, { "code": null, "e": 2932, "s": 2810, "text": "From the cluster list, click to select the cluster you want to use. This will navigate the page to the Cluster Edit page." }, { "code": null, "e": 3006, "s": 2932, "text": "In the Cluster Edit page, click “Advanced Options” to expand the section." }, { "code": null, "e": 3116, "s": 3006, "text": "Select “JDBC/ODBC” tab. There will be a lot of information here, but we only need to focus on the “JDBC URL”." }, { "code": null, "e": 3242, "s": 3116, "text": "5. Copy the whole URL to some text editor. This URL CANNOT be directly used, and we need to “derive” the correct URL from it." }, { "code": null, "e": 3299, "s": 3242, "text": "Here is the URL I copied from the “JDBC URL” text field:" }, { "code": null, "e": 3499, "s": 3299, "text": "jdbc:spark://australiasoutheast.azuredatabricks.net:443/default;transportMode=http;ssl=1;httpPath=sql/protocolv1/o/***************/****-******-*******;AuthMech=3;UID=token;PWD=<personal-access-token>" }, { "code": null, "e": 3569, "s": 3499, "text": "The components we need from this URL is shown in the square brackets:" }, { "code": null, "e": 3773, "s": 3569, "text": "jdbc:spark[://australiasoutheast.azuredatabricks.net:443/]default;transportMode=http;ssl=1;httpPath=[sql/protocolv1/o/***************/****-******-*******];AuthMech=3;UID=token;PWD=<personal-access-token>" }, { "code": null, "e": 3876, "s": 3773, "text": "We also need to add a protocol at the front, which is HTTPS. So, the final URL will become as follows:" }, { "code": null, "e": 3980, "s": 3876, "text": "https://australiasoutheast.azuredatabricks.net:443/sql/protocolv1/o/***************/****-******-*******" }, { "code": null, "e": 4031, "s": 3980, "text": "We need to create a user token for authentication." }, { "code": null, "e": 4154, "s": 4031, "text": "Firstly, find the user icon in the top right corner. Click the icon, and then select “User Settings” in the dropdown menu." }, { "code": null, "e": 4348, "s": 4154, "text": "In the “User Setting” page, click the button “Generate New Token”. In the pop-up window, input the comment field which will be used to remind yourself in the future what is this token used for." }, { "code": null, "e": 4532, "s": 4348, "text": "The “Lifetime” will determine after how many days the token will be revoked automatically. Please be noted that if the token lifespan is unspecified, the token will live indefinitely." }, { "code": null, "e": 4596, "s": 4532, "text": "After clicked the “Generate” button, a token will be generated." }, { "code": null, "e": 4770, "s": 4596, "text": "**IMPORTANT** You will not be able to retrieve the token once you have clicked the “Done” button. So, please make sure you copy the token and save it to a secured place now." }, { "code": null, "e": 4819, "s": 4770, "text": "Now, we can get data from Databricks in PowerBI." }, { "code": null, "e": 4920, "s": 4819, "text": "In PowerBI, click “Get Data” > search “Spark” > Select “Spark” in the list > click “Connect” button." }, { "code": null, "e": 5089, "s": 4920, "text": "In the pop-up window, fill the URL https://australiasoutheast.azuredatabricks.net:443/sql/protocolv1/o/***************/****-******-******* into the “Server” text field." }, { "code": null, "e": 5374, "s": 5089, "text": "Then, select “HTTP” for the protocol. For the “Data Connectivity mode”, we choose “DirectQuery”. This is because we are very likely to deal with a large dataset when we need Azure Databricks in practice, so importing all the data into PowerBI will not be a good idea in that scenario." }, { "code": null, "e": 5700, "s": 5374, "text": "After clicking the “OK” button, we will be able to see all the tables in the current Azure Databricks Cluster. If there are many tables in the cluster, we can search the table in the navigator. Then, click the “Load” button to add the table as a data source. Of course, you can import multiple tables at one time in practice." }, { "code": null, "e": 5751, "s": 5700, "text": "Now, we can create visualisations from Delta Lake." }, { "code": null, "e": 5928, "s": 5751, "text": "This article has demonstrated how to connect to Azure Databricks from Microsoft PowerBI. The most critical steps are getting the Spark URL and User Token from Azure Databricks." }, { "code": null, "e": 6044, "s": 5928, "text": "Hopefully, this article can help Data Scientists/Engineers to create visualisations from Azure Databricks directly." }, { "code": null, "e": 6055, "s": 6044, "text": "medium.com" } ]
How to create transparent Status Bar and Navigation Bar in iOS?
You might have come across many application where the screen extends to complete screen i.e transparent Status Bar and transparent navigation bar. Here we will be seeing how to create an application where the you’ll be having transparent status and navigation bar. So let’s get started Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “TransparentViews” Step 2 − Embed the View Controller in Navigation Controller. Add Image View and shown and add image. Step 3 − Run the application without adding any piece of code for making status and navigation bar transparent. The screen looks like below Step 4 − Now Open ViewController.swift and add following code in viewDidLoad method. override func viewDidLoad(){ super.viewDidLoad() self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: .default) self.navigationController!.navigationBar.shadowImage = UIImage() self.navigationController!.navigationBar.isTranslucent = true } Step 5 − Run the application
[ { "code": null, "e": 1209, "s": 1062, "text": "You might have come across many application where the screen extends to complete screen i.e transparent Status Bar and transparent navigation bar." }, { "code": null, "e": 1327, "s": 1209, "text": "Here we will be seeing how to create an application where the you’ll be having transparent status and navigation bar." }, { "code": null, "e": 1348, "s": 1327, "text": "So let’s get started" }, { "code": null, "e": 1443, "s": 1348, "text": "Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “TransparentViews”" }, { "code": null, "e": 1544, "s": 1443, "text": "Step 2 − Embed the View Controller in Navigation Controller. Add Image View and shown and add image." }, { "code": null, "e": 1656, "s": 1544, "text": "Step 3 − Run the application without adding any piece of code for making status and navigation bar transparent." }, { "code": null, "e": 1684, "s": 1656, "text": "The screen looks like below" }, { "code": null, "e": 1769, "s": 1684, "text": "Step 4 − Now Open ViewController.swift and add following code in viewDidLoad method." }, { "code": null, "e": 2045, "s": 1769, "text": "override func viewDidLoad(){\n super.viewDidLoad()\n self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: .default)\n self.navigationController!.navigationBar.shadowImage = UIImage()\n self.navigationController!.navigationBar.isTranslucent = true\n}" }, { "code": null, "e": 2074, "s": 2045, "text": "Step 5 − Run the application" } ]
Perl | keys() Function - GeeksforGeeks
25 Jun, 2019 keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function. Syntax: keys(HASH) Parameter:HASH: Hash whose keys are to be printed Return: For scalar context, it returns the number of keys in the hash whereas for List context it returns a list of keys. Example 1: #!/usr/bin/perl %hash = ('Ten' => 10, 'Eleven' => 11, 'Twelve' => 12, 'Thirteen' => 13); @values = values( %hash );print("Values are ", join("-", @values), "\n"); @keys = keys( %hash );print("Keys are ", join("-", @keys), "\n"); Output: Values are 11-12-13-10 Keys are Eleven-Twelve-Thirteen-Ten Example 2: #!/usr/bin/perl %hash = ('Geek' => 1, 'For' => 2, 'Geeks' => 3); @values = values( %hash );print("Values are ", join("-", @values), "\n"); @keys = keys( %hash );print("Keys are ", join("-", @keys), "\n"); Output: Values are 3-2-1 Keys are Geeks-For-Geek Perl-function Perl-Hash-Functions Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Perl Tutorial - Learn Perl With Examples Perl | Hashes Perl | Basic Syntax of a Perl Program Perl | Opening and Reading a File Perl | Multidimensional Hashes How to Install Perl on Windows? Perl | CGI Programming Perl | Sorting of Arrays Perl | Data Types Perl | Operators | Set - 1
[ { "code": null, "e": 23679, "s": 23651, "text": "\n25 Jun, 2019" }, { "code": null, "e": 23872, "s": 23679, "text": "keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function." }, { "code": null, "e": 23891, "s": 23872, "text": "Syntax: keys(HASH)" }, { "code": null, "e": 23941, "s": 23891, "text": "Parameter:HASH: Hash whose keys are to be printed" }, { "code": null, "e": 24063, "s": 23941, "text": "Return: For scalar context, it returns the number of keys in the hash whereas for List context it returns a list of keys." }, { "code": null, "e": 24074, "s": 24063, "text": "Example 1:" }, { "code": "#!/usr/bin/perl %hash = ('Ten' => 10, 'Eleven' => 11, 'Twelve' => 12, 'Thirteen' => 13); @values = values( %hash );print(\"Values are \", join(\"-\", @values), \"\\n\"); @keys = keys( %hash );print(\"Keys are \", join(\"-\", @keys), \"\\n\");", "e": 24331, "s": 24074, "text": null }, { "code": null, "e": 24339, "s": 24331, "text": "Output:" }, { "code": null, "e": 24399, "s": 24339, "text": "Values are 11-12-13-10\nKeys are Eleven-Twelve-Thirteen-Ten" }, { "code": null, "e": 24410, "s": 24399, "text": "Example 2:" }, { "code": "#!/usr/bin/perl %hash = ('Geek' => 1, 'For' => 2, 'Geeks' => 3); @values = values( %hash );print(\"Values are \", join(\"-\", @values), \"\\n\"); @keys = keys( %hash );print(\"Keys are \", join(\"-\", @keys), \"\\n\");", "e": 24635, "s": 24410, "text": null }, { "code": null, "e": 24643, "s": 24635, "text": "Output:" }, { "code": null, "e": 24686, "s": 24643, "text": "Values are 3-2-1\nKeys are Geeks-For-Geek\n" }, { "code": null, "e": 24700, "s": 24686, "text": "Perl-function" }, { "code": null, "e": 24720, "s": 24700, "text": "Perl-Hash-Functions" }, { "code": null, "e": 24725, "s": 24720, "text": "Perl" }, { "code": null, "e": 24730, "s": 24725, "text": "Perl" }, { "code": null, "e": 24828, "s": 24730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24837, "s": 24828, "text": "Comments" }, { "code": null, "e": 24850, "s": 24837, "text": "Old Comments" }, { "code": null, "e": 24891, "s": 24850, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 24905, "s": 24891, "text": "Perl | Hashes" }, { "code": null, "e": 24943, "s": 24905, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 24977, "s": 24943, "text": "Perl | Opening and Reading a File" }, { "code": null, "e": 25008, "s": 24977, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 25040, "s": 25008, "text": "How to Install Perl on Windows?" }, { "code": null, "e": 25063, "s": 25040, "text": "Perl | CGI Programming" }, { "code": null, "e": 25088, "s": 25063, "text": "Perl | Sorting of Arrays" }, { "code": null, "e": 25106, "s": 25088, "text": "Perl | Data Types" } ]
How to center canvas in HTML5?
To center canvas in HTML 5, include the canvas tag in div tag. Then we can center align the div tag. By doing so, the canvas is also center aligned. <!DOCTYPE html>. <html> <body> <div style = "text-align:center;"> <canvas style = "background-color:GREEN;">This is my canvas</canvas> </div> </body> </html>
[ { "code": null, "e": 1211, "s": 1062, "text": "To center canvas in HTML 5, include the canvas tag in div tag. Then we can center align the div tag. By doing so, the canvas is also center aligned." }, { "code": null, "e": 1396, "s": 1211, "text": "<!DOCTYPE html>.\n<html>\n <body>\n <div style = \"text-align:center;\">\n <canvas style = \"background-color:GREEN;\">This is my canvas</canvas>\n </div>\n </body>\n</html>" } ]
Sum of maximum of all subarrays by adding even frequent maximum twice - GeeksforGeeks
07 Feb, 2022 Given an array arr[] consisting of N integers (All array elements are a perfect power of 2), the task is to calculate the sum of the maximum elements in all the subarrays. Note: If the frequency of the maximum element in a subarray is even, add twice the value of that element to the sum. Examples: Input: arr[] = {1, 2}Output: 5Explanation: All possible subarrays are {1}, {1, 2}, {2}. Subarray 1: {1}. Maximum = 1. Sum = 1.Subarray 2: {1, 2}. Maximum = 2. Sum = 3.Subarray 3: {2}. Maximum = 2.Sum = 5.Therefore, required output is 5. Input: arr[] = {4, 4}Output: 16Explanation: All possible subarrays are {4}, {4, 4}, {4}.Subarray 1: {4}. Maximum = 4. Sum = 1.Subarray 2: {4, 4}. Maximum = 4. Since the maximum occurs twice in the subarray, Sum = 4 + 8 = 12.Subarray 3: {4}. Maximum = 4. Sum = 16.Therefore, required output is 16. Naive Approach: The simplest approach to solve this problem is to generate all possible subarrays of the given array and find the maximum element in all subarrays along with the count of their occurrences. Finally, print the sum of all the maximum elements obtained. Follow the steps below to solve the problem: Initialize a variable, say sum, to store the required sum of maximum of all subarrays. Generate all possible subarrays of the given array arr[]. For each subarray generated, find the frequency of the largest element and check if the frequency is even or not. If found to be true, add 2 * maximum to sum. Otherwise, add maximum to sum. After completing the above steps, print the value of sum 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 calculate sum of // maximum of all subarrays void findSum(vector<int>a) { // Stores the sum of maximums int ans = 0; // Traverse the array for(int low = 0; low < a.size(); low++) { for(int high = low; high < a.size(); high++) { // Store the frequency of the // maximum element in subarray int count = 0; int maxNumber = 0; // Finding maximum for(int i = low; i <= high; i++) { // Increment frequency by 1 if (a[i] == maxNumber) count++; // If new maximum is obtained else if (a[i] > maxNumber) { maxNumber = a[i]; count = 1; } } // If frequency of maximum // is even, then add 2*maxNumber. // Otherwise, add maxNumber ans += maxNumber * ((count % 2 == 0) ? 2 : 1); } } // Print the sum obtained cout << (ans); } // Driver Code int main() { vector<int>arr = { 2, 1, 4, 4, 2 }; // Function Call findSum(arr); } // This code is contributed by amreshkumar3 // Java program for the above approach import java.io.*; class GFG { // Function to calculate sum of // maximum of all subarrays public static void findSum(int a[]) { // Stores the sum of maximums int ans = 0; // Traverse the array for (int low = 0; low < a.length; low++) { for (int high = low; high < a.length; high++) { // Store the frequency of the // maximum element in subarray int count = 0; int maxNumber = 0; // Finding maximum for (int i = low; i <= high; i++) { // Increment frequency by 1 if (a[i] == maxNumber) count++; // If new maximum is obtained else if (a[i] > maxNumber) { maxNumber = a[i]; count = 1; } } // If frequency of maximum // is even, then add 2*maxNumber. // Otherwise, add maxNumber ans += maxNumber * ((count % 2 == 0) ? 2 : 1); } } // Print the sum obtained System.out.println(ans); } // Driver Code public static void main(String[] args) { int[] arr = { 2, 1, 4, 4, 2 }; // Function Call findSum(arr); } } # Python3 program for the above approach # Function to calculate sum of # maximum of all subarrays def findSum(a): # Stores the sum of maximums ans = 0 # Traverse the array for low in range(0, len(a)): for high in range(low,len(a)): # Store the frequency of the # maximum element in subarray count = 0 maxNumber = 0 # Finding maximum for i in range(low, high + 1): # Increment frequency by 1 if (a[i] == maxNumber): count += 1 # If new maximum is obtained elif (a[i] > maxNumber): maxNumber = a[i] count = 1 # If frequency of maximum # is even, then add 2*maxNumber. # Otherwise, add maxNumber if count % 2: ans += maxNumber else: ans += maxNumber * 2 # Print the sum obtained print(ans) # Driver Code arr = [ 2, 1, 4, 4, 2 ] # Function Call findSum(arr) # This code is contributed by rohitsingh07052 // C# program for the above approach using System; class GFG { // Function to calculate sum of // maximum of all subarrays public static void findSum(int[] a) { // Stores the sum of maximums int ans = 0; // Traverse the array for (int low = 0; low < a.Length; low++) { for (int high = low; high < a.Length; high++) { // Store the frequency of the // maximum element in subarray int count = 0; int maxNumber = 0; // Finding maximum for (int i = low; i <= high; i++) { // Increment frequency by 1 if (a[i] == maxNumber) count++; // If new maximum is obtained else if (a[i] > maxNumber) { maxNumber = a[i]; count = 1; } } // If frequency of maximum // is even, then add 2*maxNumber. // Otherwise, add maxNumber ans += maxNumber * ((count % 2 == 0) ? 2 : 1); } } // Print the sum obtained Console.WriteLine(ans); } // Driver Code public static void Main() { int[] arr = { 2, 1, 4, 4, 2 }; // Function Call findSum(arr); } } // This code is contributed by ukasp. <script> // JavaScript program for the above approach // Function to calculate sum of // maximum of all subarrays function findSum(a) { // Stores the sum of maximums var ans = 0; // Traverse the array for (var low = 0; low < a.length; low++) { for (var high = low; high < a.length; high++) { // Store the frequency of the // maximum element in subarray var count = 0; var maxNumber = 0; // Finding maximum for (var i = low; i <= high; i++) { // Increment frequency by 1 if (a[i] === maxNumber) count++; // If new maximum is obtained else if (a[i] > maxNumber) { maxNumber = a[i]; count = 1; } } // If frequency of maximum // is even, then add 2*maxNumber. // Otherwise, add maxNumber ans += maxNumber * (count % 2 === 0 ? 2 : 1); } } // Print the sum obtained document.write(ans); } // Driver Code var arr = [2, 1, 4, 4, 2]; // Function Call findSum(arr); </script> 75 Time Complexity: O(N3)Auxiliary Space: O(1) Optimized Approach: To optimize the above approach, the idea is to store the prefix sums of every bit of array elements and find the frequency of the largest element in a subarray in O(1) computational complexity. This approach works as all the array elements are powers of 2. 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 maximum // in subarray {arr[low], ..., arr[high]} int getCountLargestNumber( int low, int high, int i, vector<vector<int>> prefixSums); // Function to calculate the prefix // sum array vector<vector<int>> getPrefixSums( vector<int> a); // Function to calculate sum of // maximum of all subarrays void findSum(vector<int> a) { // Calculate prefix sum array vector<vector<int>> prefixSums = getPrefixSums(a); // Store the sum of maximums int ans = 0; // Traverse the array for (int low = 0; low < a.size(); low++) { for (int high = low; high < a.size(); high++) { // Store the frequency of the // maximum element in subarray int count = 0; int maxNumber = 0; // Store prefix sum of every bit for (int i = 30; i >= 0; i--) { // Get the frequency of the // largest element in subarray count = getCountLargestNumber( low, high, i, prefixSums); if (count > 0) { maxNumber = (1 << i); // If frequency of the largest // element is even, add 2 * maxNumber // Otherwise, add maxNumber ans += maxNumber * ((count % 2 == 0) ? 2 : 1); break; } } } } // Print the required answer cout << ans; } // Function to calculate the prefix // sum array vector<vector<int>> getPrefixSums( vector<int> a) { // Initialize prefix array vector<vector<int>> prefix(32, vector<int>(a.size() + 1, 0)); // Start traversing the array for (int j = 0; j < a.size(); j++) { // Update the prefix array for // each element in the array for (int i = 0; i <= 30; i++) { // To check which bit is set int mask = (1 << i); prefix[i][j + 1] += prefix[i][j]; if ((a[j] & mask) > 0) prefix[i][j + 1]++; } } // Return prefix array return prefix; } // Function to find the maximum // in subarray {arr[low], ..., arr[high]} int getCountLargestNumber( int low, int high, int i, vector<vector<int>> prefixSums) { return prefixSums[i][high + 1] - prefixSums[i][low]; } // Driver Code int main() { vector<int> arr = { 2, 1, 4, 4, 2 }; // Function Call findSum(arr); return 0; } // This code is contributed // by Shubham Singh // Java program for the above approach import java.io.*; class GFG { // Function to calculate sum of // maximum of all subarrays public static void findSum(int a[]) { // Calculate prefix sum array int[][] prefixSums = getPrefixSums(a); // Store the sum of maximums int ans = 0; // Traverse the array for (int low = 0; low < a.length; low++) { for (int high = low; high < a.length; high++) { // Store the frequency of the // maximum element in subarray int count = 0; int maxNumber = 0; // Store prefix sum of every bit for (int i = 30; i >= 0; i--) { // Get the frequency of the // largest element in subarray count = getCountLargestNumber( low, high, i, prefixSums); if (count > 0) { maxNumber = (1 << i); // If frequency of the largest // element is even, add 2 * maxNumber // Otherwise, add maxNumber ans += maxNumber * ((count % 2 == 0) ? 2 : 1); break; } } } } // Print the required answer System.out.println(ans); } // Function to calculate the prefix // sum array public static int[][] getPrefixSums( int[] a) { // Initialize prefix array int[][] prefix = new int[32][a.length + 1]; // Start traversing the array for (int j = 0; j < a.length; j++) { // Update the prefix array for // each element in the array for (int i = 0; i <= 30; i++) { // To check which bit is set int mask = (1 << i); prefix[i][j + 1] += prefix[i][j]; if ((a[j] & mask) > 0) prefix[i][j + 1]++; } } // Return prefix array return prefix; } // Function to find the maximum // in subarray {arr[low], ..., arr[high]} public static int getCountLargestNumber( int low, int high, int i, int[][] prefixSums) { return prefixSums[i][high + 1] - prefixSums[i][low]; } // Driver Code public static void main(String[] args) { int[] arr = { 2, 1, 4, 4, 2 }; // Function Call findSum(arr); } } # Python program for the above approach # Function to calculate sum of # maximum of all subarrays def findSum(a): # Calculate prefix sum array prefixSums = getPrefixSums(a); # Store the sum of maximums ans = 1; # Traverse the array for low in range(len(a)): for high in range(len(a)): # Store the frequency of the # maximum element in subarray count = 0; maxNumber = 0; # Store prefix sum of every bit for i in range(30,0,-1): # Get the frequency of the # largest element in subarray count = getCountLargestNumber(low, high, i, prefixSums); if (count > 0): maxNumber = (1 << i); # If frequency of the largest # element is even, add 2 * maxNumber # Otherwise, add maxNumber if(count % 2 == 0): ans += maxNumber * 2; else: ans += maxNumber * 1; break; # Print the required answer print(ans); # Function to calculate the prefix # sum array def getPrefixSums(a): # Initialize prefix array prefix = [[0 for i in range(len(a)+1)] for j in range(32)]; # Start traversing the array for j in range(len(a)): # Update the prefix array for # each element in the array for i in range(31): # To check which bit is set mask = (1 << i); prefix[i][j + 1] += prefix[i][j]; if ((a[j] & mask) > 0): prefix[i][j + 1]+=1; # Return prefix array return prefix; # Function to find the maximum # in subarray:arr[low], ..., arr[high] def getCountLargestNumber(low, high, i, prefixSums): return prefixSums[i][high + 1] - prefixSums[i][low]; # Driver Code if __name__ == '__main__': arr = [ 2, 1, 4, 4, 2 ]; # Function Call findSum(arr); # This code is contributed by gauravrajput1 // C# program for the above approach using System; public class GFG { // Function to calculate sum of // maximum of all subarrays public static void findSum(int []a) { // Calculate prefix sum array int[,] prefixSums = getPrefixSums(a); // Store the sum of maximums int ans = 0; // Traverse the array for (int low = 0; low < a.Length; low++) { for (int high = low; high < a.Length; high++) { // Store the frequency of the // maximum element in subarray int count = 0; int maxNumber = 0; // Store prefix sum of every bit for (int i = 30; i >= 0; i--) { // Get the frequency of the // largest element in subarray count = getCountLargestNumber(low, high, i, prefixSums); if (count > 0) { maxNumber = (1 << i); // If frequency of the largest // element is even, add 2 * maxNumber // Otherwise, add maxNumber ans += maxNumber * ((count % 2 == 0) ? 2 : 1); break; } } } } // Print the required answer Console.WriteLine(ans); } // Function to calculate the prefix // sum array public static int[,] getPrefixSums(int[] a) { // Initialize prefix array int[,] prefix = new int[32,a.Length + 1]; // Start traversing the array for (int j = 0; j < a.Length; j++) { // Update the prefix array for // each element in the array for (int i = 0; i <= 30; i++) { // To check which bit is set int mask = (1 << i); prefix[i, j + 1] += prefix[i,j]; if ((a[j] & mask) > 0) prefix[i, j + 1]++; } } // Return prefix array return prefix; } // Function to find the maximum // in subarray {arr[low], ..., arr[high]} public static int getCountLargestNumber(int low, int high, int i, int[,] prefixSums) { return prefixSums[i,high + 1] - prefixSums[i,low]; } // Driver Code public static void Main(String[] args) { int[] arr = { 2, 1, 4, 4, 2 }; // Function Call findSum(arr); } } // This code is contributed by gauravrajput1 <script> // javascript program for the above approach // Function to calculate sum of // maximum of all subarrays function findSum(a) { // Calculate prefix sum array var prefixSums = getPrefixSums(a); // Store the sum of maximums var ans = 0; // Traverse the array for (var low = 0; low < a.length; low++) { for (var high = low; high < a.length; high++) { // Store the frequency of the // maximum element in subarray var count = 0; var maxNumber = 0; // Store prefix sum of every bit for (var i = 30; i >= 0; i--) { // Get the frequency of the // largest element in subarray count = getCountLargestNumber(low, high, i, prefixSums); if (count > 0) { maxNumber = (1 << i); // If frequency of the largest // element is even, add 2 * maxNumber // Otherwise, add maxNumber ans += maxNumber * ((count % 2 == 0) ? 2 : 1); break; } } } } // Print the required answer document.write(ans); } // Function to calculate the prefix // sum array function getPrefixSums(a) { // Initialize prefix array var prefix = Array(32).fill().map(()=>Array(a.length + 1).fill(0)); // Start traversing the array for (var j = 0; j < a.length; j++) { // Update the prefix array for // each element in the array for (var i = 0; i <= 30; i++) { // To check which bit is set var mask = (1 << i); prefix[i][j + 1] += prefix[i][j]; if ((a[j] & mask) > 0) prefix[i][j + 1]++; } } // Return prefix array return prefix; } // Function to find the maximum // in subarray {arr[low], ..., arr[high]} function getCountLargestNumber(low , high , i, prefixSums) { return prefixSums[i][high + 1] - prefixSums[i][low]; } // Driver Code var arr = [ 2, 1, 4, 4, 2 ]; // Function Call findSum(arr); // This code is contributed by gauravrajput1 </script> 75 Time Complexity: O(N2)Auxiliary Space: O(32 * N) Efficient Approach: To optimize the above approach, the idea is to use the property that all the array elements are powers of 2, and leverage that property to solve the problem. Follow the steps below to solve the problem: Iterate through all powers of 2 in descending order. Consider any arbitrary power of 2 as a mask. Divide the array into subarrays such that no subarray will contain arr[index] = -1, where an index is any valid position in the array. Let the subarray obtained from the above step be S. Traverse through S and add the values contributed by only the subarrays in S, which have the current mask, from the outer loop. Also set the corresponding position, where arr[index] = mask, to arr[index] = -1. To calculate the values contributed by all the subarrays in S that contains the mask and maintain three counters as oddCount, eventCount, and the frequency of mask. The pointer prev points to the previous index, such that arr[prev] = mask. At any index, where arr[index] = mask, get the count of integers between the last occurrence of the mask and the current occurrence by subtracting prev from the index. Use this count and the parity of frequency of mask, to get the values contributed by all contiguous subarrays that contain a mask, using the formula count = (index – prev) and add the count to the answer. If the frequency of the maximum is even or odd and if the parity is odd: Values contributed by all the contiguous subarrays that have the frequency of mask as odd is (count – 1)*evenCount + oddCount. Values contributed by all the contiguous subarrays that have the frequency of mask as even is 2*(count – 1)*oddCount + 2*evenCount. Values contributed by all the contiguous subarrays that have the frequency of mask as odd is (count – 1)*evenCount + oddCount. Values contributed by all the contiguous subarrays that have the frequency of mask as even is 2*(count – 1)*oddCount + 2*evenCount. Otherwise, if the parity is even: Values contributed by all the contiguous subarrays that have the frequency of mask as odd is (count – 1)*oddCount + evenCount. Values contributed by all the contiguous subarrays that have the frequency of mask as even is 2*(count – 1) * evenCount + 2 * oddCount. Values contributed by all the contiguous subarrays that have the frequency of mask as odd is (count – 1)*oddCount + evenCount. Values contributed by all the contiguous subarrays that have the frequency of mask as even is 2*(count – 1) * evenCount + 2 * oddCount. Add all the corresponding values to the answer. Also add the count to evenCount if parity is even. Otherwise, add count to oddCount. Below is the implementation of the above approach: Java C# Javascript // Java program for the above approach import java.io.*; class GFG { // Function to calculate sum of // maximum of all subarrays public static void findSum(int a[]) { int ans = 0; int prev = -1; // Iterate over the range [30, 0] for (int i = 30; i >= 0; i--) { int mask = (1 << i); // Inner loop through the // length of the array for (int j = 0; j < a.length; j++) { // Divide the array such // that no subarray will // have any index set to -1 if (a[j] == -1) { ans += findSumOfValuesOfRange( a, prev + 1, j - 1, mask); prev = j; } } // Find the sum of subarray ans += findSumOfValuesOfRange( a, prev + 1, a.length - 1, mask); } // Print the sum obtained System.out.println(ans); } // Function that takes any subarray // S and return values contributed // by only the subarrays in S containing mask public static int findSumOfValuesOfRange( int[] a, int low, int high, int mask) { if (low > high) return 0; // Stores count even, odd count of // occurrences and maximum element int evenCount = 0, oddCount = 0, countLargestNumber = 0; int prev = low - 1, ans = 0; // Traverse from low to high for (int i = low; i <= high; i++) { // Checking if this position // in the array is mask if ((mask & a[i]) > 0) { // Mask is the largest // number in subarray. // Increment count by 1 countLargestNumber++; // Store parity as 0 or 1 int parity = countLargestNumber % 2; // Setting a[i]=-1, this // will help in splitting // array into subarrays a[i] = -1; int count = i - prev; ans += count; // Add values contributed // by those subarrays that // have an odd frequency ans += (count - 1) * ((parity == 1) ? evenCount : oddCount); ans += ((parity == 1) ? oddCount : evenCount); // Adding values contributed // by those subarrays that // have an even frequency ans += 2 * (count - 1) * ((parity == 1) ? oddCount : evenCount); ans += 2 * ((parity == 1) ? evenCount : oddCount); // Set the prev pointer // to this position prev = i; if (parity == 1) oddCount += count; else evenCount += count; } } if (prev != low - 1) { int count = high - prev; int parity = countLargestNumber % 2; ans += count * ((parity == 1) ? oddCount : evenCount); ans += 2 * count * ((parity == 1) ? evenCount : oddCount); ans *= mask; } // Return the final sum return ans; } // Driver Code public static void main(String[] args) { int[] arr = { 2, 1, 4, 4, 2 }; // Function call findSum(arr); } } // C# program for the above approach using System; public class GFG { // Function to calculate sum of // maximum of all subarrays public static void findSum(int []a) { int ans = 0; int prev = -1; // Iterate over the range [30, 0] for (int i = 30; i >= 0; i--) { int mask = (1 << i); // Inner loop through the // length of the array for (int j = 0; j < a.Length; j++) { // Divide the array such // that no subarray will // have any index set to -1 if (a[j] == -1) { ans += findSumOfValuesOfRange(a, prev + 1, j - 1, mask); prev = j; } } // Find the sum of subarray ans += findSumOfValuesOfRange(a, prev + 1, a.Length - 1, mask); } // Print the sum obtained Console.WriteLine(ans); } // Function that takes any subarray // S and return values contributed // by only the subarrays in S containing mask public static int findSumOfValuesOfRange(int[] a, int low, int high, int mask) { if (low > high) return 0; // Stores count even, odd count of // occurrences and maximum element int evenCount = 0, oddCount = 0, countLargestNumber = 0; int prev = low - 1, ans = 0; // Traverse from low to high for (int i = low; i <= high; i++) { // Checking if this position // in the array is mask if ((mask & a[i]) > 0) { // Mask is the largest // number in subarray. // Increment count by 1 countLargestNumber++; // Store parity as 0 or 1 int parity = countLargestNumber % 2; // Setting a[i]=-1, this // will help in splitting // array into subarrays a[i] = -1; int count = i - prev; ans += count; // Add values contributed // by those subarrays that // have an odd frequency ans += (count - 1) * ((parity == 1) ? evenCount : oddCount); ans += ((parity == 1) ? oddCount : evenCount); // Adding values contributed // by those subarrays that // have an even frequency ans += 2 * (count - 1) * ((parity == 1) ? oddCount : evenCount); ans += 2 * ((parity == 1) ? evenCount : oddCount); // Set the prev pointer // to this position prev = i; if (parity == 1) oddCount += count; else evenCount += count; } } if (prev != low - 1) { int count = high - prev; int parity = countLargestNumber % 2; ans += count * ((parity == 1) ? oddCount : evenCount); ans += 2 * count * ((parity == 1) ? evenCount : oddCount); ans *= mask; } // Return the readonly sum return ans; } // Driver Code public static void Main(String[] args) { int[] arr = { 2, 1, 4, 4, 2 }; // Function call findSum(arr); } } // This code is contributed by gauravrajput1 <script> // javascript program for the above approach // Function to calculate sum of // maximum of all subarrays function findSum(a) { var ans = 0; var prev = -1; // Iterate over the range [30, 0] for (var i = 30; i >= 0; i--) { var mask = (1 << i); // Inner loop through the // length of the array for (var j = 0; j < a.length; j++) { // Divide the array such // that no subarray will // have any index set to -1 if (a[j] == -1) { ans += findSumOfValuesOfRange(a, prev + 1, j - 1, mask); prev = j; } } // Find the sum of subarray ans += findSumOfValuesOfRange(a, prev + 1, a.length - 1, mask); } // Print the sum obtained document.write(ans); } // Function that takes any subarray // S and return values contributed // by only the subarrays in S containing mask function findSumOfValuesOfRange(a , low , high , mask) { if (low > high) return 0; // Stores count even, odd count of // occurrences and maximum element var evenCount = 0, oddCount = 0, countLargestNumber = 0; var prev = low - 1, ans = 0; // Traverse from low to high for (var i = low; i <= high; i++) { // Checking if this position // in the array is mask if ((mask & a[i]) > 0) { // Mask is the largest // number in subarray. // Increment count by 1 countLargestNumber++; // Store parity as 0 or 1 var parity = countLargestNumber % 2; // Setting a[i]=-1, this // will help in splitting // array into subarrays a[i] = -1; var count = i - prev; ans += count; // Add values contributed // by those subarrays that // have an odd frequency ans += (count - 1) * ((parity == 1) ? evenCount : oddCount); ans += ((parity == 1) ? oddCount : evenCount); // Adding values contributed // by those subarrays that // have an even frequency ans += 2 * (count - 1) * ((parity == 1) ? oddCount : evenCount); ans += 2 * ((parity == 1) ? evenCount : oddCount); // Set the prev pointer // to this position prev = i; if (parity == 1) oddCount += count; else evenCount += count; } } if (prev != low - 1) { var count = high - prev; var parity = countLargestNumber % 2; ans += count * ((parity == 1) ? oddCount : evenCount); ans += 2 * count * ((parity == 1) ? evenCount : oddCount); ans *= mask; } // Return the final sum return ans; } // Driver Code var arr = [ 2, 1, 4, 4, 2 ]; // Function call findSum(arr); // This code is contributed by gauravrajput1 </script> 75 Time Complexity: O(30*N)Auxiliary Space: O(1) jithin ukasp rohitsingh07052 simmytarika5 rdtank amreshkumar3 GauravRajput1 simranarora5sos SHUBHAMSINGH10 adnanirshad158 saurabh1990aror frequency-counting maths-power setBitCount subarray Arrays Bit Magic Mathematical Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Multidimensional Arrays in Java Queue | Set 1 (Introduction and Array Implementation) Linear Search Python | Using 2D arrays/lists the right way Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Cyclic Redundancy Check and Modulo-2 Division Count set bits in an integer
[ { "code": null, "e": 24785, "s": 24754, "text": " \n07 Feb, 2022\n" }, { "code": null, "e": 24958, "s": 24785, "text": "Given an array arr[] consisting of N integers (All array elements are a perfect power of 2), the task is to calculate the sum of the maximum elements in all the subarrays. " }, { "code": null, "e": 25075, "s": 24958, "text": "Note: If the frequency of the maximum element in a subarray is even, add twice the value of that element to the sum." }, { "code": null, "e": 25085, "s": 25075, "text": "Examples:" }, { "code": null, "e": 25322, "s": 25085, "text": "Input: arr[] = {1, 2}Output: 5Explanation: All possible subarrays are {1}, {1, 2}, {2}. Subarray 1: {1}. Maximum = 1. Sum = 1.Subarray 2: {1, 2}. Maximum = 2. Sum = 3.Subarray 3: {2}. Maximum = 2.Sum = 5.Therefore, required output is 5." }, { "code": null, "e": 25619, "s": 25322, "text": "Input: arr[] = {4, 4}Output: 16Explanation: All possible subarrays are {4}, {4, 4}, {4}.Subarray 1: {4}. Maximum = 4. Sum = 1.Subarray 2: {4, 4}. Maximum = 4. Since the maximum occurs twice in the subarray, Sum = 4 + 8 = 12.Subarray 3: {4}. Maximum = 4. Sum = 16.Therefore, required output is 16." }, { "code": null, "e": 25931, "s": 25619, "text": "Naive Approach: The simplest approach to solve this problem is to generate all possible subarrays of the given array and find the maximum element in all subarrays along with the count of their occurrences. Finally, print the sum of all the maximum elements obtained. Follow the steps below to solve the problem:" }, { "code": null, "e": 26018, "s": 25931, "text": "Initialize a variable, say sum, to store the required sum of maximum of all subarrays." }, { "code": null, "e": 26076, "s": 26018, "text": "Generate all possible subarrays of the given array arr[]." }, { "code": null, "e": 26266, "s": 26076, "text": "For each subarray generated, find the frequency of the largest element and check if the frequency is even or not. If found to be true, add 2 * maximum to sum. Otherwise, add maximum to sum." }, { "code": null, "e": 26338, "s": 26266, "text": "After completing the above steps, print the value of sum as the result." }, { "code": null, "e": 26389, "s": 26338, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26393, "s": 26389, "text": "C++" }, { "code": null, "e": 26398, "s": 26393, "text": "Java" }, { "code": null, "e": 26406, "s": 26398, "text": "Python3" }, { "code": null, "e": 26409, "s": 26406, "text": "C#" }, { "code": null, "e": 26420, "s": 26409, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach\n#include<bits/stdc++.h>\nusing namespace std;\n \n// Function to calculate sum of\n// maximum of all subarrays\nvoid findSum(vector<int>a)\n{\n // Stores the sum of maximums\n int ans = 0;\n \n // Traverse the array\n for(int low = 0;\n low < a.size(); \n low++) \n {\n for(int high = low;\n high < a.size();\n high++)\n {\n \n // Store the frequency of the\n // maximum element in subarray\n int count = 0;\n int maxNumber = 0;\n \n // Finding maximum\n for(int i = low;\n i <= high; i++) \n {\n \n // Increment frequency by 1\n if (a[i] == maxNumber)\n count++;\n \n // If new maximum is obtained\n else if (a[i] > maxNumber)\n {\n maxNumber = a[i];\n count = 1;\n }\n }\n \n // If frequency of maximum\n // is even, then add 2*maxNumber.\n // Otherwise, add maxNumber\n ans += maxNumber * ((count % 2 == 0) ? 2 : 1);\n }\n }\n \n // Print the sum obtained\n cout << (ans);\n}\n \n// Driver Code\nint main()\n{\n vector<int>arr = { 2, 1, 4, 4, 2 };\n \n // Function Call\n findSum(arr);\n}\n \n// This code is contributed by amreshkumar3\n\n\n\n\n\n", "e": 27895, "s": 26430, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program for the above approach\n \nimport java.io.*;\n \nclass GFG {\n \n // Function to calculate sum of\n // maximum of all subarrays\n public static void findSum(int a[])\n {\n // Stores the sum of maximums\n int ans = 0;\n \n // Traverse the array\n for (int low = 0;\n low < a.length; low++) {\n \n for (int high = low;\n high < a.length;\n high++) {\n \n // Store the frequency of the\n // maximum element in subarray\n int count = 0;\n int maxNumber = 0;\n \n // Finding maximum\n for (int i = low;\n i <= high; i++) {\n \n // Increment frequency by 1\n if (a[i] == maxNumber)\n count++;\n \n // If new maximum is obtained\n else if (a[i] > maxNumber) {\n maxNumber = a[i];\n count = 1;\n }\n }\n \n // If frequency of maximum\n // is even, then add 2*maxNumber.\n // Otherwise, add maxNumber\n ans += maxNumber\n * ((count % 2 == 0) ? 2 : 1);\n }\n }\n \n // Print the sum obtained\n System.out.println(ans);\n }\n \n // Driver Code\n public static void main(String[] args)\n {\n int[] arr = { 2, 1, 4, 4, 2 };\n \n // Function Call\n findSum(arr);\n }\n}\n\n\n\n\n\n", "e": 29463, "s": 27905, "text": null }, { "code": "\n\n\n\n\n\n\n# Python3 program for the above approach\n \n# Function to calculate sum of\n# maximum of all subarrays\ndef findSum(a):\n \n # Stores the sum of maximums\n ans = 0\n \n # Traverse the array\n for low in range(0, len(a)):\n for high in range(low,len(a)):\n \n # Store the frequency of the\n # maximum element in subarray\n count = 0\n maxNumber = 0\n \n # Finding maximum\n for i in range(low, high + 1):\n \n # Increment frequency by 1\n if (a[i] == maxNumber):\n count += 1\n \n # If new maximum is obtained\n elif (a[i] > maxNumber):\n maxNumber = a[i]\n count = 1\n \n # If frequency of maximum\n # is even, then add 2*maxNumber.\n # Otherwise, add maxNumber\n if count % 2:\n ans += maxNumber\n else:\n ans += maxNumber * 2\n \n # Print the sum obtained\n print(ans)\n \n# Driver Code\narr = [ 2, 1, 4, 4, 2 ]\n \n# Function Call\nfindSum(arr)\n \n# This code is contributed by rohitsingh07052\n\n\n\n\n\n", "e": 30523, "s": 29473, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program for the above approach\nusing System;\n \nclass GFG {\n \n // Function to calculate sum of\n // maximum of all subarrays\n public static void findSum(int[] a)\n {\n \n // Stores the sum of maximums\n int ans = 0;\n \n // Traverse the array\n for (int low = 0; low < a.Length; low++) {\n \n for (int high = low; high < a.Length; high++) {\n \n // Store the frequency of the\n // maximum element in subarray\n int count = 0;\n int maxNumber = 0;\n \n // Finding maximum\n for (int i = low; i <= high; i++) {\n \n // Increment frequency by 1\n if (a[i] == maxNumber)\n count++;\n \n // If new maximum is obtained\n else if (a[i] > maxNumber) {\n maxNumber = a[i];\n count = 1;\n }\n }\n \n // If frequency of maximum\n // is even, then add 2*maxNumber.\n // Otherwise, add maxNumber\n ans += maxNumber\n * ((count % 2 == 0) ? 2 : 1);\n }\n }\n \n // Print the sum obtained\n Console.WriteLine(ans);\n }\n \n // Driver Code\n public static void Main()\n {\n int[] arr = { 2, 1, 4, 4, 2 };\n \n // Function Call\n findSum(arr);\n }\n}\n \n// This code is contributed by ukasp.\n\n\n\n\n\n", "e": 31790, "s": 30533, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n \n // JavaScript program for the above approach\n \n // Function to calculate sum of\n // maximum of all subarrays\n function findSum(a) {\n // Stores the sum of maximums\n var ans = 0;\n \n // Traverse the array\n for (var low = 0; low < a.length; low++) {\n for (var high = low; high < a.length; high++) {\n // Store the frequency of the\n // maximum element in subarray\n var count = 0;\n var maxNumber = 0;\n \n // Finding maximum\n for (var i = low; i <= high; i++) {\n // Increment frequency by 1\n if (a[i] === maxNumber) count++;\n // If new maximum is obtained\n else if (a[i] > maxNumber) {\n maxNumber = a[i];\n count = 1;\n }\n }\n \n // If frequency of maximum\n // is even, then add 2*maxNumber.\n // Otherwise, add maxNumber\n ans += maxNumber * (count % 2 === 0 ? 2 : 1);\n }\n }\n \n // Print the sum obtained\n document.write(ans);\n }\n \n // Driver Code\n var arr = [2, 1, 4, 4, 2];\n \n // Function Call\n findSum(arr);\n \n</script>\n\n\n\n\n\n", "e": 33071, "s": 31800, "text": null }, { "code": null, "e": 33074, "s": 33071, "text": "75" }, { "code": null, "e": 33120, "s": 33076, "text": "Time Complexity: O(N3)Auxiliary Space: O(1)" }, { "code": null, "e": 33397, "s": 33120, "text": "Optimized Approach: To optimize the above approach, the idea is to store the prefix sums of every bit of array elements and find the frequency of the largest element in a subarray in O(1) computational complexity. This approach works as all the array elements are powers of 2." }, { "code": null, "e": 33448, "s": 33397, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 33452, "s": 33448, "text": "C++" }, { "code": null, "e": 33457, "s": 33452, "text": "Java" }, { "code": null, "e": 33465, "s": 33457, "text": "Python3" }, { "code": null, "e": 33468, "s": 33465, "text": "C#" }, { "code": null, "e": 33479, "s": 33468, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// c++ program for the above approach\n#include<bits/stdc++.h>\nusing namespace std;\n \n// Function to find the maximum\n// in subarray {arr[low], ..., arr[high]}\nint getCountLargestNumber(\n int low, int high, int i,\n vector<vector<int>> prefixSums);\n \n// Function to calculate the prefix\n// sum array\nvector<vector<int>> getPrefixSums(\n vector<int> a);\n \n// Function to calculate sum of\n// maximum of all subarrays\nvoid findSum(vector<int> a)\n{\n // Calculate prefix sum array\n vector<vector<int>> prefixSums\n = getPrefixSums(a);\n \n // Store the sum of maximums\n int ans = 0;\n \n // Traverse the array\n for (int low = 0;\n low < a.size();\n low++) {\n \n for (int high = low;\n high < a.size();\n high++) {\n \n // Store the frequency of the\n // maximum element in subarray\n int count = 0;\n int maxNumber = 0;\n \n // Store prefix sum of every bit\n for (int i = 30; i >= 0; i--) {\n \n // Get the frequency of the\n // largest element in subarray\n count = getCountLargestNumber(\n low, high, i, prefixSums);\n \n if (count > 0) {\n maxNumber = (1 << i);\n \n // If frequency of the largest\n // element is even, add 2 * maxNumber\n // Otherwise, add maxNumber\n ans += maxNumber\n * ((count % 2 == 0) ? 2 : 1);\n break;\n }\n }\n }\n }\n \n // Print the required answer\n cout << ans;\n}\n \n// Function to calculate the prefix\n// sum array\nvector<vector<int>> getPrefixSums(\n vector<int> a)\n{\n \n // Initialize prefix array\n vector<vector<int>> prefix(32, vector<int>(a.size() + 1, 0));\n \n // Start traversing the array\n for (int j = 0; j < a.size(); j++) {\n \n // Update the prefix array for\n // each element in the array\n for (int i = 0; i <= 30; i++) {\n \n // To check which bit is set\n int mask = (1 << i);\n prefix[i][j + 1] += prefix[i][j];\n if ((a[j] & mask) > 0)\n prefix[i][j + 1]++;\n }\n }\n \n // Return prefix array\n return prefix;\n}\n \n// Function to find the maximum\n// in subarray {arr[low], ..., arr[high]}\nint getCountLargestNumber(\n int low, int high, int i,\n vector<vector<int>> prefixSums)\n{\n return prefixSums[i][high + 1]\n - prefixSums[i][low];\n}\n \n// Driver Code\nint main()\n{\n vector<int> arr = { 2, 1, 4, 4, 2 };\n \n // Function Call\n findSum(arr);\n return 0;\n}\n \n// This code is contributed\n// by Shubham Singh\n\n\n\n\n\n", "e": 35940, "s": 33489, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program for the above approach\nimport java.io.*;\n \nclass GFG {\n \n // Function to calculate sum of\n // maximum of all subarrays\n public static void findSum(int a[])\n {\n // Calculate prefix sum array\n int[][] prefixSums\n = getPrefixSums(a);\n \n // Store the sum of maximums\n int ans = 0;\n \n // Traverse the array\n for (int low = 0;\n low < a.length;\n low++) {\n \n for (int high = low;\n high < a.length;\n high++) {\n \n // Store the frequency of the\n // maximum element in subarray\n int count = 0;\n int maxNumber = 0;\n \n // Store prefix sum of every bit\n for (int i = 30; i >= 0; i--) {\n \n // Get the frequency of the\n // largest element in subarray\n count = getCountLargestNumber(\n low, high, i, prefixSums);\n \n if (count > 0) {\n maxNumber = (1 << i);\n \n // If frequency of the largest\n // element is even, add 2 * maxNumber\n // Otherwise, add maxNumber\n ans += maxNumber\n * ((count % 2 == 0) ? 2 : 1);\n break;\n }\n }\n }\n }\n \n // Print the required answer\n System.out.println(ans);\n }\n \n // Function to calculate the prefix\n // sum array\n public static int[][] getPrefixSums(\n int[] a)\n {\n \n // Initialize prefix array\n int[][] prefix = new int[32][a.length + 1];\n \n // Start traversing the array\n for (int j = 0; j < a.length; j++) {\n \n // Update the prefix array for\n // each element in the array\n for (int i = 0; i <= 30; i++) {\n \n // To check which bit is set\n int mask = (1 << i);\n prefix[i][j + 1] += prefix[i][j];\n if ((a[j] & mask) > 0)\n prefix[i][j + 1]++;\n }\n }\n \n // Return prefix array\n return prefix;\n }\n \n // Function to find the maximum\n // in subarray {arr[low], ..., arr[high]}\n public static int\n getCountLargestNumber(\n int low, int high, int i,\n int[][] prefixSums)\n {\n return prefixSums[i][high + 1]\n - prefixSums[i][low];\n }\n \n // Driver Code\n public static void main(String[] args)\n {\n int[] arr = { 2, 1, 4, 4, 2 };\n \n // Function Call\n findSum(arr);\n }\n}\n\n\n\n\n\n", "e": 38678, "s": 35950, "text": null }, { "code": "\n\n\n\n\n\n\n# Python program for the above approach\n \n# Function to calculate sum of\n# maximum of all subarrays\ndef findSum(a):\n \n # Calculate prefix sum array\n prefixSums = getPrefixSums(a);\n \n # Store the sum of maximums\n ans = 1;\n \n # Traverse the array\n for low in range(len(a)):\n \n for high in range(len(a)):\n \n # Store the frequency of the\n # maximum element in subarray\n count = 0;\n maxNumber = 0;\n \n # Store prefix sum of every bit\n for i in range(30,0,-1):\n \n # Get the frequency of the\n # largest element in subarray\n count = getCountLargestNumber(low, high, i, prefixSums);\n \n if (count > 0):\n maxNumber = (1 << i);\n \n # If frequency of the largest\n # element is even, add 2 * maxNumber\n # Otherwise, add maxNumber\n if(count % 2 == 0):\n ans += maxNumber * 2;\n else:\n ans += maxNumber * 1;\n break;\n \n # Print the required answer\n print(ans);\n \n# Function to calculate the prefix\n# sum array\ndef getPrefixSums(a):\n \n # Initialize prefix array\n prefix = [[0 for i in range(len(a)+1)] for j in range(32)];\n \n # Start traversing the array\n for j in range(len(a)):\n \n # Update the prefix array for\n # each element in the array\n for i in range(31):\n \n # To check which bit is set\n mask = (1 << i);\n prefix[i][j + 1] += prefix[i][j];\n if ((a[j] & mask) > 0):\n prefix[i][j + 1]+=1;\n \n # Return prefix array\n return prefix;\n \n# Function to find the maximum\n# in subarray:arr[low], ..., arr[high]\ndef getCountLargestNumber(low, high, i, prefixSums):\n return prefixSums[i][high + 1] - prefixSums[i][low];\n \n# Driver Code\nif __name__ == '__main__':\n arr = [ 2, 1, 4, 4, 2 ];\n \n # Function Call\n findSum(arr);\n \n# This code is contributed by gauravrajput1 \n\n\n\n\n\n", "e": 40816, "s": 38688, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program for the above approach\n \n \nusing System;\npublic class GFG {\n \n // Function to calculate sum of\n // maximum of all subarrays\n public static void findSum(int []a) {\n // Calculate prefix sum array\n int[,] prefixSums = getPrefixSums(a);\n \n // Store the sum of maximums\n int ans = 0;\n \n // Traverse the array\n for (int low = 0; low < a.Length; low++) {\n \n for (int high = low; high < a.Length; high++) {\n \n // Store the frequency of the\n // maximum element in subarray\n int count = 0;\n int maxNumber = 0;\n \n // Store prefix sum of every bit\n for (int i = 30; i >= 0; i--) {\n \n // Get the frequency of the\n // largest element in subarray\n count = getCountLargestNumber(low, high, i, prefixSums);\n \n if (count > 0) {\n maxNumber = (1 << i);\n \n // If frequency of the largest\n // element is even, add 2 * maxNumber\n // Otherwise, add maxNumber\n ans += maxNumber * ((count % 2 == 0) ? 2 : 1);\n break;\n }\n }\n }\n }\n \n // Print the required answer\n Console.WriteLine(ans);\n }\n \n // Function to calculate the prefix\n // sum array\n public static int[,] getPrefixSums(int[] a) {\n \n // Initialize prefix array\n int[,] prefix = new int[32,a.Length + 1];\n \n // Start traversing the array\n for (int j = 0; j < a.Length; j++) {\n \n // Update the prefix array for\n // each element in the array\n for (int i = 0; i <= 30; i++) {\n \n // To check which bit is set\n int mask = (1 << i);\n prefix[i, j + 1] += prefix[i,j];\n if ((a[j] & mask) > 0)\n prefix[i, j + 1]++;\n }\n }\n \n // Return prefix array\n return prefix;\n }\n \n // Function to find the maximum\n // in subarray {arr[low], ..., arr[high]}\n public static int getCountLargestNumber(int low, int high, int i, int[,] prefixSums) {\n return prefixSums[i,high + 1] - prefixSums[i,low];\n }\n \n // Driver Code\n public static void Main(String[] args) {\n int[] arr = { 2, 1, 4, 4, 2 };\n \n // Function Call\n findSum(arr);\n }\n}\n \n// This code is contributed by gauravrajput1 \n\n\n\n\n\n", "e": 43410, "s": 40826, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n// javascript program for the above approach\n \n // Function to calculate sum of\n // maximum of all subarrays\n function findSum(a)\n {\n \n // Calculate prefix sum array\n var prefixSums = getPrefixSums(a);\n \n // Store the sum of maximums\n var ans = 0;\n \n // Traverse the array\n for (var low = 0; low < a.length; low++) {\n \n for (var high = low; high < a.length; high++) {\n \n // Store the frequency of the\n // maximum element in subarray\n var count = 0;\n var maxNumber = 0;\n \n // Store prefix sum of every bit\n for (var i = 30; i >= 0; i--) {\n \n // Get the frequency of the\n // largest element in subarray\n count = getCountLargestNumber(low, high, i, prefixSums);\n \n if (count > 0) {\n maxNumber = (1 << i);\n \n // If frequency of the largest\n // element is even, add 2 * maxNumber\n // Otherwise, add maxNumber\n ans += maxNumber * ((count % 2 == 0) ? 2 : 1);\n break;\n }\n }\n }\n }\n \n // Print the required answer\n document.write(ans);\n }\n \n // Function to calculate the prefix\n // sum array\n function getPrefixSums(a) {\n \n // Initialize prefix array\n var prefix = Array(32).fill().map(()=>Array(a.length + 1).fill(0));\n \n // Start traversing the array\n for (var j = 0; j < a.length; j++) {\n \n // Update the prefix array for\n // each element in the array\n for (var i = 0; i <= 30; i++) {\n \n // To check which bit is set\n var mask = (1 << i);\n prefix[i][j + 1] += prefix[i][j];\n if ((a[j] & mask) > 0)\n prefix[i][j + 1]++;\n }\n }\n \n // Return prefix array\n return prefix;\n }\n \n // Function to find the maximum\n // in subarray {arr[low], ..., arr[high]}\n function getCountLargestNumber(low , high , i, prefixSums) {\n return prefixSums[i][high + 1] - prefixSums[i][low];\n }\n \n // Driver Code\n var arr = [ 2, 1, 4, 4, 2 ];\n \n // Function Call\n findSum(arr);\n \n// This code is contributed by gauravrajput1\n</script>\n\n\n\n\n\n", "e": 45913, "s": 43420, "text": null }, { "code": null, "e": 45916, "s": 45913, "text": "75" }, { "code": null, "e": 45967, "s": 45918, "text": "Time Complexity: O(N2)Auxiliary Space: O(32 * N)" }, { "code": null, "e": 46190, "s": 45967, "text": "Efficient Approach: To optimize the above approach, the idea is to use the property that all the array elements are powers of 2, and leverage that property to solve the problem. Follow the steps below to solve the problem:" }, { "code": null, "e": 46288, "s": 46190, "text": "Iterate through all powers of 2 in descending order. Consider any arbitrary power of 2 as a mask." }, { "code": null, "e": 46423, "s": 46288, "text": "Divide the array into subarrays such that no subarray will contain arr[index] = -1, where an index is any valid position in the array." }, { "code": null, "e": 46685, "s": 46423, "text": "Let the subarray obtained from the above step be S. Traverse through S and add the values contributed by only the subarrays in S, which have the current mask, from the outer loop. Also set the corresponding position, where arr[index] = mask, to arr[index] = -1." }, { "code": null, "e": 46850, "s": 46685, "text": "To calculate the values contributed by all the subarrays in S that contains the mask and maintain three counters as oddCount, eventCount, and the frequency of mask." }, { "code": null, "e": 46925, "s": 46850, "text": "The pointer prev points to the previous index, such that arr[prev] = mask." }, { "code": null, "e": 47298, "s": 46925, "text": "At any index, where arr[index] = mask, get the count of integers between the last occurrence of the mask and the current occurrence by subtracting prev from the index. Use this count and the parity of frequency of mask, to get the values contributed by all contiguous subarrays that contain a mask, using the formula count = (index – prev) and add the count to the answer." }, { "code": null, "e": 47633, "s": 47298, "text": "If the frequency of the maximum is even or odd and if the parity is odd:\n\nValues contributed by all the contiguous subarrays that have the frequency of mask as odd is (count – 1)*evenCount + oddCount.\nValues contributed by all the contiguous subarrays that have the frequency of mask as even is 2*(count – 1)*oddCount + 2*evenCount.\n\n" }, { "code": null, "e": 47760, "s": 47633, "text": "Values contributed by all the contiguous subarrays that have the frequency of mask as odd is (count – 1)*evenCount + oddCount." }, { "code": null, "e": 47892, "s": 47760, "text": "Values contributed by all the contiguous subarrays that have the frequency of mask as even is 2*(count – 1)*oddCount + 2*evenCount." }, { "code": null, "e": 48192, "s": 47892, "text": "Otherwise, if the parity is even:\n\nValues contributed by all the contiguous subarrays that have the frequency of mask as odd is (count – 1)*oddCount + evenCount.\nValues contributed by all the contiguous subarrays that have the frequency of mask as even is 2*(count – 1) * evenCount + 2 * oddCount.\n\n" }, { "code": null, "e": 48319, "s": 48192, "text": "Values contributed by all the contiguous subarrays that have the frequency of mask as odd is (count – 1)*oddCount + evenCount." }, { "code": null, "e": 48455, "s": 48319, "text": "Values contributed by all the contiguous subarrays that have the frequency of mask as even is 2*(count – 1) * evenCount + 2 * oddCount." }, { "code": null, "e": 48588, "s": 48455, "text": "Add all the corresponding values to the answer. Also add the count to evenCount if parity is even. Otherwise, add count to oddCount." }, { "code": null, "e": 48639, "s": 48588, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 48644, "s": 48639, "text": "Java" }, { "code": null, "e": 48647, "s": 48644, "text": "C#" }, { "code": null, "e": 48658, "s": 48647, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// Java program for the above approach\nimport java.io.*;\n \nclass GFG {\n \n // Function to calculate sum of\n // maximum of all subarrays\n public static void findSum(int a[])\n {\n int ans = 0;\n int prev = -1;\n \n // Iterate over the range [30, 0]\n for (int i = 30; i >= 0; i--) {\n int mask = (1 << i);\n \n // Inner loop through the\n // length of the array\n for (int j = 0;\n j < a.length; j++) {\n \n // Divide the array such\n // that no subarray will\n // have any index set to -1\n if (a[j] == -1) {\n ans += findSumOfValuesOfRange(\n a, prev + 1, j - 1, mask);\n prev = j;\n }\n }\n \n // Find the sum of subarray\n ans += findSumOfValuesOfRange(\n a, prev + 1, a.length - 1, mask);\n }\n \n // Print the sum obtained\n System.out.println(ans);\n }\n \n // Function that takes any subarray\n // S and return values contributed\n // by only the subarrays in S containing mask\n public static int findSumOfValuesOfRange(\n int[] a, int low, int high, int mask)\n {\n if (low > high)\n return 0;\n \n // Stores count even, odd count of\n // occurrences and maximum element\n int evenCount = 0, oddCount = 0,\n countLargestNumber = 0;\n int prev = low - 1, ans = 0;\n \n // Traverse from low to high\n for (int i = low; i <= high; i++) {\n \n // Checking if this position\n // in the array is mask\n if ((mask & a[i]) > 0) {\n \n // Mask is the largest\n // number in subarray.\n // Increment count by 1\n countLargestNumber++;\n \n // Store parity as 0 or 1\n int parity = countLargestNumber % 2;\n \n // Setting a[i]=-1, this\n // will help in splitting\n // array into subarrays\n a[i] = -1;\n int count = i - prev;\n ans += count;\n \n // Add values contributed\n // by those subarrays that\n // have an odd frequency\n ans += (count - 1)\n * ((parity == 1) ? evenCount\n : oddCount);\n ans += ((parity == 1) ? oddCount\n : evenCount);\n \n // Adding values contributed\n // by those subarrays that\n // have an even frequency\n ans += 2 * (count - 1)\n * ((parity == 1) ? oddCount\n : evenCount);\n ans += 2\n * ((parity == 1) ? evenCount\n : oddCount);\n \n // Set the prev pointer\n // to this position\n prev = i;\n \n if (parity == 1)\n oddCount += count;\n else\n evenCount += count;\n }\n }\n \n if (prev != low - 1) {\n int count = high - prev;\n int parity = countLargestNumber % 2;\n \n ans += count\n * ((parity == 1)\n ? oddCount\n : evenCount);\n ans += 2 * count\n * ((parity == 1)\n ? evenCount\n : oddCount);\n ans *= mask;\n }\n \n // Return the final sum\n return ans;\n }\n \n // Driver Code\n public static void main(String[] args)\n {\n int[] arr = { 2, 1, 4, 4, 2 };\n \n // Function call\n findSum(arr);\n }\n}\n\n\n\n\n\n", "e": 52567, "s": 48668, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program for the above approach\nusing System;\npublic class GFG {\n \n // Function to calculate sum of\n // maximum of all subarrays\n public static void findSum(int []a) {\n int ans = 0;\n int prev = -1;\n \n // Iterate over the range [30, 0]\n for (int i = 30; i >= 0; i--) {\n int mask = (1 << i);\n \n // Inner loop through the\n // length of the array\n for (int j = 0; j < a.Length; j++) {\n \n // Divide the array such\n // that no subarray will\n // have any index set to -1\n if (a[j] == -1) {\n ans += findSumOfValuesOfRange(a, prev + 1, j - 1, mask);\n prev = j;\n }\n }\n \n // Find the sum of subarray\n ans += findSumOfValuesOfRange(a, prev + 1, a.Length - 1, mask);\n }\n \n // Print the sum obtained\n Console.WriteLine(ans);\n }\n \n // Function that takes any subarray\n // S and return values contributed\n // by only the subarrays in S containing mask\n public static int findSumOfValuesOfRange(int[] a, int low, \n int high, int mask) \n {\n if (low > high)\n return 0;\n \n // Stores count even, odd count of\n // occurrences and maximum element\n int evenCount = 0, oddCount = 0, countLargestNumber = 0;\n int prev = low - 1, ans = 0;\n \n // Traverse from low to high\n for (int i = low; i <= high; i++) {\n \n // Checking if this position\n // in the array is mask\n if ((mask & a[i]) > 0) {\n \n // Mask is the largest\n // number in subarray.\n // Increment count by 1\n countLargestNumber++;\n \n // Store parity as 0 or 1\n int parity = countLargestNumber % 2;\n \n // Setting a[i]=-1, this\n // will help in splitting\n // array into subarrays\n a[i] = -1;\n int count = i - prev;\n ans += count;\n \n // Add values contributed\n // by those subarrays that\n // have an odd frequency\n ans += (count - 1) * ((parity == 1) ? evenCount : oddCount);\n ans += ((parity == 1) ? oddCount : evenCount);\n \n // Adding values contributed\n // by those subarrays that\n // have an even frequency\n ans += 2 * (count - 1) * ((parity == 1) ? oddCount : evenCount);\n ans += 2 * ((parity == 1) ? evenCount : oddCount);\n \n // Set the prev pointer\n // to this position\n prev = i;\n \n if (parity == 1)\n oddCount += count;\n else\n evenCount += count;\n }\n }\n \n if (prev != low - 1) {\n int count = high - prev;\n int parity = countLargestNumber % 2;\n \n ans += count * ((parity == 1) ? oddCount : evenCount);\n ans += 2 * count * ((parity == 1) ? evenCount : oddCount);\n ans *= mask;\n }\n \n // Return the readonly sum\n return ans;\n }\n \n // Driver Code\n public static void Main(String[] args) {\n int[] arr = { 2, 1, 4, 4, 2 };\n \n // Function call\n findSum(arr);\n }\n}\n \n// This code is contributed by gauravrajput1\n\n\n\n\n\n", "e": 56114, "s": 52577, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n// javascript program for the above approach\n \n // Function to calculate sum of\n // maximum of all subarrays\n function findSum(a) {\n var ans = 0;\n var prev = -1;\n \n // Iterate over the range [30, 0]\n for (var i = 30; i >= 0; i--) {\n var mask = (1 << i);\n \n // Inner loop through the\n // length of the array\n for (var j = 0; j < a.length; j++) {\n \n // Divide the array such\n // that no subarray will\n // have any index set to -1\n if (a[j] == -1) {\n ans += findSumOfValuesOfRange(a, prev + 1, j - 1, mask);\n prev = j;\n }\n }\n \n // Find the sum of subarray\n ans += findSumOfValuesOfRange(a, prev + 1, a.length - 1, mask);\n }\n \n // Print the sum obtained\n document.write(ans);\n }\n \n // Function that takes any subarray\n // S and return values contributed\n // by only the subarrays in S containing mask\n function findSumOfValuesOfRange(a , low , high , mask) {\n if (low > high)\n return 0;\n \n // Stores count even, odd count of\n // occurrences and maximum element\n var evenCount = 0, oddCount = 0, countLargestNumber = 0;\n var prev = low - 1, ans = 0;\n \n // Traverse from low to high\n for (var i = low; i <= high; i++) {\n \n // Checking if this position\n // in the array is mask\n if ((mask & a[i]) > 0) {\n \n // Mask is the largest\n // number in subarray.\n // Increment count by 1\n countLargestNumber++;\n \n // Store parity as 0 or 1\n var parity = countLargestNumber % 2;\n \n // Setting a[i]=-1, this\n // will help in splitting\n // array into subarrays\n a[i] = -1;\n var count = i - prev;\n ans += count;\n \n // Add values contributed\n // by those subarrays that\n // have an odd frequency\n ans += (count - 1) * ((parity == 1) ? evenCount : oddCount);\n ans += ((parity == 1) ? oddCount : evenCount);\n \n // Adding values contributed\n // by those subarrays that\n // have an even frequency\n ans += 2 * (count - 1) * ((parity == 1) ? oddCount : evenCount);\n ans += 2 * ((parity == 1) ? evenCount : oddCount);\n \n // Set the prev pointer\n // to this position\n prev = i;\n \n if (parity == 1)\n oddCount += count;\n else\n evenCount += count;\n }\n }\n \n if (prev != low - 1) {\n var count = high - prev;\n var parity = countLargestNumber % 2;\n \n ans += count * ((parity == 1) ? oddCount : evenCount);\n ans += 2 * count * ((parity == 1) ? evenCount : oddCount);\n ans *= mask;\n }\n \n // Return the final sum\n return ans;\n }\n \n // Driver Code\n var arr = [ 2, 1, 4, 4, 2 ];\n \n // Function call\n findSum(arr);\n \n// This code is contributed by gauravrajput1\n</script>\n\n\n\n\n\n", "e": 59503, "s": 56124, "text": null }, { "code": null, "e": 59506, "s": 59503, "text": "75" }, { "code": null, "e": 59554, "s": 59508, "text": "Time Complexity: O(30*N)Auxiliary Space: O(1)" }, { "code": null, "e": 59561, "s": 59554, "text": "jithin" }, { "code": null, "e": 59567, "s": 59561, "text": "ukasp" }, { "code": null, "e": 59583, "s": 59567, "text": "rohitsingh07052" }, { "code": null, "e": 59596, "s": 59583, "text": "simmytarika5" }, { "code": null, "e": 59603, "s": 59596, "text": "rdtank" }, { "code": null, "e": 59616, "s": 59603, "text": "amreshkumar3" }, { "code": null, "e": 59630, "s": 59616, "text": "GauravRajput1" }, { "code": null, "e": 59646, "s": 59630, "text": "simranarora5sos" }, { "code": null, "e": 59661, "s": 59646, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 59676, "s": 59661, "text": "adnanirshad158" }, { "code": null, "e": 59692, "s": 59676, "text": "saurabh1990aror" }, { "code": null, "e": 59713, "s": 59692, "text": "\nfrequency-counting\n" }, { "code": null, "e": 59727, "s": 59713, "text": "\nmaths-power\n" }, { "code": null, "e": 59741, "s": 59727, "text": "\nsetBitCount\n" }, { "code": null, "e": 59752, "s": 59741, "text": "\nsubarray\n" }, { "code": null, "e": 59761, "s": 59752, "text": "\nArrays\n" }, { "code": null, "e": 59773, "s": 59761, "text": "\nBit Magic\n" }, { "code": null, "e": 59788, "s": 59773, "text": "\nMathematical\n" }, { "code": null, "e": 59800, "s": 59788, "text": "\nSearching\n" }, { "code": null, "e": 60005, "s": 59800, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 60053, "s": 60005, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 60085, "s": 60053, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 60139, "s": 60085, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 60153, "s": 60139, "text": "Linear Search" }, { "code": null, "e": 60198, "s": 60153, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 60225, "s": 60198, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 60271, "s": 60225, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 60339, "s": 60271, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 60385, "s": 60339, "text": "Cyclic Redundancy Check and Modulo-2 Division" } ]
Reverse a Doubly linked list using recursion - GeeksforGeeks
25 Oct, 2021 Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked ListAlgorithm 1) If list is empty, return 2) Reverse head by swapping head->prev and head->next 3) If prev = NULL it means that list is fully reversed. Else reverse(head->prev) C++ Java Python3 C# Javascript // C++ implementation to reverse a doubly// linked list using recursion#include <bits/stdc++.h>using namespace std; // a node of the doubly linked liststruct Node { int data; Node *next, *prev;}; // function to get a new nodeNode* getNode(int data){ // allocate space Node* new_node = new Node; new_node->data = data; new_node->next = new_node->prev = NULL; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, Node* new_node){ // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to reverse a doubly linked listNode* Reverse(Node* node){ // If empty list, return if (!node) return NULL; // Otherwise, swap the next and prev Node* temp = node->next; node->next = node->prev; node->prev = temp; // If the prev is now NULL, the list // has been fully reversed if (!node->prev) return node; // Otherwise, keep going return Reverse(node->prev);} // Function to print nodes in a given doubly// linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ // Start with the empty list Node* head = NULL; // Create doubly linked: 10<->8<->4<->2 */ push(&head, getNode(2)); push(&head, getNode(4)); push(&head, getNode(8)); push(&head, getNode(10)); cout << "Original list: "; printList(head); // Reverse doubly linked list head = Reverse(head); cout << "\nReversed list: "; printList(head); return 0;} // Java implementation to reverse a doubly// linked list using recursionclass GFG{ // a node of the doubly linked liststatic class Node{ int data; Node next, prev;}; // function to get a new nodestatic Node getNode(int data){ // allocate space Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){ // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to reverse a doubly linked liststatic Node Reverse(Node node){ // If empty list, return if (node == null) return null; // Otherwise, swap the next and prev Node temp = node.next; node.next = node.prev; node.prev = temp; // If the prev is now null, the list // has been fully reversed if (node.prev == null) return node; // Otherwise, keep going return Reverse(node.prev);} // Function to print nodes in a given doubly// linked liststatic void printList(Node head){ while (head != null) { System.out.print( head.data + " "); head = head.next; }} // Driver codepublic static void main(String args[]){ // Start with the empty list Node head = null; // Create doubly linked: 10<.8<.4<.2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); System.out.print( "Original list: "); printList(head); // Reverse doubly linked list head = Reverse(head); System.out.print("\nReversed list: "); printList(head);}} // This code is contributed by Arnab Kundu # Python3 implementation to reverse a doubly# linked list using recursionimport math # a node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.next = None # function to get a new nodedef getNode(data): # allocate space new_node = Node(data) new_node.data = data new_node.next = new_node.prev = None return new_node # function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_node): # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if (head_ref != None): head_ref.prev = new_node # move the head to point to the new node head_ref = new_node return head_ref # function to reverse a doubly linked listdef Reverse(node): # If empty list, return if not node: return None # Otherwise, swap the next and prev temp = node.next node.next = node.prev node.prev = temp # If the prev is now None, the list # has been fully reversed if not node.prev: return node # Otherwise, keep going return Reverse(node.prev) # Function to print nodes in a given doubly# linked listdef printList(head): while (head != None) : print(head.data, end = " ") head = head.next # Driver Codeif __name__=='__main__': # Start with the empty list head = None # Create doubly linked: 10<.8<.4<.2 */ head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); print("Original list: ", end = "") printList(head) # Reverse doubly linked list head = Reverse(head) print("\nReversed list: ", end = "") printList(head) # This code is contributed by Srathore // C# implementation to reverse a doublyusing System; // linked list using recursionclass GFG{ // a node of the doubly linked listpublic class Node{ public int data; public Node next, prev;}; // function to get a new nodestatic Node getNode(int data){ // allocate space Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){ // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to reverse a doubly linked liststatic Node Reverse(Node node){ // If empty list, return if (node == null) return null; // Otherwise, swap the next and prev Node temp = node.next; node.next = node.prev; node.prev = temp; // If the prev is now null, the list // has been fully reversed if (node.prev == null) return node; // Otherwise, keep going return Reverse(node.prev);} // Function to print nodes in a given doubly// linked liststatic void printList(Node head){ while (head != null) { Console.Write( head.data + " "); head = head.next; }} // Driver codepublic static void Main(String []argsS){ // Start with the empty list Node head = null; // Create doubly linked: 10<.8<.4<.2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); Console.Write( "Original list: "); printList(head); // Reverse doubly linked list head = Reverse(head); Console.Write("\nReversed list: "); printList(head);}} // This code is contributed by Arnab Kundu <script>// javascript implementation to reverse a doubly// linked list using recursion // a node of the doubly linked listclass Node { constructor(val) { this.data = val; this.prev = null; this.next = null; }} // function to get a new node function getNode(data) { // allocate spacevar new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List function push(head_ref, new_node) { // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref; } // function to reverse a doubly linked list function Reverse(node) { // If empty list, return if (node == null) return null; // Otherwise, swap the next and prevvar temp = node.next; node.next = node.prev; node.prev = temp; // If the prev is now null, the list // has been fully reversed if (node.prev == null) return node; // Otherwise, keep going return Reverse(node.prev); } // Function to print nodes in a given doubly // linked list function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } } // Driver code // Start with the empty listvar head = null; // Create doubly linked: 10<.8<.4<.2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); document.write("Original list: "); printList(head); // Reverse doubly linked list head = Reverse(head); document.write("<br/>Reversed list: "); printList(head); // This code contributed by umadevi9616</script> Output: Original list: 10 8 4 2 Reversed list: 2 4 8 10 andrew1234 sapnasingh4991 umadevi9616 ankita_saini doubly linked list Linked List Recursion Linked List Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a node in a Doubly Linked List Given a linked list which is sorted, how will you insert in sorted way Insert a node at a specific position in a linked list Circular Linked List | Set 2 (Traversal) Program to implement Singly Linked List in C++ using class Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number
[ { "code": null, "e": 24569, "s": 24541, "text": "\n25 Oct, 2021" }, { "code": null, "e": 24626, "s": 24569, "text": "Given a doubly linked list. Reverse it using recursion. " }, { "code": null, "e": 24655, "s": 24626, "text": "Original Doubly linked list " }, { "code": null, "e": 24688, "s": 24659, "text": "Reversed Doubly linked list " }, { "code": null, "e": 24934, "s": 24692, "text": "We have discussed Iterative solution to reverse a Doubly Linked ListAlgorithm 1) If list is empty, return 2) Reverse head by swapping head->prev and head->next 3) If prev = NULL it means that list is fully reversed. Else reverse(head->prev) " }, { "code": null, "e": 24938, "s": 24934, "text": "C++" }, { "code": null, "e": 24943, "s": 24938, "text": "Java" }, { "code": null, "e": 24951, "s": 24943, "text": "Python3" }, { "code": null, "e": 24954, "s": 24951, "text": "C#" }, { "code": null, "e": 24965, "s": 24954, "text": "Javascript" }, { "code": "// C++ implementation to reverse a doubly// linked list using recursion#include <bits/stdc++.h>using namespace std; // a node of the doubly linked liststruct Node { int data; Node *next, *prev;}; // function to get a new nodeNode* getNode(int data){ // allocate space Node* new_node = new Node; new_node->data = data; new_node->next = new_node->prev = NULL; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, Node* new_node){ // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to reverse a doubly linked listNode* Reverse(Node* node){ // If empty list, return if (!node) return NULL; // Otherwise, swap the next and prev Node* temp = node->next; node->next = node->prev; node->prev = temp; // If the prev is now NULL, the list // has been fully reversed if (!node->prev) return node; // Otherwise, keep going return Reverse(node->prev);} // Function to print nodes in a given doubly// linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ // Start with the empty list Node* head = NULL; // Create doubly linked: 10<->8<->4<->2 */ push(&head, getNode(2)); push(&head, getNode(4)); push(&head, getNode(8)); push(&head, getNode(10)); cout << \"Original list: \"; printList(head); // Reverse doubly linked list head = Reverse(head); cout << \"\\nReversed list: \"; printList(head); return 0;}", "e": 26866, "s": 24965, "text": null }, { "code": "// Java implementation to reverse a doubly// linked list using recursionclass GFG{ // a node of the doubly linked liststatic class Node{ int data; Node next, prev;}; // function to get a new nodestatic Node getNode(int data){ // allocate space Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){ // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to reverse a doubly linked liststatic Node Reverse(Node node){ // If empty list, return if (node == null) return null; // Otherwise, swap the next and prev Node temp = node.next; node.next = node.prev; node.prev = temp; // If the prev is now null, the list // has been fully reversed if (node.prev == null) return node; // Otherwise, keep going return Reverse(node.prev);} // Function to print nodes in a given doubly// linked liststatic void printList(Node head){ while (head != null) { System.out.print( head.data + \" \"); head = head.next; }} // Driver codepublic static void main(String args[]){ // Start with the empty list Node head = null; // Create doubly linked: 10<.8<.4<.2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); System.out.print( \"Original list: \"); printList(head); // Reverse doubly linked list head = Reverse(head); System.out.print(\"\\nReversed list: \"); printList(head);}} // This code is contributed by Arnab Kundu", "e": 28873, "s": 26866, "text": null }, { "code": "# Python3 implementation to reverse a doubly# linked list using recursionimport math # a node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.next = None # function to get a new nodedef getNode(data): # allocate space new_node = Node(data) new_node.data = data new_node.next = new_node.prev = None return new_node # function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_node): # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if (head_ref != None): head_ref.prev = new_node # move the head to point to the new node head_ref = new_node return head_ref # function to reverse a doubly linked listdef Reverse(node): # If empty list, return if not node: return None # Otherwise, swap the next and prev temp = node.next node.next = node.prev node.prev = temp # If the prev is now None, the list # has been fully reversed if not node.prev: return node # Otherwise, keep going return Reverse(node.prev) # Function to print nodes in a given doubly# linked listdef printList(head): while (head != None) : print(head.data, end = \" \") head = head.next # Driver Codeif __name__=='__main__': # Start with the empty list head = None # Create doubly linked: 10<.8<.4<.2 */ head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); print(\"Original list: \", end = \"\") printList(head) # Reverse doubly linked list head = Reverse(head) print(\"\\nReversed list: \", end = \"\") printList(head) # This code is contributed by Srathore", "e": 30770, "s": 28873, "text": null }, { "code": "// C# implementation to reverse a doublyusing System; // linked list using recursionclass GFG{ // a node of the doubly linked listpublic class Node{ public int data; public Node next, prev;}; // function to get a new nodestatic Node getNode(int data){ // allocate space Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){ // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to reverse a doubly linked liststatic Node Reverse(Node node){ // If empty list, return if (node == null) return null; // Otherwise, swap the next and prev Node temp = node.next; node.next = node.prev; node.prev = temp; // If the prev is now null, the list // has been fully reversed if (node.prev == null) return node; // Otherwise, keep going return Reverse(node.prev);} // Function to print nodes in a given doubly// linked liststatic void printList(Node head){ while (head != null) { Console.Write( head.data + \" \"); head = head.next; }} // Driver codepublic static void Main(String []argsS){ // Start with the empty list Node head = null; // Create doubly linked: 10<.8<.4<.2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); Console.Write( \"Original list: \"); printList(head); // Reverse doubly linked list head = Reverse(head); Console.Write(\"\\nReversed list: \"); printList(head);}} // This code is contributed by Arnab Kundu", "e": 32795, "s": 30770, "text": null }, { "code": "<script>// javascript implementation to reverse a doubly// linked list using recursion // a node of the doubly linked listclass Node { constructor(val) { this.data = val; this.prev = null; this.next = null; }} // function to get a new node function getNode(data) { // allocate spacevar new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List function push(head_ref, new_node) { // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref; } // function to reverse a doubly linked list function Reverse(node) { // If empty list, return if (node == null) return null; // Otherwise, swap the next and prevvar temp = node.next; node.next = node.prev; node.prev = temp; // If the prev is now null, the list // has been fully reversed if (node.prev == null) return node; // Otherwise, keep going return Reverse(node.prev); } // Function to print nodes in a given doubly // linked list function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } } // Driver code // Start with the empty listvar head = null; // Create doubly linked: 10<.8<.4<.2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); document.write(\"Original list: \"); printList(head); // Reverse doubly linked list head = Reverse(head); document.write(\"<br/>Reversed list: \"); printList(head); // This code contributed by umadevi9616</script>", "e": 35014, "s": 32795, "text": null }, { "code": null, "e": 35024, "s": 35014, "text": "Output: " }, { "code": null, "e": 35075, "s": 35024, "text": "Original list: 10 8 4 2 \nReversed list: 2 4 8 10" }, { "code": null, "e": 35088, "s": 35077, "text": "andrew1234" }, { "code": null, "e": 35103, "s": 35088, "text": "sapnasingh4991" }, { "code": null, "e": 35115, "s": 35103, "text": "umadevi9616" }, { "code": null, "e": 35128, "s": 35115, "text": "ankita_saini" }, { "code": null, "e": 35147, "s": 35128, "text": "doubly linked list" }, { "code": null, "e": 35159, "s": 35147, "text": "Linked List" }, { "code": null, "e": 35169, "s": 35159, "text": "Recursion" }, { "code": null, "e": 35181, "s": 35169, "text": "Linked List" }, { "code": null, "e": 35191, "s": 35181, "text": "Recursion" }, { "code": null, "e": 35289, "s": 35191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35298, "s": 35289, "text": "Comments" }, { "code": null, "e": 35311, "s": 35298, "text": "Old Comments" }, { "code": null, "e": 35349, "s": 35311, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 35420, "s": 35349, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 35474, "s": 35420, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 35515, "s": 35474, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 35574, "s": 35515, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 35634, "s": 35574, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35719, "s": 35634, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 35729, "s": 35719, "text": "Recursion" }, { "code": null, "e": 35756, "s": 35729, "text": "Program for Tower of Hanoi" } ]
Understanding Explicit vs Implicit measures in Power BI | by Nikola Ilic | Towards Data Science
One of the most challenging concepts for new Power BI users is to understand the difference between Measures and Calculated Columns. Or, to be more specific, the concept itself is not a big issue, but the most daunting thing for Power BI rookies is to understand when to use which. Since I’ve already written about the use-cases for both Calculated Columns and Measures, and briefly explained different scenarios when you want to use each of those, while recently presenting at the New Stars of Data conference, I’ve got a question to explain the difference between explicit and implicit measures. I’ve already answered here shortly, but I promised to dedicate a separate article to this topic. So, in this article, I will focus solely on Measures, and try to explain in-depth the difference between explicit and implicit measures. Ok, you’ve heard about Measures in Power BI, and that’s it. What on Earth are now implicit measures?! Or explicit? Don’t panic, keep reading and I promise you that by the end of this article, you will have a good understanding of those two and what are their main advantages and downsides. Implicit measures — “Thank you” Power BI First of all, I know that we all like things that are automatically created for us, and Power BI does pretty well in that regard. One of the things Power BI performs for us is creating of implicit measures. As you can notice in the illustration above, Power BI identified numeric fields in our data model and automatically marked them with the Sigma sign. That means that these column values will be summarized, once you drag them to a report visual. Let’s check how this works in reality: I’ve dragged my productID column into the table visual and I see that Power BI automatically applied some kind of aggregation. Now, you can define what type of aggregation you want to apply to a specific column, or not to aggregate at all (hint: choose Don’t Summarize option): Here, Power BI performed the Count aggregate function over my productID column. Looking at the picture above, one can (too) easily conclude that there is a lot of flexibility when working with implicit measures — you can choose between a bunch of predefined aggregations, including even fancy statistics’ calculations, such as Standard Deviation, Variance, or Median...All of that, with just one single click! So, why should someone bother writing DAX, when (almost) everything is already pre-baked for us? Before I show you why using implicit measures can come back to haunt you, let me just shortly overview how implicit measures work with non-numeric fields in your data model. My text field InteractionType can be summarized in four different ways: First, Last, Count (Distinct), and Count. Of course, it can be also non-summarized, like in the example above. Similar, Date columns offer their own set of predefined aggregations: No matter how appealing looks the possibility to save time and effort by using automatically created measures, you should try to avoid that, as it comes with some obvious downsides. Imagine that you have a non-additive or semi-additive measure, such as the Unit price of the product, or bank account balance. You don’t want these values to be simply summed in your report, as that is not expected behavior for those measures. Therefore, it can easily happen that your report produces unexpected incorrect outcomes if implicit measures are being used. Another limitation of implicit measures is that you can’t use them in multiple different aggregation types. Let’s say that I want to know both the total number of my customers, but also the total number of unique (distinct) customers. By using implicit measure, I can choose only one of those options... Writing measures in an explicit way, using DAX language, requires more time and effort in the beginning since you need to do some manual work. But, you will bear the fruits later, believe me. Back to our previous challenge — to display both the total number of customers and the total number of unique (distinct) customer in our report can be easily solved using explicit measures: Total Customers = COUNT(TableName[CustomerID])Total Unique Customers = DISTINCTCOUNT(TableName[customerID]) So, as you can notice, we used the same column as a reference to multiple different measures, to produce the desired outcome. While implicit measures can support some really basic scenarios, as soon as your report needs more complex calculations, you’ll have to switch to explicit measures. However, the main advantage of using explicit measures instead of implicit ones is their reusability. You define measure once and you can refer to it as many times as you need. The other obvious benefit is the easier maintenance of the data model. If you create a base explicit measure, such as: Sales Amt = SUM(TableName[Sales Amount]) You can use this measure as a reference in 20 other different measures (for example, to calculate gross margin, YoY, etc.)! If any background logic needs to be changed, you will change it at only one single place (in the base measure), and all referring measures will automatically apply the new logic. Now, as you learned the difference between implicit and explicit measures and obvious benefits from using the latter, let me wrap-up with some best practices regarding working with measures in your reports: Don’t forget to format your measures properly — that means, if you’re working with values related to money (Sales Amount, for example), you may want to format them as a Currency. Be consistent with the formatting, if your numbers are limited to two decimal places, then stick with it in the whole report Once you’re done with creating explicit measures based on a specific column, you should hide that column in the report. That way, you will prevent inadequate usage of the column (for example, simple summing of bank balance from the account). So, you as a data modeler take responsibility for summarization options In this example, I defined both Total Customers and Total Unique Customers measures, so I don’t want someone to perform a SUM of customerID. Therefore, I will hide the customerID column in the Fields list. Organize your measures into separate folders — It’s not an issue when your report has just a few measures. But, things become more complicated when you need to operate with tens or even hundreds of measures. To prevent that, I always use the following technique to better organize my measures. By default, the measure will reside in the table where you created it. You can change this by clicking on the measure, then under the Modeling tab, change the Home Table for that specific measure: However, this will just move the measure from one table to another, which doesn’t solve the problem. In order to tackle this, I need to create a brand new table which will hold my measures only. Under the Home tab, select Enter Data and create a plain empty table called RepMeasures: Click Load and you will see a new table in your model. After that, click on your measure, and under the Home table, select RepMeasures. Finally, just simply delete Column 1 and you are good to go. This way, you can separate and group your measures. Trust me, it will make your life much easier, especially once you create multiple measures in your report. As I’ve already said: we all prefer to take an easier path to meet our goals. That’s completely legitimate, and Power BI is your “best friend” when it comes to supporting you on that path. However, there are many important considerations to take into account when choosing which path to take. I don’t want to say: never use implicit measures! By writing this article, I just wanted to point out some possible pitfalls and limitations when using them, and why you should still prefer writing explicit measures instead. Thanks for reading! Become a member and read every story on Medium! Subscribe here to get more insightful data articles!
[ { "code": null, "e": 454, "s": 172, "text": "One of the most challenging concepts for new Power BI users is to understand the difference between Measures and Calculated Columns. Or, to be more specific, the concept itself is not a big issue, but the most daunting thing for Power BI rookies is to understand when to use which." }, { "code": null, "e": 867, "s": 454, "text": "Since I’ve already written about the use-cases for both Calculated Columns and Measures, and briefly explained different scenarios when you want to use each of those, while recently presenting at the New Stars of Data conference, I’ve got a question to explain the difference between explicit and implicit measures. I’ve already answered here shortly, but I promised to dedicate a separate article to this topic." }, { "code": null, "e": 1004, "s": 867, "text": "So, in this article, I will focus solely on Measures, and try to explain in-depth the difference between explicit and implicit measures." }, { "code": null, "e": 1294, "s": 1004, "text": "Ok, you’ve heard about Measures in Power BI, and that’s it. What on Earth are now implicit measures?! Or explicit? Don’t panic, keep reading and I promise you that by the end of this article, you will have a good understanding of those two and what are their main advantages and downsides." }, { "code": null, "e": 1335, "s": 1294, "text": "Implicit measures — “Thank you” Power BI" }, { "code": null, "e": 1542, "s": 1335, "text": "First of all, I know that we all like things that are automatically created for us, and Power BI does pretty well in that regard. One of the things Power BI performs for us is creating of implicit measures." }, { "code": null, "e": 1786, "s": 1542, "text": "As you can notice in the illustration above, Power BI identified numeric fields in our data model and automatically marked them with the Sigma sign. That means that these column values will be summarized, once you drag them to a report visual." }, { "code": null, "e": 1825, "s": 1786, "text": "Let’s check how this works in reality:" }, { "code": null, "e": 2103, "s": 1825, "text": "I’ve dragged my productID column into the table visual and I see that Power BI automatically applied some kind of aggregation. Now, you can define what type of aggregation you want to apply to a specific column, or not to aggregate at all (hint: choose Don’t Summarize option):" }, { "code": null, "e": 2513, "s": 2103, "text": "Here, Power BI performed the Count aggregate function over my productID column. Looking at the picture above, one can (too) easily conclude that there is a lot of flexibility when working with implicit measures — you can choose between a bunch of predefined aggregations, including even fancy statistics’ calculations, such as Standard Deviation, Variance, or Median...All of that, with just one single click!" }, { "code": null, "e": 2610, "s": 2513, "text": "So, why should someone bother writing DAX, when (almost) everything is already pre-baked for us?" }, { "code": null, "e": 2784, "s": 2610, "text": "Before I show you why using implicit measures can come back to haunt you, let me just shortly overview how implicit measures work with non-numeric fields in your data model." }, { "code": null, "e": 2967, "s": 2784, "text": "My text field InteractionType can be summarized in four different ways: First, Last, Count (Distinct), and Count. Of course, it can be also non-summarized, like in the example above." }, { "code": null, "e": 3037, "s": 2967, "text": "Similar, Date columns offer their own set of predefined aggregations:" }, { "code": null, "e": 3219, "s": 3037, "text": "No matter how appealing looks the possibility to save time and effort by using automatically created measures, you should try to avoid that, as it comes with some obvious downsides." }, { "code": null, "e": 3588, "s": 3219, "text": "Imagine that you have a non-additive or semi-additive measure, such as the Unit price of the product, or bank account balance. You don’t want these values to be simply summed in your report, as that is not expected behavior for those measures. Therefore, it can easily happen that your report produces unexpected incorrect outcomes if implicit measures are being used." }, { "code": null, "e": 3892, "s": 3588, "text": "Another limitation of implicit measures is that you can’t use them in multiple different aggregation types. Let’s say that I want to know both the total number of my customers, but also the total number of unique (distinct) customers. By using implicit measure, I can choose only one of those options..." }, { "code": null, "e": 4084, "s": 3892, "text": "Writing measures in an explicit way, using DAX language, requires more time and effort in the beginning since you need to do some manual work. But, you will bear the fruits later, believe me." }, { "code": null, "e": 4274, "s": 4084, "text": "Back to our previous challenge — to display both the total number of customers and the total number of unique (distinct) customer in our report can be easily solved using explicit measures:" }, { "code": null, "e": 4382, "s": 4274, "text": "Total Customers = COUNT(TableName[CustomerID])Total Unique Customers = DISTINCTCOUNT(TableName[customerID])" }, { "code": null, "e": 4508, "s": 4382, "text": "So, as you can notice, we used the same column as a reference to multiple different measures, to produce the desired outcome." }, { "code": null, "e": 4673, "s": 4508, "text": "While implicit measures can support some really basic scenarios, as soon as your report needs more complex calculations, you’ll have to switch to explicit measures." }, { "code": null, "e": 4850, "s": 4673, "text": "However, the main advantage of using explicit measures instead of implicit ones is their reusability. You define measure once and you can refer to it as many times as you need." }, { "code": null, "e": 4969, "s": 4850, "text": "The other obvious benefit is the easier maintenance of the data model. If you create a base explicit measure, such as:" }, { "code": null, "e": 5010, "s": 4969, "text": "Sales Amt = SUM(TableName[Sales Amount])" }, { "code": null, "e": 5313, "s": 5010, "text": "You can use this measure as a reference in 20 other different measures (for example, to calculate gross margin, YoY, etc.)! If any background logic needs to be changed, you will change it at only one single place (in the base measure), and all referring measures will automatically apply the new logic." }, { "code": null, "e": 5520, "s": 5313, "text": "Now, as you learned the difference between implicit and explicit measures and obvious benefits from using the latter, let me wrap-up with some best practices regarding working with measures in your reports:" }, { "code": null, "e": 5824, "s": 5520, "text": "Don’t forget to format your measures properly — that means, if you’re working with values related to money (Sales Amount, for example), you may want to format them as a Currency. Be consistent with the formatting, if your numbers are limited to two decimal places, then stick with it in the whole report" }, { "code": null, "e": 6138, "s": 5824, "text": "Once you’re done with creating explicit measures based on a specific column, you should hide that column in the report. That way, you will prevent inadequate usage of the column (for example, simple summing of bank balance from the account). So, you as a data modeler take responsibility for summarization options" }, { "code": null, "e": 6344, "s": 6138, "text": "In this example, I defined both Total Customers and Total Unique Customers measures, so I don’t want someone to perform a SUM of customerID. Therefore, I will hide the customerID column in the Fields list." }, { "code": null, "e": 6835, "s": 6344, "text": "Organize your measures into separate folders — It’s not an issue when your report has just a few measures. But, things become more complicated when you need to operate with tens or even hundreds of measures. To prevent that, I always use the following technique to better organize my measures. By default, the measure will reside in the table where you created it. You can change this by clicking on the measure, then under the Modeling tab, change the Home Table for that specific measure:" }, { "code": null, "e": 7030, "s": 6835, "text": "However, this will just move the measure from one table to another, which doesn’t solve the problem. In order to tackle this, I need to create a brand new table which will hold my measures only." }, { "code": null, "e": 7119, "s": 7030, "text": "Under the Home tab, select Enter Data and create a plain empty table called RepMeasures:" }, { "code": null, "e": 7255, "s": 7119, "text": "Click Load and you will see a new table in your model. After that, click on your measure, and under the Home table, select RepMeasures." }, { "code": null, "e": 7316, "s": 7255, "text": "Finally, just simply delete Column 1 and you are good to go." }, { "code": null, "e": 7475, "s": 7316, "text": "This way, you can separate and group your measures. Trust me, it will make your life much easier, especially once you create multiple measures in your report." }, { "code": null, "e": 7664, "s": 7475, "text": "As I’ve already said: we all prefer to take an easier path to meet our goals. That’s completely legitimate, and Power BI is your “best friend” when it comes to supporting you on that path." }, { "code": null, "e": 7993, "s": 7664, "text": "However, there are many important considerations to take into account when choosing which path to take. I don’t want to say: never use implicit measures! By writing this article, I just wanted to point out some possible pitfalls and limitations when using them, and why you should still prefer writing explicit measures instead." }, { "code": null, "e": 8013, "s": 7993, "text": "Thanks for reading!" }, { "code": null, "e": 8061, "s": 8013, "text": "Become a member and read every story on Medium!" } ]
PDFBox - Adding Pages
In the previous chapter, we have seen how to create a PDF document. After creating a PDF document, you need to add pages to it. Let us now understand how to add pages in a PDF document. You can create an empty page by instantiating the PDPage class and add it to the PDF document using the addPage() method of the PDDocument class. Following are the steps to create an empty document and add pages to it. Create an empty PDF document by instantiating the PDDocument class as shown below. PDDocument document = new PDDocument(); The PDPage class represents a page in the PDF document therefore, you can create an empty page by instantiating this class as shown in the following code block. PDPage my_page = new PDPage(); You can add a page to the PDF document using the addPage() method of the PDDocument class. To this method you need to pass the PDPage object as a parameter. Therefore, add the blank page created in the previous step to the PDDocument object as shown in the following code block. document.addPage(my_page); In this way you can add as many pages as you want to a PDF document. After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block. document.save("Path"); Finally close the document using the close() method of the PDDocument class as shown below. document.close(); This example demonstrates how to create a PDF Document and add pages to it. Here we will create a PDF Document named my_doc.pdf and further add 10 blank pages to it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Adding_pages.java. package document; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; public class Adding_Pages { public static void main(String args[]) throws IOException { //Creating PDF document object PDDocument document = new PDDocument(); for (int i=0; i<10; i++) { //Creating a blank page PDPage blankPage = new PDPage(); //Adding the blank page to the document document.addPage( blankPage ); } //Saving the document document.save("C:/PdfBox_Examples/my_doc.pdf"); System.out.println("PDF created"); //Closing the document document.close(); } } Compile and execute the saved Java file from the command prompt using the following commands − javac Adding_pages.java java Adding_pages Upon execution, the above program creates a PDF document with blank pages displaying the following message − PDF created If you verify the specified path, you can find the created PDF document as shown in the following screenshot. Print Add Notes Bookmark this page
[ { "code": null, "e": 2213, "s": 2027, "text": "In the previous chapter, we have seen how to create a PDF document. After creating a PDF document, you need to add pages to it. Let us now understand how to add pages in a PDF document." }, { "code": null, "e": 2359, "s": 2213, "text": "You can create an empty page by instantiating the PDPage class and add it to the PDF document using the addPage() method of the PDDocument class." }, { "code": null, "e": 2432, "s": 2359, "text": "Following are the steps to create an empty document and add pages to it." }, { "code": null, "e": 2515, "s": 2432, "text": "Create an empty PDF document by instantiating the PDDocument class as shown below." }, { "code": null, "e": 2556, "s": 2515, "text": "PDDocument document = new PDDocument();\n" }, { "code": null, "e": 2717, "s": 2556, "text": "The PDPage class represents a page in the PDF document therefore, you can create an empty page by instantiating this class as shown in the following code block." }, { "code": null, "e": 2749, "s": 2717, "text": "PDPage my_page = new PDPage();\n" }, { "code": null, "e": 2906, "s": 2749, "text": "You can add a page to the PDF document using the addPage() method of the PDDocument class. To this method you need to pass the PDPage object as a parameter." }, { "code": null, "e": 3028, "s": 2906, "text": "Therefore, add the blank page created in the previous step to the PDDocument object as shown in the following code block." }, { "code": null, "e": 3056, "s": 3028, "text": "document.addPage(my_page);\n" }, { "code": null, "e": 3125, "s": 3056, "text": "In this way you can add as many pages as you want to a PDF document." }, { "code": null, "e": 3261, "s": 3125, "text": "After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block." }, { "code": null, "e": 3285, "s": 3261, "text": "document.save(\"Path\");\n" }, { "code": null, "e": 3377, "s": 3285, "text": "Finally close the document using the close() method of the PDDocument class as shown below." }, { "code": null, "e": 3396, "s": 3377, "text": "document.close();\n" }, { "code": null, "e": 3661, "s": 3396, "text": "This example demonstrates how to create a PDF Document and add pages to it. Here we will create a PDF Document named my_doc.pdf and further add 10 blank pages to it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Adding_pages.java." }, { "code": null, "e": 4390, "s": 3661, "text": "package document;\n \nimport java.io.IOException;\n\nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.pdmodel.PDPage;\n\npublic class Adding_Pages {\n\n public static void main(String args[]) throws IOException {\n \n //Creating PDF document object \n PDDocument document = new PDDocument();\n\n for (int i=0; i<10; i++) {\n //Creating a blank page \n PDPage blankPage = new PDPage();\n\n //Adding the blank page to the document\n document.addPage( blankPage );\n } \n \n //Saving the document\n document.save(\"C:/PdfBox_Examples/my_doc.pdf\");\n System.out.println(\"PDF created\");\n \n //Closing the document\n document.close();\n\n } \n} " }, { "code": null, "e": 4485, "s": 4390, "text": "Compile and execute the saved Java file from the command prompt using the following commands −" }, { "code": null, "e": 4530, "s": 4485, "text": "javac Adding_pages.java \njava Adding_pages \n" }, { "code": null, "e": 4639, "s": 4530, "text": "Upon execution, the above program creates a PDF document with blank pages displaying the following message −" }, { "code": null, "e": 4653, "s": 4639, "text": "PDF created \n" }, { "code": null, "e": 4763, "s": 4653, "text": "If you verify the specified path, you can find the created PDF document as shown in the following screenshot." }, { "code": null, "e": 4770, "s": 4763, "text": " Print" }, { "code": null, "e": 4781, "s": 4770, "text": " Add Notes" } ]
C++ String Library - begin
It returns an iterator pointing to the first character of the string. Following is the declaration for std::string::begin. iterator begin(); const_iterator begin() const; iterator begin() noexcept; const_iterator begin() const noexcept; none It returns an iterator to the beginning of the string. Never throw any exceptions. In below example for std::string::begin. #include <iostream> #include <string> int main () { std::string str ("Tutorials point"); for ( std::string::iterator it=str.begin(); it!=str.end(); ++it) std::cout << *it; std::cout << '\n'; return 0; } The sample output should be like this − Tutorials point Print Add Notes Bookmark this page
[ { "code": null, "e": 2673, "s": 2603, "text": "It returns an iterator pointing to the first character of the string." }, { "code": null, "e": 2726, "s": 2673, "text": "Following is the declaration for std::string::begin." }, { "code": null, "e": 2777, "s": 2726, "text": " iterator begin();\nconst_iterator begin() const;" }, { "code": null, "e": 2846, "s": 2777, "text": " iterator begin() noexcept;\nconst_iterator begin() const noexcept;" }, { "code": null, "e": 2851, "s": 2846, "text": "none" }, { "code": null, "e": 2906, "s": 2851, "text": "It returns an iterator to the beginning of the string." }, { "code": null, "e": 2934, "s": 2906, "text": "Never throw any exceptions." }, { "code": null, "e": 2975, "s": 2934, "text": "In below example for std::string::begin." }, { "code": null, "e": 3198, "s": 2975, "text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string str (\"Tutorials point\");\n for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)\n std::cout << *it;\n std::cout << '\\n';\n\n return 0;\n}" }, { "code": null, "e": 3238, "s": 3198, "text": "The sample output should be like this −" }, { "code": null, "e": 3257, "s": 3238, "text": "Tutorials point \n" }, { "code": null, "e": 3264, "s": 3257, "text": " Print" }, { "code": null, "e": 3275, "s": 3264, "text": " Add Notes" } ]
CSS overflow: auto
The CSS overflow: auto, adds a scrollbar only when it's needed, unlike overflow:scroll. You can try to run the following code to implement CSS overflow: auto property: Live Demo <!DOCTYPE html> <html> <head> <style> div { background-color: orange; width: 250px; height: 45px; border: 2px solid blue; overflow: auto; } </style> </head> <body> <h1>Heading</h1> <div>Overflow property used here. This is a demo text to show the working of CSS overflow: auto. This won't hide the content. A scrollbar would be visible, only if needed.</div> </body> </html>
[ { "code": null, "e": 1230, "s": 1062, "text": "The CSS overflow: auto, adds a scrollbar only when it's needed, unlike overflow:scroll. You can try to run the following code to implement CSS overflow: auto property:" }, { "code": null, "e": 1240, "s": 1230, "text": "Live Demo" }, { "code": null, "e": 1729, "s": 1240, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div {\n background-color: orange;\n width: 250px;\n height: 45px;\n border: 2px solid blue;\n overflow: auto;\n }\n </style>\n </head>\n <body>\n <h1>Heading</h1>\n <div>Overflow property used here. This is a demo text to show the working of CSS overflow: auto. This won't hide the content. A scrollbar would be visible, only if needed.</div>\n </body>\n</html>" } ]
Don’t Panic If You Ever Make the Wrong Git Commit. I’ve Got You Covered | by Taylor Zhancher | Towards Data Science
5 months ago when I first started contributing to open source, something made me nervous all the time. Every single commit message on the branch had to follow a format, or your pull request doesn’t get merged. Specifically, it should be: “PREFIX: Summary of what this commit is about”. What happens if you have worked on a pull request for 2 months, but get the last commit message wrong? Well..... I decided that I didn’t want to know. I used to hold my breath, and triple check everything before pushing. I even postponed opening a branch because I didn’t want to risk it. To calm down and learn git, and eventually, interactive rebase, has been hands down one of the best investments a git user at my stage can make. The good news is: it’s not rocket science. Take a look and tell me what you think. Git basics such as clone, add, commit, push are better explained by many other authors. I would make the best of your time by putting links to them here: For people who identify themselves as complete beginners, I recommend this clear guide with a hands-on project. It is brought to you by Anne Bonner, the deputy editor of Towards Data Science. towardsdatascience.com If you would prefer a course. I highly recommend this one. This course is way advanced than this article. It dives way into the mechanisms and explains things from the root. It’s also filled with animations and real, concrete examples. As I’ve enjoyed it a lot, it is only natural to put it here for people interested in learning more. app.pluralsight.com This book is also helpful. I didn’t get most of the concepts in How Git Works on the first few tries, but much of it came clear after reading this. git-scm.com Two of the most common mistakes I make Wrong commit message (e.g. messing up the prefix) Wrong commit content (e.g. extra line, extra space) Interactive rebase is far more capable than fixing these, but I’m focusing on the two since I run into them the most. Simply put, it is redefining the sequence of what happened in the past. So what we’re actually doing, when changing the past, is first make a new thing happen. Then we replace that new event with the commit that actually happened. However, interactive rebase makes things pretty simple. Even if you don’t understand this part, it will not stop you from getting the core takeaways of this article. do git log and copy the hash of the commit. It should be the 5a6e6cdc63ecd1ad4c03ed004099d298b776e06a in the example below % git logcommit 5a6e6cdc63ecd1ad4c03ed004099d298b776e06a (HEAD -> branch-name, origin/branch-name)Author: my-username <myemail@gmail.com>Date: Tue Sep 7 19:14:08 2021 Here’s the command git rebase -i 5a6e6cdc63ecd1ad4c03ed004099d298b776e06a^ Notice that it consists of git rebase -ithe hash code^ git rebase -i the hash code ^ to put it simply, ^ means that you want to start changing the past from this point. It’s like an arrow that points to the place we would start. If you will, something like git rebase -i 5a6e6cdc^ will also work, because they will just look for the hash that starts with the prefix. If the previous step didn’t work because the editor doesn’t work with it, try this, and then step two again: git config --global core.editor vim This will allow you to do the interactive rebase in the terminal window. I prefer this and will provide further instructions on how to work with it below. This is the most complicated step. You should be getting something like this: % git rebase -i 5a6e6^hint: Waiting for your editor to close the file...pick 5a6e6cdc63 The commit message here. Note by the author # Rebase 71b43c0db0..5a6e6cdc63 onto 71b43c0db0 (1 command)## Commands:# p, pick <commit> = use commit# r, reword <commit> = use commit, but edit the commit message# e, edit <commit> = use commit, but stop for amending# s, squash <commit> = use commit, but meld into previous commit# f, fixup <commit> = like "squash", but discard this commit's log message# x, exec <command> = run command (the rest of the line) using shell# b, break = stop here (continue rebase later with 'git rebase --continue')# d, drop <commit> = remove commit# l, label <label> = label current HEAD with a name# t, reset <label> = reset HEAD to a label# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]# . create a merge commit using the original merge commit's# . message (or the oneline, if no original merge commit was# . specified). Use -c <commit> to reword the commit message. Take a look at all the commands! Git rebase -i is capable of so much. Yet for now, I’m only going to stick with the only one I use a lot: edit. Go change the pick into edit, then save and close the file. If you’re using the vim editor like me, here are the keys to that: i = start editing. Up/down/left/right to navigate through the lines. backspace to delete the “pick” text. Type normally. esc =stop editing :wq = save w and close q enter to execute You have the code that you want to change. See for yourself by doing git status. It should be as if you haven’t stage those files yet. Make your changes now. If you only want to change the commit message, just skip this section. The harsh truth is that we can’t compile and test the code during a git rebase, but the good news is I have something almost as good. If the commit you would want to edit is the latest one, this should work: Before doing the rebase, make the changes and compile as you wish. Then do git stash. This is a command that’s a little like “cmd/ctrl + z” or “cut”. It takes away all the changes and stores them away. Later as you are rebasing and have arrived at this stage, do git stash pop. This will “cmd/ctrl + v” or “paste” the changes here. Voila. You have the changes. This hint message should show up in the terminal — You can amend the commit now, withgit commit --amendOnce you are satisfied with your changes, rungit rebase --continue Do as it says, but first git add all the changes. This is necessary to proceed. Then git commit --amend The following should show up in your editor: Commit message here. Note by the author# Please enter the commit message for your changes. Lines starting# with '#' will be ignored, and an empty message aborts the commit.## Date: Tue Sep 7 19:14:08 2021## interactive rebase in progress; onto 71b43c0db9# Last command done (1 command done):# edit 5a6e6cdc62 SCI: Set name of new file to tts, function name to ttsPickLB2NotebookTopic, and remove extra lines# No commands remaining.# You are currently editing a commit while rebasing branch 'sci-tts' on '71b43c0db9'. High time to edit the commit message. You should be fine with the vim editor keys I have mentioned above. They work the same way. Then wrap up the rebase with this. git rebase --continue Time to show your work. Instead of git push, do: git push --force This is because we have made changes to the history, which is conflicting with what is stored on the remote (on Github). --force means to “Do it anyway. I am certain that I have the right version”. After this, you should see the changes you want on Github. git rebase --abort this stops the time-traveling and takes you back to the normal state. Sincerely I hope you will be alright with whatever git problems you are facing or might face in the future. Instead of wishing that you will never run into any problems, I would say... Lasting happiness comes from the ability to deal with the bad stuff in life. and I wish you will cope with yours well. The Medium membership made it possible for me to learn enough and write for Towards Data Science. Sign up with my personal link, then let me know, and I will send you a pdf that shares my full journey.
[ { "code": null, "e": 274, "s": 171, "text": "5 months ago when I first started contributing to open source, something made me nervous all the time." }, { "code": null, "e": 381, "s": 274, "text": "Every single commit message on the branch had to follow a format, or your pull request doesn’t get merged." }, { "code": null, "e": 457, "s": 381, "text": "Specifically, it should be: “PREFIX: Summary of what this commit is about”." }, { "code": null, "e": 560, "s": 457, "text": "What happens if you have worked on a pull request for 2 months, but get the last commit message wrong?" }, { "code": null, "e": 570, "s": 560, "text": "Well....." }, { "code": null, "e": 608, "s": 570, "text": "I decided that I didn’t want to know." }, { "code": null, "e": 746, "s": 608, "text": "I used to hold my breath, and triple check everything before pushing. I even postponed opening a branch because I didn’t want to risk it." }, { "code": null, "e": 891, "s": 746, "text": "To calm down and learn git, and eventually, interactive rebase, has been hands down one of the best investments a git user at my stage can make." }, { "code": null, "e": 974, "s": 891, "text": "The good news is: it’s not rocket science. Take a look and tell me what you think." }, { "code": null, "e": 1128, "s": 974, "text": "Git basics such as clone, add, commit, push are better explained by many other authors. I would make the best of your time by putting links to them here:" }, { "code": null, "e": 1320, "s": 1128, "text": "For people who identify themselves as complete beginners, I recommend this clear guide with a hands-on project. It is brought to you by Anne Bonner, the deputy editor of Towards Data Science." }, { "code": null, "e": 1343, "s": 1320, "text": "towardsdatascience.com" }, { "code": null, "e": 1402, "s": 1343, "text": "If you would prefer a course. I highly recommend this one." }, { "code": null, "e": 1679, "s": 1402, "text": "This course is way advanced than this article. It dives way into the mechanisms and explains things from the root. It’s also filled with animations and real, concrete examples. As I’ve enjoyed it a lot, it is only natural to put it here for people interested in learning more." }, { "code": null, "e": 1699, "s": 1679, "text": "app.pluralsight.com" }, { "code": null, "e": 1847, "s": 1699, "text": "This book is also helpful. I didn’t get most of the concepts in How Git Works on the first few tries, but much of it came clear after reading this." }, { "code": null, "e": 1859, "s": 1847, "text": "git-scm.com" }, { "code": null, "e": 1898, "s": 1859, "text": "Two of the most common mistakes I make" }, { "code": null, "e": 1948, "s": 1898, "text": "Wrong commit message (e.g. messing up the prefix)" }, { "code": null, "e": 2000, "s": 1948, "text": "Wrong commit content (e.g. extra line, extra space)" }, { "code": null, "e": 2118, "s": 2000, "text": "Interactive rebase is far more capable than fixing these, but I’m focusing on the two since I run into them the most." }, { "code": null, "e": 2190, "s": 2118, "text": "Simply put, it is redefining the sequence of what happened in the past." }, { "code": null, "e": 2278, "s": 2190, "text": "So what we’re actually doing, when changing the past, is first make a new thing happen." }, { "code": null, "e": 2349, "s": 2278, "text": "Then we replace that new event with the commit that actually happened." }, { "code": null, "e": 2515, "s": 2349, "text": "However, interactive rebase makes things pretty simple. Even if you don’t understand this part, it will not stop you from getting the core takeaways of this article." }, { "code": null, "e": 2638, "s": 2515, "text": "do git log and copy the hash of the commit. It should be the 5a6e6cdc63ecd1ad4c03ed004099d298b776e06a in the example below" }, { "code": null, "e": 2807, "s": 2638, "text": "% git logcommit 5a6e6cdc63ecd1ad4c03ed004099d298b776e06a (HEAD -> branch-name, origin/branch-name)Author: my-username <myemail@gmail.com>Date: Tue Sep 7 19:14:08 2021" }, { "code": null, "e": 2826, "s": 2807, "text": "Here’s the command" }, { "code": null, "e": 2882, "s": 2826, "text": "git rebase -i 5a6e6cdc63ecd1ad4c03ed004099d298b776e06a^" }, { "code": null, "e": 2909, "s": 2882, "text": "Notice that it consists of" }, { "code": null, "e": 2937, "s": 2909, "text": "git rebase -ithe hash code^" }, { "code": null, "e": 2951, "s": 2937, "text": "git rebase -i" }, { "code": null, "e": 2965, "s": 2951, "text": "the hash code" }, { "code": null, "e": 2967, "s": 2965, "text": "^" }, { "code": null, "e": 3111, "s": 2967, "text": "to put it simply, ^ means that you want to start changing the past from this point. It’s like an arrow that points to the place we would start." }, { "code": null, "e": 3249, "s": 3111, "text": "If you will, something like git rebase -i 5a6e6cdc^ will also work, because they will just look for the hash that starts with the prefix." }, { "code": null, "e": 3358, "s": 3249, "text": "If the previous step didn’t work because the editor doesn’t work with it, try this, and then step two again:" }, { "code": null, "e": 3394, "s": 3358, "text": "git config --global core.editor vim" }, { "code": null, "e": 3549, "s": 3394, "text": "This will allow you to do the interactive rebase in the terminal window. I prefer this and will provide further instructions on how to work with it below." }, { "code": null, "e": 3584, "s": 3549, "text": "This is the most complicated step." }, { "code": null, "e": 3627, "s": 3584, "text": "You should be getting something like this:" }, { "code": null, "e": 4644, "s": 3627, "text": "% git rebase -i 5a6e6^hint: Waiting for your editor to close the file...pick 5a6e6cdc63 The commit message here. Note by the author # Rebase 71b43c0db0..5a6e6cdc63 onto 71b43c0db0 (1 command)## Commands:# p, pick <commit> = use commit# r, reword <commit> = use commit, but edit the commit message# e, edit <commit> = use commit, but stop for amending# s, squash <commit> = use commit, but meld into previous commit# f, fixup <commit> = like \"squash\", but discard this commit's log message# x, exec <command> = run command (the rest of the line) using shell# b, break = stop here (continue rebase later with 'git rebase --continue')# d, drop <commit> = remove commit# l, label <label> = label current HEAD with a name# t, reset <label> = reset HEAD to a label# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]# . create a merge commit using the original merge commit's# . message (or the oneline, if no original merge commit was# . specified). Use -c <commit> to reword the commit message." }, { "code": null, "e": 4788, "s": 4644, "text": "Take a look at all the commands! Git rebase -i is capable of so much. Yet for now, I’m only going to stick with the only one I use a lot: edit." }, { "code": null, "e": 4848, "s": 4788, "text": "Go change the pick into edit, then save and close the file." }, { "code": null, "e": 4915, "s": 4848, "text": "If you’re using the vim editor like me, here are the keys to that:" }, { "code": null, "e": 4984, "s": 4915, "text": "i = start editing. Up/down/left/right to navigate through the lines." }, { "code": null, "e": 5036, "s": 4984, "text": "backspace to delete the “pick” text. Type normally." }, { "code": null, "e": 5054, "s": 5036, "text": "esc =stop editing" }, { "code": null, "e": 5079, "s": 5054, "text": ":wq = save w and close q" }, { "code": null, "e": 5096, "s": 5079, "text": "enter to execute" }, { "code": null, "e": 5231, "s": 5096, "text": "You have the code that you want to change. See for yourself by doing git status. It should be as if you haven’t stage those files yet." }, { "code": null, "e": 5254, "s": 5231, "text": "Make your changes now." }, { "code": null, "e": 5325, "s": 5254, "text": "If you only want to change the commit message, just skip this section." }, { "code": null, "e": 5459, "s": 5325, "text": "The harsh truth is that we can’t compile and test the code during a git rebase, but the good news is I have something almost as good." }, { "code": null, "e": 5533, "s": 5459, "text": "If the commit you would want to edit is the latest one, this should work:" }, { "code": null, "e": 5600, "s": 5533, "text": "Before doing the rebase, make the changes and compile as you wish." }, { "code": null, "e": 5735, "s": 5600, "text": "Then do git stash. This is a command that’s a little like “cmd/ctrl + z” or “cut”. It takes away all the changes and stores them away." }, { "code": null, "e": 5894, "s": 5735, "text": "Later as you are rebasing and have arrived at this stage, do git stash pop. This will “cmd/ctrl + v” or “paste” the changes here. Voila. You have the changes." }, { "code": null, "e": 5945, "s": 5894, "text": "This hint message should show up in the terminal —" }, { "code": null, "e": 6064, "s": 5945, "text": "You can amend the commit now, withgit commit --amendOnce you are satisfied with your changes, rungit rebase --continue" }, { "code": null, "e": 6144, "s": 6064, "text": "Do as it says, but first git add all the changes. This is necessary to proceed." }, { "code": null, "e": 6168, "s": 6144, "text": "Then git commit --amend" }, { "code": null, "e": 6213, "s": 6168, "text": "The following should show up in your editor:" }, { "code": null, "e": 6738, "s": 6213, "text": "Commit message here. Note by the author# Please enter the commit message for your changes. Lines starting# with '#' will be ignored, and an empty message aborts the commit.## Date: Tue Sep 7 19:14:08 2021## interactive rebase in progress; onto 71b43c0db9# Last command done (1 command done):# edit 5a6e6cdc62 SCI: Set name of new file to tts, function name to ttsPickLB2NotebookTopic, and remove extra lines# No commands remaining.# You are currently editing a commit while rebasing branch 'sci-tts' on '71b43c0db9'." }, { "code": null, "e": 6868, "s": 6738, "text": "High time to edit the commit message. You should be fine with the vim editor keys I have mentioned above. They work the same way." }, { "code": null, "e": 6903, "s": 6868, "text": "Then wrap up the rebase with this." }, { "code": null, "e": 6925, "s": 6903, "text": "git rebase --continue" }, { "code": null, "e": 6949, "s": 6925, "text": "Time to show your work." }, { "code": null, "e": 6974, "s": 6949, "text": "Instead of git push, do:" }, { "code": null, "e": 6991, "s": 6974, "text": "git push --force" }, { "code": null, "e": 7112, "s": 6991, "text": "This is because we have made changes to the history, which is conflicting with what is stored on the remote (on Github)." }, { "code": null, "e": 7189, "s": 7112, "text": "--force means to “Do it anyway. I am certain that I have the right version”." }, { "code": null, "e": 7248, "s": 7189, "text": "After this, you should see the changes you want on Github." }, { "code": null, "e": 7267, "s": 7248, "text": "git rebase --abort" }, { "code": null, "e": 7337, "s": 7267, "text": "this stops the time-traveling and takes you back to the normal state." }, { "code": null, "e": 7445, "s": 7337, "text": "Sincerely I hope you will be alright with whatever git problems you are facing or might face in the future." }, { "code": null, "e": 7522, "s": 7445, "text": "Instead of wishing that you will never run into any problems, I would say..." }, { "code": null, "e": 7599, "s": 7522, "text": "Lasting happiness comes from the ability to deal with the bad stuff in life." }, { "code": null, "e": 7641, "s": 7599, "text": "and I wish you will cope with yours well." } ]
Tryit Editor v3.7
Tryit: HTML RGB color values
[]
Check horizontal and vertical symmetry in binary matrix
13 Jun, 2022 Given a 2D binary matrix of N rows and M columns. The task is to check whether the matrix is horizontal symmetric, vertical symmetric, or both. The matrix is said to be horizontal symmetric if the first row is the same as the last row, the second row is the same as the second last row, and so on. And the matrix is said to be vertical symmetric if the first column is the same as the last column, the second column is the same as the second last column, and so on. Print “VERTICAL” if the matrix is vertically symmetric, “HORIZONTAL” if the matrix is vertically symmetric, “BOTH” if the matrix is vertical and horizontal symmetric, and “NO” if not symmetric. Examples: Input: N = 3 M = 3 0 1 0 0 0 0 0 1 0 Output: Both First and third row are same and also second row is in middle. So Horizontal Symmetric. Similarly, First and third column are same and also second column is in middle, so Vertical Symmetric. Input: 0 0 1 1 1 0 0 0 1. Output: Both The idea is to use pointers indicating two rows (or columns) and compare each cell of both the pointed rows (or columns). For Horizontal Symmetry, initialize one pointer i = 0 and another pointer j = N – 1. Now, compare each element of i-th row and j-th row. Increase i by 1 and decrease j by 1 in each loop cycle. If at least one, not an identical element, is found, mark the matrix as not horizontal symmetric.Similarly, for Vertical Symmetry, initialize one pointer i = 0 and another pointer j = M – 1. Now, compare each element of i-th column and j-th column. Increase i by 1 and decrease j by 1 in each loop cycle. If at least one, not an identical element, is found, mark the matrix as not vertical symmetric. Below is the implementation of the above idea: C++ Java Python3 C# PHP Javascript // C++ program to find if a matrix is symmetric.#include <bits/stdc++.h>#define MAX 1000using namespace std; void checkHV(int arr[][MAX], int N, int M){ // Initializing as both horizontal and vertical // symmetric. bool horizontal = true, vertical = true; // Checking for Horizontal Symmetry. We compare // first row with last row, second row with second // last row and so on. for (int i = 0, k = N - 1; i < N / 2; i++, k--) { // Checking each cell of a column. for (int j = 0; j < M; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } // Checking for Vertical Symmetry. We compare // first column with last column, second column // with second last column and so on. for (int i = 0, k = M - 1; i < M / 2; i++, k--) { // Checking each cell of a row. for (int j = 0; j < N; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { vertical = false; break; } } } if (!horizontal && !vertical) cout << "NO\n"; else if (horizontal && !vertical) cout << "HORIZONTAL\n"; else if (vertical && !horizontal) cout << "VERTICAL\n"; else cout << "BOTH\n";} // Driven Programint main(){ int mat[MAX][MAX] = { { 1, 0, 1 }, { 0, 0, 0 }, { 1, 0, 1 } }; checkHV(mat, 3, 3); return 0;} // Java program to find if// a matrix is symmetric.import java.io.*; public class GFG { static void checkHV(int[][] arr, int N, int M) { // Initializing as both horizontal // and vertical symmetric. boolean horizontal = true; boolean vertical = true; // Checking for Horizontal Symmetry. // We compare first row with last // row, second row with second // last row and so on. for (int i = 0, k = N - 1; i < N / 2; i++, k--) { // Checking each cell of a column. for (int j = 0; j < M; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } // Checking for Vertical Symmetry. We compare // first column with last column, second column // with second last column and so on. for (int i = 0, k = M - 1; i < M / 2; i++, k--) { // Checking each cell of a row. for (int j = 0; j < N; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } if (!horizontal && !vertical) System.out.println("NO"); else if (horizontal && !vertical) System.out.println("HORIZONTAL"); else if (vertical && !horizontal) System.out.println("VERTICAL"); else System.out.println("BOTH"); } // Driver Code static public void main(String[] args) { int[][] mat = { { 1, 0, 1 }, { 0, 0, 0 }, { 1, 0, 1 } }; checkHV(mat, 3, 3); }} // This code is contributed by vt_m. # Python3 program to find if a matrix is symmetric.MAX = 1000 def checkHV(arr, N, M): # Initializing as both horizontal and vertical # symmetric. horizontal = True vertical = True # Checking for Horizontal Symmetry. We compare # first row with last row, second row with second # last row and so on. i = 0 k = N - 1 while(i < N // 2): # Checking each cell of a column. for j in range(M): # check if every cell is identical if (arr[i][j] != arr[k][j]): horizontal = False break i += 1 k -= 1 # Checking for Vertical Symmetry. We compare # first column with last column, second column # with second last column and so on. i = 0 k = M - 1 while(i < M // 2): # Checking each cell of a row. for j in range(N): # check if every cell is identical if (arr[i][j] != arr[k][j]): vertical = False break i += 1 k -= 1 if (not horizontal and not vertical): print("NO") else if (horizontal and not vertical): print("HORIZONTAL") else if (vertical and not horizontal): print("VERTICAL") else: print("BOTH") # Driver codemat = [[1, 0, 1],[ 0, 0, 0],[1, 0, 1]] checkHV(mat, 3, 3) # This code is contributed by shubhamsingh10 // C# program to find if// a matrix is symmetric.using System; public class GFG { static void checkHV(int[, ] arr, int N, int M) { // Initializing as both horizontal // and vertical symmetric. bool horizontal = true; bool vertical = true; // Checking for Horizontal Symmetry. // We compare first row with last // row, second row with second // last row and so on. for (int i = 0, k = N - 1; i < N / 2; i++, k--) { // Checking each cell of a column. for (int j = 0; j < M; j++) { // check if every cell is identical if (arr[i, j] != arr[k, j]) { horizontal = false; break; } } } // Checking for Vertical Symmetry. We compare // first column with last column, second column // with second last column and so on. for (int i = 0, k = M - 1; i < M / 2; i++, k--) { // Checking each cell of a row. for (int j = 0; j < N; j++) { // check if every cell is identical if (arr[i, j] != arr[k, j]) { horizontal = false; break; } } } if (!horizontal && !vertical) Console.WriteLine("NO"); else if (horizontal && !vertical) Console.WriteLine("HORIZONTAL"); else if (vertical && !horizontal) Console.WriteLine("VERTICAL"); else Console.WriteLine("BOTH"); } // Driver Code static public void Main() { int[, ] mat = { { 1, 0, 1 }, { 0, 0, 0 }, { 1, 0, 1 } }; checkHV(mat, 3, 3); }} // This code is contributed by vt_m. <?php// PHP program to find if// a matrix is symmetric. function checkHV($arr, $N, $M){ // Initializing as both horizontal // and vertical symmetric. $horizontal = true; $vertical = true; // Checking for Horizontal Symmetry. // We compare first row with last row, // second row with second last row // and so on. for ($i = 0, $k = $N - 1; $i < $N / 2; $i++, $k--) { // Checking each cell of a column. for ($j = 0; $j < $M; $j++) { // check if every cell is identical if ($arr[$i][$j] != $arr[$k][$j]) { $horizontal = false; break; } } } // Checking for Vertical Symmetry. // We compare first column with // last column, second column with // second last column and so on. for ($i = 0, $k = $M - 1; $i < $M / 2; $i++, $k--) { // Checking each cell of a row. for ($j = 0; $j < $N; $j++) { // check if every cell is identical if ($arr[$i][$j] != $arr[$k][$j]) { $horizontal = false; break; } } } if (!$horizontal && !$vertical) echo "NO\n"; else if ($horizontal && !$vertical) cout << "HORIZONTAL\n"; else if ($vertical && !$horizontal) echo "VERTICAL\n"; else echo "BOTH\n";} // Driver Code$mat = array(array (1, 0, 1), array (0, 0, 0), array (1, 0, 1));checkHV($mat, 3, 3); // This code is contributed by nitin mittal.?> <script> // Javascript program to find if // a matrix is symmetric. function checkHV(arr, N, M) { // Initializing as both horizontal // and vertical symmetric. let horizontal = true; let vertical = true; // Checking for Horizontal Symmetry. // We compare first row with last // row, second row with second // last row and so on. for (let i = 0, k = N - 1; i < parseInt(N / 2, 10); i++, k--) { // Checking each cell of a column. for (let j = 0; j < M; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } // Checking for Vertical Symmetry. We compare // first column with last column, second column // with second last column and so on. for (let i = 0, k = M - 1; i < parseInt(M / 2, 10); i++, k--) { // Checking each cell of a row. for (let j = 0; j < N; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } if (!horizontal && !vertical) document.write("NO"); else if (horizontal && !vertical) document.write("HORIZONTAL"); else if (vertical && !horizontal) document.write("VERTICAL"); else document.write("BOTH"); } let mat = [ [ 1, 0, 1 ], [ 0, 0, 0 ], [ 1, 0, 1 ] ]; checkHV(mat, 3, 3); </script> Output: BOTH Time Complexity: O(N*M).Auxiliary Space: O(1)This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m nitin mittal ADITYAGUPTA25 SHUBHAMSINGH10 mukesh07 as5853535 simmytarika5 codewithmini Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 712, "s": 52, "text": "Given a 2D binary matrix of N rows and M columns. The task is to check whether the matrix is horizontal symmetric, vertical symmetric, or both. The matrix is said to be horizontal symmetric if the first row is the same as the last row, the second row is the same as the second last row, and so on. And the matrix is said to be vertical symmetric if the first column is the same as the last column, the second column is the same as the second last column, and so on. Print “VERTICAL” if the matrix is vertically symmetric, “HORIZONTAL” if the matrix is vertically symmetric, “BOTH” if the matrix is vertical and horizontal symmetric, and “NO” if not symmetric." }, { "code": null, "e": 724, "s": 712, "text": "Examples: " }, { "code": null, "e": 1008, "s": 724, "text": "Input: N = 3 M = 3\n0 1 0\n0 0 0\n0 1 0\nOutput: Both\nFirst and third row are same and also second row \nis in middle. So Horizontal Symmetric.\nSimilarly, First and third column are same and\nalso second column is in middle, so Vertical \nSymmetric.\n\nInput:\n0 0 1\n1 1 0\n0 0 1.\nOutput: Both " }, { "code": null, "e": 1724, "s": 1008, "text": "The idea is to use pointers indicating two rows (or columns) and compare each cell of both the pointed rows (or columns). For Horizontal Symmetry, initialize one pointer i = 0 and another pointer j = N – 1. Now, compare each element of i-th row and j-th row. Increase i by 1 and decrease j by 1 in each loop cycle. If at least one, not an identical element, is found, mark the matrix as not horizontal symmetric.Similarly, for Vertical Symmetry, initialize one pointer i = 0 and another pointer j = M – 1. Now, compare each element of i-th column and j-th column. Increase i by 1 and decrease j by 1 in each loop cycle. If at least one, not an identical element, is found, mark the matrix as not vertical symmetric." }, { "code": null, "e": 1772, "s": 1724, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 1776, "s": 1772, "text": "C++" }, { "code": null, "e": 1781, "s": 1776, "text": "Java" }, { "code": null, "e": 1789, "s": 1781, "text": "Python3" }, { "code": null, "e": 1792, "s": 1789, "text": "C#" }, { "code": null, "e": 1796, "s": 1792, "text": "PHP" }, { "code": null, "e": 1807, "s": 1796, "text": "Javascript" }, { "code": "// C++ program to find if a matrix is symmetric.#include <bits/stdc++.h>#define MAX 1000using namespace std; void checkHV(int arr[][MAX], int N, int M){ // Initializing as both horizontal and vertical // symmetric. bool horizontal = true, vertical = true; // Checking for Horizontal Symmetry. We compare // first row with last row, second row with second // last row and so on. for (int i = 0, k = N - 1; i < N / 2; i++, k--) { // Checking each cell of a column. for (int j = 0; j < M; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } // Checking for Vertical Symmetry. We compare // first column with last column, second column // with second last column and so on. for (int i = 0, k = M - 1; i < M / 2; i++, k--) { // Checking each cell of a row. for (int j = 0; j < N; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { vertical = false; break; } } } if (!horizontal && !vertical) cout << \"NO\\n\"; else if (horizontal && !vertical) cout << \"HORIZONTAL\\n\"; else if (vertical && !horizontal) cout << \"VERTICAL\\n\"; else cout << \"BOTH\\n\";} // Driven Programint main(){ int mat[MAX][MAX] = { { 1, 0, 1 }, { 0, 0, 0 }, { 1, 0, 1 } }; checkHV(mat, 3, 3); return 0;}", "e": 3360, "s": 1807, "text": null }, { "code": "// Java program to find if// a matrix is symmetric.import java.io.*; public class GFG { static void checkHV(int[][] arr, int N, int M) { // Initializing as both horizontal // and vertical symmetric. boolean horizontal = true; boolean vertical = true; // Checking for Horizontal Symmetry. // We compare first row with last // row, second row with second // last row and so on. for (int i = 0, k = N - 1; i < N / 2; i++, k--) { // Checking each cell of a column. for (int j = 0; j < M; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } // Checking for Vertical Symmetry. We compare // first column with last column, second column // with second last column and so on. for (int i = 0, k = M - 1; i < M / 2; i++, k--) { // Checking each cell of a row. for (int j = 0; j < N; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } if (!horizontal && !vertical) System.out.println(\"NO\"); else if (horizontal && !vertical) System.out.println(\"HORIZONTAL\"); else if (vertical && !horizontal) System.out.println(\"VERTICAL\"); else System.out.println(\"BOTH\"); } // Driver Code static public void main(String[] args) { int[][] mat = { { 1, 0, 1 }, { 0, 0, 0 }, { 1, 0, 1 } }; checkHV(mat, 3, 3); }} // This code is contributed by vt_m.", "e": 5240, "s": 3360, "text": null }, { "code": "# Python3 program to find if a matrix is symmetric.MAX = 1000 def checkHV(arr, N, M): # Initializing as both horizontal and vertical # symmetric. horizontal = True vertical = True # Checking for Horizontal Symmetry. We compare # first row with last row, second row with second # last row and so on. i = 0 k = N - 1 while(i < N // 2): # Checking each cell of a column. for j in range(M): # check if every cell is identical if (arr[i][j] != arr[k][j]): horizontal = False break i += 1 k -= 1 # Checking for Vertical Symmetry. We compare # first column with last column, second column # with second last column and so on. i = 0 k = M - 1 while(i < M // 2): # Checking each cell of a row. for j in range(N): # check if every cell is identical if (arr[i][j] != arr[k][j]): vertical = False break i += 1 k -= 1 if (not horizontal and not vertical): print(\"NO\") else if (horizontal and not vertical): print(\"HORIZONTAL\") else if (vertical and not horizontal): print(\"VERTICAL\") else: print(\"BOTH\") # Driver codemat = [[1, 0, 1],[ 0, 0, 0],[1, 0, 1]] checkHV(mat, 3, 3) # This code is contributed by shubhamsingh10", "e": 6675, "s": 5240, "text": null }, { "code": "// C# program to find if// a matrix is symmetric.using System; public class GFG { static void checkHV(int[, ] arr, int N, int M) { // Initializing as both horizontal // and vertical symmetric. bool horizontal = true; bool vertical = true; // Checking for Horizontal Symmetry. // We compare first row with last // row, second row with second // last row and so on. for (int i = 0, k = N - 1; i < N / 2; i++, k--) { // Checking each cell of a column. for (int j = 0; j < M; j++) { // check if every cell is identical if (arr[i, j] != arr[k, j]) { horizontal = false; break; } } } // Checking for Vertical Symmetry. We compare // first column with last column, second column // with second last column and so on. for (int i = 0, k = M - 1; i < M / 2; i++, k--) { // Checking each cell of a row. for (int j = 0; j < N; j++) { // check if every cell is identical if (arr[i, j] != arr[k, j]) { horizontal = false; break; } } } if (!horizontal && !vertical) Console.WriteLine(\"NO\"); else if (horizontal && !vertical) Console.WriteLine(\"HORIZONTAL\"); else if (vertical && !horizontal) Console.WriteLine(\"VERTICAL\"); else Console.WriteLine(\"BOTH\"); } // Driver Code static public void Main() { int[, ] mat = { { 1, 0, 1 }, { 0, 0, 0 }, { 1, 0, 1 } }; checkHV(mat, 3, 3); }} // This code is contributed by vt_m.", "e": 8525, "s": 6675, "text": null }, { "code": "<?php// PHP program to find if// a matrix is symmetric. function checkHV($arr, $N, $M){ // Initializing as both horizontal // and vertical symmetric. $horizontal = true; $vertical = true; // Checking for Horizontal Symmetry. // We compare first row with last row, // second row with second last row // and so on. for ($i = 0, $k = $N - 1; $i < $N / 2; $i++, $k--) { // Checking each cell of a column. for ($j = 0; $j < $M; $j++) { // check if every cell is identical if ($arr[$i][$j] != $arr[$k][$j]) { $horizontal = false; break; } } } // Checking for Vertical Symmetry. // We compare first column with // last column, second column with // second last column and so on. for ($i = 0, $k = $M - 1; $i < $M / 2; $i++, $k--) { // Checking each cell of a row. for ($j = 0; $j < $N; $j++) { // check if every cell is identical if ($arr[$i][$j] != $arr[$k][$j]) { $horizontal = false; break; } } } if (!$horizontal && !$vertical) echo \"NO\\n\"; else if ($horizontal && !$vertical) cout << \"HORIZONTAL\\n\"; else if ($vertical && !$horizontal) echo \"VERTICAL\\n\"; else echo \"BOTH\\n\";} // Driver Code$mat = array(array (1, 0, 1), array (0, 0, 0), array (1, 0, 1));checkHV($mat, 3, 3); // This code is contributed by nitin mittal.?>", "e": 10092, "s": 8525, "text": null }, { "code": "<script> // Javascript program to find if // a matrix is symmetric. function checkHV(arr, N, M) { // Initializing as both horizontal // and vertical symmetric. let horizontal = true; let vertical = true; // Checking for Horizontal Symmetry. // We compare first row with last // row, second row with second // last row and so on. for (let i = 0, k = N - 1; i < parseInt(N / 2, 10); i++, k--) { // Checking each cell of a column. for (let j = 0; j < M; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } // Checking for Vertical Symmetry. We compare // first column with last column, second column // with second last column and so on. for (let i = 0, k = M - 1; i < parseInt(M / 2, 10); i++, k--) { // Checking each cell of a row. for (let j = 0; j < N; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } if (!horizontal && !vertical) document.write(\"NO\"); else if (horizontal && !vertical) document.write(\"HORIZONTAL\"); else if (vertical && !horizontal) document.write(\"VERTICAL\"); else document.write(\"BOTH\"); } let mat = [ [ 1, 0, 1 ], [ 0, 0, 0 ], [ 1, 0, 1 ] ]; checkHV(mat, 3, 3); </script>", "e": 11826, "s": 10092, "text": null }, { "code": null, "e": 11836, "s": 11826, "text": "Output: " }, { "code": null, "e": 11841, "s": 11836, "text": "BOTH" }, { "code": null, "e": 12323, "s": 11841, "text": "Time Complexity: O(N*M).Auxiliary Space: O(1)This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 12328, "s": 12323, "text": "vt_m" }, { "code": null, "e": 12341, "s": 12328, "text": "nitin mittal" }, { "code": null, "e": 12355, "s": 12341, "text": "ADITYAGUPTA25" }, { "code": null, "e": 12370, "s": 12355, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 12379, "s": 12370, "text": "mukesh07" }, { "code": null, "e": 12389, "s": 12379, "text": "as5853535" }, { "code": null, "e": 12402, "s": 12389, "text": "simmytarika5" }, { "code": null, "e": 12415, "s": 12402, "text": "codewithmini" }, { "code": null, "e": 12422, "s": 12415, "text": "Matrix" }, { "code": null, "e": 12429, "s": 12422, "text": "Matrix" } ]
unsigned char in C with Examples
06 Aug, 2020 char is the most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers. Now character datatype can be divided into 2 types: signed charunsigned char signed char unsigned char unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255. Syntax: unsigned char [variable_name] = [value] Example: unsigned char ch = 'a'; Initializing an unsigned char: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value 97 will be converted to a character value, i.e. ‘a’ and it will be inserted in unsigned char.// C program to show unsigned char #include <stdio.h> int main(){ int chr = 97; unsigned char i = chr; printf("unsigned char: %c\n", i); return 0;}Output:unsigned char: a Initializing an unsigned char with signed value: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value -1 will be first converted to a range 0-255 by rounding. So it will be 255. Now, this value will be converted to a character value, i.e. ‘ÿ’ and it will be inserted in unsigned char.// C program to show unsigned char #include <stdio.h> int main(){ int chr = -1; unsigned char i = chr; printf("unsigned char: %c\n", i); return 0;}Output:unsigned char: ÿ // C program to show unsigned char #include <stdio.h> int main(){ int chr = 97; unsigned char i = chr; printf("unsigned char: %c\n", i); return 0;} unsigned char: a Initializing an unsigned char with signed value: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value -1 will be first converted to a range 0-255 by rounding. So it will be 255. Now, this value will be converted to a character value, i.e. ‘ÿ’ and it will be inserted in unsigned char. // C program to show unsigned char #include <stdio.h> int main(){ int chr = -1; unsigned char i = chr; printf("unsigned char: %c\n", i); return 0;} unsigned char: ÿ Zero97M C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Header files in C/C++ and its uses C Program to read contents of Whole File How to return multiple values from a function in C or C++? C++ Program to check Prime Number Producer Consumer Problem in C C Program to Swap two Numbers Program to find Prime Numbers Between given Interval Set, Clear and Toggle a given bit of a number in C C program to sort an array in ascending order time() function in C
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Aug, 2020" }, { "code": null, "e": 182, "s": 52, "text": "char is the most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers." }, { "code": null, "e": 234, "s": 182, "text": "Now character datatype can be divided into 2 types:" }, { "code": null, "e": 259, "s": 234, "text": "signed charunsigned char" }, { "code": null, "e": 271, "s": 259, "text": "signed char" }, { "code": null, "e": 285, "s": 271, "text": "unsigned char" }, { "code": null, "e": 514, "s": 285, "text": "unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255." }, { "code": null, "e": 522, "s": 514, "text": "Syntax:" }, { "code": null, "e": 563, "s": 522, "text": "unsigned char [variable_name] = [value]\n" }, { "code": null, "e": 572, "s": 563, "text": "Example:" }, { "code": null, "e": 597, "s": 572, "text": "unsigned char ch = 'a';\n" }, { "code": null, "e": 1549, "s": 597, "text": "Initializing an unsigned char: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value 97 will be converted to a character value, i.e. ‘a’ and it will be inserted in unsigned char.// C program to show unsigned char #include <stdio.h> int main(){ int chr = 97; unsigned char i = chr; printf(\"unsigned char: %c\\n\", i); return 0;}Output:unsigned char: a\nInitializing an unsigned char with signed value: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value -1 will be first converted to a range 0-255 by rounding. So it will be 255. Now, this value will be converted to a character value, i.e. ‘ÿ’ and it will be inserted in unsigned char.// C program to show unsigned char #include <stdio.h> int main(){ int chr = -1; unsigned char i = chr; printf(\"unsigned char: %c\\n\", i); return 0;}Output:unsigned char: ÿ\n" }, { "code": "// C program to show unsigned char #include <stdio.h> int main(){ int chr = 97; unsigned char i = chr; printf(\"unsigned char: %c\\n\", i); return 0;}", "e": 1715, "s": 1549, "text": null }, { "code": null, "e": 1733, "s": 1715, "text": "unsigned char: a\n" }, { "code": null, "e": 2074, "s": 1733, "text": "Initializing an unsigned char with signed value: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value -1 will be first converted to a range 0-255 by rounding. So it will be 255. Now, this value will be converted to a character value, i.e. ‘ÿ’ and it will be inserted in unsigned char." }, { "code": "// C program to show unsigned char #include <stdio.h> int main(){ int chr = -1; unsigned char i = chr; printf(\"unsigned char: %c\\n\", i); return 0;}", "e": 2240, "s": 2074, "text": null }, { "code": null, "e": 2259, "s": 2240, "text": "unsigned char: ÿ\n" }, { "code": null, "e": 2267, "s": 2259, "text": "Zero97M" }, { "code": null, "e": 2278, "s": 2267, "text": "C Programs" }, { "code": null, "e": 2376, "s": 2278, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2411, "s": 2376, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 2452, "s": 2411, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 2511, "s": 2452, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 2545, "s": 2511, "text": "C++ Program to check Prime Number" }, { "code": null, "e": 2576, "s": 2545, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 2606, "s": 2576, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 2659, "s": 2606, "text": "Program to find Prime Numbers Between given Interval" }, { "code": null, "e": 2710, "s": 2659, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 2756, "s": 2710, "text": "C program to sort an array in ascending order" } ]
read command in Linux with Examples
24 May, 2019 read command in Linux system is used to read from a file descriptor. Basically, this command read up the total number of bytes from the specified file descriptor into the buffer. If the number or count is zero then this command may detect the errors. But on success, it returns the number of bytes read. Zero indicates the end of the file. If some errors found then it returns -1. Syntax: read Examples: read command without any option: The read command asks for the user’s input and exit once the user provides some input. In the following example we are acquiring the user’s name and then showing the user’s name with a greeting.echo "what is your name..?";read name;echo "hello $name" echo "what is your name..?";read name;echo "hello $name" linux-command Linux-Shell-Commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 May, 2019" }, { "code": null, "e": 434, "s": 53, "text": "read command in Linux system is used to read from a file descriptor. Basically, this command read up the total number of bytes from the specified file descriptor into the buffer. If the number or count is zero then this command may detect the errors. But on success, it returns the number of bytes read. Zero indicates the end of the file. If some errors found then it returns -1." }, { "code": null, "e": 442, "s": 434, "text": "Syntax:" }, { "code": null, "e": 449, "s": 442, "text": "read \n" }, { "code": null, "e": 459, "s": 449, "text": "Examples:" }, { "code": null, "e": 579, "s": 459, "text": "read command without any option: The read command asks for the user’s input and exit once the user provides some input." }, { "code": null, "e": 743, "s": 579, "text": "In the following example we are acquiring the user’s name and then showing the user’s name with a greeting.echo \"what is your name..?\";read name;echo \"hello $name\"" }, { "code": null, "e": 800, "s": 743, "text": "echo \"what is your name..?\";read name;echo \"hello $name\"" }, { "code": null, "e": 814, "s": 800, "text": "linux-command" }, { "code": null, "e": 835, "s": 814, "text": "Linux-Shell-Commands" }, { "code": null, "e": 846, "s": 835, "text": "Linux-Unix" } ]