title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
GATE | GATE-CS-2014-(Set-3) | Question 12 - GeeksforGeeks | 28 Jun, 2021
Let X and Y be finite sets and f: X -> Y be a function. Which one of the following statements is TRUE?(A) A(B) B(C) C(D) DAnswer: (D)Explanation:
Let x = {a, b, c} and y = {1, 2}
A Function f maps each element of x to 1 in y.
f(a)=1 , f(b)=1 , f(c) =1
A = {a, b} B = {b, c}
----------------------------------------------
A ]
| f(A u B) | = |f({a, b, c})| = 3
| f(A)|+|f(B)| = 2 + 2 = 4 , LHS != RHS.
----------------------------------------------
B ]
f(A ∩ B) = f({b}) = { 1 }
f(A) ∩ f(B) = {1, 1} ∩ {1, 1} = {1, 1}
LHS != RHS
-----------------------------------------------
C ]
|f(A ∩ B)| = |f({b})| = |{ 1 }| = 1
min{|f(A)|,|f(B)|} = min(2,2) = 2
LHS != RHS
-----------------------------------------------
D ] In a function a value can be mapped only to one value.
Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38 | [
{
"code": null,
"e": 24559,
"s": 24531,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24705,
"s": 24559,
"text": "Let X and Y be finite sets and f: X -> Y be a function. Which one of the following statements is TRUE?(A) A(B) B(C) C(D) DAnswer: (D)Explanation:"
},
{
"code": null,
"e": 25326,
"s": 24705,
"text": "Let x = {a, b, c} and y = {1, 2}\nA Function f maps each element of x to 1 in y.\nf(a)=1 , f(b)=1 , f(c) =1\nA = {a, b} B = {b, c}\n----------------------------------------------\nA ]\n| f(A u B) | = |f({a, b, c})| = 3\n| f(A)|+|f(B)| = 2 + 2 = 4 , LHS != RHS.\n----------------------------------------------\nB ]\nf(A ∩ B) = f({b}) = { 1 }\nf(A) ∩ f(B) = {1, 1} ∩ {1, 1} = {1, 1}\nLHS != RHS\n-----------------------------------------------\nC ]\n|f(A ∩ B)| = |f({b})| = |{ 1 }| = 1\nmin{|f(A)|,|f(B)|} = min(2,2) = 2\nLHS != RHS\n-----------------------------------------------\nD ] In a function a value can be mapped only to one value."
},
{
"code": null,
"e": 25348,
"s": 25326,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25369,
"s": 25348,
"text": "GATE-CS-2014-(Set-3)"
},
{
"code": null,
"e": 25395,
"s": 25369,
"text": "GATE-GATE-CS-2014-(Set-3)"
},
{
"code": null,
"e": 25400,
"s": 25395,
"text": "GATE"
},
{
"code": null,
"e": 25498,
"s": 25400,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25532,
"s": 25498,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 25574,
"s": 25532,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25608,
"s": 25574,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25650,
"s": 25608,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25683,
"s": 25650,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25717,
"s": 25683,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25759,
"s": 25717,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 61"
},
{
"code": null,
"e": 25801,
"s": 25759,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25843,
"s": 25801,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
}
] |
Predict the Selling Price of HDB Resale Flats | by Jim Meng Kok | Towards Data Science | There are multiple factors affecting the selling price of HDB resale flats in Singapore. Therefore, by using linear regression, I am interested in finding out how the selling price of a HDB resale flat changes based on its following characteristics in this mini exercise:
its distance to the Central Business District (CBD)
its distance to the nearest MRT station
its flat size
its floor level
its remaining years of lease
The resources for this mini exercise can be found on my GitHub which includes the dataset, and the Python notebook files — data preprocessing, and data processing (including the building of linear regression).
The following are the data sources used in this mini exercise:
HDB Resale Flat Prices from Data.gov.sg (as of 3 May 2021)
OneMap API
There are 5 comma-separated values (CSV) files in the HDB Resale Flat Prices dataset in terms of different time periods — 1990 to 1999, 2000 to 2012, 2012 to 2014, 2015 to 2016, and 2017 onwards respectively.
In this mini exercise, all time periods are considered in the analysis. Hence, there is a need to combine all 5 different CSV files as one whole dataset.
import globimport pandas as pddf = pd.concat([pd.read_csv(f) for f in glob.glob("./data/*.csv")], ignore_index=True)
As we can see from the dataset, it is not comprehensive enough to answer the problem statement of this mini exercise. Henceforth, there is a need to compute the remaining lease from this year (2021) onwards as well as complementing with the OneMap API to do geocoding in order to compute the distance between each flat and its nearest MRT station, and the distance between each flat and the CBD (based on Raffles Place).
Prior to conduct geocoding, missing values and duplicate values of the raw dataset would be removed. Furthermore, the address of each HDB flat is constructed in order to retrieve its geo-location.
df['address'] = df['block'] + " " + df['street_name']address_list = df['address'].unique() # to be iterated in order to retrieve the geo-location of each address
Geocoding is done using JSON requests to conduct querying in order to obtain the geo-location of each HDB flat, and the geo-locations of the MRT stations as shown in the picture below. With these, we can compute the distance between each flat and its nearest MRT station. Furthermore, with the geo-locations of all the HDB flats, we can compute the distance between each flat and the CBD.
The followings are the code template to retrieve data from OneMap API as well as the MRT stations that were used as a list to retrieve their geo-locations.
import jsonimport requestsquery_string = 'https://developers.onemap.sg/commonapi/search?searchVal='+query_address+'&returnGeom=Y&getAddrDetails=Y' # define your query_address variable (e.g. HDB address)resp = requests.get(query_string)data = json.loads(try_resp.content)
The final plate to add to our dataset is to compute the remaining lease of each flat from this year onwards. HDB leases are 99 years long so as to compute the remaining lease, a new variable is defined as the following where the starting lease date variable is used:
df['lease_remain_years'] = 99 - (2021 - df['lease_commence_date'])
Ta-da! The new processed dataset is generated!
One necessary step to handle the newly generated dataset is to make sure each of the variables is in its correct data type respectively.
df['resale_price'] = df['resale_price'].astype('float')df['floor_area_sqm'] = df['floor_area_sqm'].astype('float')df['lease_commence_date'] = df['lease_commence_date'].astype('int64')df['lease_remain_years'] = df['lease_remain_years'].astype('int64')df.dtypes
One of the factors to look into is the floor level. The floor level variable is a categorical variable that has different floor level ranges.
Therefore, the median is applied to map each HDB flat’s floor level.
import statisticsdef get_median(x): split_list = x.split(' TO ') float_list = [float(i) for i in split_list] median = statistics.median(float_list) return mediandf['storey_median'] = df['storey_range'].apply(lambda x: get_median(x))
Now it is time to extract the relevant variables that answer the problem statement as our new data frame that is used for building the linear regression model.
#cbd_dist = CBD distance#min_dist_mrt = Distance to the nearest MRT station#floor_area_sqm = Flat size#lease_remain_years = Remaing years of lease#storey_median = Floor level#resale_price = Selling price (dependent variable)df_new = df[['cbd_dist','min_dist_mrt','floor_area_sqm','lease_remain_years','storey_median','resale_price']]
From above, we can infer that the floor size has the highest strength relationship that impacts the resale price as this relationship is positively moderate. Distance to the nearest MRT station has the lowest strength relationship that impacts the resale price as this relationship is negatively weak. Regardless of a positive or a negative relationship, the strength of the rest of the variables that impact the resale price is moderate.
The latest dataset will be split into 75% training dataset and 25% test dataset. In this mini exercise, the dependent variable (y) is the resale price variable while the others are independent variables (X).
from sklearn.model_selection import train_test_splitX=scope_df.to_numpy()[:,:-1]y=scope_df.to_numpy()[:,-1] #resale_price is at the last column of the latest datasetX_train, X_test, y_train, y_test = train_test_split(X,y,random_state=42,test_size=0.25)
Now, it’s time to build the linear regression model!
from sklearn.linear_model import LinearRegressionline = LinearRegression()line.fit(X_train,y_train)line.score(X_train, y_train) # 0.8027920069011848
The R-squared score of the model is 0.803, which is actually considered pretty good!
Let’s further examine the results of the model — Mean Squared Error (MSE), Statistical Significance of Coefficients, both the Mean Absolute Error (MAE) and the Root Mean Squared Error (RMSE), and the Variance Inflation Factor (VIF).
def MSE(ys, y_hats): # Mean Squared Error function n = len(ys) differences = ys - y_hats squared_diffs = differences ** 2 summed_squared_differences = sum(squared_diffs) return (1/n) * summed_squared_differencesMSE(line.predict(X_train),y_train) # 4490363021.170545
The MSE shows that, on average, the error of prediction predicting the selling price of a HDB resale flat is about 67010.171 (+/-).
MSE can be used as an indicator to check how close the predicted selling price is to the actual selling price.
From the table, the p-value in the model is 0, which is less than 0.05, which shows that the independent variables have a statistically significant relationship with the resale price variable.
By answering the problem statement, the model helps to estimate the following variables that impact the selling price of a HDB resale flat:
For every 1 metre further away from the CBD, the selling price drops by $18.12
For every 1 metre further away from the nearest MRT station, the selling price drops by $49.04
For every 1 square metre of flat size increases, the selling price rises by $4353.13
For every 1 remaining year lease, the selling price rises by $4079.25
For every rise in 1 floor, the selling price rises by $5065.95
from sklearn import metricsmetrics.mean_absolute_error(scope_df["resale_price"], predictions)# 51060.924629381385np.sqrt(metrics.mean_squared_error(scope_df["resale_price"], predictions))# 66948.4376270297
As compared to the mean of the resale price of the dataset, the MAE is relatively very small as it is about 1% of the mean of the resale price.
For RMSE, the model’s prediction will miss out $66948.44 on average where it consists of about a 15% error rate, as compared to the mean of the resale price of the dataset. Therefore, the error rate of the model’s prediction is relatively high.
From the table, we can see that VIF values are all below 4. Hence, all the independent variables that should not be correlated with each other are not correlated.
To conclude, we can say that the explanatory variables have a statistically significant relationship with the resale price of a HDB flat. With that, it helps us explain how each explanatory variable impacts the changes in the selling price of a HDB resale flat. Furthermore, as compared to the rest of the explanatory variables, the strength of the relationship between the floor size and the resale price of a HDB flat is the highest which has a positive moderate relationship. However, to improve the analysis, factors such as the towns (planning areas) of the HDB flats as well as the political boundaries where the HDB flats are located can be considered to answer the problem statement. | [
{
"code": null,
"e": 444,
"s": 172,
"text": "There are multiple factors affecting the selling price of HDB resale flats in Singapore. Therefore, by using linear regression, I am interested in finding out how the selling price of a HDB resale flat changes based on its following characteristics in this mini exercise:"
},
{
"code": null,
"e": 496,
"s": 444,
"text": "its distance to the Central Business District (CBD)"
},
{
"code": null,
"e": 536,
"s": 496,
"text": "its distance to the nearest MRT station"
},
{
"code": null,
"e": 550,
"s": 536,
"text": "its flat size"
},
{
"code": null,
"e": 566,
"s": 550,
"text": "its floor level"
},
{
"code": null,
"e": 595,
"s": 566,
"text": "its remaining years of lease"
},
{
"code": null,
"e": 805,
"s": 595,
"text": "The resources for this mini exercise can be found on my GitHub which includes the dataset, and the Python notebook files — data preprocessing, and data processing (including the building of linear regression)."
},
{
"code": null,
"e": 868,
"s": 805,
"text": "The following are the data sources used in this mini exercise:"
},
{
"code": null,
"e": 927,
"s": 868,
"text": "HDB Resale Flat Prices from Data.gov.sg (as of 3 May 2021)"
},
{
"code": null,
"e": 938,
"s": 927,
"text": "OneMap API"
},
{
"code": null,
"e": 1147,
"s": 938,
"text": "There are 5 comma-separated values (CSV) files in the HDB Resale Flat Prices dataset in terms of different time periods — 1990 to 1999, 2000 to 2012, 2012 to 2014, 2015 to 2016, and 2017 onwards respectively."
},
{
"code": null,
"e": 1301,
"s": 1147,
"text": "In this mini exercise, all time periods are considered in the analysis. Hence, there is a need to combine all 5 different CSV files as one whole dataset."
},
{
"code": null,
"e": 1418,
"s": 1301,
"text": "import globimport pandas as pddf = pd.concat([pd.read_csv(f) for f in glob.glob(\"./data/*.csv\")], ignore_index=True)"
},
{
"code": null,
"e": 1839,
"s": 1418,
"text": "As we can see from the dataset, it is not comprehensive enough to answer the problem statement of this mini exercise. Henceforth, there is a need to compute the remaining lease from this year (2021) onwards as well as complementing with the OneMap API to do geocoding in order to compute the distance between each flat and its nearest MRT station, and the distance between each flat and the CBD (based on Raffles Place)."
},
{
"code": null,
"e": 2036,
"s": 1839,
"text": "Prior to conduct geocoding, missing values and duplicate values of the raw dataset would be removed. Furthermore, the address of each HDB flat is constructed in order to retrieve its geo-location."
},
{
"code": null,
"e": 2198,
"s": 2036,
"text": "df['address'] = df['block'] + \" \" + df['street_name']address_list = df['address'].unique() # to be iterated in order to retrieve the geo-location of each address"
},
{
"code": null,
"e": 2587,
"s": 2198,
"text": "Geocoding is done using JSON requests to conduct querying in order to obtain the geo-location of each HDB flat, and the geo-locations of the MRT stations as shown in the picture below. With these, we can compute the distance between each flat and its nearest MRT station. Furthermore, with the geo-locations of all the HDB flats, we can compute the distance between each flat and the CBD."
},
{
"code": null,
"e": 2743,
"s": 2587,
"text": "The followings are the code template to retrieve data from OneMap API as well as the MRT stations that were used as a list to retrieve their geo-locations."
},
{
"code": null,
"e": 3014,
"s": 2743,
"text": "import jsonimport requestsquery_string = 'https://developers.onemap.sg/commonapi/search?searchVal='+query_address+'&returnGeom=Y&getAddrDetails=Y' # define your query_address variable (e.g. HDB address)resp = requests.get(query_string)data = json.loads(try_resp.content)"
},
{
"code": null,
"e": 3281,
"s": 3014,
"text": "The final plate to add to our dataset is to compute the remaining lease of each flat from this year onwards. HDB leases are 99 years long so as to compute the remaining lease, a new variable is defined as the following where the starting lease date variable is used:"
},
{
"code": null,
"e": 3348,
"s": 3281,
"text": "df['lease_remain_years'] = 99 - (2021 - df['lease_commence_date'])"
},
{
"code": null,
"e": 3395,
"s": 3348,
"text": "Ta-da! The new processed dataset is generated!"
},
{
"code": null,
"e": 3532,
"s": 3395,
"text": "One necessary step to handle the newly generated dataset is to make sure each of the variables is in its correct data type respectively."
},
{
"code": null,
"e": 3792,
"s": 3532,
"text": "df['resale_price'] = df['resale_price'].astype('float')df['floor_area_sqm'] = df['floor_area_sqm'].astype('float')df['lease_commence_date'] = df['lease_commence_date'].astype('int64')df['lease_remain_years'] = df['lease_remain_years'].astype('int64')df.dtypes"
},
{
"code": null,
"e": 3934,
"s": 3792,
"text": "One of the factors to look into is the floor level. The floor level variable is a categorical variable that has different floor level ranges."
},
{
"code": null,
"e": 4003,
"s": 3934,
"text": "Therefore, the median is applied to map each HDB flat’s floor level."
},
{
"code": null,
"e": 4248,
"s": 4003,
"text": "import statisticsdef get_median(x): split_list = x.split(' TO ') float_list = [float(i) for i in split_list] median = statistics.median(float_list) return mediandf['storey_median'] = df['storey_range'].apply(lambda x: get_median(x))"
},
{
"code": null,
"e": 4408,
"s": 4248,
"text": "Now it is time to extract the relevant variables that answer the problem statement as our new data frame that is used for building the linear regression model."
},
{
"code": null,
"e": 4742,
"s": 4408,
"text": "#cbd_dist = CBD distance#min_dist_mrt = Distance to the nearest MRT station#floor_area_sqm = Flat size#lease_remain_years = Remaing years of lease#storey_median = Floor level#resale_price = Selling price (dependent variable)df_new = df[['cbd_dist','min_dist_mrt','floor_area_sqm','lease_remain_years','storey_median','resale_price']]"
},
{
"code": null,
"e": 5181,
"s": 4742,
"text": "From above, we can infer that the floor size has the highest strength relationship that impacts the resale price as this relationship is positively moderate. Distance to the nearest MRT station has the lowest strength relationship that impacts the resale price as this relationship is negatively weak. Regardless of a positive or a negative relationship, the strength of the rest of the variables that impact the resale price is moderate."
},
{
"code": null,
"e": 5389,
"s": 5181,
"text": "The latest dataset will be split into 75% training dataset and 25% test dataset. In this mini exercise, the dependent variable (y) is the resale price variable while the others are independent variables (X)."
},
{
"code": null,
"e": 5642,
"s": 5389,
"text": "from sklearn.model_selection import train_test_splitX=scope_df.to_numpy()[:,:-1]y=scope_df.to_numpy()[:,-1] #resale_price is at the last column of the latest datasetX_train, X_test, y_train, y_test = train_test_split(X,y,random_state=42,test_size=0.25)"
},
{
"code": null,
"e": 5695,
"s": 5642,
"text": "Now, it’s time to build the linear regression model!"
},
{
"code": null,
"e": 5844,
"s": 5695,
"text": "from sklearn.linear_model import LinearRegressionline = LinearRegression()line.fit(X_train,y_train)line.score(X_train, y_train) # 0.8027920069011848"
},
{
"code": null,
"e": 5929,
"s": 5844,
"text": "The R-squared score of the model is 0.803, which is actually considered pretty good!"
},
{
"code": null,
"e": 6162,
"s": 5929,
"text": "Let’s further examine the results of the model — Mean Squared Error (MSE), Statistical Significance of Coefficients, both the Mean Absolute Error (MAE) and the Root Mean Squared Error (RMSE), and the Variance Inflation Factor (VIF)."
},
{
"code": null,
"e": 6443,
"s": 6162,
"text": "def MSE(ys, y_hats): # Mean Squared Error function n = len(ys) differences = ys - y_hats squared_diffs = differences ** 2 summed_squared_differences = sum(squared_diffs) return (1/n) * summed_squared_differencesMSE(line.predict(X_train),y_train) # 4490363021.170545"
},
{
"code": null,
"e": 6575,
"s": 6443,
"text": "The MSE shows that, on average, the error of prediction predicting the selling price of a HDB resale flat is about 67010.171 (+/-)."
},
{
"code": null,
"e": 6686,
"s": 6575,
"text": "MSE can be used as an indicator to check how close the predicted selling price is to the actual selling price."
},
{
"code": null,
"e": 6879,
"s": 6686,
"text": "From the table, the p-value in the model is 0, which is less than 0.05, which shows that the independent variables have a statistically significant relationship with the resale price variable."
},
{
"code": null,
"e": 7019,
"s": 6879,
"text": "By answering the problem statement, the model helps to estimate the following variables that impact the selling price of a HDB resale flat:"
},
{
"code": null,
"e": 7098,
"s": 7019,
"text": "For every 1 metre further away from the CBD, the selling price drops by $18.12"
},
{
"code": null,
"e": 7193,
"s": 7098,
"text": "For every 1 metre further away from the nearest MRT station, the selling price drops by $49.04"
},
{
"code": null,
"e": 7278,
"s": 7193,
"text": "For every 1 square metre of flat size increases, the selling price rises by $4353.13"
},
{
"code": null,
"e": 7348,
"s": 7278,
"text": "For every 1 remaining year lease, the selling price rises by $4079.25"
},
{
"code": null,
"e": 7411,
"s": 7348,
"text": "For every rise in 1 floor, the selling price rises by $5065.95"
},
{
"code": null,
"e": 7617,
"s": 7411,
"text": "from sklearn import metricsmetrics.mean_absolute_error(scope_df[\"resale_price\"], predictions)# 51060.924629381385np.sqrt(metrics.mean_squared_error(scope_df[\"resale_price\"], predictions))# 66948.4376270297"
},
{
"code": null,
"e": 7761,
"s": 7617,
"text": "As compared to the mean of the resale price of the dataset, the MAE is relatively very small as it is about 1% of the mean of the resale price."
},
{
"code": null,
"e": 8006,
"s": 7761,
"text": "For RMSE, the model’s prediction will miss out $66948.44 on average where it consists of about a 15% error rate, as compared to the mean of the resale price of the dataset. Therefore, the error rate of the model’s prediction is relatively high."
},
{
"code": null,
"e": 8169,
"s": 8006,
"text": "From the table, we can see that VIF values are all below 4. Hence, all the independent variables that should not be correlated with each other are not correlated."
}
] |
Train Custom Dataset Mask RCNN. A tutorial to easily train custom... | by Michael Chan | Towards Data Science | Step by step explanation of how to train your Mask RCNN model with custom dataset.
First of all simply clone the following repository, it is a demo of an individual class segmentation. (we will cover multiple class too).
git clone https://github.com/miki998/Custom_Train_MaskRCNN
As mentioned in the README.md it is needed to install a mrcnn lib, which is not canonically given. You will simply need to do the following:
git clone https://github.com/matterport/Mask_RCNN.gitcd Mask_RCNNpython setup.py installcd ../rm -rf Mask_RCNN
On top of all, a starting weight is needed, of course you can write your own random initializer, but in our case we decided to simply pick the default .h5 given by the original author. To get the weight, you can get it from my drive.
cd weightswget https://drive.google.com/open?id=1h62_fPkdrBufw1xCaeGwm2SgLWVtFHFQcd ../
After cloning the repository, you should get the following structure. All modifications to be made are within the train.py file, and therefore using your favorite text editor, you will simply have to edit and then add the datasets.
From line 65 till 74, simply modify the category variable and the class names for it to match your dataset (here is the what is originally written):
# define 81 classes that the coco model knowns aboutCategory = 'food'class_names = [‘bread-wholemeal’, ‘potatoes-steamed’, ‘broccoli’, ‘butter’, ‘hard-cheese’, ‘water’, ‘banana’, ‘wine-white’, ‘bread-white’, ‘apple’, ‘pizza-margherita-baked’, ‘salad-leaf-salad-green’, ‘zucchini’, ‘water-mineral’, ‘coffee-with-caffeine’, ‘avocado’, ‘tomato’, ‘dark-chocolate’, ‘white-coffee-with-caffeine’, ‘egg’, ‘mixed-salad-chopped-without-sauce’, ‘sweet-pepper’, ‘mixed-vegetables’, ‘mayonnaise’, ‘rice’, ‘chips-french-fries’, ‘carrot’, ‘tomato-sauce’, ‘cucumber’, ‘wine-red’, ‘cheese’, ‘strawberries’, ‘espresso-with-caffeine’, ‘tea’, ‘chicken’, ‘jam’, ‘leaf-spinach’, ‘pasta-spaghetti’, ‘french-beans’, ‘bread-whole-wheat’]
EXTRA NOTE: Obviously if you want to change hyper parameter such as learning step/ nb of GPU per image or batch size, here is how to do it.
class CustomConfig(Config): """Configuration for training on the toy dataset. Derives from the base Config class and overrides some values. """ # Give the configuration a recognizable name NAME = category # We use a GPU with 12GB memory, which can fit two images. # Adjust down if you use a smaller GPU. IMAGES_PER_GPU = 1 # Number of classes (including background) NUM_CLASSES = 1 + len(class_names) # Background + toy # Number of training steps per epoch STEPS_PER_EPOCH = 100 # Skip detections with < 90% confidence DETECTION_MIN_CONFIDENCE = 0.9
You will simply need to change the parameters written on this part of train.py. For more parameters, you can check the matterport’s github: https://github.com/matterport/Mask_RCNN
Wrapping up, after putting your own dataset in the dataset folder (check inside the folders to know what to put in and the format of it), running the following command starts the training:
python3 train.py train --dataset=./dataset --weights=coco
You should get this illustration after entering the command:
Thanks a bunch for reading and stay tuned for further interesting articles ! You can contact me whenever for further information or if you wanna work together on the subject. Also, a nice click on this link (toward the affiliate program) would really help me out! You will simply have to achieve some quick tasks (simply wait and activate notifications) and all of that will really help me out for more future hardware related content! | [
{
"code": null,
"e": 255,
"s": 172,
"text": "Step by step explanation of how to train your Mask RCNN model with custom dataset."
},
{
"code": null,
"e": 393,
"s": 255,
"text": "First of all simply clone the following repository, it is a demo of an individual class segmentation. (we will cover multiple class too)."
},
{
"code": null,
"e": 452,
"s": 393,
"text": "git clone https://github.com/miki998/Custom_Train_MaskRCNN"
},
{
"code": null,
"e": 593,
"s": 452,
"text": "As mentioned in the README.md it is needed to install a mrcnn lib, which is not canonically given. You will simply need to do the following:"
},
{
"code": null,
"e": 704,
"s": 593,
"text": "git clone https://github.com/matterport/Mask_RCNN.gitcd Mask_RCNNpython setup.py installcd ../rm -rf Mask_RCNN"
},
{
"code": null,
"e": 938,
"s": 704,
"text": "On top of all, a starting weight is needed, of course you can write your own random initializer, but in our case we decided to simply pick the default .h5 given by the original author. To get the weight, you can get it from my drive."
},
{
"code": null,
"e": 1026,
"s": 938,
"text": "cd weightswget https://drive.google.com/open?id=1h62_fPkdrBufw1xCaeGwm2SgLWVtFHFQcd ../"
},
{
"code": null,
"e": 1258,
"s": 1026,
"text": "After cloning the repository, you should get the following structure. All modifications to be made are within the train.py file, and therefore using your favorite text editor, you will simply have to edit and then add the datasets."
},
{
"code": null,
"e": 1407,
"s": 1258,
"text": "From line 65 till 74, simply modify the category variable and the class names for it to match your dataset (here is the what is originally written):"
},
{
"code": null,
"e": 2121,
"s": 1407,
"text": "# define 81 classes that the coco model knowns aboutCategory = 'food'class_names = [‘bread-wholemeal’, ‘potatoes-steamed’, ‘broccoli’, ‘butter’, ‘hard-cheese’, ‘water’, ‘banana’, ‘wine-white’, ‘bread-white’, ‘apple’, ‘pizza-margherita-baked’, ‘salad-leaf-salad-green’, ‘zucchini’, ‘water-mineral’, ‘coffee-with-caffeine’, ‘avocado’, ‘tomato’, ‘dark-chocolate’, ‘white-coffee-with-caffeine’, ‘egg’, ‘mixed-salad-chopped-without-sauce’, ‘sweet-pepper’, ‘mixed-vegetables’, ‘mayonnaise’, ‘rice’, ‘chips-french-fries’, ‘carrot’, ‘tomato-sauce’, ‘cucumber’, ‘wine-red’, ‘cheese’, ‘strawberries’, ‘espresso-with-caffeine’, ‘tea’, ‘chicken’, ‘jam’, ‘leaf-spinach’, ‘pasta-spaghetti’, ‘french-beans’, ‘bread-whole-wheat’]"
},
{
"code": null,
"e": 2261,
"s": 2121,
"text": "EXTRA NOTE: Obviously if you want to change hyper parameter such as learning step/ nb of GPU per image or batch size, here is how to do it."
},
{
"code": null,
"e": 2857,
"s": 2261,
"text": "class CustomConfig(Config): \"\"\"Configuration for training on the toy dataset. Derives from the base Config class and overrides some values. \"\"\" # Give the configuration a recognizable name NAME = category # We use a GPU with 12GB memory, which can fit two images. # Adjust down if you use a smaller GPU. IMAGES_PER_GPU = 1 # Number of classes (including background) NUM_CLASSES = 1 + len(class_names) # Background + toy # Number of training steps per epoch STEPS_PER_EPOCH = 100 # Skip detections with < 90% confidence DETECTION_MIN_CONFIDENCE = 0.9"
},
{
"code": null,
"e": 3037,
"s": 2857,
"text": "You will simply need to change the parameters written on this part of train.py. For more parameters, you can check the matterport’s github: https://github.com/matterport/Mask_RCNN"
},
{
"code": null,
"e": 3226,
"s": 3037,
"text": "Wrapping up, after putting your own dataset in the dataset folder (check inside the folders to know what to put in and the format of it), running the following command starts the training:"
},
{
"code": null,
"e": 3284,
"s": 3226,
"text": "python3 train.py train --dataset=./dataset --weights=coco"
},
{
"code": null,
"e": 3345,
"s": 3284,
"text": "You should get this illustration after entering the command:"
}
] |
jQuery | remove() - GeeksforGeeks | 13 Feb, 2019
The remove() method in JQuery used to remove all the selected elements including all the text. This method also remove data and all the events of the selected elements.Syntax:
$(selector).remove()
Return Value: It will return all the data of the selected elements deleted.Example 1:
Input: $("p").remove()
Output: Output will be all the elements of the paragraph get deleted.
Code 1:
<html> <head> <script src="https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js"> //this is JQuery CDN directed from the JQuery website </script> <script> $(document).ready(function() { $("button").click(function() { $("p").remove(); }); }); </script></head> <body> <div style="padding-left:220px;padding-top:100px;"> <p style="font-size:35px;">Welcome to GFG!!!.</p> <button style="padding:15px;">Click ME</button> </div></body> </html>
Output:Before clicking the button :After clicking on button :We can also find and remove elements using its class name with the help of JQuery remove() method.Syntax:
$(".class_name").remove()
Return value: It will return all the portion deleted on the page with the class name.Example 2:
Input: $(".geek").remove()
Output: Here "gfg!!!" get deleted.
Code #2:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs /jquery/3.3.1/jquery.min.js"> //this is JQuery CDN directed from the JQuery website </script> <script> $(document).ready(function() { $("button").click(function() { $(".geeks").remove(); }); }); </script></head> <body> <div style="margin-left:180px; font-size:35px;padding-top:100px"> <p class="geeks">Welcome to GFG!!!.</p> <p class="geeks">Hello, My class is geeks</p> <button>Click ME</button> </div></body> </html>
Output:Before clicking on button :After clicking on button :Except button everything get remove
jQuery-HTML/CSS
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to add options to a select element using jQuery? | [
{
"code": null,
"e": 25361,
"s": 25333,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 25537,
"s": 25361,
"text": "The remove() method in JQuery used to remove all the selected elements including all the text. This method also remove data and all the events of the selected elements.Syntax:"
},
{
"code": null,
"e": 25559,
"s": 25537,
"text": "$(selector).remove()\n"
},
{
"code": null,
"e": 25645,
"s": 25559,
"text": "Return Value: It will return all the data of the selected elements deleted.Example 1:"
},
{
"code": null,
"e": 25738,
"s": 25645,
"text": "Input: $(\"p\").remove()\nOutput: Output will be all the elements of the paragraph get deleted."
},
{
"code": null,
"e": 25746,
"s": 25738,
"text": "Code 1:"
},
{
"code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js\"> //this is JQuery CDN directed from the JQuery website </script> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"p\").remove(); }); }); </script></head> <body> <div style=\"padding-left:220px;padding-top:100px;\"> <p style=\"font-size:35px;\">Welcome to GFG!!!.</p> <button style=\"padding:15px;\">Click ME</button> </div></body> </html>",
"e": 26306,
"s": 25746,
"text": null
},
{
"code": null,
"e": 26473,
"s": 26306,
"text": "Output:Before clicking the button :After clicking on button :We can also find and remove elements using its class name with the help of JQuery remove() method.Syntax:"
},
{
"code": null,
"e": 26500,
"s": 26473,
"text": "$(\".class_name\").remove()\n"
},
{
"code": null,
"e": 26596,
"s": 26500,
"text": "Return value: It will return all the portion deleted on the page with the class name.Example 2:"
},
{
"code": null,
"e": 26659,
"s": 26596,
"text": "Input: $(\".geek\").remove()\nOutput: Here \"gfg!!!\" get deleted. "
},
{
"code": null,
"e": 26668,
"s": 26659,
"text": "Code #2:"
},
{
"code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs /jquery/3.3.1/jquery.min.js\"> //this is JQuery CDN directed from the JQuery website </script> <script> $(document).ready(function() { $(\"button\").click(function() { $(\".geeks\").remove(); }); }); </script></head> <body> <div style=\"margin-left:180px; font-size:35px;padding-top:100px\"> <p class=\"geeks\">Welcome to GFG!!!.</p> <p class=\"geeks\">Hello, My class is geeks</p> <button>Click ME</button> </div></body> </html>",
"e": 27267,
"s": 26668,
"text": null
},
{
"code": null,
"e": 27363,
"s": 27267,
"text": "Output:Before clicking on button :After clicking on button :Except button everything get remove"
},
{
"code": null,
"e": 27379,
"s": 27363,
"text": "jQuery-HTML/CSS"
},
{
"code": null,
"e": 27390,
"s": 27379,
"text": "JavaScript"
},
{
"code": null,
"e": 27397,
"s": 27390,
"text": "JQuery"
},
{
"code": null,
"e": 27495,
"s": 27397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27556,
"s": 27495,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27597,
"s": 27556,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27637,
"s": 27597,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27691,
"s": 27637,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27739,
"s": 27691,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27785,
"s": 27739,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 27848,
"s": 27785,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 27877,
"s": 27848,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27933,
"s": 27877,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
}
] |
Software Serial in Arduino | The SoftwareSerial library was developed to ensure that any pins of Arduino can exchange Serial data with other peripherals, like GNSS receivers, using software. Arduino Uno, for example, has only one HardwareSerial port (pins 0 and 1), which is connected to the USB via the USB to UART conversion chip. Thus, if you have any other peripheral that requires serial communication, in the absence of SoftwareSerial, you’d have to do away with USB Serial communication.
SoftwareSerial has some limitations −
If you are using multiple SoftwareSerial ports, only one can receive data at a time
If you are using multiple SoftwareSerial ports, only one can receive data at a time
Speeds can be up to a maximum of 115200 bps
Speeds can be up to a maximum of 115200 bps
Other limitations of this library, specific to some Arduino boards, can be found here.
The SoftwareSerial library is included in Arduino IDE Versions 1.0 and above, and you don’t need to install it separately. Defining the Software Serial is very straightforward. An example is shown below −
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
As you can see, you need to create a SoftwareSerial object using two arguments − the RX pin and the TX pin. The other functions are similar to Serial. For example,
Serial.begin(9600) translates to mySerial.begin(9600)
Serial.println("Hello World") has the equivalent mySerial.println("Hello World") and so on.
You are encouraged to go through the examples that come in with the SoftwareSerial library. They can be found in File → Examples → SoftwareSerial. | [
{
"code": null,
"e": 1528,
"s": 1062,
"text": "The SoftwareSerial library was developed to ensure that any pins of Arduino can exchange Serial data with other peripherals, like GNSS receivers, using software. Arduino Uno, for example, has only one HardwareSerial port (pins 0 and 1), which is connected to the USB via the USB to UART conversion chip. Thus, if you have any other peripheral that requires serial communication, in the absence of SoftwareSerial, you’d have to do away with USB Serial communication."
},
{
"code": null,
"e": 1566,
"s": 1528,
"text": "SoftwareSerial has some limitations −"
},
{
"code": null,
"e": 1650,
"s": 1566,
"text": "If you are using multiple SoftwareSerial ports, only one can receive data at a time"
},
{
"code": null,
"e": 1734,
"s": 1650,
"text": "If you are using multiple SoftwareSerial ports, only one can receive data at a time"
},
{
"code": null,
"e": 1778,
"s": 1734,
"text": "Speeds can be up to a maximum of 115200 bps"
},
{
"code": null,
"e": 1822,
"s": 1778,
"text": "Speeds can be up to a maximum of 115200 bps"
},
{
"code": null,
"e": 1909,
"s": 1822,
"text": "Other limitations of this library, specific to some Arduino boards, can be found here."
},
{
"code": null,
"e": 2114,
"s": 1909,
"text": "The SoftwareSerial library is included in Arduino IDE Versions 1.0 and above, and you don’t need to install it separately. Defining the Software Serial is very straightforward. An example is shown below −"
},
{
"code": null,
"e": 2185,
"s": 2114,
"text": "#include <SoftwareSerial.h>\nSoftwareSerial mySerial(10, 11); // RX, TX"
},
{
"code": null,
"e": 2349,
"s": 2185,
"text": "As you can see, you need to create a SoftwareSerial object using two arguments − the RX pin and the TX pin. The other functions are similar to Serial. For example,"
},
{
"code": null,
"e": 2403,
"s": 2349,
"text": "Serial.begin(9600) translates to mySerial.begin(9600)"
},
{
"code": null,
"e": 2495,
"s": 2403,
"text": "Serial.println(\"Hello World\") has the equivalent mySerial.println(\"Hello World\") and so on."
},
{
"code": null,
"e": 2642,
"s": 2495,
"text": "You are encouraged to go through the examples that come in with the SoftwareSerial library. They can be found in File → Examples → SoftwareSerial."
}
] |
How to find index of last occurrence of a substring in a string in Python? | Python has a rfind() method which searches from the end of a string for the occurrence of a substring. It returns the index of last occurrence if found, else -1. You can use it as follows:
>>> 'some of the some'.rfind('some')
12
>>> 'some of the some'.rfind('none')
-1
>>> "NikolaTesla".rfind('kola')
2 | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "Python has a rfind() method which searches from the end of a string for the occurrence of a substring. It returns the index of last occurrence if found, else -1. You can use it as follows:"
},
{
"code": null,
"e": 1365,
"s": 1251,
"text": ">>> 'some of the some'.rfind('some')\n12\n>>> 'some of the some'.rfind('none')\n-1\n>>> \"NikolaTesla\".rfind('kola')\n2"
}
] |
Minimum steps to make the product of the array equal to 1 - GeeksforGeeks | 28 Mar, 2022
Given an array arr[] containing N integers. In one step, any element of the array can either be increased or decreased by one. The task is to find minimum steps required such that the product of the array elements becomes 1.
Examples:
Input: arr[] = { -2, 4, 0 } Output: 5 We can change -2 to -1, 0 to -1 and 4 to 1. So, a total of 5 steps are required to update the elements such that the product of the final array is 1.
Input: arr[] = { -1, 1, -1 } Output: 0
Approach: Follow the steps below to solve the problem:
The product of the array elements can only be equal to 1 when there are only 1s and -1s in the array and the count of -1s is even.Now, all the positive numbers can be reduced to 1 because they are closer to 1 than they are closer to -1.Similarly, all the negative numbers can be updated to -1.If there are 0s present in the array then they can be reduced to either 1 or -1 according to the situation (the count of -1s must be even).If the count of -ve numbers are even then they are always going to yield -1.But if there are odd number of -ve numbers then they are going to yield an odd number of -1s. To fix that, there are two possibilities: First try to find the count 0s in the array because it will take 1 operation to be -1.If there are no zeros in the array then just add 2 in the answer because it will take two steps to make -1 to 1.
The product of the array elements can only be equal to 1 when there are only 1s and -1s in the array and the count of -1s is even.
Now, all the positive numbers can be reduced to 1 because they are closer to 1 than they are closer to -1.
Similarly, all the negative numbers can be updated to -1.
If there are 0s present in the array then they can be reduced to either 1 or -1 according to the situation (the count of -1s must be even).
If the count of -ve numbers are even then they are always going to yield -1.
But if there are odd number of -ve numbers then they are going to yield an odd number of -1s. To fix that, there are two possibilities: First try to find the count 0s in the array because it will take 1 operation to be -1.If there are no zeros in the array then just add 2 in the answer because it will take two steps to make -1 to 1.
First try to find the count 0s in the array because it will take 1 operation to be -1.
If there are no zeros in the array then just add 2 in the answer because it will take two steps to make -1 to 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// steps requiredint MinStep(int a[], int n){ // To store the count of 0s, positive // and negative numbers int positive = 0, negative = 0, zero = 0; // To store the ans int step = 0; for (int i = 0; i < n; i++) { // If array element is // equal to 0 if (a[i] == 0) { zero++; } // If array element is // a negative number else if (a[i] < 0) { negative++; // Extra cost needed // to make it -1 step = step + (-1 - a[i]); } // If array element is // a positive number else { positive++; // Extra cost needed // to make it 1 step = step + (a[i] - 1); } } // Now the array will // have -1, 0 and 1 only if (negative % 2 == 0) { // As count of negative is even // so we will change all 0 to 1 // total cost here will be // count of 0s step = step + zero; } else { // If there are zeroes present // in the array if (zero > 0) { // Change one zero to -1 // and rest of them to 1 // Total cost here will // be count of '0' step = step + zero; } // If there are no zeros in the array else { // As no 0s are available so we // have to change one -1 to 1 // which will cost 2 to // change -1 to 1 step = step + 2; } } return step;} // Driver codeint main(){ int a[] = { 0, -2, -1, -3, 4 }; int n = sizeof(a) / sizeof(a[0]); cout << MinStep(a, n); return 0;}
// Java implementation of the approachclass GFG { // Function to return the minimum // steps required static int MinStep(int a[], int n) { // To store the count of 0s, positive // and negative numbers int positive = 0, negative = 0, zero = 0; // To store the ans int step = 0; for (int i = 0; i < n; i++) { // If array element is // equal to 0 if (a[i] == 0) { zero++; } // If array element is // a negative number else if (a[i] < 0) { negative++; // Extra cost needed // to make it -1 step = step + (-1 - a[i]); } // If array element is // a positive number else { positive++; // Extra cost needed // to make it 1 step = step + (a[i] - 1); } } // Now the array will // have -1, 0 and 1 only if (negative % 2 == 0) { // As count of negative is even // so we will change all 0 to 1 // total cost here will be // count of 0s step = step + zero; } else { // If there are zeroes present // in the array if (zero > 0) { // Change one zero to -1 // and rest of them to 1 // Total cost here will // be count of '0' step = step + zero; } // If there are no zeros in the array else { // As no 0s are available so we // have to change one -1 to 1 // which will cost 2 to // change -1 to 1 step = step + 2; } } return step; } // Driver code public static void main(String[] args) { int a[] = { 0, -2, -1, -3, 4 }; int n = a.length; System.out.println(MinStep(a, n)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach # Function to return the minimum# steps requireddef MinStep(a, n): # To store the count of 0s, positive # and negative numbers positive = 0; negative = 0; zero = 0; # To store the ans step = 0; for i in range(n): # If array element is # equal to 0 if (a[i] == 0): zero += 1; # If array element is # a negative number elif (a[i] < 0): negative += 1; # Extra cost needed # to make it -1 step = step + (-1 - a[i]); # If array element is # a positive number else: positive += 1; # Extra cost needed # to make it 1 step = step + (a[i] - 1); # Now the array will # have -1, 0 and 1 only if (negative % 2 == 0): # As count of negative is even # so we will change all 0 to 1 # total cost here will be # count of 0s step = step + zero; else: # If there are zeroes present # in the array if (zero > 0): # Change one zero to -1 # and rest of them to 1 # Total cost here will # be count of '0' step = step + zero; # If there are no zeros in the array else: # As no 0s are available so we # have to change one -1 to 1 # which will cost 2 to # change -1 to 1 step = step + 2; return step; # Driver codeif __name__ == '__main__': a = [0, -2, -1, -3, 4]; n = len(a); print(MinStep(a, n)); # This code is contributed by PrinciRaj1992
// C# implementation of the approachusing System; class GFG { // Function to return the minimum // steps required static int MinStep(int[] a, int n) { // To store the count of 0s, // positive and negative numbers int positive = 0, negative = 0, zero = 0; // To store the ans int step = 0; for (int i = 0; i < n; i++) { // If array element is // equal to 0 if (a[i] == 0) { zero++; } // If array element is // a negative number else if (a[i] < 0) { negative++; // Extra cost needed // to make it -1 step = step + (-1 - a[i]); } // If array element is // a positive number else { positive++; // Extra cost needed // to make it 1 step = step + (a[i] - 1); } } // Now the array will // have -1, 0 and 1 only if (negative % 2 == 0) { // As count of negative is even // so we will change all 0 to 1 // total cost here will be // count of 0s step = step + zero; } else { // If there are zeroes present // in the array if (zero > 0) { // Change one zero to -1 // and rest of them to 1 // Total cost here will // be count of '0' step = step + zero; } // If there are no zeros in the array else { // As no 0s are available so we // have to change one -1 to 1 // which will cost 2 to // change -1 to 1 step = step + 2; } } return step; } // Driver code static public void Main() { int[] a = { 0, -2, -1, -3, 4 }; int n = a.Length; Console.Write(MinStep(a, n)); }} // This code is contributed by ajit.
<script> // Javascript implementation of the approach // Function to return the minimum// steps requiredfunction MinStep(a, n){ // To store the count of 0s, positive // and negative numbers let positive = 0, negative = 0, zero = 0; // To store the ans let step = 0; for (let i = 0; i < n; i++) { // If array element is // equal to 0 if (a[i] == 0) { zero++; } // If array element is // a negative number else if (a[i] < 0) { negative++; // Extra cost needed // to make it -1 step = step + (-1 - a[i]); } // If array element is // a positive number else { positive++; // Extra cost needed // to make it 1 step = step + (a[i] - 1); } } // Now the array will // have -1, 0 and 1 only if (negative % 2 == 0) { // As count of negative is even // so we will change all 0 to 1 // total cost here will be // count of 0s step = step + zero; } else { // If there are zeroes present // in the array if (zero > 0) { // Change one zero to -1 // and rest of them to 1 // Total cost here will // be count of '0' step = step + zero; } // If there are no zeros in the array else { // As no 0s are available so we // have to change one -1 to 1 // which will cost 2 to // change -1 to 1 step = step + 2; } } return step;} // Driver code let a = [ 0, -2, -1, -3, 4 ]; let n = a.length; document.write(MinStep(a, n)); </script>
7
Time Complexity: O(N)
Auxiliary Space: O(1)
YouTubeGeeksforGeeks Practice24.9K subscribersMinimum steps to make product equal to one | Recently asked questions in Amazon interviewsWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 30:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mPPNFyBNyJY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLM68oyaqFM7Q-sv3gA5xbzfgVkoQ0xDrW
ankthon
jit_t
princiraj1992
subhammahato348
sagarshaw2001
gabaa406
simmytarika5
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25124,
"s": 25096,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 25349,
"s": 25124,
"text": "Given an array arr[] containing N integers. In one step, any element of the array can either be increased or decreased by one. The task is to find minimum steps required such that the product of the array elements becomes 1."
},
{
"code": null,
"e": 25360,
"s": 25349,
"text": "Examples: "
},
{
"code": null,
"e": 25548,
"s": 25360,
"text": "Input: arr[] = { -2, 4, 0 } Output: 5 We can change -2 to -1, 0 to -1 and 4 to 1. So, a total of 5 steps are required to update the elements such that the product of the final array is 1."
},
{
"code": null,
"e": 25589,
"s": 25548,
"text": "Input: arr[] = { -1, 1, -1 } Output: 0 "
},
{
"code": null,
"e": 25644,
"s": 25589,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26487,
"s": 25644,
"text": "The product of the array elements can only be equal to 1 when there are only 1s and -1s in the array and the count of -1s is even.Now, all the positive numbers can be reduced to 1 because they are closer to 1 than they are closer to -1.Similarly, all the negative numbers can be updated to -1.If there are 0s present in the array then they can be reduced to either 1 or -1 according to the situation (the count of -1s must be even).If the count of -ve numbers are even then they are always going to yield -1.But if there are odd number of -ve numbers then they are going to yield an odd number of -1s. To fix that, there are two possibilities: First try to find the count 0s in the array because it will take 1 operation to be -1.If there are no zeros in the array then just add 2 in the answer because it will take two steps to make -1 to 1."
},
{
"code": null,
"e": 26618,
"s": 26487,
"text": "The product of the array elements can only be equal to 1 when there are only 1s and -1s in the array and the count of -1s is even."
},
{
"code": null,
"e": 26725,
"s": 26618,
"text": "Now, all the positive numbers can be reduced to 1 because they are closer to 1 than they are closer to -1."
},
{
"code": null,
"e": 26783,
"s": 26725,
"text": "Similarly, all the negative numbers can be updated to -1."
},
{
"code": null,
"e": 26923,
"s": 26783,
"text": "If there are 0s present in the array then they can be reduced to either 1 or -1 according to the situation (the count of -1s must be even)."
},
{
"code": null,
"e": 27000,
"s": 26923,
"text": "If the count of -ve numbers are even then they are always going to yield -1."
},
{
"code": null,
"e": 27335,
"s": 27000,
"text": "But if there are odd number of -ve numbers then they are going to yield an odd number of -1s. To fix that, there are two possibilities: First try to find the count 0s in the array because it will take 1 operation to be -1.If there are no zeros in the array then just add 2 in the answer because it will take two steps to make -1 to 1."
},
{
"code": null,
"e": 27422,
"s": 27335,
"text": "First try to find the count 0s in the array because it will take 1 operation to be -1."
},
{
"code": null,
"e": 27535,
"s": 27422,
"text": "If there are no zeros in the array then just add 2 in the answer because it will take two steps to make -1 to 1."
},
{
"code": null,
"e": 27588,
"s": 27535,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27592,
"s": 27588,
"text": "C++"
},
{
"code": null,
"e": 27597,
"s": 27592,
"text": "Java"
},
{
"code": null,
"e": 27605,
"s": 27597,
"text": "Python3"
},
{
"code": null,
"e": 27608,
"s": 27605,
"text": "C#"
},
{
"code": null,
"e": 27619,
"s": 27608,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// steps requiredint MinStep(int a[], int n){ // To store the count of 0s, positive // and negative numbers int positive = 0, negative = 0, zero = 0; // To store the ans int step = 0; for (int i = 0; i < n; i++) { // If array element is // equal to 0 if (a[i] == 0) { zero++; } // If array element is // a negative number else if (a[i] < 0) { negative++; // Extra cost needed // to make it -1 step = step + (-1 - a[i]); } // If array element is // a positive number else { positive++; // Extra cost needed // to make it 1 step = step + (a[i] - 1); } } // Now the array will // have -1, 0 and 1 only if (negative % 2 == 0) { // As count of negative is even // so we will change all 0 to 1 // total cost here will be // count of 0s step = step + zero; } else { // If there are zeroes present // in the array if (zero > 0) { // Change one zero to -1 // and rest of them to 1 // Total cost here will // be count of '0' step = step + zero; } // If there are no zeros in the array else { // As no 0s are available so we // have to change one -1 to 1 // which will cost 2 to // change -1 to 1 step = step + 2; } } return step;} // Driver codeint main(){ int a[] = { 0, -2, -1, -3, 4 }; int n = sizeof(a) / sizeof(a[0]); cout << MinStep(a, n); return 0;}",
"e": 29443,
"s": 27619,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the minimum // steps required static int MinStep(int a[], int n) { // To store the count of 0s, positive // and negative numbers int positive = 0, negative = 0, zero = 0; // To store the ans int step = 0; for (int i = 0; i < n; i++) { // If array element is // equal to 0 if (a[i] == 0) { zero++; } // If array element is // a negative number else if (a[i] < 0) { negative++; // Extra cost needed // to make it -1 step = step + (-1 - a[i]); } // If array element is // a positive number else { positive++; // Extra cost needed // to make it 1 step = step + (a[i] - 1); } } // Now the array will // have -1, 0 and 1 only if (negative % 2 == 0) { // As count of negative is even // so we will change all 0 to 1 // total cost here will be // count of 0s step = step + zero; } else { // If there are zeroes present // in the array if (zero > 0) { // Change one zero to -1 // and rest of them to 1 // Total cost here will // be count of '0' step = step + zero; } // If there are no zeros in the array else { // As no 0s are available so we // have to change one -1 to 1 // which will cost 2 to // change -1 to 1 step = step + 2; } } return step; } // Driver code public static void main(String[] args) { int a[] = { 0, -2, -1, -3, 4 }; int n = a.length; System.out.println(MinStep(a, n)); }} // This code is contributed by AnkitRai01",
"e": 31579,
"s": 29443,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the minimum# steps requireddef MinStep(a, n): # To store the count of 0s, positive # and negative numbers positive = 0; negative = 0; zero = 0; # To store the ans step = 0; for i in range(n): # If array element is # equal to 0 if (a[i] == 0): zero += 1; # If array element is # a negative number elif (a[i] < 0): negative += 1; # Extra cost needed # to make it -1 step = step + (-1 - a[i]); # If array element is # a positive number else: positive += 1; # Extra cost needed # to make it 1 step = step + (a[i] - 1); # Now the array will # have -1, 0 and 1 only if (negative % 2 == 0): # As count of negative is even # so we will change all 0 to 1 # total cost here will be # count of 0s step = step + zero; else: # If there are zeroes present # in the array if (zero > 0): # Change one zero to -1 # and rest of them to 1 # Total cost here will # be count of '0' step = step + zero; # If there are no zeros in the array else: # As no 0s are available so we # have to change one -1 to 1 # which will cost 2 to # change -1 to 1 step = step + 2; return step; # Driver codeif __name__ == '__main__': a = [0, -2, -1, -3, 4]; n = len(a); print(MinStep(a, n)); # This code is contributed by PrinciRaj1992",
"e": 33268,
"s": 31579,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { // Function to return the minimum // steps required static int MinStep(int[] a, int n) { // To store the count of 0s, // positive and negative numbers int positive = 0, negative = 0, zero = 0; // To store the ans int step = 0; for (int i = 0; i < n; i++) { // If array element is // equal to 0 if (a[i] == 0) { zero++; } // If array element is // a negative number else if (a[i] < 0) { negative++; // Extra cost needed // to make it -1 step = step + (-1 - a[i]); } // If array element is // a positive number else { positive++; // Extra cost needed // to make it 1 step = step + (a[i] - 1); } } // Now the array will // have -1, 0 and 1 only if (negative % 2 == 0) { // As count of negative is even // so we will change all 0 to 1 // total cost here will be // count of 0s step = step + zero; } else { // If there are zeroes present // in the array if (zero > 0) { // Change one zero to -1 // and rest of them to 1 // Total cost here will // be count of '0' step = step + zero; } // If there are no zeros in the array else { // As no 0s are available so we // have to change one -1 to 1 // which will cost 2 to // change -1 to 1 step = step + 2; } } return step; } // Driver code static public void Main() { int[] a = { 0, -2, -1, -3, 4 }; int n = a.Length; Console.Write(MinStep(a, n)); }} // This code is contributed by ajit.",
"e": 35393,
"s": 33268,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the minimum// steps requiredfunction MinStep(a, n){ // To store the count of 0s, positive // and negative numbers let positive = 0, negative = 0, zero = 0; // To store the ans let step = 0; for (let i = 0; i < n; i++) { // If array element is // equal to 0 if (a[i] == 0) { zero++; } // If array element is // a negative number else if (a[i] < 0) { negative++; // Extra cost needed // to make it -1 step = step + (-1 - a[i]); } // If array element is // a positive number else { positive++; // Extra cost needed // to make it 1 step = step + (a[i] - 1); } } // Now the array will // have -1, 0 and 1 only if (negative % 2 == 0) { // As count of negative is even // so we will change all 0 to 1 // total cost here will be // count of 0s step = step + zero; } else { // If there are zeroes present // in the array if (zero > 0) { // Change one zero to -1 // and rest of them to 1 // Total cost here will // be count of '0' step = step + zero; } // If there are no zeros in the array else { // As no 0s are available so we // have to change one -1 to 1 // which will cost 2 to // change -1 to 1 step = step + 2; } } return step;} // Driver code let a = [ 0, -2, -1, -3, 4 ]; let n = a.length; document.write(MinStep(a, n)); </script>",
"e": 37158,
"s": 35393,
"text": null
},
{
"code": null,
"e": 37160,
"s": 37158,
"text": "7"
},
{
"code": null,
"e": 37185,
"s": 37162,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 37207,
"s": 37185,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 38091,
"s": 37207,
"text": "YouTubeGeeksforGeeks Practice24.9K subscribersMinimum steps to make product equal to one | Recently asked questions in Amazon interviewsWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 30:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=mPPNFyBNyJY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 38133,
"s": 38091,
"text": "?list=PLM68oyaqFM7Q-sv3gA5xbzfgVkoQ0xDrW "
},
{
"code": null,
"e": 38141,
"s": 38133,
"text": "ankthon"
},
{
"code": null,
"e": 38147,
"s": 38141,
"text": "jit_t"
},
{
"code": null,
"e": 38161,
"s": 38147,
"text": "princiraj1992"
},
{
"code": null,
"e": 38177,
"s": 38161,
"text": "subhammahato348"
},
{
"code": null,
"e": 38191,
"s": 38177,
"text": "sagarshaw2001"
},
{
"code": null,
"e": 38200,
"s": 38191,
"text": "gabaa406"
},
{
"code": null,
"e": 38213,
"s": 38200,
"text": "simmytarika5"
},
{
"code": null,
"e": 38220,
"s": 38213,
"text": "Arrays"
},
{
"code": null,
"e": 38233,
"s": 38220,
"text": "Mathematical"
},
{
"code": null,
"e": 38240,
"s": 38233,
"text": "Arrays"
},
{
"code": null,
"e": 38253,
"s": 38240,
"text": "Mathematical"
},
{
"code": null,
"e": 38351,
"s": 38253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38419,
"s": 38351,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 38467,
"s": 38419,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 38511,
"s": 38467,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 38543,
"s": 38511,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 38566,
"s": 38543,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 38596,
"s": 38566,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38656,
"s": 38596,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38671,
"s": 38656,
"text": "C++ Data Types"
},
{
"code": null,
"e": 38714,
"s": 38671,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to handle proxy in Selenium in Java? | We can handle proxy in Selenium in Java with the help of PROXY class.
import java.io.IOException;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
public class ProxySelJav {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver;
String prox = "localhost:8080";
// set browser settings with Desired Capabilities
Proxy p = new Proxy(); p.setHttpProxy(prox).setFtpProxy(prox).setSslProxy(prox)
.setSocksProxy(prox);
DesiredCapabilities c = new DesiredCapabilities();
c.setCapability(CapabilityType.PROXY, p);
// utilize capabilities on launching browser driver
driver = new Firefox(c);
}
} | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "We can handle proxy in Selenium in Java with the help of PROXY class."
},
{
"code": null,
"e": 1932,
"s": 1132,
"text": "import java.io.IOException;\nimport org.openqa.selenium.Proxy;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport org.openqa.selenium.remote.CapabilityType;\nimport org.openqa.selenium.remote.DesiredCapabilities;\npublic class ProxySelJav {\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n WebDriver driver;\n String prox = \"localhost:8080\";\n // set browser settings with Desired Capabilities\n Proxy p = new Proxy(); p.setHttpProxy(prox).setFtpProxy(prox).setSslProxy(prox)\n .setSocksProxy(prox);\n DesiredCapabilities c = new DesiredCapabilities();\n c.setCapability(CapabilityType.PROXY, p);\n // utilize capabilities on launching browser driver\n driver = new Firefox(c);\n }\n}"
}
] |
C/C++ Program for Linear Search | 11 Jun, 2022
Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].
ALGORITHM :Step 1: Start Step 2: Declare an array, and search data variable-x.Step 3: Traverse the entire array until search data is found. If search data is present then return its location else return -1Step 4: print data Step 5: Stop
Pseudocode :
PROCEDURE LINEAR_SEARCH (LIST, VALUE)
FOR EACH ITEM IN THE LIST
IF SEARCH ITEM == VALUE
RETURN THE ITEM'S LOCATION
ELSE
RETURN -1
END FOR
END PROCEDURE
C/C++
C++
#include <bits/stdc++.h>using namespace std; // Linearly search x in arr[]. If x is present then return// its location, otherwise return -1int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Driver codeint main(){ int arr[] = { 3, 4, 1, 7, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 4; int index = search(arr, n, x); if (index == -1) cout << "Element is not present in the array"; else cout << "Element found at position " << index; return 0;}
Output:
Element found at position 1
The time complexity of the above algorithm is O(n).
BEST CASE COMPLEXITY The best-case time complexity – O(1).when the search element is present at the first location of the array it will return the search data location and will terminate the loop and the best case occur. So the best-case time complexity of the linear search is o(1). AVERAGE CASE COMPLEXITY when the search element is present at the random location of the array then the array will traverse until search data is found.The average case time complexity – O(n).WORST-CASE COMPLEXITYwhen the search element is present at the last location of the array then the worst case occurs So the worst-case time complexity of the linear search is o(1).The worst-case time complexity – O(n)SPACE COMPLEXITY:
The space complexity of the linear search is o(n) cause it takes no extra space to store data.
Please refer complete article on Linear Search for more details!
reshmapatil2772
C Programs
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
C++ Program to check Prime Number
Producer Consumer Problem in C
C Program to Swap two Numbers
How to Append a Character to a String in C
Maximum and minimum of an array using minimum number of comparisons
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number
Search, insert and delete in an unsorted array | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jun, 2022"
},
{
"code": null,
"e": 153,
"s": 52,
"text": "Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[]. "
},
{
"code": null,
"e": 481,
"s": 153,
"text": "ALGORITHM :Step 1: Start Step 2: Declare an array, and search data variable-x.Step 3: Traverse the entire array until search data is found. If search data is present then return its location else return -1Step 4: print data Step 5: Stop"
},
{
"code": null,
"e": 494,
"s": 481,
"text": "Pseudocode :"
},
{
"code": null,
"e": 686,
"s": 494,
"text": "PROCEDURE LINEAR_SEARCH (LIST, VALUE)\n FOR EACH ITEM IN THE LIST\n IF SEARCH ITEM == VALUE\n RETURN THE ITEM'S LOCATION\n ELSE\n RETURN -1\n END FOR\nEND PROCEDURE"
},
{
"code": null,
"e": 692,
"s": 686,
"text": "C/C++"
},
{
"code": null,
"e": 696,
"s": 692,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Linearly search x in arr[]. If x is present then return// its location, otherwise return -1int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Driver codeint main(){ int arr[] = { 3, 4, 1, 7, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 4; int index = search(arr, n, x); if (index == -1) cout << \"Element is not present in the array\"; else cout << \"Element found at position \" << index; return 0;}",
"e": 1270,
"s": 696,
"text": null
},
{
"code": null,
"e": 1278,
"s": 1270,
"text": "Output:"
},
{
"code": null,
"e": 1306,
"s": 1278,
"text": "Element found at position 1"
},
{
"code": null,
"e": 1359,
"s": 1306,
"text": "The time complexity of the above algorithm is O(n). "
},
{
"code": null,
"e": 2070,
"s": 1359,
"text": "BEST CASE COMPLEXITY The best-case time complexity – O(1).when the search element is present at the first location of the array it will return the search data location and will terminate the loop and the best case occur. So the best-case time complexity of the linear search is o(1). AVERAGE CASE COMPLEXITY when the search element is present at the random location of the array then the array will traverse until search data is found.The average case time complexity – O(n).WORST-CASE COMPLEXITYwhen the search element is present at the last location of the array then the worst case occurs So the worst-case time complexity of the linear search is o(1).The worst-case time complexity – O(n)SPACE COMPLEXITY:"
},
{
"code": null,
"e": 2166,
"s": 2070,
"text": "The space complexity of the linear search is o(n) cause it takes no extra space to store data. "
},
{
"code": null,
"e": 2231,
"s": 2166,
"text": "Please refer complete article on Linear Search for more details!"
},
{
"code": null,
"e": 2247,
"s": 2231,
"text": "reshmapatil2772"
},
{
"code": null,
"e": 2258,
"s": 2247,
"text": "C Programs"
},
{
"code": null,
"e": 2268,
"s": 2258,
"text": "Searching"
},
{
"code": null,
"e": 2278,
"s": 2268,
"text": "Searching"
},
{
"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": 2417,
"s": 2376,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 2451,
"s": 2417,
"text": "C++ Program to check Prime Number"
},
{
"code": null,
"e": 2482,
"s": 2451,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 2512,
"s": 2482,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 2555,
"s": 2512,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 2623,
"s": 2555,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 2679,
"s": 2623,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 2727,
"s": 2679,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 2751,
"s": 2727,
"text": "Find the Missing Number"
}
] |
matplotlib.pyplot.jet() in Python | 22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The jet() function in pyplot module of matplotlib library is used to set the colormap to “jet”.
Syntax: matplotlib.pyplot.jet()
Parameters: This method does not accepts any parameter.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.jet() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.colorbar(tpc)plt.jet()plt.title('matplotlib.pyplot.jet() function Example', fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.jet()plt.title('matplotlib.pyplot.jet() function Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 319,
"s": 223,
"text": "The jet() function in pyplot module of matplotlib library is used to set the colormap to “jet”."
},
{
"code": null,
"e": 351,
"s": 319,
"text": "Syntax: matplotlib.pyplot.jet()"
},
{
"code": null,
"e": 407,
"s": 351,
"text": "Parameters: This method does not accepts any parameter."
},
{
"code": null,
"e": 455,
"s": 407,
"text": "Returns: This method does not return any value."
},
{
"code": null,
"e": 540,
"s": 455,
"text": "Below examples illustrate the matplotlib.pyplot.jet() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 552,
"s": 540,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.colorbar(tpc)plt.jet()plt.title('matplotlib.pyplot.jet() function Example', fontweight =\"bold\")plt.show()",
"e": 1403,
"s": 552,
"text": null
},
{
"code": null,
"e": 1411,
"s": 1403,
"text": "Output:"
},
{
"code": null,
"e": 1423,
"s": 1411,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap =\"binary_r\", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.jet()plt.title('matplotlib.pyplot.jet() function Example', fontweight =\"bold\")plt.show()",
"e": 2221,
"s": 1423,
"text": null
},
{
"code": null,
"e": 2229,
"s": 2221,
"text": "Output:"
},
{
"code": null,
"e": 2247,
"s": 2229,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2254,
"s": 2247,
"text": "Python"
},
{
"code": null,
"e": 2352,
"s": 2254,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2384,
"s": 2352,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2411,
"s": 2384,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2432,
"s": 2411,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2455,
"s": 2432,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2511,
"s": 2455,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2542,
"s": 2511,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2584,
"s": 2542,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2626,
"s": 2584,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2665,
"s": 2626,
"text": "Python | datetime.timedelta() function"
}
] |
Java Program to Delete a Column in a Table Using JDBC - GeeksforGeeks | 14 Aug, 2021
Before deleting a column in a table, first is need to connect the java application to the database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides the applications to JDBC connection and JDBC driver provides manager to driver connection.
Algorithm: Always remember these 7 thumb golden steps to deal with JDBC in order to deal with the database and between App(Main) class and connection class of it.
Importing the databaseRegistering the Java classEstablishing a connectionCreating a statementExecuting the queryProcess the resultsClosing connection
Importing the database
Registering the Java class
Establishing a connection
Creating a statement
Executing the query
Process the results
Closing connection
Procedure: to delete a column in a table from the database created using JDBC is as follows:
Step 1: Loading “mysqlconnector.jar” in the program.
Step 2: Creating a database and adding a table with records
Using MySQL‘cmd’ DriverDriverManager()Connection()Statement()Resultset() which the classes provided by JDBC API
‘cmd’ Driver
DriverManager()
Connection()
Statement()
Resultset() which the classes provided by JDBC API
Further 5 steps are demonstrated in the java program. (App class or Main class) of the Connection class.
Implementation: Java program using JDBC to delete a Column in a Table
Java
// Java program using JDBC to// Delete a Column in a Table // Step 1: Importing database filesimport java.sql.*; public class GFG { // URL that points to mysql database // DB stands for database static final String url = "jdbc:mysql://localhost:3306/db"; // Main driver method public static void main(String[] args) throws ClassNotFoundException { // Try block to check exceptions try { // Step 2: Load and Register drivers // Class.forName() method is user for // driver registration with name of the driver // as argument that used MySQL driver Class.forName("com.mysql.jdbc.Driver"); // Step 3: Create a connection // getConnection() establishes a connection // It takes url that points to your database // username and password of MySQL connections as // arguments Connection conn = DriverManager.getConnection( url, "root", "1234"); // create.Statement() creates statement object // which is responsible for executing queries on // table Statement stmt = conn.createStatement(); // Executing the query student is the table // name & address is column // Step 4: Create a statement String query = "ALTER TABLE student Drop address"; // Step 5: Execute the query // executeUpdate() returns number of rows // affected by the execution of the statement int result = stmt.executeUpdate(query); // Step 6: Process the results // if result is greater than 0 // it means values has been added if (result > 0) System.out.println( "A column from the table is deleted."); else System.out.println("unsuccessful deletion "); // Step 7: Closing connection conn.close(); } // Catch block to handle exceptions catch (SQLException e) { // Print the exception System.out.println(e); } }}
Output:
akshaysingh98088
sooda367
JDBC
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23892,
"s": 23864,
"text": "\n14 Aug, 2021"
},
{
"code": null,
"e": 24282,
"s": 23892,
"text": "Before deleting a column in a table, first is need to connect the java application to the database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides the applications to JDBC connection and JDBC driver provides manager to driver connection. "
},
{
"code": null,
"e": 24445,
"s": 24282,
"text": "Algorithm: Always remember these 7 thumb golden steps to deal with JDBC in order to deal with the database and between App(Main) class and connection class of it."
},
{
"code": null,
"e": 24595,
"s": 24445,
"text": "Importing the databaseRegistering the Java classEstablishing a connectionCreating a statementExecuting the queryProcess the resultsClosing connection"
},
{
"code": null,
"e": 24618,
"s": 24595,
"text": "Importing the database"
},
{
"code": null,
"e": 24645,
"s": 24618,
"text": "Registering the Java class"
},
{
"code": null,
"e": 24671,
"s": 24645,
"text": "Establishing a connection"
},
{
"code": null,
"e": 24692,
"s": 24671,
"text": "Creating a statement"
},
{
"code": null,
"e": 24712,
"s": 24692,
"text": "Executing the query"
},
{
"code": null,
"e": 24732,
"s": 24712,
"text": "Process the results"
},
{
"code": null,
"e": 24751,
"s": 24732,
"text": "Closing connection"
},
{
"code": null,
"e": 24844,
"s": 24751,
"text": "Procedure: to delete a column in a table from the database created using JDBC is as follows:"
},
{
"code": null,
"e": 24897,
"s": 24844,
"text": "Step 1: Loading “mysqlconnector.jar” in the program."
},
{
"code": null,
"e": 24958,
"s": 24897,
"text": "Step 2: Creating a database and adding a table with records "
},
{
"code": null,
"e": 25070,
"s": 24958,
"text": "Using MySQL‘cmd’ DriverDriverManager()Connection()Statement()Resultset() which the classes provided by JDBC API"
},
{
"code": null,
"e": 25083,
"s": 25070,
"text": "‘cmd’ Driver"
},
{
"code": null,
"e": 25099,
"s": 25083,
"text": "DriverManager()"
},
{
"code": null,
"e": 25112,
"s": 25099,
"text": "Connection()"
},
{
"code": null,
"e": 25124,
"s": 25112,
"text": "Statement()"
},
{
"code": null,
"e": 25175,
"s": 25124,
"text": "Resultset() which the classes provided by JDBC API"
},
{
"code": null,
"e": 25280,
"s": 25175,
"text": "Further 5 steps are demonstrated in the java program. (App class or Main class) of the Connection class."
},
{
"code": null,
"e": 25350,
"s": 25280,
"text": "Implementation: Java program using JDBC to delete a Column in a Table"
},
{
"code": null,
"e": 25355,
"s": 25350,
"text": "Java"
},
{
"code": "// Java program using JDBC to// Delete a Column in a Table // Step 1: Importing database filesimport java.sql.*; public class GFG { // URL that points to mysql database // DB stands for database static final String url = \"jdbc:mysql://localhost:3306/db\"; // Main driver method public static void main(String[] args) throws ClassNotFoundException { // Try block to check exceptions try { // Step 2: Load and Register drivers // Class.forName() method is user for // driver registration with name of the driver // as argument that used MySQL driver Class.forName(\"com.mysql.jdbc.Driver\"); // Step 3: Create a connection // getConnection() establishes a connection // It takes url that points to your database // username and password of MySQL connections as // arguments Connection conn = DriverManager.getConnection( url, \"root\", \"1234\"); // create.Statement() creates statement object // which is responsible for executing queries on // table Statement stmt = conn.createStatement(); // Executing the query student is the table // name & address is column // Step 4: Create a statement String query = \"ALTER TABLE student Drop address\"; // Step 5: Execute the query // executeUpdate() returns number of rows // affected by the execution of the statement int result = stmt.executeUpdate(query); // Step 6: Process the results // if result is greater than 0 // it means values has been added if (result > 0) System.out.println( \"A column from the table is deleted.\"); else System.out.println(\"unsuccessful deletion \"); // Step 7: Closing connection conn.close(); } // Catch block to handle exceptions catch (SQLException e) { // Print the exception System.out.println(e); } }}",
"e": 27549,
"s": 25355,
"text": null
},
{
"code": null,
"e": 27557,
"s": 27549,
"text": "Output:"
},
{
"code": null,
"e": 27574,
"s": 27557,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 27583,
"s": 27574,
"text": "sooda367"
},
{
"code": null,
"e": 27588,
"s": 27583,
"text": "JDBC"
},
{
"code": null,
"e": 27595,
"s": 27588,
"text": "Picked"
},
{
"code": null,
"e": 27619,
"s": 27595,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27624,
"s": 27619,
"text": "Java"
},
{
"code": null,
"e": 27638,
"s": 27624,
"text": "Java Programs"
},
{
"code": null,
"e": 27657,
"s": 27638,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27662,
"s": 27657,
"text": "Java"
},
{
"code": null,
"e": 27760,
"s": 27662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27769,
"s": 27760,
"text": "Comments"
},
{
"code": null,
"e": 27782,
"s": 27769,
"text": "Old Comments"
},
{
"code": null,
"e": 27803,
"s": 27782,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27818,
"s": 27803,
"text": "Stream In Java"
},
{
"code": null,
"e": 27837,
"s": 27818,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27883,
"s": 27837,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27913,
"s": 27883,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27957,
"s": 27913,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27983,
"s": 27957,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28017,
"s": 27983,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28064,
"s": 28017,
"text": "Implementing a Linked List in Java using Class"
}
] |
C program to Check Whether a Number is Positive or Negative or Zero? | A number which is greater than 0 is positive and less than 0 are negative. The concept of positive and negative is very important in number theory and programming also. Calculations rely on this concept only.
Input: 0
Output:0 is zero
Using conditional statement check the number with 0 weather it is greater than 0 or smaller than 0.
#include <iostream>
using namespace std;
int main() {
int n=0;
if(n>0) {
printf("%d is positive",n);
} else if(n<0) {
printf("%d is negative",n);
} else {
printf("%d is zero",n);
}
return 0;
} | [
{
"code": null,
"e": 1271,
"s": 1062,
"text": "A number which is greater than 0 is positive and less than 0 are negative. The concept of positive and negative is very important in number theory and programming also. Calculations rely on this concept only."
},
{
"code": null,
"e": 1297,
"s": 1271,
"text": "Input: 0\nOutput:0 is zero"
},
{
"code": null,
"e": 1397,
"s": 1297,
"text": "Using conditional statement check the number with 0 weather it is greater than 0 or smaller than 0."
},
{
"code": null,
"e": 1626,
"s": 1397,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int n=0;\n if(n>0) {\n printf(\"%d is positive\",n);\n } else if(n<0) {\n printf(\"%d is negative\",n);\n } else {\n printf(\"%d is zero\",n);\n }\n return 0;\n}"
}
] |
Placing plot on Tkinter main window in Python | Oftentimes, we need to deal with plots in our Tkinter GUI-based application. To support the plots for the available data points, Python provides a Matplotlib package that can be imported into the application easily. In order to add a plot for the given data points, we have to install several other packages such as NumPy along with Matplotlib. NumPy is a Python library that helps to deal with scientific calculation in the Data.
In this example, we will create data points for the car prices starting from (100000) with the units in the range of 1000 to 5000.
#Import the required Libraries
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
#Create an instance of Tkinter frame
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
def graph():
car_prices=np.random.normal(100000, 5000, 1000)
plt.hist(car_prices, 20)
plt.show()
#Create a button to show the plot
Button(win, text= "Show Graph", command= graph).pack(pady=20)
win.mainloop()
If we will run the above code, it will display a window that contains a button "Show Graph".
When we click the button, it will display the graph on the screen. | [
{
"code": null,
"e": 1493,
"s": 1062,
"text": "Oftentimes, we need to deal with plots in our Tkinter GUI-based application. To support the plots for the available data points, Python provides a Matplotlib package that can be imported into the application easily. In order to add a plot for the given data points, we have to install several other packages such as NumPy along with Matplotlib. NumPy is a Python library that helps to deal with scientific calculation in the Data."
},
{
"code": null,
"e": 1624,
"s": 1493,
"text": "In this example, we will create data points for the car prices starting from (100000) with the units in the range of 1000 to 5000."
},
{
"code": null,
"e": 2055,
"s": 1624,
"text": "#Import the required Libraries\nfrom tkinter import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Create an instance of Tkinter frame\nwin= Tk()\n\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n\ndef graph():\n car_prices=np.random.normal(100000, 5000, 1000)\n plt.hist(car_prices, 20)\n plt.show()\n\n#Create a button to show the plot\nButton(win, text= \"Show Graph\", command= graph).pack(pady=20)\nwin.mainloop()"
},
{
"code": null,
"e": 2148,
"s": 2055,
"text": "If we will run the above code, it will display a window that contains a button \"Show Graph\"."
},
{
"code": null,
"e": 2215,
"s": 2148,
"text": "When we click the button, it will display the graph on the screen."
}
] |
How to convert JSON into a Pandas DataFrame | by B. Chen | Towards Data Science | Reading data is the first step in any data science project. Often, you’ll work with data in JSON format and run into problems at the very beginning. In this article, you’ll learn how to use the Pandas built-in functions read_json() and json_normalize() to deal with the following common problems:
Reading simple JSON from a local fileReading simple JSON from a URLFlattening nested list from JSON objectFlattening nested list and dict from JSON objectExtracting a value from deeply nested JSON
Reading simple JSON from a local file
Reading simple JSON from a URL
Flattening nested list from JSON object
Flattening nested list and dict from JSON object
Extracting a value from deeply nested JSON
Please check out Notebook for the source code.
Let’s begin with a simple example.
[ { "id": "A001", "name": "Tom", "math": 60, "physics": 66, "chemistry": 61 }, { "id": "A002", "name": "James", "math": 89, "physics": 76, "chemistry": 51 }, { "id": "A003", "name": "Jenny", "math": 79, "physics": 90, "chemistry": 78 }]
To read a JSON file via Pandas, we can use the read_json() method.
df = pd.read_json('data/simple.json')
The result looks great. Let’s take a look at the data types with df.info(). By default, columns that are numerical are cast to numeric types, for example, the math, physics, and chemistry columns have been cast to int64.
>>> df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 3 entries, 0 to 2Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 3 non-null object 1 name 3 non-null object 2 math 3 non-null int64 3 physics 3 non-null int64 4 chemistry 3 non-null int64 dtypes: int64(3), object(2)memory usage: 248.0+ bytes
Pandas read_json() accepts a URL.
URL = 'http://raw.githubusercontent.com/BindiChen/machine-learning/master/data-analysis/027-pandas-convert-json/data/simple.json'df = pd.read_json(URL)
>>> df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 3 entries, 0 to 2Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 3 non-null object 1 name 3 non-null object 2 math 3 non-null int64 3 physics 3 non-null int64 4 chemistry 3 non-null int64 dtypes: int64(3), object(2)memory usage: 248.0+ bytes
Same as reading from a local file, it returns a DataFrame, and columns that are numerical are cast to numeric types by default.
Pandas read_json() works great for flattened JSON like we have in the previous example. What about JSON with a nested list? Let’s see how to convert the following JSON into a DataFrame:
{ "school_name": "ABC primary school", "class": "Year 1", "students": [ { "id": "A001", "name": "Tom", "math": 60, "physics": 66, "chemistry": 61 }, { "id": "A002", "name": "James", "math": 89, "physics": 76, "chemistry": 51 }, { "id": "A003", "name": "Jenny", "math": 79, "physics": 90, "chemistry": 78 }]}
To read it with pandas read_json()
df = pd.read_json('data/nested_list.json')
After reading this JSON, we can see that our nested list is put up into a single column students. How can we flatten the nested list? One solution is to apply a custom function to flatten the values in students.
This certainly does our work, but it requires extra code to get the data in the form we require. We can solve this effectively using the Pandas json_normalize() function.
import json# load data using Python JSON modulewith open('data/nested_array.json','r') as f: data = json.loads(f.read())# Flatten datadf_nested_list = pd.json_normalize(data, record_path =['students'])
data = json.loads(f.read()) load data using Python json module. After that, json_normalize() is called with the argument record_path set to ['students'] to flatten the nested list in students.
The result looks great but doesn’t include school_name and class. To include them, we can use the argument meta to specify a list of metadata we want in the result.
# To include school_name and classdf_nested_list = pd.json_normalize( data, record_path =['students'], meta=['school_name', 'class'])
Next, let’s try to read a more complex JSON data, with a nested list and a nested dictionary.
{ "school_name": "local primary school", "class": "Year 1", "info": { "president": "John Kasich", "address": "ABC road, London, UK", "contacts": { "email": "[email protected]", "tel": "123456789" } }, "students": [ { "id": "A001", "name": "Tom", "math": 60, "physics": 66, "chemistry": 61 }, { "id": "A002", "name": "James", "math": 89, "physics": 76, "chemistry": 51 }, { "id": "A003", "name": "Jenny", "math": 79, "physics": 90, "chemistry": 78 }]}
We will get a ValueError when trying to read it using read_json().
To read it probably, we can use json_normalize()
import json# load data using Python JSON modulewith open('data/nested_mix.json','r') as f: data = json.loads(f.read()) # Normalizing datadf = pd.json_normalize(data, record_path =['students'])
And to include class, president (a property of info), and tel (a property of contacts.info), we can use the argument meta to specify the path to the property.
df = pd.json_normalize( data, record_path =['students'], meta=[ 'class', ['info', 'president'], ['info', 'contacts', 'tel'] ])
Please check out the following article if you would like to learn more about Pandas json_normalize():
towardsdatascience.com
Pandas json_normalize() can do most of the work when working with nested data from a JSON file. However, it flattens the entire nested data when your goal might actually be to extract one value. For example, to extract the property math from the following JSON file.
{ "school_name": "local primary school", "class": "Year 1", "students": [ { "id": "A001", "name": "Tom", "grade": { "math": 60, "physics": 66, "chemistry": 61 } }, { "id": "A002", "name": "James", "grade": { "math": 89, "physics": 76, "chemistry": 51 } }, { "id": "A003", "name": "Jenny", "grade": { "math": 79, "physics": 90, "chemistry": 78 } }]}
How can we do that more effectively? The answer is using read_json with glom.
from glom import glomdf = pd.read_json('data/nested_deep.json')df['students'].apply(lambda row: glom(row, 'grade.math'))0 601 892 79Name: students, dtype: int64
glom is a Python library that allows us to use . notation to access property from a deeply nested object.
Pandas read_json() function is a quick and convenient way for converting simple flattened JSON into a Pandas DataFrame. When dealing with nested JSON, we can use the Pandas built-in json_normalize() function.
I hope this article will help you to save time in converting JSON data into a DataFrame. I recommend you to check out the documentation for read_json() and json_normalize() APIs, and to know about other things you can do.
Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning.
Using Pandas method chaining to improve code readability
All Pandas json_normalize() you should know for flattening JSON
How to do a Custom Sort on Pandas DataFrame
All the Pandas shift() you should know for data analysis
When to use Pandas transform() function
Pandas concat() tricks you should know
Difference between apply() and transform() in Pandas
All the Pandas merge() you should know
Working with datetime in Pandas DataFrame
Pandas read_csv() tricks you should know
4 tricks you should know to parse date columns with Pandas read_csv()
More tutorials can be found on my Github | [
{
"code": null,
"e": 469,
"s": 172,
"text": "Reading data is the first step in any data science project. Often, you’ll work with data in JSON format and run into problems at the very beginning. In this article, you’ll learn how to use the Pandas built-in functions read_json() and json_normalize() to deal with the following common problems:"
},
{
"code": null,
"e": 666,
"s": 469,
"text": "Reading simple JSON from a local fileReading simple JSON from a URLFlattening nested list from JSON objectFlattening nested list and dict from JSON objectExtracting a value from deeply nested JSON"
},
{
"code": null,
"e": 704,
"s": 666,
"text": "Reading simple JSON from a local file"
},
{
"code": null,
"e": 735,
"s": 704,
"text": "Reading simple JSON from a URL"
},
{
"code": null,
"e": 775,
"s": 735,
"text": "Flattening nested list from JSON object"
},
{
"code": null,
"e": 824,
"s": 775,
"text": "Flattening nested list and dict from JSON object"
},
{
"code": null,
"e": 867,
"s": 824,
"text": "Extracting a value from deeply nested JSON"
},
{
"code": null,
"e": 914,
"s": 867,
"text": "Please check out Notebook for the source code."
},
{
"code": null,
"e": 949,
"s": 914,
"text": "Let’s begin with a simple example."
},
{
"code": null,
"e": 1237,
"s": 949,
"text": "[ { \"id\": \"A001\", \"name\": \"Tom\", \"math\": 60, \"physics\": 66, \"chemistry\": 61 }, { \"id\": \"A002\", \"name\": \"James\", \"math\": 89, \"physics\": 76, \"chemistry\": 51 }, { \"id\": \"A003\", \"name\": \"Jenny\", \"math\": 79, \"physics\": 90, \"chemistry\": 78 }]"
},
{
"code": null,
"e": 1304,
"s": 1237,
"text": "To read a JSON file via Pandas, we can use the read_json() method."
},
{
"code": null,
"e": 1342,
"s": 1304,
"text": "df = pd.read_json('data/simple.json')"
},
{
"code": null,
"e": 1563,
"s": 1342,
"text": "The result looks great. Let’s take a look at the data types with df.info(). By default, columns that are numerical are cast to numeric types, for example, the math, physics, and chemistry columns have been cast to int64."
},
{
"code": null,
"e": 1993,
"s": 1563,
"text": ">>> df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 3 entries, 0 to 2Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 3 non-null object 1 name 3 non-null object 2 math 3 non-null int64 3 physics 3 non-null int64 4 chemistry 3 non-null int64 dtypes: int64(3), object(2)memory usage: 248.0+ bytes"
},
{
"code": null,
"e": 2027,
"s": 1993,
"text": "Pandas read_json() accepts a URL."
},
{
"code": null,
"e": 2179,
"s": 2027,
"text": "URL = 'http://raw.githubusercontent.com/BindiChen/machine-learning/master/data-analysis/027-pandas-convert-json/data/simple.json'df = pd.read_json(URL)"
},
{
"code": null,
"e": 2609,
"s": 2179,
"text": ">>> df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 3 entries, 0 to 2Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 3 non-null object 1 name 3 non-null object 2 math 3 non-null int64 3 physics 3 non-null int64 4 chemistry 3 non-null int64 dtypes: int64(3), object(2)memory usage: 248.0+ bytes"
},
{
"code": null,
"e": 2737,
"s": 2609,
"text": "Same as reading from a local file, it returns a DataFrame, and columns that are numerical are cast to numeric types by default."
},
{
"code": null,
"e": 2923,
"s": 2737,
"text": "Pandas read_json() works great for flattened JSON like we have in the previous example. What about JSON with a nested list? Let’s see how to convert the following JSON into a DataFrame:"
},
{
"code": null,
"e": 3363,
"s": 2923,
"text": "{ \"school_name\": \"ABC primary school\", \"class\": \"Year 1\", \"students\": [ { \"id\": \"A001\", \"name\": \"Tom\", \"math\": 60, \"physics\": 66, \"chemistry\": 61 }, { \"id\": \"A002\", \"name\": \"James\", \"math\": 89, \"physics\": 76, \"chemistry\": 51 }, { \"id\": \"A003\", \"name\": \"Jenny\", \"math\": 79, \"physics\": 90, \"chemistry\": 78 }]}"
},
{
"code": null,
"e": 3398,
"s": 3363,
"text": "To read it with pandas read_json()"
},
{
"code": null,
"e": 3441,
"s": 3398,
"text": "df = pd.read_json('data/nested_list.json')"
},
{
"code": null,
"e": 3653,
"s": 3441,
"text": "After reading this JSON, we can see that our nested list is put up into a single column students. How can we flatten the nested list? One solution is to apply a custom function to flatten the values in students."
},
{
"code": null,
"e": 3824,
"s": 3653,
"text": "This certainly does our work, but it requires extra code to get the data in the form we require. We can solve this effectively using the Pandas json_normalize() function."
},
{
"code": null,
"e": 4029,
"s": 3824,
"text": "import json# load data using Python JSON modulewith open('data/nested_array.json','r') as f: data = json.loads(f.read())# Flatten datadf_nested_list = pd.json_normalize(data, record_path =['students'])"
},
{
"code": null,
"e": 4222,
"s": 4029,
"text": "data = json.loads(f.read()) load data using Python json module. After that, json_normalize() is called with the argument record_path set to ['students'] to flatten the nested list in students."
},
{
"code": null,
"e": 4387,
"s": 4222,
"text": "The result looks great but doesn’t include school_name and class. To include them, we can use the argument meta to specify a list of metadata we want in the result."
},
{
"code": null,
"e": 4532,
"s": 4387,
"text": "# To include school_name and classdf_nested_list = pd.json_normalize( data, record_path =['students'], meta=['school_name', 'class'])"
},
{
"code": null,
"e": 4626,
"s": 4532,
"text": "Next, let’s try to read a more complex JSON data, with a nested list and a nested dictionary."
},
{
"code": null,
"e": 5243,
"s": 4626,
"text": "{ \"school_name\": \"local primary school\", \"class\": \"Year 1\", \"info\": { \"president\": \"John Kasich\", \"address\": \"ABC road, London, UK\", \"contacts\": { \"email\": \"[email protected]\", \"tel\": \"123456789\" } }, \"students\": [ { \"id\": \"A001\", \"name\": \"Tom\", \"math\": 60, \"physics\": 66, \"chemistry\": 61 }, { \"id\": \"A002\", \"name\": \"James\", \"math\": 89, \"physics\": 76, \"chemistry\": 51 }, { \"id\": \"A003\", \"name\": \"Jenny\", \"math\": 79, \"physics\": 90, \"chemistry\": 78 }]}"
},
{
"code": null,
"e": 5310,
"s": 5243,
"text": "We will get a ValueError when trying to read it using read_json()."
},
{
"code": null,
"e": 5359,
"s": 5310,
"text": "To read it probably, we can use json_normalize()"
},
{
"code": null,
"e": 5558,
"s": 5359,
"text": "import json# load data using Python JSON modulewith open('data/nested_mix.json','r') as f: data = json.loads(f.read()) # Normalizing datadf = pd.json_normalize(data, record_path =['students'])"
},
{
"code": null,
"e": 5717,
"s": 5558,
"text": "And to include class, president (a property of info), and tel (a property of contacts.info), we can use the argument meta to specify the path to the property."
},
{
"code": null,
"e": 5880,
"s": 5717,
"text": "df = pd.json_normalize( data, record_path =['students'], meta=[ 'class', ['info', 'president'], ['info', 'contacts', 'tel'] ])"
},
{
"code": null,
"e": 5982,
"s": 5880,
"text": "Please check out the following article if you would like to learn more about Pandas json_normalize():"
},
{
"code": null,
"e": 6005,
"s": 5982,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6272,
"s": 6005,
"text": "Pandas json_normalize() can do most of the work when working with nested data from a JSON file. However, it flattens the entire nested data when your goal might actually be to extract one value. For example, to extract the property math from the following JSON file."
},
{
"code": null,
"e": 6841,
"s": 6272,
"text": "{ \"school_name\": \"local primary school\", \"class\": \"Year 1\", \"students\": [ { \"id\": \"A001\", \"name\": \"Tom\", \"grade\": { \"math\": 60, \"physics\": 66, \"chemistry\": 61 } }, { \"id\": \"A002\", \"name\": \"James\", \"grade\": { \"math\": 89, \"physics\": 76, \"chemistry\": 51 } }, { \"id\": \"A003\", \"name\": \"Jenny\", \"grade\": { \"math\": 79, \"physics\": 90, \"chemistry\": 78 } }]}"
},
{
"code": null,
"e": 6919,
"s": 6841,
"text": "How can we do that more effectively? The answer is using read_json with glom."
},
{
"code": null,
"e": 7089,
"s": 6919,
"text": "from glom import glomdf = pd.read_json('data/nested_deep.json')df['students'].apply(lambda row: glom(row, 'grade.math'))0 601 892 79Name: students, dtype: int64"
},
{
"code": null,
"e": 7195,
"s": 7089,
"text": "glom is a Python library that allows us to use . notation to access property from a deeply nested object."
},
{
"code": null,
"e": 7404,
"s": 7195,
"text": "Pandas read_json() function is a quick and convenient way for converting simple flattened JSON into a Pandas DataFrame. When dealing with nested JSON, we can use the Pandas built-in json_normalize() function."
},
{
"code": null,
"e": 7626,
"s": 7404,
"text": "I hope this article will help you to save time in converting JSON data into a DataFrame. I recommend you to check out the documentation for read_json() and json_normalize() APIs, and to know about other things you can do."
},
{
"code": null,
"e": 7778,
"s": 7626,
"text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning."
},
{
"code": null,
"e": 7835,
"s": 7778,
"text": "Using Pandas method chaining to improve code readability"
},
{
"code": null,
"e": 7899,
"s": 7835,
"text": "All Pandas json_normalize() you should know for flattening JSON"
},
{
"code": null,
"e": 7943,
"s": 7899,
"text": "How to do a Custom Sort on Pandas DataFrame"
},
{
"code": null,
"e": 8000,
"s": 7943,
"text": "All the Pandas shift() you should know for data analysis"
},
{
"code": null,
"e": 8040,
"s": 8000,
"text": "When to use Pandas transform() function"
},
{
"code": null,
"e": 8079,
"s": 8040,
"text": "Pandas concat() tricks you should know"
},
{
"code": null,
"e": 8132,
"s": 8079,
"text": "Difference between apply() and transform() in Pandas"
},
{
"code": null,
"e": 8171,
"s": 8132,
"text": "All the Pandas merge() you should know"
},
{
"code": null,
"e": 8213,
"s": 8171,
"text": "Working with datetime in Pandas DataFrame"
},
{
"code": null,
"e": 8254,
"s": 8213,
"text": "Pandas read_csv() tricks you should know"
},
{
"code": null,
"e": 8324,
"s": 8254,
"text": "4 tricks you should know to parse date columns with Pandas read_csv()"
}
] |
C++ Vector Library - vector() Function | The C++ default constructor std::vector::vector() constructs an empty container, with zero elements. Size of this container is always zero.
The storage for container is allocated by internal allocator.
Following is the declaration for std::vector::vector() constructor form std::vector header.
explicit vector (const allocator_type& alloc = allocator_type());
explicit vector (const allocator_type& alloc = allocator_type());
alloc − allocator object
This allocator object is responsible for performing all memory allocation of this container.
Container keeps and uses the internal copy of this container. Member type allocator_type is a internal allocator which is second parameter of the class template.
Constructor never returns value
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::vector() constructor.
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v1;
cout << "size of v1 = " << v1.size() << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
size of v1 = 0
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2743,
"s": 2603,
"text": "The C++ default constructor std::vector::vector() constructs an empty container, with zero elements. Size of this container is always zero."
},
{
"code": null,
"e": 2805,
"s": 2743,
"text": "The storage for container is allocated by internal allocator."
},
{
"code": null,
"e": 2897,
"s": 2805,
"text": "Following is the declaration for std::vector::vector() constructor form std::vector header."
},
{
"code": null,
"e": 2964,
"s": 2897,
"text": "explicit vector (const allocator_type& alloc = allocator_type());\n"
},
{
"code": null,
"e": 3031,
"s": 2964,
"text": "explicit vector (const allocator_type& alloc = allocator_type());\n"
},
{
"code": null,
"e": 3056,
"s": 3031,
"text": "alloc − allocator object"
},
{
"code": null,
"e": 3311,
"s": 3056,
"text": "This allocator object is responsible for performing all memory allocation of this container.\nContainer keeps and uses the internal copy of this container. Member type allocator_type is a internal allocator which is second parameter of the class template."
},
{
"code": null,
"e": 3343,
"s": 3311,
"text": "Constructor never returns value"
},
{
"code": null,
"e": 3388,
"s": 3343,
"text": "This member function never throws exception."
},
{
"code": null,
"e": 3407,
"s": 3388,
"text": "Constant i.e. O(1)"
},
{
"code": null,
"e": 3483,
"s": 3407,
"text": "The following example shows the usage of std::vector::vector() constructor."
},
{
"code": null,
"e": 3646,
"s": 3483,
"text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v1;\n\n cout << \"size of v1 = \" << v1.size() << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3729,
"s": 3646,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3745,
"s": 3729,
"text": "size of v1 = 0\n"
},
{
"code": null,
"e": 3752,
"s": 3745,
"text": " Print"
},
{
"code": null,
"e": 3763,
"s": 3752,
"text": " Add Notes"
}
] |
Top AutoML open source tools to automate your deep learning applications | by Philippe Bouaziz,Data Scientist at Africa4Data,PhD | Towards Data Science | Article Co-authors with : @bonnefoypy and @emeric.chaize CEOs at Olexya.
Building the best model is a key step after exploratory data analysis and feature selection in any data science project. In deep learning this process consists of building layers by layers complexes neural networks (Perceptron, Vanilla, Convolutives, Recurrent) that will fit the data.
In most cases, the data need to be processed from images, voices, videos, text, and numbers into matrix formats. Finding innovative ways to obtain the best model and prediction in few lines of code is a tremendous advantage especially when classifying images for computer vision applications. Automate model selection methods for deep learning of images datasets generally include Autokeras and Azure studio.
To become a unicorn data scientist mastering the most recent Automate Neural Networks methods is a must-have skill. In this article, we will review the 2 best Kaggle winners’ Automate neural networks selections tools which can be implemented in an easy and fast manner.
Autokeras
Autokeras
AutoKeras is an AutoML system based on Keras developed by DATA Lab at Texas A&M University. This framework can build a model with complex elements (embeddings, features augmentations, etc..) automatically pre-processing the data (text, images, numbers, categorical data) and finding the best neural architecture (numbers of layers, percent of dropout layers, optimizers, etc...).
Let’s try with the MNIST dataset which consists of 60k handwritten digits ranging from 0–9.
The first step is to import the libraries :
# Import libraries!pip install autokerasimport numpy as npimport TensorFlow as tffrom tensorflow.keras.datasets import mnistimport autokeras as ak
The second step is to load your data :
# Load the data (x_train, y_train), (x_test, y_test) = mnist.load_data()print(x_train.shape) # (60000, 28, 28)print(y_train.shape) # (60000,)print(y_train[:3]) # array([7, 2, 1], dtype=uint8)
Output
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] — 0s 0us/step (60000, 28, 28) (60000,)
The third step is to initialize the image classifier, the max_trials parameter indicates the pipeline number of models used , for more complicated datasets the max_trials parameter need to be equal to 1.
# Initialize the image classifierclf = ak.ImageClassifier(overwrite=True, max_trials=1)# Input the training dataclf.fit(x_train, y_train, epochs=10)# Make prediction with the best model on the test datasetpredicted_y = clf.predict(x_test)print(predicted_y)# Evaluate the model on the test datasetprint(clf.evaluate(x_test, y_test))
AutoKeras provides an easy way to use elements of convolutional neural networks, like convolutional layers, max-pooling, and flattening. Without the need to define the inner structure of the neural networks. Let’s make the validation step :
# With 85% training dataset and 15% validation dataset clf.fit(x_train, y_train,validation_split=0.15,epochs=10)
Some high-level configurations can be configure using the ImageBlock argument of automodel. This option offert block type options (resnet, vp16, ..), normalization and data augmentation parameters.
# Initialize AutoKeras input and output nodesinput_node = ak.ImageInput()output_node = ak.ImageBlock()# Your neural network options, here we try Resnetblock_type="resnet",# You can Normalize the datasetnormalize=True,# You can add data augmentationaugment=False)(input_node)# Build your output layer with the numbers of classes (in this example, 10 numbers 0-9)output_node = ak.ClassificationHead()(output_node)# Compile the input and output layers clf = ak.AutoModel(inputs=input_node, outputs=output_node, overwrite=True, max_trials=1)# Train the model on the training datasetclf.fit(x_train, y_train, epochs=10)
Output
You can also use tf.dataset with TPU to get faster results:
# Build your tensors from the train and test datasets train_set = tf.data.Dataset.from_tensor_slices(((x_train,), (y_train,)))test_set = tf.data.Dataset.from_tensor_slices(((x_test,), (y_test,)))# Create your autokeras image classifier clf = ak.ImageClassifier(overwrite=True, max_trials=1)# Train the model on the training datasetclf.fit(train_set, epochs=1)# Predict with the model with the test datasetpredicted_y = clf.predict(test_set)# Evaluate the model with the test dataset print(clf.evaluate(test_set))
The classification accuracy on the test dataset is 97.5%.
2. Azure studio
This free tool (without the need to register with a credit card) by Microsoft can be a modular approach that create features in an easy and fast manner automatically using personalize data engineer pipeline with complete data import options. Let’s try with the same example, the MNIST dataset which consists of handwritten digits ranging from 0–9.
The first step is to upload and create the Mnsit train and test datasets modules:
The second step is to choose the multiclass neural network :
This neural network can be fully tuned easily using the specified range for each parameter :
For more details about Azure neural network, parameters Click here. The neural network module can be used with your own customize Python or R scripts :
The next step, the neural network is train with the train and validation datasets automatically split from the training dataset :
Finally, the model is score using the classification accuracy and evaluate using the test dataset as shown below :
The classification accuracy on the test dataset is 98.8%.
For more details about Azure studio (classic version) deep learning abilities Click here.
This brief overview is a reminder of the importance of using autoML tools for choosing the right neural network architecture for images classifications. This post has the scope to covered fast and simple autoML tools for images classification as well as share useful documentation.
Sum Up
Refer to this link for a complete 8 autoML tools review with step by step python codes :
www.datasciencemusthaveskills.com
I hope you enjoy it, keep exploring! | [
{
"code": null,
"e": 245,
"s": 172,
"text": "Article Co-authors with : @bonnefoypy and @emeric.chaize CEOs at Olexya."
},
{
"code": null,
"e": 531,
"s": 245,
"text": "Building the best model is a key step after exploratory data analysis and feature selection in any data science project. In deep learning this process consists of building layers by layers complexes neural networks (Perceptron, Vanilla, Convolutives, Recurrent) that will fit the data."
},
{
"code": null,
"e": 940,
"s": 531,
"text": "In most cases, the data need to be processed from images, voices, videos, text, and numbers into matrix formats. Finding innovative ways to obtain the best model and prediction in few lines of code is a tremendous advantage especially when classifying images for computer vision applications. Automate model selection methods for deep learning of images datasets generally include Autokeras and Azure studio."
},
{
"code": null,
"e": 1210,
"s": 940,
"text": "To become a unicorn data scientist mastering the most recent Automate Neural Networks methods is a must-have skill. In this article, we will review the 2 best Kaggle winners’ Automate neural networks selections tools which can be implemented in an easy and fast manner."
},
{
"code": null,
"e": 1220,
"s": 1210,
"text": "Autokeras"
},
{
"code": null,
"e": 1230,
"s": 1220,
"text": "Autokeras"
},
{
"code": null,
"e": 1610,
"s": 1230,
"text": "AutoKeras is an AutoML system based on Keras developed by DATA Lab at Texas A&M University. This framework can build a model with complex elements (embeddings, features augmentations, etc..) automatically pre-processing the data (text, images, numbers, categorical data) and finding the best neural architecture (numbers of layers, percent of dropout layers, optimizers, etc...)."
},
{
"code": null,
"e": 1702,
"s": 1610,
"text": "Let’s try with the MNIST dataset which consists of 60k handwritten digits ranging from 0–9."
},
{
"code": null,
"e": 1746,
"s": 1702,
"text": "The first step is to import the libraries :"
},
{
"code": null,
"e": 1893,
"s": 1746,
"text": "# Import libraries!pip install autokerasimport numpy as npimport TensorFlow as tffrom tensorflow.keras.datasets import mnistimport autokeras as ak"
},
{
"code": null,
"e": 1932,
"s": 1893,
"text": "The second step is to load your data :"
},
{
"code": null,
"e": 2127,
"s": 1932,
"text": "# Load the data (x_train, y_train), (x_test, y_test) = mnist.load_data()print(x_train.shape) # (60000, 28, 28)print(y_train.shape) # (60000,)print(y_train[:3]) # array([7, 2, 1], dtype=uint8)"
},
{
"code": null,
"e": 2134,
"s": 2127,
"text": "Output"
},
{
"code": null,
"e": 2316,
"s": 2134,
"text": "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] — 0s 0us/step (60000, 28, 28) (60000,)"
},
{
"code": null,
"e": 2520,
"s": 2316,
"text": "The third step is to initialize the image classifier, the max_trials parameter indicates the pipeline number of models used , for more complicated datasets the max_trials parameter need to be equal to 1."
},
{
"code": null,
"e": 2852,
"s": 2520,
"text": "# Initialize the image classifierclf = ak.ImageClassifier(overwrite=True, max_trials=1)# Input the training dataclf.fit(x_train, y_train, epochs=10)# Make prediction with the best model on the test datasetpredicted_y = clf.predict(x_test)print(predicted_y)# Evaluate the model on the test datasetprint(clf.evaluate(x_test, y_test))"
},
{
"code": null,
"e": 3093,
"s": 2852,
"text": "AutoKeras provides an easy way to use elements of convolutional neural networks, like convolutional layers, max-pooling, and flattening. Without the need to define the inner structure of the neural networks. Let’s make the validation step :"
},
{
"code": null,
"e": 3206,
"s": 3093,
"text": "# With 85% training dataset and 15% validation dataset clf.fit(x_train, y_train,validation_split=0.15,epochs=10)"
},
{
"code": null,
"e": 3404,
"s": 3206,
"text": "Some high-level configurations can be configure using the ImageBlock argument of automodel. This option offert block type options (resnet, vp16, ..), normalization and data augmentation parameters."
},
{
"code": null,
"e": 4019,
"s": 3404,
"text": "# Initialize AutoKeras input and output nodesinput_node = ak.ImageInput()output_node = ak.ImageBlock()# Your neural network options, here we try Resnetblock_type=\"resnet\",# You can Normalize the datasetnormalize=True,# You can add data augmentationaugment=False)(input_node)# Build your output layer with the numbers of classes (in this example, 10 numbers 0-9)output_node = ak.ClassificationHead()(output_node)# Compile the input and output layers clf = ak.AutoModel(inputs=input_node, outputs=output_node, overwrite=True, max_trials=1)# Train the model on the training datasetclf.fit(x_train, y_train, epochs=10)"
},
{
"code": null,
"e": 4026,
"s": 4019,
"text": "Output"
},
{
"code": null,
"e": 4086,
"s": 4026,
"text": "You can also use tf.dataset with TPU to get faster results:"
},
{
"code": null,
"e": 4599,
"s": 4086,
"text": "# Build your tensors from the train and test datasets train_set = tf.data.Dataset.from_tensor_slices(((x_train,), (y_train,)))test_set = tf.data.Dataset.from_tensor_slices(((x_test,), (y_test,)))# Create your autokeras image classifier clf = ak.ImageClassifier(overwrite=True, max_trials=1)# Train the model on the training datasetclf.fit(train_set, epochs=1)# Predict with the model with the test datasetpredicted_y = clf.predict(test_set)# Evaluate the model with the test dataset print(clf.evaluate(test_set))"
},
{
"code": null,
"e": 4657,
"s": 4599,
"text": "The classification accuracy on the test dataset is 97.5%."
},
{
"code": null,
"e": 4673,
"s": 4657,
"text": "2. Azure studio"
},
{
"code": null,
"e": 5021,
"s": 4673,
"text": "This free tool (without the need to register with a credit card) by Microsoft can be a modular approach that create features in an easy and fast manner automatically using personalize data engineer pipeline with complete data import options. Let’s try with the same example, the MNIST dataset which consists of handwritten digits ranging from 0–9."
},
{
"code": null,
"e": 5103,
"s": 5021,
"text": "The first step is to upload and create the Mnsit train and test datasets modules:"
},
{
"code": null,
"e": 5164,
"s": 5103,
"text": "The second step is to choose the multiclass neural network :"
},
{
"code": null,
"e": 5257,
"s": 5164,
"text": "This neural network can be fully tuned easily using the specified range for each parameter :"
},
{
"code": null,
"e": 5409,
"s": 5257,
"text": "For more details about Azure neural network, parameters Click here. The neural network module can be used with your own customize Python or R scripts :"
},
{
"code": null,
"e": 5539,
"s": 5409,
"text": "The next step, the neural network is train with the train and validation datasets automatically split from the training dataset :"
},
{
"code": null,
"e": 5654,
"s": 5539,
"text": "Finally, the model is score using the classification accuracy and evaluate using the test dataset as shown below :"
},
{
"code": null,
"e": 5712,
"s": 5654,
"text": "The classification accuracy on the test dataset is 98.8%."
},
{
"code": null,
"e": 5802,
"s": 5712,
"text": "For more details about Azure studio (classic version) deep learning abilities Click here."
},
{
"code": null,
"e": 6084,
"s": 5802,
"text": "This brief overview is a reminder of the importance of using autoML tools for choosing the right neural network architecture for images classifications. This post has the scope to covered fast and simple autoML tools for images classification as well as share useful documentation."
},
{
"code": null,
"e": 6091,
"s": 6084,
"text": "Sum Up"
},
{
"code": null,
"e": 6180,
"s": 6091,
"text": "Refer to this link for a complete 8 autoML tools review with step by step python codes :"
},
{
"code": null,
"e": 6214,
"s": 6180,
"text": "www.datasciencemusthaveskills.com"
}
] |
Build Your Own Automatic Differentiation Program | by Jonathan Kernes | Towards Data Science | For anyone who’s completely lost at how graphs can be used to compute derivatives, or just wants to know how TensorFlow works at a fundamental level, this is your guide.
Deep learning is so popular and so widespread these days, it’s easy to ask the question, “Why did it take so long for people to figure this out?” There are a number of reasons why, and getting into the history of deep learning is really not the focus of this post (the introduction to Reference [1] does a nice job), but one of the key advances that makes this revolution roll is automatic differentiation (AutoDiff).
If you want to get right to technical details, skip to the section “Building an AutoDiff”, if you just want the code, skip to the section “Implementing AutoDiff in Python”
For a companion Jupyter notebook with the code used in this article, please see the following link: https://github.com/Jmkernes/Automatic-Differentiation
What’s so great about automatic differentiation you ask? Imagine you’ve got some function you’re playing around with, and you really want to know its derivative. If it’s a relatively simple function, you can probably just rattle off the answer. If f(x)=x3, then we can quickly conclude df/dx=3x2. What if it’s more complicated and you don’t just know the answer? Well, you don’t really have a lot of options here.
Option 1: if you want the numerical answer, you can go back to basics and straight up compute finite differences, using formulas like
and their more sophisticated and more accurate cousins [2]. But that’s not that satisfying. Maybe we want the symbolic answer, in terms of x’s and y’s and stuff, in which case a numerical answer just isn’t going to cut it. Or, maybe our differentiation variable x is actually a large multi-dimensional tensor, and computing the numerical difference one-by-one for every entry of that thing is going to be horribly inefficient and time-intensive.
Option 2: derive the derivative. This is supposed to be meta. What does it mean to derive a derivative? How did we know the answer to df/dx=3x2 before? Well, it turns out there’s really only two ways you figure out derivatives. If it’s a totally new function, you just have to derive the answer via its limit representation shown above. In reality though, most functions aren’t new, they’re actually just compositions of other functions. In this case, we can figure out new derivatives via the chain-rule:
One of the first physics projects I worked on involved the use some special functions called generalized hypergeometric functions. If you don’t know what those are, don’t worry, that’s the point. Like every special function, they’re miserable to deal with, and contain enough identities and special cases to fill up a Harry Potter spell book. So, disheartened, I went to my advisor and directly asked him, “Hey what in the world is this thing?”
His response was pretty simple — “It’s just some function that we know some stuff about.” That seems like a useless answer, but it’s actually kind of deep. He then asked me “you know what a cosine is, right?” To which I snarkily responded, “yeah of course I know what a cosine is.” Without hesitation, he snapped right back, “But how do you know what a cosine is? How is knowing what a hypergeometric function any different that knowing what a cosine is? At the end of the day, you know what a cosine is because you can name some identities and you can make a pretty plot of it. That’s it.”
At this point, I was stumped. I was having a mathematical existential crisis, and re-evaluating everything I had ever learned. “I know what a cosine is because I know it’s derivative is -sin(x)!”, I thought. “And, I know what sine is! Because it’s derivative is cosi...“, oh no. An infinite loop.
After reviving from my existential crisis, I came to the realization that there are two types of functions in the world: things we are familiar with like x2 or x+5, and things we are unfamiliar with, but can be composed of familiar things — like (x+5)2. Automatic differentiation is centered around this latter concept. We can frame its mission statement as:
Given a collection of elementary functions, things like e^x, cos(x), or x2, then using the rules of calculus, it is possible to determine the derivative of any function that is composed of these elementary functions.
Since we can represent functions in all sorts of ways, like through power series, Fourier series, etc. that’s a pretty powerful statement. It all works via the chain rule. The awesome thing about AutoDiff, is that it’s the mathematical equivalent of journeying around the world with zero planning. You can just keep composing and stacking functions as your heart desires, going deeper and deeper, always assured that AutoDiff is going to be able follow the breadcrumbs and compute a derivative for you.
For the rest of the post, we will assume that every function we want the derivative of can be broken up into elementary functions (if you want the derivative of a modified Bessel function of the second kind, you’re going to have to look elsewhere)
By the end of this post, you will be able to generate graphs like the following:
But with as much complexity as you like. Let’s break down what this graph means. Suppose that we are given the function
and we would like to compute the partial derivatives of f with respect to its variables x, y, and z. We can decompose this function into a composition of very basic functions, namely, a function add(x,y)=x+y that takes two number and adds them, and a function multiply(x,y)=x*y which takes two numbers and multiplies them. Basic, right? In this new form we have
It’s more a more wordy representation, but... it’s not wrong.
This form is useful, because we immediately know the derivatives of add and multiply. Furthermore, we have rewritten this as a composition of two elementary functions, so we can apply the chain rule. We obtain
Using basic calculus, we get 1*y=y, which is obviously the right answer. Though you may not notice it, whenever you compute derivatives you implicitly perform the above operation. Now, let’s make a computer do that.
In order to specify the procedure, we need to do two things: 1) tell the computer what the fundamental building blocks are 2) tell it how to put those blocks together to compute a derivative.
Let’s focus on part one first. There are four fundamental types of blocks, which we will call nodes, making use of the graph-theoretic language. These include
Variables — mutable objects (tensors) of which we want to know the gradients of.Constants — immutable objects (tensors) whose value, once specified, does not change.Placeholders — these are basically empty containers specifying where a future Variable or Constant will go, once we decide what that value should be.Operators — these are the conceptually hardest to picture, but also the most important.
Variables — mutable objects (tensors) of which we want to know the gradients of.
Constants — immutable objects (tensors) whose value, once specified, does not change.
Placeholders — these are basically empty containers specifying where a future Variable or Constant will go, once we decide what that value should be.
Operators — these are the conceptually hardest to picture, but also the most important.
The first three should be relatively straightforward. What is slightly confusing about computation graphs that takes some time to get used to, is that the nodes of the graph are actually operators and NOT variables, constants, or placeholders. Intuitively, we like to think of functions as composed of their values. When we wrote f(x, y, z) we used x, y, z. We did not write f(add, multiply). However, that’s exactly what our computer will be looking for. In general, an operator node takes inputs and returns outputs. We assume that the node emits one output only; though a tensor contains many entries, it can be considered a single output
We can now understand the graph at the beginning of the section. We only used numbers, but those could also be considered to be scalar tensors. The graph thus shows how tensors flow through computation. Get it? Tensors...Flow...TensorFlow. Now let’s consider the opposite direction, computing the gradients.
To compute the actual value of the output f(x,y,z) we run the graph forward, in the direction of the arrows, beginning with the variables x, y, z, and flowing through the Operators. Let’s now take our equation and think about it graphically. We will add one additional, trivial computation
which will help us initialize our back-propagation procedure. Inspecting our equation for the partial derivatives of f, an important thing to note is that a derivative is also a function! This means that the chain-rule derivative is also a composition of functions. Remember, composition of functions = graph. That’s the rule. What’s really nice, is that our graph structure is identical, but run backwards. You can see the structure below:
The red arrows signify the flow of derivatives from the final output to the start as a reversed computation graph. It can be computed exactly the same way, where we supply the first node with a derivative of 1, using the trivial identity df/df=1. Our goal should now be clear:
Specify all variables, placeholders, and constants in our graph
Compose these together using operators to form the final, scalar output
Compute a forward-pass which inputs values and flows through the operators to get the output. Store each node’s output value in that node.
Compute a backward-pass to compute gradients, beginning from a gradient of 1 at the final node (the output).
Making this work is the goal of the remainder of this article.
We want warn the reader up front that this involves global variables. Global variables are taboo, but the reason we use them should hopefully become clear as we go along. The graph is our global object (ok not a global variable actually a global object, sorry for the lie), which we will be adding nodes to. As far as I can tell, there isn’t an easy way to explicitly scope objects, and I believe TensorFlow, at least in V1, also used a global graph variable. If anyone has a solution to avoid global variables please post it in the comments!
Ok, warning aside, let’s get started. We first need to define our default graph class. This will be a basic structure that just keeps track of the current nodes and their types.
A few things: everything after the __init__ method you can just forget about. It doesn’t affect the code and is just there to try to make it slightly easier to deal with creating localized graphs. You can also just delete it, and make sure to run Graph()to initialize the global default graph, and del _g to erase it before and after defining a bunch of nodes. Also, we don’t really need numpy, it’s there for helping us do matrix multiplication later.
Great, we’ve got a working graph. Now let’s define each of those four classes we discussed earlier. They’re more or less all the same, with each containing a couple of unique features
The Operator class needs an inputs attribute, the Constant class needs to protect it’s values, and the rest are kind of similar. We put in some default names, like Var1, Var2, ... which are about the minimal level of descriptiveness. The name field is important for later retrieving nodes from the graph, since we won’t have any other way to identify them
Also, it’s very important we keep track of the names of the Placeholders, otherwise we really won’t have any way of hunting them down in the computational graph.
We put in some other things like a __repr__ function to automatically display nodes as a string in a format like “Operator: name:mul/2, value:3.875”. That should help us know right away what node we’re dealing with.
Now, to actually make our graph do something, we need to give it some real operators. These are going to precisely the elementary operations we’ve been talking about this whole time. Things like addition, subtraction, multiplication. We will define some of these, and to make things much easier to code, we are going to overload all of these operators (note: I couldn’t think of a better way to do this that doesn’t either repeat a ton of code or require adding methods to the base Node class in a weird way. Open to better suggestions). The one tricky operator is __neg__. Remember x -> -x is actually a multiplication operator, so the graph needs to know about that.
We’ve now got all of our infrastructure in place. We can easily build the graph by just defining Variables, Constants, or Placeholders, and performing computation per usual. The operators will take care of adding nodes to the graph and everything. We can create a graph g and add some operations via the following syntax
with Graph() as g: x = Variable(1.3) y = Variable(0.9) z = x*y+5g.variables # Will output {Variable: name:Var/0, value:1.3, Variable: name:Var/1, value:0.9}g.operators # Will output {Operator: name:add/0, Operator: name:mul/0}g.constants # Will output {Constant: name:Const/0, value:5}
As you can see, the graph correctly created a constant, and also kept track of the two operations, x*y multiplication as well as addition of the constant 5. If we run with Graph() as g again, it should erase the current default graph and begin building anew. Cool, everything works. Now, we have to use a little bit of algorithms knowledge to compute our forward and backward passes.
As it stands, our default graph just keeps track of the current nodes. It has no structure. Ultimately, we want to run our graph forward, meaning we feed it all the Variables, Constants, and Placeholders, then these flow through the operators to our output. The order that we do this in is a classical algorithms problem. We need to perform a topological sort (the CLRS book [3] is always good, or just use wikipedia). Our graph is a directed acyclic graph, meaning that each node has a beginning and end point. There are no loops. The topological sort guarantees that if we run every node in order, we will never be lacking information to compute a node. It’s like ordering class prerequisites; you adjust your schedule to to take Calc I before Calc III.
After a topological sort, our graph has truly become a graph. It finally has some solid structure! Even if this structure is just an array of ordered nodes. To complete our program, we perform the passes. The forward pass is really simple; just compute the value of each node in order, and store its value in that node so future nodes can access it if need be.
The backward pass is slightly more difficult, but not much so. Initialize the root node with a value of 1 (recall the discussion of using df/df=1). Then, only traverse the graph via its Operators. In other words, compute the gradients for all inputs of the current operator, then recursively do the same for any of those inputs that were also an operator. Here’s the code:
That’s it! We’re done with the main part of the program. What remains is to play around with this and analyze it a bit. Here’s an example of how you might calculate the gradients for a simple function
which depends on two variables and one constant. We can easily compute its derivative by hand and check that our code gets it right. First the forward pass:
val1, val2, val3 = 0.9, 0.4, 1.3with Graph() as g: x = Variable(val1, name='x') y = Variable(val2, name='y') c = Constant(val3, name='c') z = (x*y+c)*c + x order = topological_sort(z) res = forward_pass(order) grads = backward_pass(order) print("Node ordering:") for node in order: print(node) print('-'*10) print(f"Forward pass expected: {(val1*val2+val3)*val3+val1}") print(f"Forward pass computed: {res}")---------------------------------------------------""" Output:Node ordering:Variable: name:x, value:0.9Variable: name:y, value:0.4Operator: name:mul/6Constant: name:c, value:1.3Operator: name:add/6Operator: name:mul/7Operator: name:add/7----------Forward pass expected: 3.0580000000000003Forward pass computed: 3.0580000000000003"""
And for the backward pass:
dzdx_node = [a for a in order if a.name=='x'][0]dzdy_node = [a for a in order if a.name=='y'][0]dzdc_node = [a for a in order if a.name=='c'][0]print(f"dz/dx expected = {val3*val2+1}")print(f"dz/dx computed = {dzdx_node.gradient}")print(f"dz/dy expected = {val1*val3}")print(f"dz/dy computed = {dzdy_node.gradient}")print(f"dz/dc expected = {val1*val2+2*val3}")print(f"dz/dc computed = {dzdc_node.gradient}")---------------------------------------------------""" Output:dz/dx expected = 1.52dz/dx computed = 1.52dz/dy expected = 1.1700000000000002dz/dy computed = 1.1700000000000002dz/dc expected = 2.96dz/dc computed = 2.96"""
Ok, so I promised you would be able to make pretty pictures by the end of this. Here’s me keeping that promise. We will use the python library Graphviz. You may have to pip install graphviz which is why I left this off until the end. To build the graph, we just create a node for every node in the graph, then we draw edges using operators. The operators dictate the flow of the graph, so just like when we did the backward_pass, we just need the operator edges. By using the following code
We can make pretty pictures like the following
Which represents the graph of the test code we ran earlier.
If you’ve made it this far, thank you for reading! To summarize, we’ve shown that automatic differentiation is built on two ideas
All functions we are usually interested in computing the derivatives of can be represented as compositions of elementary functionsThese elementary functions are simple, or at the very least have known derivatives with which we can supply our AutoDiff program
All functions we are usually interested in computing the derivatives of can be represented as compositions of elementary functions
These elementary functions are simple, or at the very least have known derivatives with which we can supply our AutoDiff program
From there, we can create a graph, topologically sort, then run a forward-backward pass to get gradients. I hope this has been useful, and good introduction to how AutoDiff systems like TensorFlow work. Sometimes, if you just think a little bit harder about something you already know pretty well, you might just find something interesting!
[1] Goodfellow, Ian, et al. Deep learning. Vol. 1. No2. Cambridge: MIT press, 2016.
[2] https://en.wikipedia.org/wiki/Five-point_stencil
[3] Cormen, Thomas H., et al. Introduction to algorithms. MIT press, 2009. | [
{
"code": null,
"e": 341,
"s": 171,
"text": "For anyone who’s completely lost at how graphs can be used to compute derivatives, or just wants to know how TensorFlow works at a fundamental level, this is your guide."
},
{
"code": null,
"e": 759,
"s": 341,
"text": "Deep learning is so popular and so widespread these days, it’s easy to ask the question, “Why did it take so long for people to figure this out?” There are a number of reasons why, and getting into the history of deep learning is really not the focus of this post (the introduction to Reference [1] does a nice job), but one of the key advances that makes this revolution roll is automatic differentiation (AutoDiff)."
},
{
"code": null,
"e": 931,
"s": 759,
"text": "If you want to get right to technical details, skip to the section “Building an AutoDiff”, if you just want the code, skip to the section “Implementing AutoDiff in Python”"
},
{
"code": null,
"e": 1085,
"s": 931,
"text": "For a companion Jupyter notebook with the code used in this article, please see the following link: https://github.com/Jmkernes/Automatic-Differentiation"
},
{
"code": null,
"e": 1499,
"s": 1085,
"text": "What’s so great about automatic differentiation you ask? Imagine you’ve got some function you’re playing around with, and you really want to know its derivative. If it’s a relatively simple function, you can probably just rattle off the answer. If f(x)=x3, then we can quickly conclude df/dx=3x2. What if it’s more complicated and you don’t just know the answer? Well, you don’t really have a lot of options here."
},
{
"code": null,
"e": 1633,
"s": 1499,
"text": "Option 1: if you want the numerical answer, you can go back to basics and straight up compute finite differences, using formulas like"
},
{
"code": null,
"e": 2079,
"s": 1633,
"text": "and their more sophisticated and more accurate cousins [2]. But that’s not that satisfying. Maybe we want the symbolic answer, in terms of x’s and y’s and stuff, in which case a numerical answer just isn’t going to cut it. Or, maybe our differentiation variable x is actually a large multi-dimensional tensor, and computing the numerical difference one-by-one for every entry of that thing is going to be horribly inefficient and time-intensive."
},
{
"code": null,
"e": 2585,
"s": 2079,
"text": "Option 2: derive the derivative. This is supposed to be meta. What does it mean to derive a derivative? How did we know the answer to df/dx=3x2 before? Well, it turns out there’s really only two ways you figure out derivatives. If it’s a totally new function, you just have to derive the answer via its limit representation shown above. In reality though, most functions aren’t new, they’re actually just compositions of other functions. In this case, we can figure out new derivatives via the chain-rule:"
},
{
"code": null,
"e": 3030,
"s": 2585,
"text": "One of the first physics projects I worked on involved the use some special functions called generalized hypergeometric functions. If you don’t know what those are, don’t worry, that’s the point. Like every special function, they’re miserable to deal with, and contain enough identities and special cases to fill up a Harry Potter spell book. So, disheartened, I went to my advisor and directly asked him, “Hey what in the world is this thing?”"
},
{
"code": null,
"e": 3621,
"s": 3030,
"text": "His response was pretty simple — “It’s just some function that we know some stuff about.” That seems like a useless answer, but it’s actually kind of deep. He then asked me “you know what a cosine is, right?” To which I snarkily responded, “yeah of course I know what a cosine is.” Without hesitation, he snapped right back, “But how do you know what a cosine is? How is knowing what a hypergeometric function any different that knowing what a cosine is? At the end of the day, you know what a cosine is because you can name some identities and you can make a pretty plot of it. That’s it.”"
},
{
"code": null,
"e": 3918,
"s": 3621,
"text": "At this point, I was stumped. I was having a mathematical existential crisis, and re-evaluating everything I had ever learned. “I know what a cosine is because I know it’s derivative is -sin(x)!”, I thought. “And, I know what sine is! Because it’s derivative is cosi...“, oh no. An infinite loop."
},
{
"code": null,
"e": 4277,
"s": 3918,
"text": "After reviving from my existential crisis, I came to the realization that there are two types of functions in the world: things we are familiar with like x2 or x+5, and things we are unfamiliar with, but can be composed of familiar things — like (x+5)2. Automatic differentiation is centered around this latter concept. We can frame its mission statement as:"
},
{
"code": null,
"e": 4494,
"s": 4277,
"text": "Given a collection of elementary functions, things like e^x, cos(x), or x2, then using the rules of calculus, it is possible to determine the derivative of any function that is composed of these elementary functions."
},
{
"code": null,
"e": 4997,
"s": 4494,
"text": "Since we can represent functions in all sorts of ways, like through power series, Fourier series, etc. that’s a pretty powerful statement. It all works via the chain rule. The awesome thing about AutoDiff, is that it’s the mathematical equivalent of journeying around the world with zero planning. You can just keep composing and stacking functions as your heart desires, going deeper and deeper, always assured that AutoDiff is going to be able follow the breadcrumbs and compute a derivative for you."
},
{
"code": null,
"e": 5245,
"s": 4997,
"text": "For the rest of the post, we will assume that every function we want the derivative of can be broken up into elementary functions (if you want the derivative of a modified Bessel function of the second kind, you’re going to have to look elsewhere)"
},
{
"code": null,
"e": 5326,
"s": 5245,
"text": "By the end of this post, you will be able to generate graphs like the following:"
},
{
"code": null,
"e": 5446,
"s": 5326,
"text": "But with as much complexity as you like. Let’s break down what this graph means. Suppose that we are given the function"
},
{
"code": null,
"e": 5808,
"s": 5446,
"text": "and we would like to compute the partial derivatives of f with respect to its variables x, y, and z. We can decompose this function into a composition of very basic functions, namely, a function add(x,y)=x+y that takes two number and adds them, and a function multiply(x,y)=x*y which takes two numbers and multiplies them. Basic, right? In this new form we have"
},
{
"code": null,
"e": 5870,
"s": 5808,
"text": "It’s more a more wordy representation, but... it’s not wrong."
},
{
"code": null,
"e": 6080,
"s": 5870,
"text": "This form is useful, because we immediately know the derivatives of add and multiply. Furthermore, we have rewritten this as a composition of two elementary functions, so we can apply the chain rule. We obtain"
},
{
"code": null,
"e": 6296,
"s": 6080,
"text": "Using basic calculus, we get 1*y=y, which is obviously the right answer. Though you may not notice it, whenever you compute derivatives you implicitly perform the above operation. Now, let’s make a computer do that."
},
{
"code": null,
"e": 6488,
"s": 6296,
"text": "In order to specify the procedure, we need to do two things: 1) tell the computer what the fundamental building blocks are 2) tell it how to put those blocks together to compute a derivative."
},
{
"code": null,
"e": 6647,
"s": 6488,
"text": "Let’s focus on part one first. There are four fundamental types of blocks, which we will call nodes, making use of the graph-theoretic language. These include"
},
{
"code": null,
"e": 7049,
"s": 6647,
"text": "Variables — mutable objects (tensors) of which we want to know the gradients of.Constants — immutable objects (tensors) whose value, once specified, does not change.Placeholders — these are basically empty containers specifying where a future Variable or Constant will go, once we decide what that value should be.Operators — these are the conceptually hardest to picture, but also the most important."
},
{
"code": null,
"e": 7130,
"s": 7049,
"text": "Variables — mutable objects (tensors) of which we want to know the gradients of."
},
{
"code": null,
"e": 7216,
"s": 7130,
"text": "Constants — immutable objects (tensors) whose value, once specified, does not change."
},
{
"code": null,
"e": 7366,
"s": 7216,
"text": "Placeholders — these are basically empty containers specifying where a future Variable or Constant will go, once we decide what that value should be."
},
{
"code": null,
"e": 7454,
"s": 7366,
"text": "Operators — these are the conceptually hardest to picture, but also the most important."
},
{
"code": null,
"e": 8096,
"s": 7454,
"text": "The first three should be relatively straightforward. What is slightly confusing about computation graphs that takes some time to get used to, is that the nodes of the graph are actually operators and NOT variables, constants, or placeholders. Intuitively, we like to think of functions as composed of their values. When we wrote f(x, y, z) we used x, y, z. We did not write f(add, multiply). However, that’s exactly what our computer will be looking for. In general, an operator node takes inputs and returns outputs. We assume that the node emits one output only; though a tensor contains many entries, it can be considered a single output"
},
{
"code": null,
"e": 8404,
"s": 8096,
"text": "We can now understand the graph at the beginning of the section. We only used numbers, but those could also be considered to be scalar tensors. The graph thus shows how tensors flow through computation. Get it? Tensors...Flow...TensorFlow. Now let’s consider the opposite direction, computing the gradients."
},
{
"code": null,
"e": 8694,
"s": 8404,
"text": "To compute the actual value of the output f(x,y,z) we run the graph forward, in the direction of the arrows, beginning with the variables x, y, z, and flowing through the Operators. Let’s now take our equation and think about it graphically. We will add one additional, trivial computation"
},
{
"code": null,
"e": 9135,
"s": 8694,
"text": "which will help us initialize our back-propagation procedure. Inspecting our equation for the partial derivatives of f, an important thing to note is that a derivative is also a function! This means that the chain-rule derivative is also a composition of functions. Remember, composition of functions = graph. That’s the rule. What’s really nice, is that our graph structure is identical, but run backwards. You can see the structure below:"
},
{
"code": null,
"e": 9412,
"s": 9135,
"text": "The red arrows signify the flow of derivatives from the final output to the start as a reversed computation graph. It can be computed exactly the same way, where we supply the first node with a derivative of 1, using the trivial identity df/df=1. Our goal should now be clear:"
},
{
"code": null,
"e": 9476,
"s": 9412,
"text": "Specify all variables, placeholders, and constants in our graph"
},
{
"code": null,
"e": 9548,
"s": 9476,
"text": "Compose these together using operators to form the final, scalar output"
},
{
"code": null,
"e": 9687,
"s": 9548,
"text": "Compute a forward-pass which inputs values and flows through the operators to get the output. Store each node’s output value in that node."
},
{
"code": null,
"e": 9796,
"s": 9687,
"text": "Compute a backward-pass to compute gradients, beginning from a gradient of 1 at the final node (the output)."
},
{
"code": null,
"e": 9859,
"s": 9796,
"text": "Making this work is the goal of the remainder of this article."
},
{
"code": null,
"e": 10402,
"s": 9859,
"text": "We want warn the reader up front that this involves global variables. Global variables are taboo, but the reason we use them should hopefully become clear as we go along. The graph is our global object (ok not a global variable actually a global object, sorry for the lie), which we will be adding nodes to. As far as I can tell, there isn’t an easy way to explicitly scope objects, and I believe TensorFlow, at least in V1, also used a global graph variable. If anyone has a solution to avoid global variables please post it in the comments!"
},
{
"code": null,
"e": 10580,
"s": 10402,
"text": "Ok, warning aside, let’s get started. We first need to define our default graph class. This will be a basic structure that just keeps track of the current nodes and their types."
},
{
"code": null,
"e": 11033,
"s": 10580,
"text": "A few things: everything after the __init__ method you can just forget about. It doesn’t affect the code and is just there to try to make it slightly easier to deal with creating localized graphs. You can also just delete it, and make sure to run Graph()to initialize the global default graph, and del _g to erase it before and after defining a bunch of nodes. Also, we don’t really need numpy, it’s there for helping us do matrix multiplication later."
},
{
"code": null,
"e": 11217,
"s": 11033,
"text": "Great, we’ve got a working graph. Now let’s define each of those four classes we discussed earlier. They’re more or less all the same, with each containing a couple of unique features"
},
{
"code": null,
"e": 11573,
"s": 11217,
"text": "The Operator class needs an inputs attribute, the Constant class needs to protect it’s values, and the rest are kind of similar. We put in some default names, like Var1, Var2, ... which are about the minimal level of descriptiveness. The name field is important for later retrieving nodes from the graph, since we won’t have any other way to identify them"
},
{
"code": null,
"e": 11735,
"s": 11573,
"text": "Also, it’s very important we keep track of the names of the Placeholders, otherwise we really won’t have any way of hunting them down in the computational graph."
},
{
"code": null,
"e": 11951,
"s": 11735,
"text": "We put in some other things like a __repr__ function to automatically display nodes as a string in a format like “Operator: name:mul/2, value:3.875”. That should help us know right away what node we’re dealing with."
},
{
"code": null,
"e": 12620,
"s": 11951,
"text": "Now, to actually make our graph do something, we need to give it some real operators. These are going to precisely the elementary operations we’ve been talking about this whole time. Things like addition, subtraction, multiplication. We will define some of these, and to make things much easier to code, we are going to overload all of these operators (note: I couldn’t think of a better way to do this that doesn’t either repeat a ton of code or require adding methods to the base Node class in a weird way. Open to better suggestions). The one tricky operator is __neg__. Remember x -> -x is actually a multiplication operator, so the graph needs to know about that."
},
{
"code": null,
"e": 12941,
"s": 12620,
"text": "We’ve now got all of our infrastructure in place. We can easily build the graph by just defining Variables, Constants, or Placeholders, and performing computation per usual. The operators will take care of adding nodes to the graph and everything. We can create a graph g and add some operations via the following syntax"
},
{
"code": null,
"e": 13230,
"s": 12941,
"text": "with Graph() as g: x = Variable(1.3) y = Variable(0.9) z = x*y+5g.variables # Will output {Variable: name:Var/0, value:1.3, Variable: name:Var/1, value:0.9}g.operators # Will output {Operator: name:add/0, Operator: name:mul/0}g.constants # Will output {Constant: name:Const/0, value:5}"
},
{
"code": null,
"e": 13614,
"s": 13230,
"text": "As you can see, the graph correctly created a constant, and also kept track of the two operations, x*y multiplication as well as addition of the constant 5. If we run with Graph() as g again, it should erase the current default graph and begin building anew. Cool, everything works. Now, we have to use a little bit of algorithms knowledge to compute our forward and backward passes."
},
{
"code": null,
"e": 14370,
"s": 13614,
"text": "As it stands, our default graph just keeps track of the current nodes. It has no structure. Ultimately, we want to run our graph forward, meaning we feed it all the Variables, Constants, and Placeholders, then these flow through the operators to our output. The order that we do this in is a classical algorithms problem. We need to perform a topological sort (the CLRS book [3] is always good, or just use wikipedia). Our graph is a directed acyclic graph, meaning that each node has a beginning and end point. There are no loops. The topological sort guarantees that if we run every node in order, we will never be lacking information to compute a node. It’s like ordering class prerequisites; you adjust your schedule to to take Calc I before Calc III."
},
{
"code": null,
"e": 14731,
"s": 14370,
"text": "After a topological sort, our graph has truly become a graph. It finally has some solid structure! Even if this structure is just an array of ordered nodes. To complete our program, we perform the passes. The forward pass is really simple; just compute the value of each node in order, and store its value in that node so future nodes can access it if need be."
},
{
"code": null,
"e": 15104,
"s": 14731,
"text": "The backward pass is slightly more difficult, but not much so. Initialize the root node with a value of 1 (recall the discussion of using df/df=1). Then, only traverse the graph via its Operators. In other words, compute the gradients for all inputs of the current operator, then recursively do the same for any of those inputs that were also an operator. Here’s the code:"
},
{
"code": null,
"e": 15305,
"s": 15104,
"text": "That’s it! We’re done with the main part of the program. What remains is to play around with this and analyze it a bit. Here’s an example of how you might calculate the gradients for a simple function"
},
{
"code": null,
"e": 15462,
"s": 15305,
"text": "which depends on two variables and one constant. We can easily compute its derivative by hand and check that our code gets it right. First the forward pass:"
},
{
"code": null,
"e": 16221,
"s": 15462,
"text": "val1, val2, val3 = 0.9, 0.4, 1.3with Graph() as g: x = Variable(val1, name='x') y = Variable(val2, name='y') c = Constant(val3, name='c') z = (x*y+c)*c + x order = topological_sort(z) res = forward_pass(order) grads = backward_pass(order) print(\"Node ordering:\") for node in order: print(node) print('-'*10) print(f\"Forward pass expected: {(val1*val2+val3)*val3+val1}\") print(f\"Forward pass computed: {res}\")---------------------------------------------------\"\"\" Output:Node ordering:Variable: name:x, value:0.9Variable: name:y, value:0.4Operator: name:mul/6Constant: name:c, value:1.3Operator: name:add/6Operator: name:mul/7Operator: name:add/7----------Forward pass expected: 3.0580000000000003Forward pass computed: 3.0580000000000003\"\"\""
},
{
"code": null,
"e": 16248,
"s": 16221,
"text": "And for the backward pass:"
},
{
"code": null,
"e": 16876,
"s": 16248,
"text": "dzdx_node = [a for a in order if a.name=='x'][0]dzdy_node = [a for a in order if a.name=='y'][0]dzdc_node = [a for a in order if a.name=='c'][0]print(f\"dz/dx expected = {val3*val2+1}\")print(f\"dz/dx computed = {dzdx_node.gradient}\")print(f\"dz/dy expected = {val1*val3}\")print(f\"dz/dy computed = {dzdy_node.gradient}\")print(f\"dz/dc expected = {val1*val2+2*val3}\")print(f\"dz/dc computed = {dzdc_node.gradient}\")---------------------------------------------------\"\"\" Output:dz/dx expected = 1.52dz/dx computed = 1.52dz/dy expected = 1.1700000000000002dz/dy computed = 1.1700000000000002dz/dc expected = 2.96dz/dc computed = 2.96\"\"\""
},
{
"code": null,
"e": 17367,
"s": 16876,
"text": "Ok, so I promised you would be able to make pretty pictures by the end of this. Here’s me keeping that promise. We will use the python library Graphviz. You may have to pip install graphviz which is why I left this off until the end. To build the graph, we just create a node for every node in the graph, then we draw edges using operators. The operators dictate the flow of the graph, so just like when we did the backward_pass, we just need the operator edges. By using the following code"
},
{
"code": null,
"e": 17414,
"s": 17367,
"text": "We can make pretty pictures like the following"
},
{
"code": null,
"e": 17474,
"s": 17414,
"text": "Which represents the graph of the test code we ran earlier."
},
{
"code": null,
"e": 17604,
"s": 17474,
"text": "If you’ve made it this far, thank you for reading! To summarize, we’ve shown that automatic differentiation is built on two ideas"
},
{
"code": null,
"e": 17863,
"s": 17604,
"text": "All functions we are usually interested in computing the derivatives of can be represented as compositions of elementary functionsThese elementary functions are simple, or at the very least have known derivatives with which we can supply our AutoDiff program"
},
{
"code": null,
"e": 17994,
"s": 17863,
"text": "All functions we are usually interested in computing the derivatives of can be represented as compositions of elementary functions"
},
{
"code": null,
"e": 18123,
"s": 17994,
"text": "These elementary functions are simple, or at the very least have known derivatives with which we can supply our AutoDiff program"
},
{
"code": null,
"e": 18464,
"s": 18123,
"text": "From there, we can create a graph, topologically sort, then run a forward-backward pass to get gradients. I hope this has been useful, and good introduction to how AutoDiff systems like TensorFlow work. Sometimes, if you just think a little bit harder about something you already know pretty well, you might just find something interesting!"
},
{
"code": null,
"e": 18548,
"s": 18464,
"text": "[1] Goodfellow, Ian, et al. Deep learning. Vol. 1. No2. Cambridge: MIT press, 2016."
},
{
"code": null,
"e": 18601,
"s": 18548,
"text": "[2] https://en.wikipedia.org/wiki/Five-point_stencil"
}
] |
How to create a Python dictionary from text file? | Assuming a following text file (dict.txt) is present
1 aaa2 bbb3 ccc
Following Python code reads the file using open() function. Each line as string is split at space character. First component is used as key and second as value
d = {}
with open("dict.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
print (d)
The output shows contents of file in dictionary form
{1: 'aaa', 2: 'bbb', 3: 'ccc'} | [
{
"code": null,
"e": 1115,
"s": 1062,
"text": "Assuming a following text file (dict.txt) is present"
},
{
"code": null,
"e": 1131,
"s": 1115,
"text": "1 aaa2 bbb3 ccc"
},
{
"code": null,
"e": 1291,
"s": 1131,
"text": "Following Python code reads the file using open() function. Each line as string is split at space character. First component is used as key and second as value"
},
{
"code": null,
"e": 1404,
"s": 1291,
"text": "d = {}\nwith open(\"dict.txt\") as f:\nfor line in f:\n (key, val) = line.split()\n d[int(key)] = val\n\nprint (d)"
},
{
"code": null,
"e": 1457,
"s": 1404,
"text": "The output shows contents of file in dictionary form"
},
{
"code": null,
"e": 1488,
"s": 1457,
"text": "{1: 'aaa', 2: 'bbb', 3: 'ccc'}"
}
] |
Ways to sort list of dictionaries using values in python | In this article, you will learn how to sort the list of dictionaries using values in Python. We will use inbuilt method calls sorted to sort the dictionary.
We will follow the steps mentioned below to sort a dictionary using values.
Pass the list containing dictionaries and keys to the sorted method.We can pass the keys in two different ways1.Using lambda function2.Using itemgetter method
We can pass the keys in two different ways1.Using lambda function2.Using itemgetter method
1.Using lambda function
2.Using itemgetter method
Let's see the examples.
Live Demo
## list of dictionaries
dicts = [
{"name" : "John", "salary" : 10000},
{"name" : "Emma", "salary" : 30000},
{"name" : "Harry", "salary" : 15000},
{"name" : "Aslan", "salary" : 10000}
]
## sorting the above list using 'lambda' function
## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method
print(sorted(dicts, key = lambda item: item['salary']))
If you run the above program, we will get the following results.
[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]
The processing of sorting list of dictionaries using the itemgetter is similar to the above process. We pass the value to the key using itemgetter method, that's the only difference. Let's see.
Live Demo
## importing itemgetter from the operator
from operator import itemgetter
## list of dictionaries
dicts = [
{"name" : "John", "salary" : 10000},
{"name" : "Emma", "salary" : 30000},
{"name" : "Harry", "salary" : 15000},
{"name" : "Aslan", "salary" : 10000}
]
## sorting the above list using 'lambda' function
## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method
print(sorted(dicts, key = itemgetter('salary')))
If you run the above program, we will get the following results.
[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}] | [
{
"code": null,
"e": 1219,
"s": 1062,
"text": "In this article, you will learn how to sort the list of dictionaries using values in Python. We will use inbuilt method calls sorted to sort the dictionary."
},
{
"code": null,
"e": 1295,
"s": 1219,
"text": "We will follow the steps mentioned below to sort a dictionary using values."
},
{
"code": null,
"e": 1454,
"s": 1295,
"text": "Pass the list containing dictionaries and keys to the sorted method.We can pass the keys in two different ways1.Using lambda function2.Using itemgetter method"
},
{
"code": null,
"e": 1545,
"s": 1454,
"text": "We can pass the keys in two different ways1.Using lambda function2.Using itemgetter method"
},
{
"code": null,
"e": 1569,
"s": 1545,
"text": "1.Using lambda function"
},
{
"code": null,
"e": 1595,
"s": 1569,
"text": "2.Using itemgetter method"
},
{
"code": null,
"e": 1619,
"s": 1595,
"text": "Let's see the examples."
},
{
"code": null,
"e": 1630,
"s": 1619,
"text": " Live Demo"
},
{
"code": null,
"e": 2012,
"s": 1630,
"text": "## list of dictionaries\ndicts = [\n {\"name\" : \"John\", \"salary\" : 10000},\n {\"name\" : \"Emma\", \"salary\" : 30000},\n {\"name\" : \"Harry\", \"salary\" : 15000},\n {\"name\" : \"Aslan\", \"salary\" : 10000}\n]\n\n## sorting the above list using 'lambda' function\n## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method\nprint(sorted(dicts, key = lambda item: item['salary']))"
},
{
"code": null,
"e": 2077,
"s": 2012,
"text": "If you run the above program, we will get the following results."
},
{
"code": null,
"e": 2220,
"s": 2077,
"text": "[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]"
},
{
"code": null,
"e": 2414,
"s": 2220,
"text": "The processing of sorting list of dictionaries using the itemgetter is similar to the above process. We pass the value to the key using itemgetter method, that's the only difference. Let's see."
},
{
"code": null,
"e": 2425,
"s": 2414,
"text": " Live Demo"
},
{
"code": null,
"e": 2874,
"s": 2425,
"text": "## importing itemgetter from the operator\nfrom operator import itemgetter\n## list of dictionaries\ndicts = [\n {\"name\" : \"John\", \"salary\" : 10000},\n {\"name\" : \"Emma\", \"salary\" : 30000},\n {\"name\" : \"Harry\", \"salary\" : 15000},\n {\"name\" : \"Aslan\", \"salary\" : 10000}\n]\n\n## sorting the above list using 'lambda' function\n## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method\nprint(sorted(dicts, key = itemgetter('salary')))"
},
{
"code": null,
"e": 2939,
"s": 2874,
"text": "If you run the above program, we will get the following results."
},
{
"code": null,
"e": 3082,
"s": 2939,
"text": "[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]"
}
] |
Keeping credentials safe in Jupyter Notebooks | by Alexandra Souly | Towards Data Science | Jupyter Notebooks are widely used in Data Science for quick prototyping of models and interactive demonstrations. But how should we store passwords, certificates and keys securely when using them?
I will give a quick tour of the available solutions to help you keep your credentials safe.
I use Jupyter Notebooks a lot in my personal projects, and I’ve recently hit a fairly common situation that could end very badly if one hasn’t woken up on the security-conscious side of the bed. I needed to connect to the Bing API to scrape images, a paid service offered by Microsoft Azure. You basically connect with a secret authentication key that belongs to you, and you will be charged based on your usage of the API service.
If you just type the key into one of the cells and run it, even if you had the intention of deleting it once the connection is live, there is a possibility of forgetting about it and checking it into GitHub, or sending it to someone later.
But what’s wrong with updating credentials to GitHub?
The problem is that malicious bots are constantly scraping repos for any secrets accidentally pushed. Even if you fix it straight away after pushing, you’re not safe — there is a chance that is has already been scraped, or the commit history might still contain your mistake. Once your credentials are scraped, they can be used to steal your data, gain access to other services or rack up immense bills overnight on cloud computing services. The big companies are guilty of this mistake too: in 2017, hackers gained access to Uber’s private GitHub repo that stored plaintext passwords, which resulted in a 57 million user data breach.
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
In normal scripts, the situation is a bit simpler. Of course, you also shouldn’t hardcode your credentials, but you can separate them more easily. The easiest and most convenient solution is creating a config file in the root directory of the project that stores these values locally, and making sure that you add it to the .gitignore file to avoid accidentally uploading it. For a Python project, this config file could be any format that is convenient for data storage:
A python script called config.py or similar
A JSON file
A YAML file
An INI file
I recommend this article on how to use the above config file types.
Of course this is for personal/small projects, in a big company please use a professional key vault service.
The config file approach becomes very cumbersome for Jupyter Notebooks.
The point of them is to have portable code that you can quickly set up,run, change, share and carry around. This would mean that you also need to carry the config file around and make sure to keep a folder structure where all your imports work. This is even worse if you are using a browser environment like an online Jupyter Notebook or Google Colab, where folders are annoying to get to.
There is no perfect solution, but there are a few trade-offs depending on your situation.
If you don’t mind storing a config files locally and carrying them around when you need, the most pain-free is using JupyterLab instead of Jupyter Notebook. This is because JupyterLab has a file browser in the side bar, so you can see and access files like your config file with ease.
Remember to add your config files to your `.gitignore` file to avoid checking them in!
You can create any YAML or JSON config files as explained above for non-notebook scripts, but my favourite methods are:
1.a Config parser:
You can create a file called `notebook.cfg` for example, with this syntax:
[my_api]auth_key: shjdkh2648979379egkfgkss
You then load the credentials as:
1.b Dotenv
You can create an .env file at your project root directory, and dotenv will load these for you into environmental variables. The syntax is similar to Bash.
# Development settingsDOMAIN=example.orgADMIN_EMAIL=admin@${DOMAIN}ROOT_URL=${DOMAIN}/appADMIN_PW = kdhkr4rb344r4
You would load this as follows:
I like the Dotenv approach better because it is more easily shareable. If you send the notebook to someone else, all they have to do is set their own environmental variables.
GetPass lets you type in your password into an interactive cell specifically designed for secrets. Your input is hidden when typing, doesn’t get printed out anywhere, and is not saved either. You will have to retype your secret every type you re-run the cell. This is the most useful if you have very few secrets or very simple ones you can type remember and type quickly.
JupyterLab allows you to type in key-value pairs into its own Credential Store, that comes from an extension. These are saved in a file called .credentialstore, which is AES-encrypted (very safe), so you can only access the credentials when logged in to JupyterLab. However, make sure to add this to your `.gitignore` file as well.
You can use it as:
import kernel_connector as kckc.get_credential("my_secret")
For more information, see this post by the extension author.
Note that in the new version of JupyterLab, the original extension is broken but a fixed version is available if you search for @ccorbin/credentialstore.
Keyring integrates with your OS keychain manager, so that you can access any passwords from your macOS Keychain, Windows Credential Locker or other third-party service. This makes your credentials completely decoupled from your code, there’s no config file to accidentally check in.
You would use it as:
import keyringkeyring.get_keyring()keyring.get_password("system", "username")
This is the most involved out of all the previous solutions, and the only one that will cost you money. Cloud services are not free, but you can get a free trial usually, and storing a couple of secrets won’t cost you much. This is also the most professional and secure method, as nothing is stored locally. I don’t really recommend this for small projects because of the overheads of authenticating, but if you are collaborating a lot, it could provide the solution you are looking for.
Azure Key Vault — $0.03/10,000 transactions
AWS Secrets Manager— $0.40 /month/secret + $0.05 per 10,000 API call
I hope you found a method you like, and stay safe! | [
{
"code": null,
"e": 368,
"s": 171,
"text": "Jupyter Notebooks are widely used in Data Science for quick prototyping of models and interactive demonstrations. But how should we store passwords, certificates and keys securely when using them?"
},
{
"code": null,
"e": 460,
"s": 368,
"text": "I will give a quick tour of the available solutions to help you keep your credentials safe."
},
{
"code": null,
"e": 892,
"s": 460,
"text": "I use Jupyter Notebooks a lot in my personal projects, and I’ve recently hit a fairly common situation that could end very badly if one hasn’t woken up on the security-conscious side of the bed. I needed to connect to the Bing API to scrape images, a paid service offered by Microsoft Azure. You basically connect with a secret authentication key that belongs to you, and you will be charged based on your usage of the API service."
},
{
"code": null,
"e": 1132,
"s": 892,
"text": "If you just type the key into one of the cells and run it, even if you had the intention of deleting it once the connection is live, there is a possibility of forgetting about it and checking it into GitHub, or sending it to someone later."
},
{
"code": null,
"e": 1186,
"s": 1132,
"text": "But what’s wrong with updating credentials to GitHub?"
},
{
"code": null,
"e": 1821,
"s": 1186,
"text": "The problem is that malicious bots are constantly scraping repos for any secrets accidentally pushed. Even if you fix it straight away after pushing, you’re not safe — there is a chance that is has already been scraped, or the commit history might still contain your mistake. Once your credentials are scraped, they can be used to steal your data, gain access to other services or rack up immense bills overnight on cloud computing services. The big companies are guilty of this mistake too: in 2017, hackers gained access to Uber’s private GitHub repo that stored plaintext passwords, which resulted in a 57 million user data breach."
},
{
"code": null,
"e": 2121,
"s": 1821,
"text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details."
},
{
"code": null,
"e": 2593,
"s": 2121,
"text": "In normal scripts, the situation is a bit simpler. Of course, you also shouldn’t hardcode your credentials, but you can separate them more easily. The easiest and most convenient solution is creating a config file in the root directory of the project that stores these values locally, and making sure that you add it to the .gitignore file to avoid accidentally uploading it. For a Python project, this config file could be any format that is convenient for data storage:"
},
{
"code": null,
"e": 2637,
"s": 2593,
"text": "A python script called config.py or similar"
},
{
"code": null,
"e": 2649,
"s": 2637,
"text": "A JSON file"
},
{
"code": null,
"e": 2661,
"s": 2649,
"text": "A YAML file"
},
{
"code": null,
"e": 2673,
"s": 2661,
"text": "An INI file"
},
{
"code": null,
"e": 2741,
"s": 2673,
"text": "I recommend this article on how to use the above config file types."
},
{
"code": null,
"e": 2850,
"s": 2741,
"text": "Of course this is for personal/small projects, in a big company please use a professional key vault service."
},
{
"code": null,
"e": 2922,
"s": 2850,
"text": "The config file approach becomes very cumbersome for Jupyter Notebooks."
},
{
"code": null,
"e": 3312,
"s": 2922,
"text": "The point of them is to have portable code that you can quickly set up,run, change, share and carry around. This would mean that you also need to carry the config file around and make sure to keep a folder structure where all your imports work. This is even worse if you are using a browser environment like an online Jupyter Notebook or Google Colab, where folders are annoying to get to."
},
{
"code": null,
"e": 3402,
"s": 3312,
"text": "There is no perfect solution, but there are a few trade-offs depending on your situation."
},
{
"code": null,
"e": 3687,
"s": 3402,
"text": "If you don’t mind storing a config files locally and carrying them around when you need, the most pain-free is using JupyterLab instead of Jupyter Notebook. This is because JupyterLab has a file browser in the side bar, so you can see and access files like your config file with ease."
},
{
"code": null,
"e": 3774,
"s": 3687,
"text": "Remember to add your config files to your `.gitignore` file to avoid checking them in!"
},
{
"code": null,
"e": 3894,
"s": 3774,
"text": "You can create any YAML or JSON config files as explained above for non-notebook scripts, but my favourite methods are:"
},
{
"code": null,
"e": 3913,
"s": 3894,
"text": "1.a Config parser:"
},
{
"code": null,
"e": 3988,
"s": 3913,
"text": "You can create a file called `notebook.cfg` for example, with this syntax:"
},
{
"code": null,
"e": 4031,
"s": 3988,
"text": "[my_api]auth_key: shjdkh2648979379egkfgkss"
},
{
"code": null,
"e": 4065,
"s": 4031,
"text": "You then load the credentials as:"
},
{
"code": null,
"e": 4076,
"s": 4065,
"text": "1.b Dotenv"
},
{
"code": null,
"e": 4232,
"s": 4076,
"text": "You can create an .env file at your project root directory, and dotenv will load these for you into environmental variables. The syntax is similar to Bash."
},
{
"code": null,
"e": 4346,
"s": 4232,
"text": "# Development settingsDOMAIN=example.orgADMIN_EMAIL=admin@${DOMAIN}ROOT_URL=${DOMAIN}/appADMIN_PW = kdhkr4rb344r4"
},
{
"code": null,
"e": 4378,
"s": 4346,
"text": "You would load this as follows:"
},
{
"code": null,
"e": 4553,
"s": 4378,
"text": "I like the Dotenv approach better because it is more easily shareable. If you send the notebook to someone else, all they have to do is set their own environmental variables."
},
{
"code": null,
"e": 4926,
"s": 4553,
"text": "GetPass lets you type in your password into an interactive cell specifically designed for secrets. Your input is hidden when typing, doesn’t get printed out anywhere, and is not saved either. You will have to retype your secret every type you re-run the cell. This is the most useful if you have very few secrets or very simple ones you can type remember and type quickly."
},
{
"code": null,
"e": 5258,
"s": 4926,
"text": "JupyterLab allows you to type in key-value pairs into its own Credential Store, that comes from an extension. These are saved in a file called .credentialstore, which is AES-encrypted (very safe), so you can only access the credentials when logged in to JupyterLab. However, make sure to add this to your `.gitignore` file as well."
},
{
"code": null,
"e": 5277,
"s": 5258,
"text": "You can use it as:"
},
{
"code": null,
"e": 5337,
"s": 5277,
"text": "import kernel_connector as kckc.get_credential(\"my_secret\")"
},
{
"code": null,
"e": 5398,
"s": 5337,
"text": "For more information, see this post by the extension author."
},
{
"code": null,
"e": 5552,
"s": 5398,
"text": "Note that in the new version of JupyterLab, the original extension is broken but a fixed version is available if you search for @ccorbin/credentialstore."
},
{
"code": null,
"e": 5835,
"s": 5552,
"text": "Keyring integrates with your OS keychain manager, so that you can access any passwords from your macOS Keychain, Windows Credential Locker or other third-party service. This makes your credentials completely decoupled from your code, there’s no config file to accidentally check in."
},
{
"code": null,
"e": 5856,
"s": 5835,
"text": "You would use it as:"
},
{
"code": null,
"e": 5934,
"s": 5856,
"text": "import keyringkeyring.get_keyring()keyring.get_password(\"system\", \"username\")"
},
{
"code": null,
"e": 6422,
"s": 5934,
"text": "This is the most involved out of all the previous solutions, and the only one that will cost you money. Cloud services are not free, but you can get a free trial usually, and storing a couple of secrets won’t cost you much. This is also the most professional and secure method, as nothing is stored locally. I don’t really recommend this for small projects because of the overheads of authenticating, but if you are collaborating a lot, it could provide the solution you are looking for."
},
{
"code": null,
"e": 6466,
"s": 6422,
"text": "Azure Key Vault — $0.03/10,000 transactions"
},
{
"code": null,
"e": 6535,
"s": 6466,
"text": "AWS Secrets Manager— $0.40 /month/secret + $0.05 per 10,000 API call"
}
] |
MySQL - SET Syntax for Variable Assignment | The SET statement in MySQL is used to assign values for variables. Using this you can set values to, user-defined variables, variables in procedures and, system variables.
Following is the syntax of the SET statement in MySQL−
SET variable = val1, val2, val3, . . .
variable: {
user_var_name
| param_name
| local_var_name
| {GLOBAL | @@GLOBAL.} system_var_name
| {PERSIST | @@PERSIST.} system_var_name
| {PERSIST_ONLY | @@PERSIST_ONLY.} system_var_name
| [SESSION | @@SESSION. | @@] system_var_name
}
You can create variables with in the current MySQL session and use them in the queries. While defining a user d-fined variable you need to place ‘@’ before the variable name.
mysql> SET @name = 'Krishna';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @age = 25;
Query OK, 0 rows affected (0.00 sec)
mysql> SET @phone = 9012345678;
Query OK, 0 rows affected (0.00 sec)
You can retrieve the values of these variables using the SELECT statement as −
mysql> SELECT @name, @age, @phone;
+---------+------+------------+
| @name | @age | @phone |
+---------+------+------------+
| Krishna | 25 | 9012345678 |
+---------+------+------------+
1 row in set (0.07 sec)
You can define variables with in stored routines and set values to them using the SET statement.
Following is an example of declaring local variables −
DELIMITER //
CREATE PROCEDURE RepeatExample()
BEGIN
DECLARE val INT;
DECLARE squares INT;
DECLARE res VARCHAR(100);
SET val=1;
SET squares=1;
SET res = '';
REPEAT
SET squares = val*val;
SET res = CONCAT(res, squares,',');
SET val = val + 1;
UNTIL val >= 10
END REPEAT;
SELECT res;
END//
DELIMITER ;
You can call the above procedure as follows −
mysql> CALL RepeatExample;
+--------------------------+
| res |
+--------------------------+
| 1,4,9,16,25,36,49,64,81, |
+--------------------------+
1 row in set (0.07 sec)
Query OK, 0 rows affected (0.08 sec)
MySQL system variables holds global or session level values, these variables are used to configure various operations. You can set values to these variables dynamically using the SET statement
Let us verify whether loading local data is enabled, if not you can observe the local_infile variable value as −
mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile | OFF |
+---------------+-------+
1 row in set (0.57 sec)
Following query enables local_infile option as −
mysql> SET GLOBAL local_infile = 'ON';
Query OK, 0 rows affected (0.09 sec)
If you verify the value of the variable local_infile again, you can observe the changed value as −
mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile | ON |
+---------------+-------+
1 row in set (0.00 sec)
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2505,
"s": 2333,
"text": "The SET statement in MySQL is used to assign values for variables. Using this you can set values to, user-defined variables, variables in procedures and, system variables."
},
{
"code": null,
"e": 2560,
"s": 2505,
"text": "Following is the syntax of the SET statement in MySQL−"
},
{
"code": null,
"e": 2857,
"s": 2560,
"text": "SET variable = val1, val2, val3, . . .\n\nvariable: {\n user_var_name\n | param_name\n | local_var_name\n | {GLOBAL | @@GLOBAL.} system_var_name\n | {PERSIST | @@PERSIST.} system_var_name\n | {PERSIST_ONLY | @@PERSIST_ONLY.} system_var_name\n | [SESSION | @@SESSION. | @@] system_var_name\n}\n"
},
{
"code": null,
"e": 3032,
"s": 2857,
"text": "You can create variables with in the current MySQL session and use them in the queries. While defining a user d-fined variable you need to place ‘@’ before the variable name."
},
{
"code": null,
"e": 3229,
"s": 3032,
"text": "mysql> SET @name = 'Krishna';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> SET @age = 25;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> SET @phone = 9012345678;\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 3308,
"s": 3229,
"text": "You can retrieve the values of these variables using the SELECT statement as −"
},
{
"code": null,
"e": 3527,
"s": 3308,
"text": "mysql> SELECT @name, @age, @phone;\n+---------+------+------------+\n| @name | @age | @phone |\n+---------+------+------------+\n| Krishna | 25 | 9012345678 |\n+---------+------+------------+\n1 row in set (0.07 sec)"
},
{
"code": null,
"e": 3624,
"s": 3527,
"text": "You can define variables with in stored routines and set values to them using the SET statement."
},
{
"code": null,
"e": 3679,
"s": 3624,
"text": "Following is an example of declaring local variables −"
},
{
"code": null,
"e": 4026,
"s": 3679,
"text": "DELIMITER //\nCREATE PROCEDURE RepeatExample()\nBEGIN\n DECLARE val INT;\n DECLARE squares INT;\n DECLARE res VARCHAR(100);\n SET val=1;\n SET squares=1;\n SET res = '';\n REPEAT\n SET squares = val*val;\n SET res = CONCAT(res, squares,',');\n SET val = val + 1;\n UNTIL val >= 10\n END REPEAT;\n SELECT res;\nEND//\nDELIMITER ;"
},
{
"code": null,
"e": 4072,
"s": 4026,
"text": "You can call the above procedure as follows −"
},
{
"code": null,
"e": 4305,
"s": 4072,
"text": "mysql> CALL RepeatExample;\n+--------------------------+\n| res |\n+--------------------------+\n| 1,4,9,16,25,36,49,64,81, |\n+--------------------------+\n1 row in set (0.07 sec)\nQuery OK, 0 rows affected (0.08 sec)"
},
{
"code": null,
"e": 4498,
"s": 4305,
"text": "MySQL system variables holds global or session level values, these variables are used to configure various operations. You can set values to these variables dynamically using the SET statement"
},
{
"code": null,
"e": 4611,
"s": 4498,
"text": "Let us verify whether loading local data is enabled, if not you can observe the local_infile variable value as −"
},
{
"code": null,
"e": 4815,
"s": 4611,
"text": "mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';\n+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| local_infile | OFF |\n+---------------+-------+\n1 row in set (0.57 sec)"
},
{
"code": null,
"e": 4864,
"s": 4815,
"text": "Following query enables local_infile option as −"
},
{
"code": null,
"e": 4940,
"s": 4864,
"text": "mysql> SET GLOBAL local_infile = 'ON';\nQuery OK, 0 rows affected (0.09 sec)"
},
{
"code": null,
"e": 5039,
"s": 4940,
"text": "If you verify the value of the variable local_infile again, you can observe the changed value as −"
},
{
"code": null,
"e": 5243,
"s": 5039,
"text": "mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';\n+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| local_infile | ON |\n+---------------+-------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 5276,
"s": 5243,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5304,
"s": 5276,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5339,
"s": 5304,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5356,
"s": 5339,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5390,
"s": 5356,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5425,
"s": 5390,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 5459,
"s": 5425,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5487,
"s": 5459,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5520,
"s": 5487,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5540,
"s": 5520,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5573,
"s": 5540,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5591,
"s": 5573,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 5598,
"s": 5591,
"text": " Print"
},
{
"code": null,
"e": 5609,
"s": 5598,
"text": " Add Notes"
}
] |
How to create a tuple with string and int items in C#? | Firstly, set two items in the tuple.
Tuple<int, string> tuple = new Tuple<int, string>(20, "Tom");
Now check for first item in the tuple, which is an integer.
if (tuple.Item1 == 20) {
Console.WriteLine(tuple.Item1);
}
Now check for second item in the tuple, which is a string −
if (tuple.Item2 == "Tom") {
Console.WriteLine(tuple.Item2);
}
The following is an example to create a tuple with string and int items.
Live Demo
using System;
using System.Threading;
namespace Demo {
class Program {
static void Main(string[] args) {
Tuple<int, string> tuple = new Tuple<int, string>(20, "Tom");
if (tuple.Item1 == 20) {
Console.WriteLine(tuple.Item1);
}
if (tuple.Item2 == "Tom") {
Console.WriteLine(tuple.Item2);
}
}
}
}
20
Tom | [
{
"code": null,
"e": 1099,
"s": 1062,
"text": "Firstly, set two items in the tuple."
},
{
"code": null,
"e": 1161,
"s": 1099,
"text": "Tuple<int, string> tuple = new Tuple<int, string>(20, \"Tom\");"
},
{
"code": null,
"e": 1221,
"s": 1161,
"text": "Now check for first item in the tuple, which is an integer."
},
{
"code": null,
"e": 1283,
"s": 1221,
"text": "if (tuple.Item1 == 20) {\n Console.WriteLine(tuple.Item1);\n}"
},
{
"code": null,
"e": 1343,
"s": 1283,
"text": "Now check for second item in the tuple, which is a string −"
},
{
"code": null,
"e": 1408,
"s": 1343,
"text": "if (tuple.Item2 == \"Tom\") {\n Console.WriteLine(tuple.Item2);\n}"
},
{
"code": null,
"e": 1481,
"s": 1408,
"text": "The following is an example to create a tuple with string and int items."
},
{
"code": null,
"e": 1492,
"s": 1481,
"text": " Live Demo"
},
{
"code": null,
"e": 1873,
"s": 1492,
"text": "using System;\nusing System.Threading;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n Tuple<int, string> tuple = new Tuple<int, string>(20, \"Tom\");\n if (tuple.Item1 == 20) {\n Console.WriteLine(tuple.Item1);\n }\n if (tuple.Item2 == \"Tom\") {\n Console.WriteLine(tuple.Item2);\n }\n }\n }\n}"
},
{
"code": null,
"e": 1880,
"s": 1873,
"text": "20\nTom"
}
] |
How to create a Custom Ratingbar in Android using Kotlin? | This example demonstrates how to create a Custom Ratingbar in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16sp"
tools:context=".MainActivity">
<RatingBar
android:id="@+id/ratingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:numStars="5"
android:rating="2.0"
android:stepSize="1.0" />
<Button
android:id="@+id/buttonCheck"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ratingBar"
android:layout_centerHorizontal="true"
android:text="CHECK" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/holo_red_dark"
android:textSize="24sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.Button
import android.widget.RatingBar
import android.widget.RatingBar.OnRatingBarChangeListener
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var ratingBar: RatingBar
lateinit var button: Button
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
ratingBar = findViewById(R.id.ratingBar)
ratingBar.numStars = 5
button = findViewById(R.id.buttonCheck)
textView = findViewById(R.id.textView)
ratingBar.onRatingBarChangeListener =
OnRatingBarChangeListener {
_, rating, _ ->
Toast.makeText(
this@MainActivity, "Stars: " +
rating.toInt(), Toast.LENGTH_SHORT
).show()
}
button.setOnClickListener {
textView.text = "You have got " + ratingBar.rating.toInt()+ " stars"
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "This example demonstrates how to create a Custom Ratingbar in Android using Kotlin."
},
{
"code": null,
"e": 1275,
"s": 1146,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1340,
"s": 1275,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2438,
"s": 1340,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16sp\"\n tools:context=\".MainActivity\">\n <RatingBar\n android:id=\"@+id/ratingBar\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:numStars=\"5\"\n android:rating=\"2.0\"\n android:stepSize=\"1.0\" />\n <Button\n android:id=\"@+id/buttonCheck\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/ratingBar\"\n android:layout_centerHorizontal=\"true\"\n android:text=\"CHECK\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/holo_red_dark\"\n android:textSize=\"24sp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2493,
"s": 2438,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3590,
"s": 2493,
"text": "import android.os.Bundle\nimport android.widget.Button\nimport android.widget.RatingBar\nimport android.widget.RatingBar.OnRatingBarChangeListener\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var ratingBar: RatingBar\n lateinit var button: Button\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n ratingBar = findViewById(R.id.ratingBar)\n ratingBar.numStars = 5\n button = findViewById(R.id.buttonCheck)\n textView = findViewById(R.id.textView)\n ratingBar.onRatingBarChangeListener =\n OnRatingBarChangeListener {\n _, rating, _ ->\n Toast.makeText(\n this@MainActivity, \"Stars: \" +\n rating.toInt(), Toast.LENGTH_SHORT\n ).show()\n }\n button.setOnClickListener {\n textView.text = \"You have got \" + ratingBar.rating.toInt()+ \" stars\"\n }\n }\n}"
},
{
"code": null,
"e": 3645,
"s": 3590,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4298,
"s": 3645,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?> \n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n</application>"
},
{
"code": null,
"e": 4646,
"s": 4298,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Can finally block be used without catch in Java? | Yes, it is not mandatory to use catch block with finally. You can have to try and finally.
Live Demo
public class Test {
public static void main(String args[]) {
int a[] = new int[2];
try {
} finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
First element value: 6
Exception in thread "main" The finally statement is executed
java.lang.ArrayIndexOutOfBoundsException: 3
at a5Exception_Handling.Test.main(Test.java:7) | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "Yes, it is not mandatory to use catch block with finally. You can have to try and finally."
},
{
"code": null,
"e": 1163,
"s": 1153,
"text": "Live Demo"
},
{
"code": null,
"e": 1446,
"s": 1163,
"text": "public class Test {\n public static void main(String args[]) {\n int a[] = new int[2];\n try {\n } finally {\n a[0] = 6;\n System.out.println(\"First element value: \" + a[0]);\n System.out.println(\"The finally statement is executed\");\n }\n }\n}"
},
{
"code": null,
"e": 1627,
"s": 1446,
"text": "First element value: 6\nException in thread \"main\" The finally statement is executed\njava.lang.ArrayIndexOutOfBoundsException: 3\n at a5Exception_Handling.Test.main(Test.java:7)"
}
] |
Make Beautiful Spatial Visualizations with Plotly and Mapbox | by Will Norris | Towards Data Science | I recently wrote a post about visualizing weather data from NOAA. We walked through processing the data and making some basic interactive maps with Plotly. In this article I want to use the same data but focus on the options we have available for improving our web maps with Plotly and Mapbox. Web maps can serve many purposes, and having a quality base map that helps emphasize or provide context to your data points can make a huge difference in the quality of your visualizations.
Mapbox is a startup that provides the maps for websites like Foursquare and The Weather Channel along with developing some of the most powerful open source tools for creating web maps. The Mapbox JavaScript library has been the best web mapping tool available for several years and now we can take advantage of Mapbox in Python using Plotly.
Plotly has two main types of maps, Geo maps and Mapbox maps. Geo maps are outline based and Mapbox maps are tile based. The main difference between the two is that an outline based map draws everything at once, while a tile based map has a hierarchy of information that is rendered at different levels of zoom.
If I have a map that starts at a global scale and I want users to be able to zoom into see fine levels of granularity, then a tile based map may suit my needs better than an outline map. Since tile based maps don’t have to load in all of the information right away they can be less memory intensive, but having to process the granularity changes when zooming increases a tile maps processing power overhead. This means that tile based maps are fantastic for making a lot of information available without cluttering the map, but they require more data and processing power.
Here is the same map rendered both as an outline map and a tile based map. Try zooming in and see if you can find some notable differences between the two.
At first glance these maps may look quite similar aside from using different projections. But when you start to zoom in you begin to see the advantages of a tile based map. Country borders become visible as they become relevant and less obtrusive to the data points; even cities, roads, and rivers load into the base map as you zoom into finer and finer scales.
Having access to this kind of detail can really make a visualization feel professional, and the varying granularity is helpful when working at multiple scales. If we wanted to show country borders using Plotly’s Scattergeo function we would need to draw them at all scales, like this:
This plot is much busier than the two without country borders at this scale. And we still lack details that the tile map offers like country names and cities. These kinds of features can be configured on the outline map, but they aren’t very practical for an outline map that can quickly become cluttered.
Despite these downsides, outline maps do still have a place. When creating maps of smaller regions we often don’t need to render data at multiple scales, which means there is no reason to add the data and processing overhead of a tile based map. Also, when making maps for presentations it can be advantageous to customize an outline based map to maximize quick readability from a distance. Not to mention that conference rooms don’t always have the best wifi, and I have seen my fair share of web maps load extremely slowly to the dismay of the person speaking.
Mapbox GL JS is a JavaScript library made for web mapping with interactive tile maps. Plotly refers to the Mapbox JavaScript library when we invoke one of the Plotly Mapbox functions in Python. Since some versions of the Mapbox GL JS library are open source, using these functions with an open source base map does not require a Mapbox API key. However, Mapbox as a company has extremely high quality vector tile base maps available that will require a Mapbox API key to use. Mapbox has a great free tier that allows up to 50,000 map loads per month, which is plenty for most users.
Most web maps have traditionally used raster tiles to construct a map, but Mapbox allows us to take advantage of vector tiles as well. If you are familiar with GIS data, a raster is a grid of values (images) and vector data is geometry data — normally points, lines, and polygons.
Raster tiles are a set of images that line up next to each other to form a complete map. As you zoom in, different levels of raster tiles can be loaded to show new features at different scales. Vector tiles work very similarly to this, however the tiles contain pre-generated vector data that suit the zoom and location you are viewing.
There are a lot of upsides to vector tiles. They don’t have to be exactly the same size like raster tiles and they are rendered by the client’s computer, which can make them much lighter weight to host. Vector data also is generally much smaller than raster data making using the map snappier since you are relying less on a fast internet connection. Vector data can even render rasters if needed making it incredibly flexible.
With Plotly we have access to both raster and vector tile base maps. The raster tile base maps we have access to are open source, like Open Street Map’s base maps. Mapbox provides access to vector tile base maps, but they require a Mapbox API token to access. Below I will go through some of the available base maps and show you the practical differences.
All of the raster tile base maps that we have access to are open source and don’t require an API token to make use of. Here are a few examples of what is available:
Open Street Map
Even though we are using a base map from Open Street Map, we still invoke the “Scattermapbox()” function. This is because Plotly makes use of the open source Mapbox JavaScript library to plot tiled maps regardless of whether they are raster or vector tiles.
USGS Imagery Raster Tiles
The United States Geological Survey has a plethora of imagery available online, including some great base maps! The easiest way to use a raster tile image layer like this is to render an empty white canvas and then manually render the base map underneath the data or “traces”.
It’s pretty cool what kinds of maps can be so easily created and shared using Plotly! Imagery like this can provide really useful context to climate data, although you will probably notice that my color scale could use some adjustment to accommodate the dark colors in this base map. Since tile based web maps are a popular standard, there are many available base maps out there that can be easily accessed.
Note: If you are running on a slower internet connection it may take longer for these maps to load. Raster tiles can be quite large, which means a lot of data has to be transferred to your browser.
USGS Hydrological Raster Tiles
If we use this link instead as our source, we can get a hydrological base map from USGS as well:
source = ["https://basemap.nationalmap.gov/arcgis/rest/services/USGSHydroCached/MapServer/tile/{z}/{y}/{x}"]
You will notice with some USGS data products that the data is much more complete in North America, so there may not be useful hydrologic information in some parts of the world. Overall it is really impressive how much free and useful data is available from USGS, NOAA, etc.
USGS Shaded Relief Base Map
Here is a shaded relief base map as one final example of what is available for free from USGS. Keep in mind that there are other raster tile map data sets available online as well that I will link in the Resources section at the end.
"source": [ "https://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/tile/{z}/{y}/{x}"]
Vector tile base maps are acquired from Mapbox’s servers, which means we need a Mapbox account and API token to use them. If your computer is fairly modern, you will likely notice a fairly large improvement in the responsiveness and detail from these vector tile maps. Since vector data is rendered by your computer there is less data being transferred from a server to your machine, which generally means faster loading times.
Mapbox Dark Style
The syntax for plotting with a Mapbox base map is quite similar to the open source alternatives. Instead of specifying the layers, we simply pass a “mapbox” dictionary with our API key and other parameters. The “style” is what determines which Mapbox base map your map uses.
Streets Style
If you are looking for more detail in streets and cities then the “streets” style will suit your use case well. It trades off a lot of the detail in outdoor recreation from the previous map for extremes detail in streets, paths, and parks. This base map allows us to zoom in to see the names of even very small streets. This base map even has all of the campus building names and walking paths mapped in my hometown of Boulder, Colorado.
Outdoors Style
Mapbox even has base maps like the “outdoors” style, which has important land marks and details for hiking, biking, and other outdoor activities. You can even zoom into areas like Breckenridge, Colorado and see the ski runs rendered as you get close enough:
We can see that Plotly and Mapbox give us access to a wide range of base maps to suit many different user needs. Even loading in raster tiles from a third party like USGS is fairly straightforward. It is awesome to have access to such a powerful web mapping tool in Python since being able to produce quality maps without using JavaScript can reduce a lot of friction in your workflow.
USGS Base Maps | [
{
"code": null,
"e": 655,
"s": 171,
"text": "I recently wrote a post about visualizing weather data from NOAA. We walked through processing the data and making some basic interactive maps with Plotly. In this article I want to use the same data but focus on the options we have available for improving our web maps with Plotly and Mapbox. Web maps can serve many purposes, and having a quality base map that helps emphasize or provide context to your data points can make a huge difference in the quality of your visualizations."
},
{
"code": null,
"e": 997,
"s": 655,
"text": "Mapbox is a startup that provides the maps for websites like Foursquare and The Weather Channel along with developing some of the most powerful open source tools for creating web maps. The Mapbox JavaScript library has been the best web mapping tool available for several years and now we can take advantage of Mapbox in Python using Plotly."
},
{
"code": null,
"e": 1308,
"s": 997,
"text": "Plotly has two main types of maps, Geo maps and Mapbox maps. Geo maps are outline based and Mapbox maps are tile based. The main difference between the two is that an outline based map draws everything at once, while a tile based map has a hierarchy of information that is rendered at different levels of zoom."
},
{
"code": null,
"e": 1881,
"s": 1308,
"text": "If I have a map that starts at a global scale and I want users to be able to zoom into see fine levels of granularity, then a tile based map may suit my needs better than an outline map. Since tile based maps don’t have to load in all of the information right away they can be less memory intensive, but having to process the granularity changes when zooming increases a tile maps processing power overhead. This means that tile based maps are fantastic for making a lot of information available without cluttering the map, but they require more data and processing power."
},
{
"code": null,
"e": 2037,
"s": 1881,
"text": "Here is the same map rendered both as an outline map and a tile based map. Try zooming in and see if you can find some notable differences between the two."
},
{
"code": null,
"e": 2399,
"s": 2037,
"text": "At first glance these maps may look quite similar aside from using different projections. But when you start to zoom in you begin to see the advantages of a tile based map. Country borders become visible as they become relevant and less obtrusive to the data points; even cities, roads, and rivers load into the base map as you zoom into finer and finer scales."
},
{
"code": null,
"e": 2684,
"s": 2399,
"text": "Having access to this kind of detail can really make a visualization feel professional, and the varying granularity is helpful when working at multiple scales. If we wanted to show country borders using Plotly’s Scattergeo function we would need to draw them at all scales, like this:"
},
{
"code": null,
"e": 2990,
"s": 2684,
"text": "This plot is much busier than the two without country borders at this scale. And we still lack details that the tile map offers like country names and cities. These kinds of features can be configured on the outline map, but they aren’t very practical for an outline map that can quickly become cluttered."
},
{
"code": null,
"e": 3553,
"s": 2990,
"text": "Despite these downsides, outline maps do still have a place. When creating maps of smaller regions we often don’t need to render data at multiple scales, which means there is no reason to add the data and processing overhead of a tile based map. Also, when making maps for presentations it can be advantageous to customize an outline based map to maximize quick readability from a distance. Not to mention that conference rooms don’t always have the best wifi, and I have seen my fair share of web maps load extremely slowly to the dismay of the person speaking."
},
{
"code": null,
"e": 4136,
"s": 3553,
"text": "Mapbox GL JS is a JavaScript library made for web mapping with interactive tile maps. Plotly refers to the Mapbox JavaScript library when we invoke one of the Plotly Mapbox functions in Python. Since some versions of the Mapbox GL JS library are open source, using these functions with an open source base map does not require a Mapbox API key. However, Mapbox as a company has extremely high quality vector tile base maps available that will require a Mapbox API key to use. Mapbox has a great free tier that allows up to 50,000 map loads per month, which is plenty for most users."
},
{
"code": null,
"e": 4417,
"s": 4136,
"text": "Most web maps have traditionally used raster tiles to construct a map, but Mapbox allows us to take advantage of vector tiles as well. If you are familiar with GIS data, a raster is a grid of values (images) and vector data is geometry data — normally points, lines, and polygons."
},
{
"code": null,
"e": 4754,
"s": 4417,
"text": "Raster tiles are a set of images that line up next to each other to form a complete map. As you zoom in, different levels of raster tiles can be loaded to show new features at different scales. Vector tiles work very similarly to this, however the tiles contain pre-generated vector data that suit the zoom and location you are viewing."
},
{
"code": null,
"e": 5182,
"s": 4754,
"text": "There are a lot of upsides to vector tiles. They don’t have to be exactly the same size like raster tiles and they are rendered by the client’s computer, which can make them much lighter weight to host. Vector data also is generally much smaller than raster data making using the map snappier since you are relying less on a fast internet connection. Vector data can even render rasters if needed making it incredibly flexible."
},
{
"code": null,
"e": 5538,
"s": 5182,
"text": "With Plotly we have access to both raster and vector tile base maps. The raster tile base maps we have access to are open source, like Open Street Map’s base maps. Mapbox provides access to vector tile base maps, but they require a Mapbox API token to access. Below I will go through some of the available base maps and show you the practical differences."
},
{
"code": null,
"e": 5703,
"s": 5538,
"text": "All of the raster tile base maps that we have access to are open source and don’t require an API token to make use of. Here are a few examples of what is available:"
},
{
"code": null,
"e": 5719,
"s": 5703,
"text": "Open Street Map"
},
{
"code": null,
"e": 5977,
"s": 5719,
"text": "Even though we are using a base map from Open Street Map, we still invoke the “Scattermapbox()” function. This is because Plotly makes use of the open source Mapbox JavaScript library to plot tiled maps regardless of whether they are raster or vector tiles."
},
{
"code": null,
"e": 6003,
"s": 5977,
"text": "USGS Imagery Raster Tiles"
},
{
"code": null,
"e": 6280,
"s": 6003,
"text": "The United States Geological Survey has a plethora of imagery available online, including some great base maps! The easiest way to use a raster tile image layer like this is to render an empty white canvas and then manually render the base map underneath the data or “traces”."
},
{
"code": null,
"e": 6688,
"s": 6280,
"text": "It’s pretty cool what kinds of maps can be so easily created and shared using Plotly! Imagery like this can provide really useful context to climate data, although you will probably notice that my color scale could use some adjustment to accommodate the dark colors in this base map. Since tile based web maps are a popular standard, there are many available base maps out there that can be easily accessed."
},
{
"code": null,
"e": 6886,
"s": 6688,
"text": "Note: If you are running on a slower internet connection it may take longer for these maps to load. Raster tiles can be quite large, which means a lot of data has to be transferred to your browser."
},
{
"code": null,
"e": 6917,
"s": 6886,
"text": "USGS Hydrological Raster Tiles"
},
{
"code": null,
"e": 7014,
"s": 6917,
"text": "If we use this link instead as our source, we can get a hydrological base map from USGS as well:"
},
{
"code": null,
"e": 7123,
"s": 7014,
"text": "source = [\"https://basemap.nationalmap.gov/arcgis/rest/services/USGSHydroCached/MapServer/tile/{z}/{y}/{x}\"]"
},
{
"code": null,
"e": 7397,
"s": 7123,
"text": "You will notice with some USGS data products that the data is much more complete in North America, so there may not be useful hydrologic information in some parts of the world. Overall it is really impressive how much free and useful data is available from USGS, NOAA, etc."
},
{
"code": null,
"e": 7425,
"s": 7397,
"text": "USGS Shaded Relief Base Map"
},
{
"code": null,
"e": 7659,
"s": 7425,
"text": "Here is a shaded relief base map as one final example of what is available for free from USGS. Keep in mind that there are other raster tile map data sets available online as well that I will link in the Resources section at the end."
},
{
"code": null,
"e": 7784,
"s": 7659,
"text": "\"source\": [ \"https://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/tile/{z}/{y}/{x}\"]"
},
{
"code": null,
"e": 8212,
"s": 7784,
"text": "Vector tile base maps are acquired from Mapbox’s servers, which means we need a Mapbox account and API token to use them. If your computer is fairly modern, you will likely notice a fairly large improvement in the responsiveness and detail from these vector tile maps. Since vector data is rendered by your computer there is less data being transferred from a server to your machine, which generally means faster loading times."
},
{
"code": null,
"e": 8230,
"s": 8212,
"text": "Mapbox Dark Style"
},
{
"code": null,
"e": 8505,
"s": 8230,
"text": "The syntax for plotting with a Mapbox base map is quite similar to the open source alternatives. Instead of specifying the layers, we simply pass a “mapbox” dictionary with our API key and other parameters. The “style” is what determines which Mapbox base map your map uses."
},
{
"code": null,
"e": 8519,
"s": 8505,
"text": "Streets Style"
},
{
"code": null,
"e": 8957,
"s": 8519,
"text": "If you are looking for more detail in streets and cities then the “streets” style will suit your use case well. It trades off a lot of the detail in outdoor recreation from the previous map for extremes detail in streets, paths, and parks. This base map allows us to zoom in to see the names of even very small streets. This base map even has all of the campus building names and walking paths mapped in my hometown of Boulder, Colorado."
},
{
"code": null,
"e": 8972,
"s": 8957,
"text": "Outdoors Style"
},
{
"code": null,
"e": 9230,
"s": 8972,
"text": "Mapbox even has base maps like the “outdoors” style, which has important land marks and details for hiking, biking, and other outdoor activities. You can even zoom into areas like Breckenridge, Colorado and see the ski runs rendered as you get close enough:"
},
{
"code": null,
"e": 9616,
"s": 9230,
"text": "We can see that Plotly and Mapbox give us access to a wide range of base maps to suit many different user needs. Even loading in raster tiles from a third party like USGS is fairly straightforward. It is awesome to have access to such a powerful web mapping tool in Python since being able to produce quality maps without using JavaScript can reduce a lot of friction in your workflow."
}
] |
PHP vs HTML - GeeksforGeeks | 30 Aug, 2019
Example of PHP code:
<?php echo "GeeksforGeeks"; ?>
Example of HTML code:
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <p>Hello</p></body> </html>
PHP vs HTML
Interesting Facts:
Famous websites like Facebook, Technorati, Yahoo, Wikipedia.org, WordPress.org, Twitter.com, Flickr, etc are powered by PHP.
PHP is deployed to more than 244 million websites. (Netcraft’s web survey 2013)
When PHP was developed, it stands for Personal Home Page.Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes
arrow_drop_upSave
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML
PHP
Web Technologies
Web technologies Questions
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key in PHP? | [
{
"code": null,
"e": 24739,
"s": 24711,
"text": "\n30 Aug, 2019"
},
{
"code": null,
"e": 24760,
"s": 24739,
"text": "Example of PHP code:"
},
{
"code": "<?php echo \"GeeksforGeeks\"; ?> ",
"e": 24794,
"s": 24760,
"text": null
},
{
"code": null,
"e": 24816,
"s": 24794,
"text": "Example of HTML code:"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <p>Hello</p></body> </html>",
"e": 24904,
"s": 24816,
"text": null
},
{
"code": null,
"e": 24916,
"s": 24904,
"text": "PHP vs HTML"
},
{
"code": null,
"e": 24935,
"s": 24916,
"text": "Interesting Facts:"
},
{
"code": null,
"e": 25060,
"s": 24935,
"text": "Famous websites like Facebook, Technorati, Yahoo, Wikipedia.org, WordPress.org, Twitter.com, Flickr, etc are powered by PHP."
},
{
"code": null,
"e": 25140,
"s": 25060,
"text": "PHP is deployed to more than 244 million websites. (Netcraft’s web survey 2013)"
},
{
"code": null,
"e": 25369,
"s": 25140,
"text": "When PHP was developed, it stands for Personal Home Page.Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 25506,
"s": 25369,
"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": 25511,
"s": 25506,
"text": "HTML"
},
{
"code": null,
"e": 25515,
"s": 25511,
"text": "PHP"
},
{
"code": null,
"e": 25532,
"s": 25515,
"text": "Web Technologies"
},
{
"code": null,
"e": 25559,
"s": 25532,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 25564,
"s": 25559,
"text": "HTML"
},
{
"code": null,
"e": 25568,
"s": 25564,
"text": "PHP"
},
{
"code": null,
"e": 25666,
"s": 25568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25675,
"s": 25666,
"text": "Comments"
},
{
"code": null,
"e": 25688,
"s": 25675,
"text": "Old Comments"
},
{
"code": null,
"e": 25712,
"s": 25688,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 25749,
"s": 25712,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 25778,
"s": 25749,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 25825,
"s": 25778,
"text": "How to place text on image using HTML and CSS?"
},
{
"code": null,
"e": 25887,
"s": 25825,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 25932,
"s": 25887,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 25976,
"s": 25932,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 26000,
"s": 25976,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 26040,
"s": 26000,
"text": "How to convert array to string in PHP ?"
}
] |
Zscaler Interview Experience | Campus Placement Drive 2020 - GeeksforGeeks | 03 Sep, 2020
Round 1: Online Test on Hackerrank. There were 20 MCQs of 1 marks each and 4 coding questions of total of 240 marks. MCQs were Networking, OS, and Linux/UNIX based.
Two coding questions were of 50 marks and two were 70. The questions were :
You are given a binary array (with only 1s and 0s), and you are supposed to bring all the 1s to the right and all the 0s to the left, or vice-versa. The operation that can be performed is to swap two adjacent values, find the minimum number of operations needed.You start from the 0th position and at every step, you can choose to move I (i is the step number) steps forward or can remain in your position. There is a bad index in which you cannot stand. Find the maximum index you can reach in k steps after avoiding the bad Index.Given a list of names appended with roman numbers. First sort them with names, then with the numbers appended to them, in increasing order.A string question related to appending a string multiple times to get a given string. If we can make the first string by appending the second string multiple times, then we have to return the smallest string that will produce the second string by appending one or more times.
You are given a binary array (with only 1s and 0s), and you are supposed to bring all the 1s to the right and all the 0s to the left, or vice-versa. The operation that can be performed is to swap two adjacent values, find the minimum number of operations needed.
You start from the 0th position and at every step, you can choose to move I (i is the step number) steps forward or can remain in your position. There is a bad index in which you cannot stand. Find the maximum index you can reach in k steps after avoiding the bad Index.
Given a list of names appended with roman numbers. First sort them with names, then with the numbers appended to them, in increasing order.
A string question related to appending a string multiple times to get a given string. If we can make the first string by appending the second string multiple times, then we have to return the smallest string that will produce the second string by appending one or more times.
Out of around 430 students, only 12 were selected.
Technical Interview 1:
Tell me about yourself.What is the complexity of quicksort and how to make it always nlog(n). He asked this question because I had a project on sorting visualization.Operating System Questions: What is virtualization (In terms of virtual memory). In a single-core system, 3 processes are running of size 526Mb each and the system memory is 1Gb. How is the os handling this? Question related to page replacement.Networking Questions: The process followed in DHCP protocol: Didn’t answer. Difference between TCP and UDP. What happens when you type www.google.com in your browser. What happens when you connect an Ethernet cable to your system. What is dynamic IP.
Tell me about yourself.
What is the complexity of quicksort and how to make it always nlog(n). He asked this question because I had a project on sorting visualization.
Operating System Questions: What is virtualization (In terms of virtual memory). In a single-core system, 3 processes are running of size 526Mb each and the system memory is 1Gb. How is the os handling this? Question related to page replacement.
Networking Questions: The process followed in DHCP protocol: Didn’t answer. Difference between TCP and UDP. What happens when you type www.google.com in your browser. What happens when you connect an Ethernet cable to your system. What is dynamic IP.
Then there were two coding questions:
Given an array of size n and an integer k, find the maximum values of all the subarrays of size k.Evaluate an expression tree.Asked the third question, to tell the logic of forming the expression tree, but then the time was over.
Given an array of size n and an integer k, find the maximum values of all the subarrays of size k.
Evaluate an expression tree.
Asked the third question, to tell the logic of forming the expression tree, but then the time was over.
Technical Interview 2 :
Again started with the introduction.Asked some questions about my project which I was working on (Online multiplayer game). What server you are using. Have you written some code for the login authentication? What database are you using? Why MongoDB instead of MySQL.Then asked a coding question: Given a comma-separated list of keys and some other comma-separated values in a vector of strings(like a CSV file), parse that and return a vector of the map with key-value pairs in it.Asked about child, parent, zombie process.Difference between thread and a process, I was confused and giving wrong answers, but he went on for around 10 mins.Then loaded a question from the first round (question with the badIndex), and told me to optimize my code, I was able to give the optimization in the case when we are calling the function multiple times(by storing all the results beforehand).
Again started with the introduction.
Asked some questions about my project which I was working on (Online multiplayer game). What server you are using. Have you written some code for the login authentication? What database are you using? Why MongoDB instead of MySQL.
Then asked a coding question: Given a comma-separated list of keys and some other comma-separated values in a vector of strings(like a CSV file), parse that and return a vector of the map with key-value pairs in it.
Asked about child, parent, zombie process.
Difference between thread and a process, I was confused and giving wrong answers, but he went on for around 10 mins.
Then loaded a question from the first round (question with the badIndex), and told me to optimize my code, I was able to give the optimization in the case when we are calling the function multiple times(by storing all the results beforehand).
Technical Interview 3:
Started with the introduction again.Told me about the devTest role.Create a function pointer, didn’t remember the syntaxTell something about virtualization in C++, I couldn’t answer.Wrote the code: char *ch = new char[10]; Asked about memory allocation in heap and stack. Create 10 character pointers.Then asked a coding question: Count the number of consecutive letters and append the number to the character. Not allowed to use the map or any extra space. Manipulations had to be done on the input itself. The only extra space given was some space at the end of the input string (which is equal to the length of the string). Struggled for an hour in that but didn’t reach the final answer.
Started with the introduction again.
Told me about the devTest role.
Create a function pointer, didn’t remember the syntax
Tell something about virtualization in C++, I couldn’t answer.
Wrote the code: char *ch = new char[10]; Asked about memory allocation in heap and stack. Create 10 character pointers.
Then asked a coding question: Count the number of consecutive letters and append the number to the character. Not allowed to use the map or any extra space. Manipulations had to be done on the input itself. The only extra space given was some space at the end of the input string (which is equal to the length of the string). Struggled for an hour in that but didn’t reach the final answer.
Input : “aaaabbbca”
Output : “a4b3c1a1”
HR Round:
Tell me about your experience in the past two days.What do you remember about us from yesterday’s presentation?Are you satisfied with your performance?Told about the role again in detail. (The devTest role)
Tell me about your experience in the past two days.
What do you remember about us from yesterday’s presentation?
Are you satisfied with your performance?
Told about the role again in detail. (The devTest role)
In about 2 hours they informed me through a call that I was selected. A total of 3 students got the internship and full-time offer.
Marketing
On-Campus
ZScaler
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1 (On-Campus)
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
Amazon Interview Experience for SDE-1
Directi Interview | Set 7 (Programming Questions)
Oracle Interview Experience | Set 69 (Application Engineer)
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1 | [
{
"code": null,
"e": 24979,
"s": 24951,
"text": "\n03 Sep, 2020"
},
{
"code": null,
"e": 25144,
"s": 24979,
"text": "Round 1: Online Test on Hackerrank. There were 20 MCQs of 1 marks each and 4 coding questions of total of 240 marks. MCQs were Networking, OS, and Linux/UNIX based."
},
{
"code": null,
"e": 25220,
"s": 25144,
"text": "Two coding questions were of 50 marks and two were 70. The questions were :"
},
{
"code": null,
"e": 26167,
"s": 25220,
"text": "You are given a binary array (with only 1s and 0s), and you are supposed to bring all the 1s to the right and all the 0s to the left, or vice-versa. The operation that can be performed is to swap two adjacent values, find the minimum number of operations needed.You start from the 0th position and at every step, you can choose to move I (i is the step number) steps forward or can remain in your position. There is a bad index in which you cannot stand. Find the maximum index you can reach in k steps after avoiding the bad Index.Given a list of names appended with roman numbers. First sort them with names, then with the numbers appended to them, in increasing order.A string question related to appending a string multiple times to get a given string. If we can make the first string by appending the second string multiple times, then we have to return the smallest string that will produce the second string by appending one or more times."
},
{
"code": null,
"e": 26430,
"s": 26167,
"text": "You are given a binary array (with only 1s and 0s), and you are supposed to bring all the 1s to the right and all the 0s to the left, or vice-versa. The operation that can be performed is to swap two adjacent values, find the minimum number of operations needed."
},
{
"code": null,
"e": 26701,
"s": 26430,
"text": "You start from the 0th position and at every step, you can choose to move I (i is the step number) steps forward or can remain in your position. There is a bad index in which you cannot stand. Find the maximum index you can reach in k steps after avoiding the bad Index."
},
{
"code": null,
"e": 26841,
"s": 26701,
"text": "Given a list of names appended with roman numbers. First sort them with names, then with the numbers appended to them, in increasing order."
},
{
"code": null,
"e": 27117,
"s": 26841,
"text": "A string question related to appending a string multiple times to get a given string. If we can make the first string by appending the second string multiple times, then we have to return the smallest string that will produce the second string by appending one or more times."
},
{
"code": null,
"e": 27168,
"s": 27117,
"text": "Out of around 430 students, only 12 were selected."
},
{
"code": null,
"e": 27191,
"s": 27168,
"text": "Technical Interview 1:"
},
{
"code": null,
"e": 27853,
"s": 27191,
"text": "Tell me about yourself.What is the complexity of quicksort and how to make it always nlog(n). He asked this question because I had a project on sorting visualization.Operating System Questions: What is virtualization (In terms of virtual memory). In a single-core system, 3 processes are running of size 526Mb each and the system memory is 1Gb. How is the os handling this? Question related to page replacement.Networking Questions: The process followed in DHCP protocol: Didn’t answer. Difference between TCP and UDP. What happens when you type www.google.com in your browser. What happens when you connect an Ethernet cable to your system. What is dynamic IP."
},
{
"code": null,
"e": 27877,
"s": 27853,
"text": "Tell me about yourself."
},
{
"code": null,
"e": 28021,
"s": 27877,
"text": "What is the complexity of quicksort and how to make it always nlog(n). He asked this question because I had a project on sorting visualization."
},
{
"code": null,
"e": 28267,
"s": 28021,
"text": "Operating System Questions: What is virtualization (In terms of virtual memory). In a single-core system, 3 processes are running of size 526Mb each and the system memory is 1Gb. How is the os handling this? Question related to page replacement."
},
{
"code": null,
"e": 28518,
"s": 28267,
"text": "Networking Questions: The process followed in DHCP protocol: Didn’t answer. Difference between TCP and UDP. What happens when you type www.google.com in your browser. What happens when you connect an Ethernet cable to your system. What is dynamic IP."
},
{
"code": null,
"e": 28556,
"s": 28518,
"text": "Then there were two coding questions:"
},
{
"code": null,
"e": 28786,
"s": 28556,
"text": "Given an array of size n and an integer k, find the maximum values of all the subarrays of size k.Evaluate an expression tree.Asked the third question, to tell the logic of forming the expression tree, but then the time was over."
},
{
"code": null,
"e": 28885,
"s": 28786,
"text": "Given an array of size n and an integer k, find the maximum values of all the subarrays of size k."
},
{
"code": null,
"e": 28914,
"s": 28885,
"text": "Evaluate an expression tree."
},
{
"code": null,
"e": 29018,
"s": 28914,
"text": "Asked the third question, to tell the logic of forming the expression tree, but then the time was over."
},
{
"code": null,
"e": 29042,
"s": 29018,
"text": "Technical Interview 2 :"
},
{
"code": null,
"e": 29930,
"s": 29042,
"text": "Again started with the introduction.Asked some questions about my project which I was working on (Online multiplayer game). What server you are using. Have you written some code for the login authentication? What database are you using? Why MongoDB instead of MySQL.Then asked a coding question: Given a comma-separated list of keys and some other comma-separated values in a vector of strings(like a CSV file), parse that and return a vector of the map with key-value pairs in it.Asked about child, parent, zombie process.Difference between thread and a process, I was confused and giving wrong answers, but he went on for around 10 mins.Then loaded a question from the first round (question with the badIndex), and told me to optimize my code, I was able to give the optimization in the case when we are calling the function multiple times(by storing all the results beforehand). "
},
{
"code": null,
"e": 29967,
"s": 29930,
"text": "Again started with the introduction."
},
{
"code": null,
"e": 30198,
"s": 29967,
"text": "Asked some questions about my project which I was working on (Online multiplayer game). What server you are using. Have you written some code for the login authentication? What database are you using? Why MongoDB instead of MySQL."
},
{
"code": null,
"e": 30414,
"s": 30198,
"text": "Then asked a coding question: Given a comma-separated list of keys and some other comma-separated values in a vector of strings(like a CSV file), parse that and return a vector of the map with key-value pairs in it."
},
{
"code": null,
"e": 30457,
"s": 30414,
"text": "Asked about child, parent, zombie process."
},
{
"code": null,
"e": 30574,
"s": 30457,
"text": "Difference between thread and a process, I was confused and giving wrong answers, but he went on for around 10 mins."
},
{
"code": null,
"e": 30823,
"s": 30574,
"text": "Then loaded a question from the first round (question with the badIndex), and told me to optimize my code, I was able to give the optimization in the case when we are calling the function multiple times(by storing all the results beforehand). "
},
{
"code": null,
"e": 30846,
"s": 30823,
"text": "Technical Interview 3:"
},
{
"code": null,
"e": 31538,
"s": 30846,
"text": "Started with the introduction again.Told me about the devTest role.Create a function pointer, didn’t remember the syntaxTell something about virtualization in C++, I couldn’t answer.Wrote the code: char *ch = new char[10]; Asked about memory allocation in heap and stack. Create 10 character pointers.Then asked a coding question: Count the number of consecutive letters and append the number to the character. Not allowed to use the map or any extra space. Manipulations had to be done on the input itself. The only extra space given was some space at the end of the input string (which is equal to the length of the string). Struggled for an hour in that but didn’t reach the final answer."
},
{
"code": null,
"e": 31575,
"s": 31538,
"text": "Started with the introduction again."
},
{
"code": null,
"e": 31607,
"s": 31575,
"text": "Told me about the devTest role."
},
{
"code": null,
"e": 31661,
"s": 31607,
"text": "Create a function pointer, didn’t remember the syntax"
},
{
"code": null,
"e": 31724,
"s": 31661,
"text": "Tell something about virtualization in C++, I couldn’t answer."
},
{
"code": null,
"e": 31844,
"s": 31724,
"text": "Wrote the code: char *ch = new char[10]; Asked about memory allocation in heap and stack. Create 10 character pointers."
},
{
"code": null,
"e": 32235,
"s": 31844,
"text": "Then asked a coding question: Count the number of consecutive letters and append the number to the character. Not allowed to use the map or any extra space. Manipulations had to be done on the input itself. The only extra space given was some space at the end of the input string (which is equal to the length of the string). Struggled for an hour in that but didn’t reach the final answer."
},
{
"code": null,
"e": 32275,
"s": 32235,
"text": "Input : “aaaabbbca”\nOutput : “a4b3c1a1”"
},
{
"code": null,
"e": 32285,
"s": 32275,
"text": "HR Round:"
},
{
"code": null,
"e": 32492,
"s": 32285,
"text": "Tell me about your experience in the past two days.What do you remember about us from yesterday’s presentation?Are you satisfied with your performance?Told about the role again in detail. (The devTest role)"
},
{
"code": null,
"e": 32544,
"s": 32492,
"text": "Tell me about your experience in the past two days."
},
{
"code": null,
"e": 32605,
"s": 32544,
"text": "What do you remember about us from yesterday’s presentation?"
},
{
"code": null,
"e": 32646,
"s": 32605,
"text": "Are you satisfied with your performance?"
},
{
"code": null,
"e": 32702,
"s": 32646,
"text": "Told about the role again in detail. (The devTest role)"
},
{
"code": null,
"e": 32834,
"s": 32702,
"text": "In about 2 hours they informed me through a call that I was selected. A total of 3 students got the internship and full-time offer."
},
{
"code": null,
"e": 32844,
"s": 32834,
"text": "Marketing"
},
{
"code": null,
"e": 32854,
"s": 32844,
"text": "On-Campus"
},
{
"code": null,
"e": 32862,
"s": 32854,
"text": "ZScaler"
},
{
"code": null,
"e": 32884,
"s": 32862,
"text": "Interview Experiences"
},
{
"code": null,
"e": 32982,
"s": 32884,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32991,
"s": 32982,
"text": "Comments"
},
{
"code": null,
"e": 33004,
"s": 32991,
"text": "Old Comments"
},
{
"code": null,
"e": 33063,
"s": 33004,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 33113,
"s": 33063,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 33185,
"s": 33113,
"text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022"
},
{
"code": null,
"e": 33223,
"s": 33185,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 33273,
"s": 33223,
"text": "Directi Interview | Set 7 (Programming Questions)"
},
{
"code": null,
"e": 33333,
"s": 33273,
"text": "Oracle Interview Experience | Set 69 (Application Engineer)"
},
{
"code": null,
"e": 33398,
"s": 33333,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 33448,
"s": 33398,
"text": "Amazon Interview Experience for SDE-1(Off-Campus)"
},
{
"code": null,
"e": 33494,
"s": 33448,
"text": "Amazon Interview Experience (Off-Campus) 2022"
}
] |
PHP 7 - Anonymous Classes | Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition.
<?php
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
print($msg);
}
});
$app->getLogger()->log("My first Log Message");
?>
It produces the following browser output −
My first Log Message
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2196,
"s": 2077,
"text": "Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition."
},
{
"code": null,
"e": 2710,
"s": 2196,
"text": "<?php\n interface Logger {\n public function log(string $msg);\n }\n\n class Application {\n private $logger;\n\n public function getLogger(): Logger {\n return $this->logger;\n }\n\n public function setLogger(Logger $logger) {\n $this->logger = $logger;\n } \n }\n\n $app = new Application;\n $app->setLogger(new class implements Logger {\n public function log(string $msg) {\n print($msg);\n }\n });\n\n $app->getLogger()->log(\"My first Log Message\");\n?>"
},
{
"code": null,
"e": 2753,
"s": 2710,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 2775,
"s": 2753,
"text": "My first Log Message\n"
},
{
"code": null,
"e": 2808,
"s": 2775,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 2824,
"s": 2808,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2857,
"s": 2824,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2868,
"s": 2857,
"text": " Syed Raza"
},
{
"code": null,
"e": 2903,
"s": 2868,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2920,
"s": 2903,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 2953,
"s": 2920,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2968,
"s": 2953,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 3003,
"s": 2968,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 3015,
"s": 3003,
"text": " Azaz Patel"
},
{
"code": null,
"e": 3050,
"s": 3015,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3078,
"s": 3050,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3085,
"s": 3078,
"text": " Print"
},
{
"code": null,
"e": 3096,
"s": 3085,
"text": " Add Notes"
}
] |
Batch Script - Functions with Parameters | Functions can work with parameters by simply passing them when a call is made to the function.
Call :function_name parameter1, parameter2... parametern
The parameters can then be accessed from within the function by using the tilde (~) character along with the positional number of the parameter.
Following example shows how a function can be called with parameters.
@echo off
SETLOCAL
CALL :Display 5 , 10
EXIT /B %ERRORLEVEL%
:Display
echo The value of parameter 1 is %~1
echo The value of parameter 2 is %~2
EXIT /B 0
As seen in the above example, ~1 is used to access the first parameter sent to the function, similarly ~2 is used to access the second parameter.
The above command produces the following output.
The value of parameter 1 is 5
The value of parameter 2 is 10
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2264,
"s": 2169,
"text": "Functions can work with parameters by simply passing them when a call is made to the function."
},
{
"code": null,
"e": 2322,
"s": 2264,
"text": "Call :function_name parameter1, parameter2... parametern\n"
},
{
"code": null,
"e": 2467,
"s": 2322,
"text": "The parameters can then be accessed from within the function by using the tilde (~) character along with the positional number of the parameter."
},
{
"code": null,
"e": 2537,
"s": 2467,
"text": "Following example shows how a function can be called with parameters."
},
{
"code": null,
"e": 2691,
"s": 2537,
"text": "@echo off\nSETLOCAL\nCALL :Display 5 , 10\nEXIT /B %ERRORLEVEL%\n:Display\necho The value of parameter 1 is %~1\necho The value of parameter 2 is %~2\nEXIT /B 0"
},
{
"code": null,
"e": 2837,
"s": 2691,
"text": "As seen in the above example, ~1 is used to access the first parameter sent to the function, similarly ~2 is used to access the second parameter."
},
{
"code": null,
"e": 2886,
"s": 2837,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2948,
"s": 2886,
"text": "The value of parameter 1 is 5\nThe value of parameter 2 is 10\n"
},
{
"code": null,
"e": 2955,
"s": 2948,
"text": " Print"
},
{
"code": null,
"e": 2966,
"s": 2955,
"text": " Add Notes"
}
] |
How to send a JSON object to a server using Javascript? - GeeksforGeeks | 17 Jan, 2022
JavaScript Object Notation (JSON). It is a lightweight data transferring format. It is very easy to understand by human as well as machine. It is commonly used to send data from or to server. Nowadays it is widely used in API integration because of its advantages and simplicity.In this example we are going to use AJAX (Asynchronous JavaScript And XML), to send data in background. We are using PHP for the backend.Frontend:
HTML:
In the frontend we are going to build a form which takes name and email as a input and converts it into JSON object using javascript and send it to the server. After clicking the submit button a sendJSON() is called which is defined below.
html
<!DOCTYPE html><html> <head> <title> JavaScript | Sending JSON data to server. </title> </head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> <!-- Making a text input --> <input type="text" id="name" placeholder="Your name"> <input type="email" id="email" placeholder="Email"> <!-- Button to send data --> <button onclick="sendJSON()">Send JSON</button> <!-- For printing result from server --> <p class="result" style="color:green"></p> </p> <!-- Include the JavaScript file --> <script src="index.js"></script> </body></html>
JavaScript: When sending data to a web server, the data has to be a string. So we are using JSON.stringify() function to convert data to string and send it via XHR request to the server. Below is the sample code.
javascript
function sendJSON(){ let result = document.querySelector('.result'); let name = document.querySelector('#name'); let email = document.querySelector('#email'); // Creating a XHR object let xhr = new XMLHttpRequest(); let url = "submit.php"; // open a connection xhr.open("POST", url, true); // Set the request header i.e. which type of content you are sending xhr.setRequestHeader("Content-Type", "application/json"); // Create a state change callback xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // Print received data from server result.innerHTML = this.responseText; } }; // Converting JSON data to string var data = JSON.stringify({ "name": name.value, "email": email.value }); // Sending data with the request xhr.send(data); }
Backend:
We are using PHP as a scripting language. Create a file named submit.php, in this file, we’ll decode the received data to JSON and return a sentence formed using the received data.
php
<?php header("Content-Type: application/json"); $data = json_decode(file_get_contents("php://input")); echo "Hello $data->name, your email is $data->email"; ?>
Now when you fill the details and press the Send JSON button you’ll see something like:
saurabh1990aror
JSON
Picked
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 37605,
"s": 37577,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 38033,
"s": 37605,
"text": "JavaScript Object Notation (JSON). It is a lightweight data transferring format. It is very easy to understand by human as well as machine. It is commonly used to send data from or to server. Nowadays it is widely used in API integration because of its advantages and simplicity.In this example we are going to use AJAX (Asynchronous JavaScript And XML), to send data in background. We are using PHP for the backend.Frontend: "
},
{
"code": null,
"e": 38041,
"s": 38033,
"text": "HTML: "
},
{
"code": null,
"e": 38283,
"s": 38041,
"text": "In the frontend we are going to build a form which takes name and email as a input and converts it into JSON object using javascript and send it to the server. After clicking the submit button a sendJSON() is called which is defined below. "
},
{
"code": null,
"e": 38290,
"s": 38285,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | Sending JSON data to server. </title> </head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> <!-- Making a text input --> <input type=\"text\" id=\"name\" placeholder=\"Your name\"> <input type=\"email\" id=\"email\" placeholder=\"Email\"> <!-- Button to send data --> <button onclick=\"sendJSON()\">Send JSON</button> <!-- For printing result from server --> <p class=\"result\" style=\"color:green\"></p> </p> <!-- Include the JavaScript file --> <script src=\"index.js\"></script> </body></html>",
"e": 38963,
"s": 38290,
"text": null
},
{
"code": null,
"e": 39178,
"s": 38963,
"text": "JavaScript: When sending data to a web server, the data has to be a string. So we are using JSON.stringify() function to convert data to string and send it via XHR request to the server. Below is the sample code. "
},
{
"code": null,
"e": 39189,
"s": 39178,
"text": "javascript"
},
{
"code": "function sendJSON(){ let result = document.querySelector('.result'); let name = document.querySelector('#name'); let email = document.querySelector('#email'); // Creating a XHR object let xhr = new XMLHttpRequest(); let url = \"submit.php\"; // open a connection xhr.open(\"POST\", url, true); // Set the request header i.e. which type of content you are sending xhr.setRequestHeader(\"Content-Type\", \"application/json\"); // Create a state change callback xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // Print received data from server result.innerHTML = this.responseText; } }; // Converting JSON data to string var data = JSON.stringify({ \"name\": name.value, \"email\": email.value }); // Sending data with the request xhr.send(data); }",
"e": 40268,
"s": 39189,
"text": null
},
{
"code": null,
"e": 40279,
"s": 40268,
"text": "Backend: "
},
{
"code": null,
"e": 40460,
"s": 40279,
"text": "We are using PHP as a scripting language. Create a file named submit.php, in this file, we’ll decode the received data to JSON and return a sentence formed using the received data."
},
{
"code": null,
"e": 40466,
"s": 40462,
"text": "php"
},
{
"code": "<?php header(\"Content-Type: application/json\"); $data = json_decode(file_get_contents(\"php://input\")); echo \"Hello $data->name, your email is $data->email\"; ?>",
"e": 40626,
"s": 40466,
"text": null
},
{
"code": null,
"e": 40716,
"s": 40626,
"text": "Now when you fill the details and press the Send JSON button you’ll see something like: "
},
{
"code": null,
"e": 40734,
"s": 40718,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 40739,
"s": 40734,
"text": "JSON"
},
{
"code": null,
"e": 40746,
"s": 40739,
"text": "Picked"
},
{
"code": null,
"e": 40763,
"s": 40746,
"text": "Web Technologies"
},
{
"code": null,
"e": 40790,
"s": 40763,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 40888,
"s": 40790,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40897,
"s": 40888,
"text": "Comments"
},
{
"code": null,
"e": 40910,
"s": 40897,
"text": "Old Comments"
},
{
"code": null,
"e": 40966,
"s": 40910,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 40999,
"s": 40966,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 41061,
"s": 40999,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 41104,
"s": 41061,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 41154,
"s": 41104,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 41187,
"s": 41154,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 41237,
"s": 41187,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 41297,
"s": 41237,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 41324,
"s": 41297,
"text": "File uploading in React.js"
}
] |
Creating a Snapchat-Style Filter with Python | by Andrew Udell | Towards Data Science | The introduction of augmented reality (AR) in smart phones ushered a novel approach to entertainment. From playing games like Pokémon Go to making funny faces on Snapchat, AR has become a commonplace phenomenon.
While these technologies seem advanced enough to borrow from science fiction, creating a fun, Snapchat-style filter in Python is surprisingly straightforward. In this instance, I’ll create a filter that places a pair of sunglasses on a face.
This filter, as with any AR, relies on two fundamental steps. First, it must determine where in the video frame to project an image. In this example, whatever algorithm I use must correctly identify the location of my eyes. Second, it must transform the projected image so that it’s proportional to the rest of the video frame. In this case, the image is a pair of sunglasses which must fit on a pair of eyes when projected.
While both of these challenges sound daunting, Python’s implementation to OpenCV make it fairly easy.
The first challenge to overcome is to detect a pair of eyes. The topic of facial detection and facial landmark detection are both huge topics within computer vision with many unique approaches, but this method will use Haar Cascades.
First introduced in a paper in 2001 by Paul Viola and Michael Jones, Haar Cascades are a generalized supervised machine learning technique designed specifically for quick facial detection. Instead of training from scratch, however, OpenCV provides a number of pre-built models, including face and eye detection.
The second challenge is to transform a projected image to ensure that its proportional to the face. Homography, which concerns itself with isomorphism in projected spaces, offers a solution. While the concept itself sound scary, we’ll use it to project the sunglasses onto the video frame so that it appears natural.
Obviously, both Haar Cascades and Homorgraphy are deep concepts whose details go beyond the scope of this article, but a basic understanding of what they are and what they do will help understand the code implementation.
import numpy as npimport cv2# Import the pre-trained models for face and eye detectionface_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")eye_cascade = cv2.CascadeClassifier("haarcascade_eye.xml")
Before doing much, NumPy is imported for efficient numerical calculation and OpenCV is imported for image processing.
Next, OpenCV’s built-in cascade classifier method is called. Nothing is classified, yet, but this serves to initialize the models that will be used. The XML files passed as their arguments are actually pre-trained models that specialize in detecting a frontal view of a face and eyes specifically.
These pre-trained models come built-in with OpenCV, but can be downloaded separately here. Please note, however, that these pre-trained models are licensed to Intel and may have restrictions for use.
# Global variable to cache the location of eyeseye_cache = None
A global variable is declared to create a cache. This is done for two reasons:
The Haar Cascades classifier will not be able to identify the eyes in every single frame, which will create a flickering effect. By using a cache, however, the program can refer to the location of the eyes from the last successful identification and place the glasses accordingly. This will remove the flickering and make the program run more smoothly.Sometimes the Haar Cascades will falsely identify more than two eyes, which will mess up glasses placement. Like before, using the cache, this can be corrected by referring to a previous location of the eyes.
The Haar Cascades classifier will not be able to identify the eyes in every single frame, which will create a flickering effect. By using a cache, however, the program can refer to the location of the eyes from the last successful identification and place the glasses accordingly. This will remove the flickering and make the program run more smoothly.
Sometimes the Haar Cascades will falsely identify more than two eyes, which will mess up glasses placement. Like before, using the cache, this can be corrected by referring to a previous location of the eyes.
While this makes the program run smoother, it comes at a cost. By continually referring to the location of the eyes in previous frames, the position of the glasses can lag. For somebody sitting calmly or even swaying slowly, the effect isn’t very noticeable, but a quickly moving face will see the impact.
# Capture video from the local cameracap = cv2.VideoCapture(0)while True: # Read the frame ret, frame = cap.read() # Check to make sure camera loaded the image correctly if not ret: break
This first line captures video. Note that passing 0 will use the 0th camera on the computer. If multiple are used, then passing any integer will use the nth camera.
Additionally, if a pre-recorded video needs to be used instead, then passing a string to the video’s location will also work.
Next, a infinite loop is initialized and the data from the camera is read. The variable “ret” is simply a boolean that denotes if video was actually captured from the camera and “frame” is the current frame from the camera. If “ret” is false, the loop will break.
# Convert to grayscale gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect faces faces = face_cascade.detectMultiScale(gray_frame, 1.3, 5)
The frame is converted into grayscale and then passed into the Haar Cascades to detect any face. The face is detected before the eye, because any eye detected should be located within the face. If an eye is located outside the face, then either something is wrong, such as a false positive, or something is very wrong.
The method called to detect faces will return a matrix of faces with their own (x, y)-coordinates and the width and height.
for (x, y, w, h) in faces: # Draw a rectangle around the face roi_gray = gray_frame[y:y+h, x:x+w] # Detect eyes within the grayscale region of interest eyes = eye_cascade.detectMultiScale(roi_gray)
For every face found, a subsection of the video frame is taken and called the region of interest. This region of interest is then passed through the Haar Cascades classifier that specializes in eyes. With the eyes detected, the next steps can be processed.
# Only detect 2 eyes if len(eyes) == 2: # Store the position of the eyes in cache eye_cache = eyes # If 2 eyes aren't detected, use the eye cache elif eye_cache is not None: eyes = eye_cach
As mentioned previously, if the eyes aren’t detected or more than two eyes are detected, the cache will be used instead. If two eyes are detected as expected, the cache is updated accordingly.
To project the image of the sunglasses onto the video frame so that they’re proportional, two things are needed: the (x, y)-coordinates of the sunglasses and the (x, y)-coordinates of where they’ll be projected onto the video frame. Both will be organized into simple matrices. The former will be source matrix, because it is the source of the image, and the latter will be the destination matrix, because its the destination of image.
Once both matrices are developed, a third, homography matrix, will be calculated, which gives directions on how to “stretch” the image of the sunglasses so that it fits around a pair of eyes.
# read the image and get its dimensions img = cv2.imread("glasses_transparent.png", -1) img_h = img.shape[0] img_w = img.shape[1] # Create source matrix src_mat = np.array([[0,0], [img_w, 0], [img_w, img_h], [0, img_h]])
To start, the image of the sunglasses is read into memory. Normally, images have three channels: red, green, and blue. These denote the default color space; however, some images have a fourth channel, called the alpha channel, which denotes transparency.
When I drew the pair of sunglasses, I ensured it contained a transparent background. Normally, OpenCV would ignore this, but by passing -1 into the imread method, it reads this fourth channel.
After reading the image, the dimensions are noted and the source matrix is composed of the coordinates of the top-left corner, top-right corner, bottom-right corner, and the bottom-left corner. The matrix must be in this order!
# define the destination matrix based on eye detected order. # Order of points must be top-left, top-right, bottom-left, # and bottom-right if eyes[0][0] < eyes[1][0]: dst_mat = np.array([ [x + eyes[0][0], y + eyes[0][1]], [x + eyes[1][0] + eyes[1][2], y + eyes[1][2]], [x + eyes[1][0] + eyes[1][2], y + eyes[1][1] + eyes[1][3]], [x + eyes[0][0], y + eyes[0][1] + eyes[0][3]] ]) else: dst_mat = np.array([ [x + eyes[1][0], y + eyes[1][1]], [x + eyes[0][0] + eyes[0][2], y + eyes[0][2]], [x + eyes[0][0] + eyes[0][2], y + eyes[0][1] + eyes[1][3]], [x + eyes[1][0], y + eyes[1][1] + eyes[1][3]] ])
This is where things get a little complicated. While the eyes are detected, there’s no way of knowing the order of the eyes in advance. Sometimes the right eye will be detected first and sometimes the left eye will. To test, the x-coordinate is compared between the two eyes, and then the proper destination matrix can be composed.
The destination matrix must contain the coordinates of the corners of the eyes in the same order as the source matrix. In other words, the (x, y)-coordinates of the top-left corner, top-right corner, bottom-right corner, and bottom-left corner.
Failing to do so will give unexpected results. In my first attempt, the glasses folded over themselves and looked like a graphical glitch.
# Get the dimensions of the frame face_h = frame.shape[0] face_w = frame.shape[1] # Find the Homography matrix hom = cv2.findHomography(src_mat, dst_mat)[0] # Warp the image to fit the homegraphy matrix warped = cv2.warpPerspective(img, hom, (face_w, face_h))
After quickly getting the dimensions of the video frame, the homography matrix is found using the built-in OpenCV method.
Next, the source image is warped, so now the glasses will be proportional to the face wearing them. Now the only thing left to do is project this warped image onto the video frame and display it.
# Grab the alpha channel of the warped image and create a mask mask = warped[:,:,3] # Copy and convert the mask to a float and give it 3 channels mask_scale = mask.copy() / 255.0 mask_scale = np.dstack([mask_scale] * 3) # Remove the alpha channel from the warped image warped = cv2.cvtColor(warped, cv2.COLOR_BGRA2BGR)
The mask for image will the alpha channel of the original image. A mask could also be created on a non-transparent image by using thresholding, but using a transparent image makes the process quicker and easier.
The mask is then normalized and then transformed into three channels so that it can multiplied against other matrices.
At this point, the alpha channel has served its purpose and keeping it will actually cause more problems than it solves. As a result, the final line converts the image back into a normal three channel image.
warped_multiplied = cv2.multiply(mask_scale, warped.astype("float")) image_multiplied = cv2.multiply(frame.astype(float), 1.0 - mask_scale) output = cv2.add(warped_multiplied, image_multiplied) output = output.astype("uint8")
The resulting mask is multiplied against the warped image, which will create a warped image on a “transparent” background. The video frame itself is then multiplied, which creates a gap in the image of where the glasses will be. These two images are added together and the result is a face wearing a pair of sunglasses.
cv2.imshow("SnapTalk", output) if cv2.waitKey(60) & 0xff == ord('q'): breakcap.release()cv2.destroyAllWindows()
Finally, the image is displayed. An exit condition is written so that when the “q” key is pressed it breaks the loop.
Once the loop is broken, the camera is turned off and any open windows are closed.
With any luck the final results will look something like this:
The program automatically and accurately detects my eyes and projects the glasses onto my face in real time. Even as I change my expression and move my head across the screen, the glasses follow without much issue.
Because I use cache to record the position of the glasses even when my eyes aren’t detected, the glasses remain on the screen. Consequently, I can do the trick of pretending to hold my glasses while I wipe eyes.
The glasses themselves tend to shift in size, which is a result of the Haar Cascades classifier. While it manages to find my eyes, it constantly changes the classified size. Paired with the flat image of the sunglasses, the composite looks comically cartoonish. Additional work, such as using a rolling average for the size of the glasses may accommodate for this, but it does create even more lag.
As the program runs, there is a noticeable lag when the subject moves quickly. As I shift around the screen, the glasses momentarily hover before the program finds my eyes again.
Compared to the previous demonstration, however, my movements are more rapid than a what a normal person might naturally do. Ideally, the program would find my eyes even at this speed, but it ultimately serves it purpose well enough.
While there are many tutorials and articles about face detection, using it for AR drives the possibilities of these technologies. In this article, the Haar cascades was used for eyes, but various other pre-trained model exist for different parts of the body which escalates the number of applications that might be used. Likewise, as a general machine learning technique, a custom Haar cascades may be trained and used on something not available, yet.
Paired with the novelty of AR, a simple Snapchat-style filter can be created. Homography provides a wonderful tool for projecting 2D items into video stills, producing a fun effect. | [
{
"code": null,
"e": 385,
"s": 172,
"text": "The introduction of augmented reality (AR) in smart phones ushered a novel approach to entertainment. From playing games like Pokémon Go to making funny faces on Snapchat, AR has become a commonplace phenomenon."
},
{
"code": null,
"e": 627,
"s": 385,
"text": "While these technologies seem advanced enough to borrow from science fiction, creating a fun, Snapchat-style filter in Python is surprisingly straightforward. In this instance, I’ll create a filter that places a pair of sunglasses on a face."
},
{
"code": null,
"e": 1052,
"s": 627,
"text": "This filter, as with any AR, relies on two fundamental steps. First, it must determine where in the video frame to project an image. In this example, whatever algorithm I use must correctly identify the location of my eyes. Second, it must transform the projected image so that it’s proportional to the rest of the video frame. In this case, the image is a pair of sunglasses which must fit on a pair of eyes when projected."
},
{
"code": null,
"e": 1154,
"s": 1052,
"text": "While both of these challenges sound daunting, Python’s implementation to OpenCV make it fairly easy."
},
{
"code": null,
"e": 1388,
"s": 1154,
"text": "The first challenge to overcome is to detect a pair of eyes. The topic of facial detection and facial landmark detection are both huge topics within computer vision with many unique approaches, but this method will use Haar Cascades."
},
{
"code": null,
"e": 1700,
"s": 1388,
"text": "First introduced in a paper in 2001 by Paul Viola and Michael Jones, Haar Cascades are a generalized supervised machine learning technique designed specifically for quick facial detection. Instead of training from scratch, however, OpenCV provides a number of pre-built models, including face and eye detection."
},
{
"code": null,
"e": 2017,
"s": 1700,
"text": "The second challenge is to transform a projected image to ensure that its proportional to the face. Homography, which concerns itself with isomorphism in projected spaces, offers a solution. While the concept itself sound scary, we’ll use it to project the sunglasses onto the video frame so that it appears natural."
},
{
"code": null,
"e": 2238,
"s": 2017,
"text": "Obviously, both Haar Cascades and Homorgraphy are deep concepts whose details go beyond the scope of this article, but a basic understanding of what they are and what they do will help understand the code implementation."
},
{
"code": null,
"e": 2458,
"s": 2238,
"text": "import numpy as npimport cv2# Import the pre-trained models for face and eye detectionface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")eye_cascade = cv2.CascadeClassifier(\"haarcascade_eye.xml\")"
},
{
"code": null,
"e": 2576,
"s": 2458,
"text": "Before doing much, NumPy is imported for efficient numerical calculation and OpenCV is imported for image processing."
},
{
"code": null,
"e": 2874,
"s": 2576,
"text": "Next, OpenCV’s built-in cascade classifier method is called. Nothing is classified, yet, but this serves to initialize the models that will be used. The XML files passed as their arguments are actually pre-trained models that specialize in detecting a frontal view of a face and eyes specifically."
},
{
"code": null,
"e": 3074,
"s": 2874,
"text": "These pre-trained models come built-in with OpenCV, but can be downloaded separately here. Please note, however, that these pre-trained models are licensed to Intel and may have restrictions for use."
},
{
"code": null,
"e": 3138,
"s": 3074,
"text": "# Global variable to cache the location of eyeseye_cache = None"
},
{
"code": null,
"e": 3217,
"s": 3138,
"text": "A global variable is declared to create a cache. This is done for two reasons:"
},
{
"code": null,
"e": 3778,
"s": 3217,
"text": "The Haar Cascades classifier will not be able to identify the eyes in every single frame, which will create a flickering effect. By using a cache, however, the program can refer to the location of the eyes from the last successful identification and place the glasses accordingly. This will remove the flickering and make the program run more smoothly.Sometimes the Haar Cascades will falsely identify more than two eyes, which will mess up glasses placement. Like before, using the cache, this can be corrected by referring to a previous location of the eyes."
},
{
"code": null,
"e": 4131,
"s": 3778,
"text": "The Haar Cascades classifier will not be able to identify the eyes in every single frame, which will create a flickering effect. By using a cache, however, the program can refer to the location of the eyes from the last successful identification and place the glasses accordingly. This will remove the flickering and make the program run more smoothly."
},
{
"code": null,
"e": 4340,
"s": 4131,
"text": "Sometimes the Haar Cascades will falsely identify more than two eyes, which will mess up glasses placement. Like before, using the cache, this can be corrected by referring to a previous location of the eyes."
},
{
"code": null,
"e": 4646,
"s": 4340,
"text": "While this makes the program run smoother, it comes at a cost. By continually referring to the location of the eyes in previous frames, the position of the glasses can lag. For somebody sitting calmly or even swaying slowly, the effect isn’t very noticeable, but a quickly moving face will see the impact."
},
{
"code": null,
"e": 4857,
"s": 4646,
"text": "# Capture video from the local cameracap = cv2.VideoCapture(0)while True: # Read the frame ret, frame = cap.read() # Check to make sure camera loaded the image correctly if not ret: break"
},
{
"code": null,
"e": 5022,
"s": 4857,
"text": "This first line captures video. Note that passing 0 will use the 0th camera on the computer. If multiple are used, then passing any integer will use the nth camera."
},
{
"code": null,
"e": 5148,
"s": 5022,
"text": "Additionally, if a pre-recorded video needs to be used instead, then passing a string to the video’s location will also work."
},
{
"code": null,
"e": 5412,
"s": 5148,
"text": "Next, a infinite loop is initialized and the data from the camera is read. The variable “ret” is simply a boolean that denotes if video was actually captured from the camera and “frame” is the current frame from the camera. If “ret” is false, the loop will break."
},
{
"code": null,
"e": 5574,
"s": 5412,
"text": " # Convert to grayscale gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect faces faces = face_cascade.detectMultiScale(gray_frame, 1.3, 5)"
},
{
"code": null,
"e": 5893,
"s": 5574,
"text": "The frame is converted into grayscale and then passed into the Haar Cascades to detect any face. The face is detected before the eye, because any eye detected should be located within the face. If an eye is located outside the face, then either something is wrong, such as a false positive, or something is very wrong."
},
{
"code": null,
"e": 6017,
"s": 5893,
"text": "The method called to detect faces will return a matrix of faces with their own (x, y)-coordinates and the width and height."
},
{
"code": null,
"e": 6247,
"s": 6017,
"text": " for (x, y, w, h) in faces: # Draw a rectangle around the face roi_gray = gray_frame[y:y+h, x:x+w] # Detect eyes within the grayscale region of interest eyes = eye_cascade.detectMultiScale(roi_gray)"
},
{
"code": null,
"e": 6504,
"s": 6247,
"text": "For every face found, a subsection of the video frame is taken and called the region of interest. This region of interest is then passed through the Haar Cascades classifier that specializes in eyes. With the eyes detected, the next steps can be processed."
},
{
"code": null,
"e": 6756,
"s": 6504,
"text": " # Only detect 2 eyes if len(eyes) == 2: # Store the position of the eyes in cache eye_cache = eyes # If 2 eyes aren't detected, use the eye cache elif eye_cache is not None: eyes = eye_cach"
},
{
"code": null,
"e": 6949,
"s": 6756,
"text": "As mentioned previously, if the eyes aren’t detected or more than two eyes are detected, the cache will be used instead. If two eyes are detected as expected, the cache is updated accordingly."
},
{
"code": null,
"e": 7385,
"s": 6949,
"text": "To project the image of the sunglasses onto the video frame so that they’re proportional, two things are needed: the (x, y)-coordinates of the sunglasses and the (x, y)-coordinates of where they’ll be projected onto the video frame. Both will be organized into simple matrices. The former will be source matrix, because it is the source of the image, and the latter will be the destination matrix, because its the destination of image."
},
{
"code": null,
"e": 7577,
"s": 7385,
"text": "Once both matrices are developed, a third, homography matrix, will be calculated, which gives directions on how to “stretch” the image of the sunglasses so that it fits around a pair of eyes."
},
{
"code": null,
"e": 7818,
"s": 7577,
"text": " # read the image and get its dimensions img = cv2.imread(\"glasses_transparent.png\", -1) img_h = img.shape[0] img_w = img.shape[1] # Create source matrix src_mat = np.array([[0,0], [img_w, 0], [img_w, img_h], [0, img_h]])"
},
{
"code": null,
"e": 8073,
"s": 7818,
"text": "To start, the image of the sunglasses is read into memory. Normally, images have three channels: red, green, and blue. These denote the default color space; however, some images have a fourth channel, called the alpha channel, which denotes transparency."
},
{
"code": null,
"e": 8266,
"s": 8073,
"text": "When I drew the pair of sunglasses, I ensured it contained a transparent background. Normally, OpenCV would ignore this, but by passing -1 into the imread method, it reads this fourth channel."
},
{
"code": null,
"e": 8494,
"s": 8266,
"text": "After reading the image, the dimensions are noted and the source matrix is composed of the coordinates of the top-left corner, top-right corner, bottom-right corner, and the bottom-left corner. The matrix must be in this order!"
},
{
"code": null,
"e": 9290,
"s": 8494,
"text": " # define the destination matrix based on eye detected order. # Order of points must be top-left, top-right, bottom-left, # and bottom-right if eyes[0][0] < eyes[1][0]: dst_mat = np.array([ [x + eyes[0][0], y + eyes[0][1]], [x + eyes[1][0] + eyes[1][2], y + eyes[1][2]], [x + eyes[1][0] + eyes[1][2], y + eyes[1][1] + eyes[1][3]], [x + eyes[0][0], y + eyes[0][1] + eyes[0][3]] ]) else: dst_mat = np.array([ [x + eyes[1][0], y + eyes[1][1]], [x + eyes[0][0] + eyes[0][2], y + eyes[0][2]], [x + eyes[0][0] + eyes[0][2], y + eyes[0][1] + eyes[1][3]], [x + eyes[1][0], y + eyes[1][1] + eyes[1][3]] ])"
},
{
"code": null,
"e": 9622,
"s": 9290,
"text": "This is where things get a little complicated. While the eyes are detected, there’s no way of knowing the order of the eyes in advance. Sometimes the right eye will be detected first and sometimes the left eye will. To test, the x-coordinate is compared between the two eyes, and then the proper destination matrix can be composed."
},
{
"code": null,
"e": 9867,
"s": 9622,
"text": "The destination matrix must contain the coordinates of the corners of the eyes in the same order as the source matrix. In other words, the (x, y)-coordinates of the top-left corner, top-right corner, bottom-right corner, and bottom-left corner."
},
{
"code": null,
"e": 10006,
"s": 9867,
"text": "Failing to do so will give unexpected results. In my first attempt, the glasses folded over themselves and looked like a graphical glitch."
},
{
"code": null,
"e": 10288,
"s": 10006,
"text": " # Get the dimensions of the frame face_h = frame.shape[0] face_w = frame.shape[1] # Find the Homography matrix hom = cv2.findHomography(src_mat, dst_mat)[0] # Warp the image to fit the homegraphy matrix warped = cv2.warpPerspective(img, hom, (face_w, face_h))"
},
{
"code": null,
"e": 10410,
"s": 10288,
"text": "After quickly getting the dimensions of the video frame, the homography matrix is found using the built-in OpenCV method."
},
{
"code": null,
"e": 10606,
"s": 10410,
"text": "Next, the source image is warped, so now the glasses will be proportional to the face wearing them. Now the only thing left to do is project this warped image onto the video frame and display it."
},
{
"code": null,
"e": 10947,
"s": 10606,
"text": " # Grab the alpha channel of the warped image and create a mask mask = warped[:,:,3] # Copy and convert the mask to a float and give it 3 channels mask_scale = mask.copy() / 255.0 mask_scale = np.dstack([mask_scale] * 3) # Remove the alpha channel from the warped image warped = cv2.cvtColor(warped, cv2.COLOR_BGRA2BGR)"
},
{
"code": null,
"e": 11159,
"s": 10947,
"text": "The mask for image will the alpha channel of the original image. A mask could also be created on a non-transparent image by using thresholding, but using a transparent image makes the process quicker and easier."
},
{
"code": null,
"e": 11278,
"s": 11159,
"text": "The mask is then normalized and then transformed into three channels so that it can multiplied against other matrices."
},
{
"code": null,
"e": 11486,
"s": 11278,
"text": "At this point, the alpha channel has served its purpose and keeping it will actually cause more problems than it solves. As a result, the final line converts the image back into a normal three channel image."
},
{
"code": null,
"e": 11729,
"s": 11486,
"text": " warped_multiplied = cv2.multiply(mask_scale, warped.astype(\"float\")) image_multiplied = cv2.multiply(frame.astype(float), 1.0 - mask_scale) output = cv2.add(warped_multiplied, image_multiplied) output = output.astype(\"uint8\")"
},
{
"code": null,
"e": 12049,
"s": 11729,
"text": "The resulting mask is multiplied against the warped image, which will create a warped image on a “transparent” background. The video frame itself is then multiplied, which creates a gap in the image of where the glasses will be. These two images are added together and the result is a face wearing a pair of sunglasses."
},
{
"code": null,
"e": 12179,
"s": 12049,
"text": " cv2.imshow(\"SnapTalk\", output) if cv2.waitKey(60) & 0xff == ord('q'): breakcap.release()cv2.destroyAllWindows()"
},
{
"code": null,
"e": 12297,
"s": 12179,
"text": "Finally, the image is displayed. An exit condition is written so that when the “q” key is pressed it breaks the loop."
},
{
"code": null,
"e": 12380,
"s": 12297,
"text": "Once the loop is broken, the camera is turned off and any open windows are closed."
},
{
"code": null,
"e": 12443,
"s": 12380,
"text": "With any luck the final results will look something like this:"
},
{
"code": null,
"e": 12658,
"s": 12443,
"text": "The program automatically and accurately detects my eyes and projects the glasses onto my face in real time. Even as I change my expression and move my head across the screen, the glasses follow without much issue."
},
{
"code": null,
"e": 12870,
"s": 12658,
"text": "Because I use cache to record the position of the glasses even when my eyes aren’t detected, the glasses remain on the screen. Consequently, I can do the trick of pretending to hold my glasses while I wipe eyes."
},
{
"code": null,
"e": 13269,
"s": 12870,
"text": "The glasses themselves tend to shift in size, which is a result of the Haar Cascades classifier. While it manages to find my eyes, it constantly changes the classified size. Paired with the flat image of the sunglasses, the composite looks comically cartoonish. Additional work, such as using a rolling average for the size of the glasses may accommodate for this, but it does create even more lag."
},
{
"code": null,
"e": 13448,
"s": 13269,
"text": "As the program runs, there is a noticeable lag when the subject moves quickly. As I shift around the screen, the glasses momentarily hover before the program finds my eyes again."
},
{
"code": null,
"e": 13682,
"s": 13448,
"text": "Compared to the previous demonstration, however, my movements are more rapid than a what a normal person might naturally do. Ideally, the program would find my eyes even at this speed, but it ultimately serves it purpose well enough."
},
{
"code": null,
"e": 14134,
"s": 13682,
"text": "While there are many tutorials and articles about face detection, using it for AR drives the possibilities of these technologies. In this article, the Haar cascades was used for eyes, but various other pre-trained model exist for different parts of the body which escalates the number of applications that might be used. Likewise, as a general machine learning technique, a custom Haar cascades may be trained and used on something not available, yet."
}
] |
How to find if a column is auto_increment in MySQL? | To find if a column is auto_increment in MySQL, you can use the following syntax −
select COLUMN_NAME from information_schema.columns where
TABLE_SCHEMA='yourDatabaseName' and TABLE_NAME='yourTableName' and EXTRA
like '%auto_increment%';
Let us first create a table. Here, ClientId is set AUTO_INCREMENT −
mysql> create table autoIncrementTableDemo
-> (
-> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ClientName varchar(20),
-> ClientAge int,
-> ClientAddress varchar(100),
-> ClientCountryName varchar(100)
-> );
Query OK, 0 rows affected (0.61 sec)
Now, let us find whether any of the column is auto_increment −
mysql> select COLUMN_NAME from information_schema.columns where
TABLE_SCHEMA='test' and TABLE_NAME='autoIncrementTableDemo' and EXTRA like
'%auto_increment%';
Following is the output that gives the column i.e. auto_increment −
+-------------+
| COLUMN_NAME |
+-------------+
| ClientId |
+-------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To find if a column is auto_increment in MySQL, you can use the following syntax −"
},
{
"code": null,
"e": 1300,
"s": 1145,
"text": "select COLUMN_NAME from information_schema.columns where\nTABLE_SCHEMA='yourDatabaseName' and TABLE_NAME='yourTableName' and EXTRA\nlike '%auto_increment%';"
},
{
"code": null,
"e": 1368,
"s": 1300,
"text": "Let us first create a table. Here, ClientId is set AUTO_INCREMENT −"
},
{
"code": null,
"e": 1643,
"s": 1368,
"text": "mysql> create table autoIncrementTableDemo\n -> (\n -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> ClientName varchar(20),\n -> ClientAge int,\n -> ClientAddress varchar(100),\n -> ClientCountryName varchar(100)\n -> );\nQuery OK, 0 rows affected (0.61 sec)"
},
{
"code": null,
"e": 1706,
"s": 1643,
"text": "Now, let us find whether any of the column is auto_increment −"
},
{
"code": null,
"e": 1865,
"s": 1706,
"text": "mysql> select COLUMN_NAME from information_schema.columns where\nTABLE_SCHEMA='test' and TABLE_NAME='autoIncrementTableDemo' and EXTRA like\n'%auto_increment%';"
},
{
"code": null,
"e": 1933,
"s": 1865,
"text": "Following is the output that gives the column i.e. auto_increment −"
},
{
"code": null,
"e": 2037,
"s": 1933,
"text": "+-------------+\n| COLUMN_NAME |\n+-------------+\n| ClientId |\n+-------------+\n1 row in set (0.00 sec)"
}
] |
Node.js Process exit Event | 30 Jul, 2021
The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine.
The process.exit() method is the method that is used to end the Node.js process. Every process action on the machine or a program is an event. For every event, there is even a handler associated with the particular event that executes when we fire the particular event. To assign an event handler to the event we use the object.on() method in the node.js. In this article, we will discuss process exit event in Node.js
Syntax:
process.on("exit", callbackfunction)
Parameters: This method takes the following two parameters.
exit: It is the name of the emit event in the process.
callbackfunction: It is the event handler of the event.
Return Type: The return type of this method is void.
Example 1:
index.js
console.log("Starting of the process") // Binding the event to the eventhandlerprocess.on('exit',() => { console.log("process.exit() method is fired")}) console.log("Ending of the process") // Exiting the processprocess.exit()
Run index.js file using below command:
node index.js
Output:
Starting of the process
Ending of the process
process.exit() method is fired
Example 2: Creating process exit event handler inside the user-defined event handler.
index.js
// Importing events objectconst events = require("events") console.log("Starting of the process")const eventEmitter = new events.EventEmitter() // Initializinging event Handlervar Handler = function() { // Event handler of exit event process.on('exit', () => { console.log("process.exit() method is fired") })} // Bind the user defined event eventEmitter.on("hello",Handler) // Emit the eventeventEmitter.emit("hello") console.log("Ending of the process") // Exiting the processprocess.exit()
Run index.js file using below command:
node index.js
Output:
Starting of the process
Ending of the process
process.exit() method is fired
Reference:https://nodejs.org/api/process.html#process_event_exit
gabaa406
Node.js-process-module
Picked
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": "\n30 Jul, 2021"
},
{
"code": null,
"e": 215,
"s": 28,
"text": "The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine. "
},
{
"code": null,
"e": 634,
"s": 215,
"text": "The process.exit() method is the method that is used to end the Node.js process. Every process action on the machine or a program is an event. For every event, there is even a handler associated with the particular event that executes when we fire the particular event. To assign an event handler to the event we use the object.on() method in the node.js. In this article, we will discuss process exit event in Node.js"
},
{
"code": null,
"e": 642,
"s": 634,
"text": "Syntax:"
},
{
"code": null,
"e": 679,
"s": 642,
"text": "process.on(\"exit\", callbackfunction)"
},
{
"code": null,
"e": 739,
"s": 679,
"text": "Parameters: This method takes the following two parameters."
},
{
"code": null,
"e": 794,
"s": 739,
"text": "exit: It is the name of the emit event in the process."
},
{
"code": null,
"e": 850,
"s": 794,
"text": "callbackfunction: It is the event handler of the event."
},
{
"code": null,
"e": 903,
"s": 850,
"text": "Return Type: The return type of this method is void."
},
{
"code": null,
"e": 914,
"s": 903,
"text": "Example 1:"
},
{
"code": null,
"e": 923,
"s": 914,
"text": "index.js"
},
{
"code": "console.log(\"Starting of the process\") // Binding the event to the eventhandlerprocess.on('exit',() => { console.log(\"process.exit() method is fired\")}) console.log(\"Ending of the process\") // Exiting the processprocess.exit()",
"e": 1156,
"s": 923,
"text": null
},
{
"code": null,
"e": 1195,
"s": 1156,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 1209,
"s": 1195,
"text": "node index.js"
},
{
"code": null,
"e": 1217,
"s": 1209,
"text": "Output:"
},
{
"code": null,
"e": 1294,
"s": 1217,
"text": "Starting of the process\nEnding of the process\nprocess.exit() method is fired"
},
{
"code": null,
"e": 1380,
"s": 1294,
"text": "Example 2: Creating process exit event handler inside the user-defined event handler."
},
{
"code": null,
"e": 1389,
"s": 1380,
"text": "index.js"
},
{
"code": "// Importing events objectconst events = require(\"events\") console.log(\"Starting of the process\")const eventEmitter = new events.EventEmitter() // Initializinging event Handlervar Handler = function() { // Event handler of exit event process.on('exit', () => { console.log(\"process.exit() method is fired\") })} // Bind the user defined event eventEmitter.on(\"hello\",Handler) // Emit the eventeventEmitter.emit(\"hello\") console.log(\"Ending of the process\") // Exiting the processprocess.exit()",
"e": 1902,
"s": 1389,
"text": null
},
{
"code": null,
"e": 1941,
"s": 1902,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 1955,
"s": 1941,
"text": "node index.js"
},
{
"code": null,
"e": 1963,
"s": 1955,
"text": "Output:"
},
{
"code": null,
"e": 2040,
"s": 1963,
"text": "Starting of the process\nEnding of the process\nprocess.exit() method is fired"
},
{
"code": null,
"e": 2105,
"s": 2040,
"text": "Reference:https://nodejs.org/api/process.html#process_event_exit"
},
{
"code": null,
"e": 2114,
"s": 2105,
"text": "gabaa406"
},
{
"code": null,
"e": 2137,
"s": 2114,
"text": "Node.js-process-module"
},
{
"code": null,
"e": 2144,
"s": 2137,
"text": "Picked"
},
{
"code": null,
"e": 2152,
"s": 2144,
"text": "Node.js"
},
{
"code": null,
"e": 2169,
"s": 2152,
"text": "Web Technologies"
}
] |
Data Visualization with Python | 26 Apr, 2022
In today’s world, a lot of data is being generated on a daily basis. And sometimes to analyze this data for certain trends, patterns may become difficult if the data is in its raw format. To overcome this data visualization comes into play. Data visualization provides a good, organized pictorial representation of the data which makes it easier to understand, observe, analyze. In this tutorial, we will discuss how to visualize data using Python.
Python provides various libraries that come with different features for visualizing data. All these libraries come with different features and can support various types of graphs. In this tutorial, we will be discussing four such libraries.
Matplotlib
Seaborn
Bokeh
Plotly
We will discuss these libraries one by one and will plot some most commonly used graphs.
Note: If you want to learn in-depth information about these libraries you can follow their complete tutorial.
Before diving into these libraries, at first, we will need a database to plot the data. We will be using the tips database for this complete tutorial. Let’s discuss see a brief about this database.
Tips database is the record of the tip given by the customers in a restaurant for two and a half months in the early 1990s. It contains 6 columns such as total_bill, tip, sex, smoker, day, time, size.
You can download the tips database from here.
Example:
Python3
import pandas as pd # reading the databasedata = pd.read_csv("tips.csv") # printing the top 10 rowsdisplay(data.head(10))
Output:
Matplotlib is an easy-to-use, low-level data visualization library that is built on NumPy arrays. It consists of various plots like scatter plot, line plot, histogram, etc. Matplotlib provides a lot of flexibility.
To install this type the below command in the terminal.
pip install matplotlib
Refer to the below articles to get more information setting up an environment with Matplotlib.
Environment Setup for Matplotlib
Using Matplotlib with Jupyter Notebook
After installing Matplotlib, let’s see the most commonly used plots using this library.
Scatter plots are used to observe relationships between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot.
Example:
Python3
import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv("tips.csv") # Scatter plot with day against tipplt.scatter(data['day'], data['tip']) # Adding Title to the Plotplt.title("Scatter Plot") # Setting the X and Y labelsplt.xlabel('Day')plt.ylabel('Tip') plt.show()
Output:
This graph can be more meaningful if we can add colors and also change the size of the points. We can do this by using the c and s parameter respectively of the scatter function. We can also show the color bar using the colorbar() method.
Example:
Python3
import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv("tips.csv") # Scatter plot with day against tipplt.scatter(data['day'], data['tip'], c=data['size'], s=data['total_bill']) # Adding Title to the Plotplt.title("Scatter Plot") # Setting the X and Y labelsplt.xlabel('Day')plt.ylabel('Tip') plt.colorbar() plt.show()
Output:
Line Chart is used to represent a relationship between two data X and Y on a different axis. It is plotted using the plot() function. Let’s see the below example.
Example:
Python3
import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv("tips.csv") # Scatter plot with day against tipplt.plot(data['tip'])plt.plot(data['size']) # Adding Title to the Plotplt.title("Scatter Plot") # Setting the X and Y labelsplt.xlabel('Day')plt.ylabel('Tip') plt.show()
Output:
A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. It can be created using the bar() method.
Example:
Python3
import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv("tips.csv") # Bar chart with day against tipplt.bar(data['day'], data['tip']) plt.title("Bar Chart") # Setting the X and Y labelsplt.xlabel('Day')plt.ylabel('Tip') # Adding the legendsplt.show()
Output:
A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. The hist() function is used to compute and create a histogram. In histogram, if we pass categorical data then it will automatically compute the frequency of that data i.e. how often each value occurred.
Example:
Python3
import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv("tips.csv") # hostogram of total_billsplt.hist(data['total_bill']) plt.title("Histogram") # Adding the legendsplt.show()
Output:
Note: For complete Matplotlib Tutorial, refer Matplotlib Tutorial
Seaborn is a high-level interface built on top of the Matplotlib. It provides beautiful design styles and color palettes to make more attractive graphs.
To install seaborn type the below command in the terminal.
pip install seaborn
Seaborn is built on the top of Matplotlib, therefore it can be used with the Matplotlib as well. Using both Matplotlib and Seaborn together is a very simple process. We just have to invoke the Seaborn Plotting function as normal, and then we can use Matplotlib’s customization function.
Note: Seaborn comes loaded with dataset such as tips, iris, etc. but for the sake of this tutorial we will use Pandas for loading these datasets.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") # draw lineplotsns.lineplot(x="sex", y="total_bill", data=data) # setting the title using Matplotlibplt.title('Title using Matplotlib Function') plt.show()
Output:
Scatter plot is plotted using the scatterplot() method. This is similar to Matplotlib, but additional argument data is required.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") sns.scatterplot(x='day', y='tip', data=data,)plt.show()
Output:
You will find that while using Matplotlib it will a lot difficult if you want to color each point of this plot according to the sex. But in scatter plot it can be done with the help of hue argument.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") sns.scatterplot(x='day', y='tip', data=data, hue='sex')plt.show()
Output:
Line Plot in Seaborn plotted using the lineplot() method. In this, we can pass only the data argument also.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") sns.lineplot(x='day', y='tip', data=data)plt.show()
Output:
Example 2:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") # using only data attributesns.lineplot(data=data.drop(['total_bill'], axis=1))plt.show()
Output:
Bar Plot in Seaborn can be created using the barplot() method.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") sns.barplot(x='day',y='tip', data=data, hue='sex') plt.show()
Output:
The histogram in Seaborn can be plotted using the histplot() function.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") sns.histplot(x='total_bill', data=data, kde=True, hue='sex') plt.show()
Output:
After going through all these plots you must have noticed that customizing plots using Seaborn is a lot more easier than using Matplotlib. And it is also built over matplotlib then we can also use matplotlib functions while using Seaborn.
Note: For complete Seaborn Tutorial, refer Python Seaborn Tutorial
Let’s move on to the third library of our list. Bokeh is mainly famous for its interactive charts visualization. Bokeh renders its plots using HTML and JavaScript that uses modern web browsers for presenting elegant, concise construction of novel graphics with high-level interactivity.
To install this type the below command in the terminal.
pip install bokeh
Scatter Plot in Bokeh can be plotted using the scatter() method of the plotting module. Here pass the x and y coordinates respectively.
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, showfrom bokeh.palettes import magmaimport pandas as pd # instantiating the figure objectgraph = figure(title = "Bokeh Scatter Graph") # reading the databasedata = pd.read_csv("tips.csv") color = magma(256) # plotting the graphgraph.scatter(data['total_bill'], data['tip'], color=color) # displaying the modelshow(graph)
Output:
A line plot can be created using the line() method of the plotting module.
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, showimport pandas as pd # instantiating the figure objectgraph = figure(title = "Bokeh Bar Chart") # reading the databasedata = pd.read_csv("tips.csv") # Count of each unique value of# tip columndf = data['tip'].value_counts() # plotting the graphgraph.line(df, data['tip']) # displaying the modelshow(graph)
Output:
Bar Chart can be of two types horizontal bars and vertical bars. Each can be created using the hbar() and vbar() functions of the plotting interface respectively.
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, showimport pandas as pd # instantiating the figure objectgraph = figure(title = "Bokeh Bar Chart") # reading the databasedata = pd.read_csv("tips.csv") # plotting the graphgraph.vbar(data['total_bill'], top=data['tip']) # displaying the modelshow(graph)
Output:
One of the key features of Bokeh is to add interaction to the plots. Let’s see various interactions that can be added.
click_policy property makes the legend interactive. There are two types of interactivity –
Hiding: Hides the Glyphs.
Muting: Hiding the glyph makes it vanish completely, on the other hand, muting the glyph just de-emphasizes the glyph based on the parameters.
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, showimport pandas as pd # instantiating the figure objectgraph = figure(title = "Bokeh Bar Chart") # reading the databasedata = pd.read_csv("tips.csv") # plotting the graphgraph.vbar(data['total_bill'], top=data['tip'], legend_label = "Bill VS Tips", color='green') graph.vbar(data['tip'], top=data['size'], legend_label = "Tips VS Size", color='red') graph.legend.click_policy = "hide" # displaying the modelshow(graph)
Output:
Bokeh provides GUI features similar to HTML forms like buttons, sliders, checkboxes, etc. These provide an interactive interface to the plot that allows changing the parameters of the plot, modifying plot data, etc. Let’s see how to use and add some commonly used widgets.
Buttons: This widget adds a simple button widget to the plot. We have to pass a custom JavaScript function to the CustomJS() method of the models class.
CheckboxGroup: Adds a standard check box to the plot. Similarly to buttons we have to pass the custom JavaScript function to the CustomJS() method of the models class.
RadioGroup: Adds a simple radio button and accepts a custom JavaScript function.
Example:
Python3
from bokeh.io import showfrom bokeh.models import Button, CheckboxGroup, RadioGroup, CustomJS button = Button(label="GFG") button.js_on_click(CustomJS( code="console.log('button: click!', this.toString())")) # Labels for checkbox and radio# buttonsL = ["First", "Second", "Third"] # the active parameter sets checks the selected value# by defaultcheckbox_group = CheckboxGroup(labels=L, active=[0, 2]) checkbox_group.js_on_click(CustomJS(code=""" console.log('checkbox_group: active=' + this.active, this.toString())""")) # the active parameter sets checks the selected value# by defaultradio_group = RadioGroup(labels=L, active=1) radio_group.js_on_click(CustomJS(code=""" console.log('radio_group: active=' + this.active, this.toString())""")) show(button)show(checkbox_group)show(radio_group)
Output:
Note: All these buttons will be opened on a new tab.
Sliders: Adds a slider to the plot. It also needs a custom JavaScript function.
Example:
Python3
from bokeh.io import showfrom bokeh.models import CustomJS, Slider slider = Slider(start=1, end=20, value=1, step=2, title="Slider") slider.js_on_change("value", CustomJS(code=""" console.log('slider: value=' + this.value, this.toString())""")) show(slider)
Output:
Similarly, much more widgets are available like a dropdown menu or tabs widgets can be added.
Note: For complete Bokeh tutorial, refer Python Bokeh tutorial – Interactive Data Visualization with Bokeh
This is the last library of our list and you might be wondering why plotly. Here’s why –
Potly has hover tool capabilities that allow us to detect any outliers or anomalies in numerous data points.
It allows more customization.
It makes the graph visually more attractive.
To install it type the below command in the terminal.
pip install plotly
Scatter plot in Plotly can be created using the scatter() method of plotly.express. Like Seaborn, an extra data argument is also required here.
Example:
Python3
import plotly.express as pximport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") # plotting the scatter chartfig = px.scatter(data, x="day", y="tip", color='sex') # showing the plotfig.show()
Output:
Line plot in Plotly is much accessible and illustrious annexation to plotly which manage a variety of types of data and assemble easy-to-style statistic. With px.line each data position is represented as a vertex
Example:
Python3
import plotly.express as pximport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") # plotting the scatter chartfig = px.line(data, y='tip', color='sex') # showing the plotfig.show()
Output:
Bar Chart in Plotly can be created using the bar() method of plotly.express class.
Example:
Python3
import plotly.express as pximport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") # plotting the scatter chartfig = px.bar(data, x='day', y='tip', color='sex') # showing the plotfig.show()
Output:
In plotly, histograms can be created using the histogram() function of the plotly.express class.
Example:
Python3
import plotly.express as pximport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") # plotting the scatter chartfig = px.histogram(data, x='total_bill', color='sex') # showing the plotfig.show()
Output:
Just like Bokeh, plotly also provides various interactions. Let’s discuss a few of them.
Creating Dropdown Menu: A drop-down menu is a part of the menu-button which is displayed on a screen all the time. Every menu button is associated with a Menu widget that can display the choices for that menu button when clicked on it. In plotly, there are 4 possible methods to modify the charts by using updatemenu method.
restyle: modify data or data attributes
relayout: modify layout attributes
update: modify data and layout attributes
animate: start or pause an animation
Example:
Python3
import plotly.graph_objects as pximport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") plot = px.Figure(data=[px.Scatter( x=data['day'], y=data['tip'], mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict( buttons=list([ dict( args=["type", "scatter"], label="Scatter Plot", method="restyle" ), dict( args=["type", "bar"], label="Bar Chart", method="restyle" ) ]), direction="down", ), ]) plot.show()
Output:
Adding Buttons: In plotly, actions custom Buttons are used to quickly make actions directly from a record. Custom Buttons can be added to page layouts in CRM, Marketing, and Custom Apps. There are also 4 possible methods that can be applied in custom buttons:
restyle: modify data or data attributes
relayout: modify layout attributes
update: modify data and layout attributes
animate: start or pause an animation
Example:
Python3
import plotly.graph_objects as pximport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") plot = px.Figure(data=[px.Scatter( x=data['day'], y=data['tip'], mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict( type="buttons", direction="left", buttons=list([ dict( args=["type", "scatter"], label="Scatter Plot", method="restyle" ), dict( args=["type", "bar"], label="Bar Chart", method="restyle" ) ]), ), ]) plot.show()
Output:
Creating Sliders and Selectors:
In plotly, the range slider is a custom range-type input control. It allows selecting a value or a range of values between a specified minimum and maximum range. And the range selector is a tool for selecting ranges to display within the chart. It provides buttons to select pre-configured ranges in the chart. It also provides input boxes where the minimum and maximum dates can be manually input
Example:
Python3
import plotly.graph_objects as pximport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") plot = px.Figure(data=[px.Scatter( y=data['tip'], mode='lines',)]) plot.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, step="day", stepmode="backward"), ]) ), rangeslider=dict( visible=True ), )) plot.show()
Output:
Note: For complete Plotly tutorial, refer Python Plotly tutorial
In this tutorial, we have plotted the tips dataset with the help of the four different plotting modules of Python namely Matplotlib, Seaborn, Bokeh, and Plotly. Each module showed the plot in its own unique way and each one has its own set of features like Matplotlib provides more flexibility but at the cost of writing more code whereas Seaborn being a high-level language provides allows one to achieve the same goal with a small amount of code. Each module can be used depending on the task we want to do.
Data Visualization
data-science
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 Apr, 2022"
},
{
"code": null,
"e": 477,
"s": 28,
"text": "In today’s world, a lot of data is being generated on a daily basis. And sometimes to analyze this data for certain trends, patterns may become difficult if the data is in its raw format. To overcome this data visualization comes into play. Data visualization provides a good, organized pictorial representation of the data which makes it easier to understand, observe, analyze. In this tutorial, we will discuss how to visualize data using Python."
},
{
"code": null,
"e": 718,
"s": 477,
"text": "Python provides various libraries that come with different features for visualizing data. All these libraries come with different features and can support various types of graphs. In this tutorial, we will be discussing four such libraries."
},
{
"code": null,
"e": 729,
"s": 718,
"text": "Matplotlib"
},
{
"code": null,
"e": 737,
"s": 729,
"text": "Seaborn"
},
{
"code": null,
"e": 743,
"s": 737,
"text": "Bokeh"
},
{
"code": null,
"e": 750,
"s": 743,
"text": "Plotly"
},
{
"code": null,
"e": 840,
"s": 750,
"text": "We will discuss these libraries one by one and will plot some most commonly used graphs. "
},
{
"code": null,
"e": 950,
"s": 840,
"text": "Note: If you want to learn in-depth information about these libraries you can follow their complete tutorial."
},
{
"code": null,
"e": 1148,
"s": 950,
"text": "Before diving into these libraries, at first, we will need a database to plot the data. We will be using the tips database for this complete tutorial. Let’s discuss see a brief about this database."
},
{
"code": null,
"e": 1349,
"s": 1148,
"text": "Tips database is the record of the tip given by the customers in a restaurant for two and a half months in the early 1990s. It contains 6 columns such as total_bill, tip, sex, smoker, day, time, size."
},
{
"code": null,
"e": 1395,
"s": 1349,
"text": "You can download the tips database from here."
},
{
"code": null,
"e": 1404,
"s": 1395,
"text": "Example:"
},
{
"code": null,
"e": 1412,
"s": 1404,
"text": "Python3"
},
{
"code": "import pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") # printing the top 10 rowsdisplay(data.head(10))",
"e": 1538,
"s": 1412,
"text": null
},
{
"code": null,
"e": 1546,
"s": 1538,
"text": "Output:"
},
{
"code": null,
"e": 1762,
"s": 1546,
"text": "Matplotlib is an easy-to-use, low-level data visualization library that is built on NumPy arrays. It consists of various plots like scatter plot, line plot, histogram, etc. Matplotlib provides a lot of flexibility. "
},
{
"code": null,
"e": 1818,
"s": 1762,
"text": "To install this type the below command in the terminal."
},
{
"code": null,
"e": 1841,
"s": 1818,
"text": "pip install matplotlib"
},
{
"code": null,
"e": 1936,
"s": 1841,
"text": "Refer to the below articles to get more information setting up an environment with Matplotlib."
},
{
"code": null,
"e": 1969,
"s": 1936,
"text": "Environment Setup for Matplotlib"
},
{
"code": null,
"e": 2008,
"s": 1969,
"text": "Using Matplotlib with Jupyter Notebook"
},
{
"code": null,
"e": 2096,
"s": 2008,
"text": "After installing Matplotlib, let’s see the most commonly used plots using this library."
},
{
"code": null,
"e": 2299,
"s": 2096,
"text": "Scatter plots are used to observe relationships between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot."
},
{
"code": null,
"e": 2308,
"s": 2299,
"text": "Example:"
},
{
"code": null,
"e": 2316,
"s": 2308,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv(\"tips.csv\") # Scatter plot with day against tipplt.scatter(data['day'], data['tip']) # Adding Title to the Plotplt.title(\"Scatter Plot\") # Setting the X and Y labelsplt.xlabel('Day')plt.ylabel('Tip') plt.show()",
"e": 2626,
"s": 2316,
"text": null
},
{
"code": null,
"e": 2634,
"s": 2626,
"text": "Output:"
},
{
"code": null,
"e": 2873,
"s": 2634,
"text": "This graph can be more meaningful if we can add colors and also change the size of the points. We can do this by using the c and s parameter respectively of the scatter function. We can also show the color bar using the colorbar() method."
},
{
"code": null,
"e": 2882,
"s": 2873,
"text": "Example:"
},
{
"code": null,
"e": 2890,
"s": 2882,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv(\"tips.csv\") # Scatter plot with day against tipplt.scatter(data['day'], data['tip'], c=data['size'], s=data['total_bill']) # Adding Title to the Plotplt.title(\"Scatter Plot\") # Setting the X and Y labelsplt.xlabel('Day')plt.ylabel('Tip') plt.colorbar() plt.show()",
"e": 3266,
"s": 2890,
"text": null
},
{
"code": null,
"e": 3274,
"s": 3266,
"text": "Output:"
},
{
"code": null,
"e": 3437,
"s": 3274,
"text": "Line Chart is used to represent a relationship between two data X and Y on a different axis. It is plotted using the plot() function. Let’s see the below example."
},
{
"code": null,
"e": 3446,
"s": 3437,
"text": "Example:"
},
{
"code": null,
"e": 3454,
"s": 3446,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv(\"tips.csv\") # Scatter plot with day against tipplt.plot(data['tip'])plt.plot(data['size']) # Adding Title to the Plotplt.title(\"Scatter Plot\") # Setting the X and Y labelsplt.xlabel('Day')plt.ylabel('Tip') plt.show()",
"e": 3770,
"s": 3454,
"text": null
},
{
"code": null,
"e": 3778,
"s": 3770,
"text": "Output:"
},
{
"code": null,
"e": 3996,
"s": 3778,
"text": "A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. It can be created using the bar() method."
},
{
"code": null,
"e": 4005,
"s": 3996,
"text": "Example:"
},
{
"code": null,
"e": 4013,
"s": 4005,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv(\"tips.csv\") # Bar chart with day against tipplt.bar(data['day'], data['tip']) plt.title(\"Bar Chart\") # Setting the X and Y labelsplt.xlabel('Day')plt.ylabel('Tip') # Adding the legendsplt.show()",
"e": 4307,
"s": 4013,
"text": null
},
{
"code": null,
"e": 4315,
"s": 4307,
"text": "Output:"
},
{
"code": null,
"e": 4714,
"s": 4315,
"text": "A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. The hist() function is used to compute and create a histogram. In histogram, if we pass categorical data then it will automatically compute the frequency of that data i.e. how often each value occurred."
},
{
"code": null,
"e": 4723,
"s": 4714,
"text": "Example:"
},
{
"code": null,
"e": 4731,
"s": 4723,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as plt # reading the databasedata = pd.read_csv(\"tips.csv\") # hostogram of total_billsplt.hist(data['total_bill']) plt.title(\"Histogram\") # Adding the legendsplt.show()",
"e": 4950,
"s": 4731,
"text": null
},
{
"code": null,
"e": 4958,
"s": 4950,
"text": "Output:"
},
{
"code": null,
"e": 5024,
"s": 4958,
"text": "Note: For complete Matplotlib Tutorial, refer Matplotlib Tutorial"
},
{
"code": null,
"e": 5177,
"s": 5024,
"text": "Seaborn is a high-level interface built on top of the Matplotlib. It provides beautiful design styles and color palettes to make more attractive graphs."
},
{
"code": null,
"e": 5236,
"s": 5177,
"text": "To install seaborn type the below command in the terminal."
},
{
"code": null,
"e": 5256,
"s": 5236,
"text": "pip install seaborn"
},
{
"code": null,
"e": 5543,
"s": 5256,
"text": "Seaborn is built on the top of Matplotlib, therefore it can be used with the Matplotlib as well. Using both Matplotlib and Seaborn together is a very simple process. We just have to invoke the Seaborn Plotting function as normal, and then we can use Matplotlib’s customization function."
},
{
"code": null,
"e": 5689,
"s": 5543,
"text": "Note: Seaborn comes loaded with dataset such as tips, iris, etc. but for the sake of this tutorial we will use Pandas for loading these datasets."
},
{
"code": null,
"e": 5698,
"s": 5689,
"text": "Example:"
},
{
"code": null,
"e": 5706,
"s": 5698,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") # draw lineplotsns.lineplot(x=\"sex\", y=\"total_bill\", data=data) # setting the title using Matplotlibplt.title('Title using Matplotlib Function') plt.show()",
"e": 6013,
"s": 5706,
"text": null
},
{
"code": null,
"e": 6021,
"s": 6013,
"text": "Output:"
},
{
"code": null,
"e": 6150,
"s": 6021,
"text": "Scatter plot is plotted using the scatterplot() method. This is similar to Matplotlib, but additional argument data is required."
},
{
"code": null,
"e": 6159,
"s": 6150,
"text": "Example:"
},
{
"code": null,
"e": 6167,
"s": 6159,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") sns.scatterplot(x='day', y='tip', data=data,)plt.show()",
"e": 6370,
"s": 6167,
"text": null
},
{
"code": null,
"e": 6378,
"s": 6370,
"text": "Output:"
},
{
"code": null,
"e": 6577,
"s": 6378,
"text": "You will find that while using Matplotlib it will a lot difficult if you want to color each point of this plot according to the sex. But in scatter plot it can be done with the help of hue argument."
},
{
"code": null,
"e": 6586,
"s": 6577,
"text": "Example:"
},
{
"code": null,
"e": 6594,
"s": 6586,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") sns.scatterplot(x='day', y='tip', data=data, hue='sex')plt.show()",
"e": 6821,
"s": 6594,
"text": null
},
{
"code": null,
"e": 6829,
"s": 6821,
"text": "Output:"
},
{
"code": null,
"e": 6938,
"s": 6829,
"text": "Line Plot in Seaborn plotted using the lineplot() method. In this, we can pass only the data argument also."
},
{
"code": null,
"e": 6947,
"s": 6938,
"text": "Example:"
},
{
"code": null,
"e": 6955,
"s": 6947,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") sns.lineplot(x='day', y='tip', data=data)plt.show()",
"e": 7156,
"s": 6955,
"text": null
},
{
"code": null,
"e": 7164,
"s": 7156,
"text": "Output:"
},
{
"code": null,
"e": 7175,
"s": 7164,
"text": "Example 2:"
},
{
"code": null,
"e": 7183,
"s": 7175,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") # using only data attributesns.lineplot(data=data.drop(['total_bill'], axis=1))plt.show()",
"e": 7422,
"s": 7183,
"text": null
},
{
"code": null,
"e": 7430,
"s": 7422,
"text": "Output:"
},
{
"code": null,
"e": 7493,
"s": 7430,
"text": "Bar Plot in Seaborn can be created using the barplot() method."
},
{
"code": null,
"e": 7502,
"s": 7493,
"text": "Example:"
},
{
"code": null,
"e": 7510,
"s": 7502,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") sns.barplot(x='day',y='tip', data=data, hue='sex') plt.show()",
"e": 7734,
"s": 7510,
"text": null
},
{
"code": null,
"e": 7742,
"s": 7734,
"text": "Output:"
},
{
"code": null,
"e": 7813,
"s": 7742,
"text": "The histogram in Seaborn can be plotted using the histplot() function."
},
{
"code": null,
"e": 7822,
"s": 7813,
"text": "Example:"
},
{
"code": null,
"e": 7830,
"s": 7822,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") sns.histplot(x='total_bill', data=data, kde=True, hue='sex') plt.show()",
"e": 8052,
"s": 7830,
"text": null
},
{
"code": null,
"e": 8060,
"s": 8052,
"text": "Output:"
},
{
"code": null,
"e": 8299,
"s": 8060,
"text": "After going through all these plots you must have noticed that customizing plots using Seaborn is a lot more easier than using Matplotlib. And it is also built over matplotlib then we can also use matplotlib functions while using Seaborn."
},
{
"code": null,
"e": 8366,
"s": 8299,
"text": "Note: For complete Seaborn Tutorial, refer Python Seaborn Tutorial"
},
{
"code": null,
"e": 8654,
"s": 8366,
"text": "Let’s move on to the third library of our list. Bokeh is mainly famous for its interactive charts visualization. Bokeh renders its plots using HTML and JavaScript that uses modern web browsers for presenting elegant, concise construction of novel graphics with high-level interactivity. "
},
{
"code": null,
"e": 8710,
"s": 8654,
"text": "To install this type the below command in the terminal."
},
{
"code": null,
"e": 8728,
"s": 8710,
"text": "pip install bokeh"
},
{
"code": null,
"e": 8864,
"s": 8728,
"text": "Scatter Plot in Bokeh can be plotted using the scatter() method of the plotting module. Here pass the x and y coordinates respectively."
},
{
"code": null,
"e": 8873,
"s": 8864,
"text": "Example:"
},
{
"code": null,
"e": 8881,
"s": 8873,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, showfrom bokeh.palettes import magmaimport pandas as pd # instantiating the figure objectgraph = figure(title = \"Bokeh Scatter Graph\") # reading the databasedata = pd.read_csv(\"tips.csv\") color = magma(256) # plotting the graphgraph.scatter(data['total_bill'], data['tip'], color=color) # displaying the modelshow(graph)",
"e": 9280,
"s": 8881,
"text": null
},
{
"code": null,
"e": 9288,
"s": 9280,
"text": "Output:"
},
{
"code": null,
"e": 9364,
"s": 9288,
"text": " A line plot can be created using the line() method of the plotting module."
},
{
"code": null,
"e": 9373,
"s": 9364,
"text": "Example:"
},
{
"code": null,
"e": 9381,
"s": 9373,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, showimport pandas as pd # instantiating the figure objectgraph = figure(title = \"Bokeh Bar Chart\") # reading the databasedata = pd.read_csv(\"tips.csv\") # Count of each unique value of# tip columndf = data['tip'].value_counts() # plotting the graphgraph.line(df, data['tip']) # displaying the modelshow(graph)",
"e": 9768,
"s": 9381,
"text": null
},
{
"code": null,
"e": 9776,
"s": 9768,
"text": "Output:"
},
{
"code": null,
"e": 9939,
"s": 9776,
"text": "Bar Chart can be of two types horizontal bars and vertical bars. Each can be created using the hbar() and vbar() functions of the plotting interface respectively."
},
{
"code": null,
"e": 9948,
"s": 9939,
"text": "Example:"
},
{
"code": null,
"e": 9956,
"s": 9948,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, showimport pandas as pd # instantiating the figure objectgraph = figure(title = \"Bokeh Bar Chart\") # reading the databasedata = pd.read_csv(\"tips.csv\") # plotting the graphgraph.vbar(data['total_bill'], top=data['tip']) # displaying the modelshow(graph)",
"e": 10287,
"s": 9956,
"text": null
},
{
"code": null,
"e": 10295,
"s": 10287,
"text": "Output:"
},
{
"code": null,
"e": 10414,
"s": 10295,
"text": "One of the key features of Bokeh is to add interaction to the plots. Let’s see various interactions that can be added."
},
{
"code": null,
"e": 10505,
"s": 10414,
"text": "click_policy property makes the legend interactive. There are two types of interactivity –"
},
{
"code": null,
"e": 10531,
"s": 10505,
"text": "Hiding: Hides the Glyphs."
},
{
"code": null,
"e": 10674,
"s": 10531,
"text": "Muting: Hiding the glyph makes it vanish completely, on the other hand, muting the glyph just de-emphasizes the glyph based on the parameters."
},
{
"code": null,
"e": 10683,
"s": 10674,
"text": "Example:"
},
{
"code": null,
"e": 10691,
"s": 10683,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, showimport pandas as pd # instantiating the figure objectgraph = figure(title = \"Bokeh Bar Chart\") # reading the databasedata = pd.read_csv(\"tips.csv\") # plotting the graphgraph.vbar(data['total_bill'], top=data['tip'], legend_label = \"Bill VS Tips\", color='green') graph.vbar(data['tip'], top=data['size'], legend_label = \"Tips VS Size\", color='red') graph.legend.click_policy = \"hide\" # displaying the modelshow(graph)",
"e": 11213,
"s": 10691,
"text": null
},
{
"code": null,
"e": 11221,
"s": 11213,
"text": "Output:"
},
{
"code": null,
"e": 11495,
"s": 11221,
"text": "Bokeh provides GUI features similar to HTML forms like buttons, sliders, checkboxes, etc. These provide an interactive interface to the plot that allows changing the parameters of the plot, modifying plot data, etc. Let’s see how to use and add some commonly used widgets. "
},
{
"code": null,
"e": 11648,
"s": 11495,
"text": "Buttons: This widget adds a simple button widget to the plot. We have to pass a custom JavaScript function to the CustomJS() method of the models class."
},
{
"code": null,
"e": 11816,
"s": 11648,
"text": "CheckboxGroup: Adds a standard check box to the plot. Similarly to buttons we have to pass the custom JavaScript function to the CustomJS() method of the models class."
},
{
"code": null,
"e": 11897,
"s": 11816,
"text": "RadioGroup: Adds a simple radio button and accepts a custom JavaScript function."
},
{
"code": null,
"e": 11906,
"s": 11897,
"text": "Example:"
},
{
"code": null,
"e": 11914,
"s": 11906,
"text": "Python3"
},
{
"code": "from bokeh.io import showfrom bokeh.models import Button, CheckboxGroup, RadioGroup, CustomJS button = Button(label=\"GFG\") button.js_on_click(CustomJS( code=\"console.log('button: click!', this.toString())\")) # Labels for checkbox and radio# buttonsL = [\"First\", \"Second\", \"Third\"] # the active parameter sets checks the selected value# by defaultcheckbox_group = CheckboxGroup(labels=L, active=[0, 2]) checkbox_group.js_on_click(CustomJS(code=\"\"\" console.log('checkbox_group: active=' + this.active, this.toString())\"\"\")) # the active parameter sets checks the selected value# by defaultradio_group = RadioGroup(labels=L, active=1) radio_group.js_on_click(CustomJS(code=\"\"\" console.log('radio_group: active=' + this.active, this.toString())\"\"\")) show(button)show(checkbox_group)show(radio_group)",
"e": 12727,
"s": 11914,
"text": null
},
{
"code": null,
"e": 12735,
"s": 12727,
"text": "Output:"
},
{
"code": null,
"e": 12788,
"s": 12735,
"text": "Note: All these buttons will be opened on a new tab."
},
{
"code": null,
"e": 12868,
"s": 12788,
"text": "Sliders: Adds a slider to the plot. It also needs a custom JavaScript function."
},
{
"code": null,
"e": 12877,
"s": 12868,
"text": "Example:"
},
{
"code": null,
"e": 12885,
"s": 12877,
"text": "Python3"
},
{
"code": "from bokeh.io import showfrom bokeh.models import CustomJS, Slider slider = Slider(start=1, end=20, value=1, step=2, title=\"Slider\") slider.js_on_change(\"value\", CustomJS(code=\"\"\" console.log('slider: value=' + this.value, this.toString())\"\"\")) show(slider)",
"e": 13149,
"s": 12885,
"text": null
},
{
"code": null,
"e": 13157,
"s": 13149,
"text": "Output:"
},
{
"code": null,
"e": 13251,
"s": 13157,
"text": "Similarly, much more widgets are available like a dropdown menu or tabs widgets can be added."
},
{
"code": null,
"e": 13358,
"s": 13251,
"text": "Note: For complete Bokeh tutorial, refer Python Bokeh tutorial – Interactive Data Visualization with Bokeh"
},
{
"code": null,
"e": 13447,
"s": 13358,
"text": "This is the last library of our list and you might be wondering why plotly. Here’s why –"
},
{
"code": null,
"e": 13556,
"s": 13447,
"text": "Potly has hover tool capabilities that allow us to detect any outliers or anomalies in numerous data points."
},
{
"code": null,
"e": 13586,
"s": 13556,
"text": "It allows more customization."
},
{
"code": null,
"e": 13631,
"s": 13586,
"text": "It makes the graph visually more attractive."
},
{
"code": null,
"e": 13685,
"s": 13631,
"text": "To install it type the below command in the terminal."
},
{
"code": null,
"e": 13704,
"s": 13685,
"text": "pip install plotly"
},
{
"code": null,
"e": 13848,
"s": 13704,
"text": "Scatter plot in Plotly can be created using the scatter() method of plotly.express. Like Seaborn, an extra data argument is also required here."
},
{
"code": null,
"e": 13857,
"s": 13848,
"text": "Example:"
},
{
"code": null,
"e": 13865,
"s": 13857,
"text": "Python3"
},
{
"code": "import plotly.express as pximport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") # plotting the scatter chartfig = px.scatter(data, x=\"day\", y=\"tip\", color='sex') # showing the plotfig.show()",
"e": 14079,
"s": 13865,
"text": null
},
{
"code": null,
"e": 14087,
"s": 14079,
"text": "Output:"
},
{
"code": null,
"e": 14300,
"s": 14087,
"text": "Line plot in Plotly is much accessible and illustrious annexation to plotly which manage a variety of types of data and assemble easy-to-style statistic. With px.line each data position is represented as a vertex"
},
{
"code": null,
"e": 14309,
"s": 14300,
"text": "Example:"
},
{
"code": null,
"e": 14317,
"s": 14309,
"text": "Python3"
},
{
"code": "import plotly.express as pximport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") # plotting the scatter chartfig = px.line(data, y='tip', color='sex') # showing the plotfig.show()",
"e": 14519,
"s": 14317,
"text": null
},
{
"code": null,
"e": 14527,
"s": 14519,
"text": "Output:"
},
{
"code": null,
"e": 14610,
"s": 14527,
"text": "Bar Chart in Plotly can be created using the bar() method of plotly.express class."
},
{
"code": null,
"e": 14619,
"s": 14610,
"text": "Example:"
},
{
"code": null,
"e": 14627,
"s": 14619,
"text": "Python3"
},
{
"code": "import plotly.express as pximport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") # plotting the scatter chartfig = px.bar(data, x='day', y='tip', color='sex') # showing the plotfig.show()",
"e": 14837,
"s": 14627,
"text": null
},
{
"code": null,
"e": 14845,
"s": 14837,
"text": "Output:"
},
{
"code": null,
"e": 14942,
"s": 14845,
"text": "In plotly, histograms can be created using the histogram() function of the plotly.express class."
},
{
"code": null,
"e": 14951,
"s": 14942,
"text": "Example:"
},
{
"code": null,
"e": 14959,
"s": 14951,
"text": "Python3"
},
{
"code": "import plotly.express as pximport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") # plotting the scatter chartfig = px.histogram(data, x='total_bill', color='sex') # showing the plotfig.show()",
"e": 15173,
"s": 14959,
"text": null
},
{
"code": null,
"e": 15181,
"s": 15173,
"text": "Output:"
},
{
"code": null,
"e": 15270,
"s": 15181,
"text": "Just like Bokeh, plotly also provides various interactions. Let’s discuss a few of them."
},
{
"code": null,
"e": 15595,
"s": 15270,
"text": "Creating Dropdown Menu: A drop-down menu is a part of the menu-button which is displayed on a screen all the time. Every menu button is associated with a Menu widget that can display the choices for that menu button when clicked on it. In plotly, there are 4 possible methods to modify the charts by using updatemenu method."
},
{
"code": null,
"e": 15635,
"s": 15595,
"text": "restyle: modify data or data attributes"
},
{
"code": null,
"e": 15670,
"s": 15635,
"text": "relayout: modify layout attributes"
},
{
"code": null,
"e": 15712,
"s": 15670,
"text": "update: modify data and layout attributes"
},
{
"code": null,
"e": 15749,
"s": 15712,
"text": "animate: start or pause an animation"
},
{
"code": null,
"e": 15758,
"s": 15749,
"text": "Example:"
},
{
"code": null,
"e": 15766,
"s": 15758,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as pximport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") plot = px.Figure(data=[px.Scatter( x=data['day'], y=data['tip'], mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict( buttons=list([ dict( args=[\"type\", \"scatter\"], label=\"Scatter Plot\", method=\"restyle\" ), dict( args=[\"type\", \"bar\"], label=\"Bar Chart\", method=\"restyle\" ) ]), direction=\"down\", ), ]) plot.show()",
"e": 16447,
"s": 15766,
"text": null
},
{
"code": null,
"e": 16455,
"s": 16447,
"text": "Output:"
},
{
"code": null,
"e": 16715,
"s": 16455,
"text": "Adding Buttons: In plotly, actions custom Buttons are used to quickly make actions directly from a record. Custom Buttons can be added to page layouts in CRM, Marketing, and Custom Apps. There are also 4 possible methods that can be applied in custom buttons:"
},
{
"code": null,
"e": 16755,
"s": 16715,
"text": "restyle: modify data or data attributes"
},
{
"code": null,
"e": 16790,
"s": 16755,
"text": "relayout: modify layout attributes"
},
{
"code": null,
"e": 16832,
"s": 16790,
"text": "update: modify data and layout attributes"
},
{
"code": null,
"e": 16869,
"s": 16832,
"text": "animate: start or pause an animation"
},
{
"code": null,
"e": 16878,
"s": 16869,
"text": "Example:"
},
{
"code": null,
"e": 16886,
"s": 16878,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as pximport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") plot = px.Figure(data=[px.Scatter( x=data['day'], y=data['tip'], mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict( type=\"buttons\", direction=\"left\", buttons=list([ dict( args=[\"type\", \"scatter\"], label=\"Scatter Plot\", method=\"restyle\" ), dict( args=[\"type\", \"bar\"], label=\"Bar Chart\", method=\"restyle\" ) ]), ), ]) plot.show()",
"e": 17594,
"s": 16886,
"text": null
},
{
"code": null,
"e": 17602,
"s": 17594,
"text": "Output:"
},
{
"code": null,
"e": 17634,
"s": 17602,
"text": "Creating Sliders and Selectors:"
},
{
"code": null,
"e": 18032,
"s": 17634,
"text": "In plotly, the range slider is a custom range-type input control. It allows selecting a value or a range of values between a specified minimum and maximum range. And the range selector is a tool for selecting ranges to display within the chart. It provides buttons to select pre-configured ranges in the chart. It also provides input boxes where the minimum and maximum dates can be manually input"
},
{
"code": null,
"e": 18041,
"s": 18032,
"text": "Example:"
},
{
"code": null,
"e": 18049,
"s": 18041,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as pximport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") plot = px.Figure(data=[px.Scatter( y=data['tip'], mode='lines',)]) plot.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, step=\"day\", stepmode=\"backward\"), ]) ), rangeslider=dict( visible=True ), )) plot.show()",
"e": 18522,
"s": 18049,
"text": null
},
{
"code": null,
"e": 18530,
"s": 18522,
"text": "Output:"
},
{
"code": null,
"e": 18595,
"s": 18530,
"text": "Note: For complete Plotly tutorial, refer Python Plotly tutorial"
},
{
"code": null,
"e": 19105,
"s": 18595,
"text": "In this tutorial, we have plotted the tips dataset with the help of the four different plotting modules of Python namely Matplotlib, Seaborn, Bokeh, and Plotly. Each module showed the plot in its own unique way and each one has its own set of features like Matplotlib provides more flexibility but at the cost of writing more code whereas Seaborn being a high-level language provides allows one to achieve the same goal with a small amount of code. Each module can be used depending on the task we want to do."
},
{
"code": null,
"e": 19124,
"s": 19105,
"text": "Data Visualization"
},
{
"code": null,
"e": 19137,
"s": 19124,
"text": "data-science"
},
{
"code": null,
"e": 19144,
"s": 19137,
"text": "Python"
}
] |
System of Linear Equations in three variables using Cramer’s Rule | 11 May, 2021
Cramer’s rule: In linear algebra, Cramer’s rule is an explicit formula for the solution of a system of linear equations with as many equations as unknown variables. It expresses the solution in terms of the determinants of the coefficient matrix and of matrices obtained from it by replacing one column by the column vector of the right-hand-sides of the equations. Cramer’s rule is computationally inefficient for systems of more than two or three equations.Suppose we have to solve these equations: a1x + b1y + c1z = d1 a2x + b2y + c2z = d2 a3x + b3y + c3z = d3 Following the Cramer’s Rule, first find the determinant values of all four matrices.
[Tex]D_1 = \begin{vmatrix} d_1 & b_1 & c_1\\ d_2 & b_2 & c_2\\ d_3 & b_3 & c_3\\ \end{vmatrix} [/Tex][Tex]D_3 = \begin{vmatrix} a_1 & b_1 & d_1\\ a_2 & b_2 & d_2\\ a_3 & b_3 & d_3\\ \end{vmatrix} [/Tex]
There are 2 cases: Case I : When D ≠ 0 In this case we have, x = D1/D y = D2/D z = D3/D Hence unique value of x, y, z will be obtained. Case II : When D = 0 (a) When at least one of D1, D2 and D3 is non zero: Then no solution is possible and hence system of equations will be inconsistent. (b) When D = 0 and D1 = D2 = D3 = 0: Then the system of equations will be consistent and it will have infinitely many solutions.
Example
Consider the following system of linear equations. [2x – y + 3z = 9], [x + y + z = 6], [x – y + z = 2]
[Tex]D_1 = \begin{vmatrix} 9 & -1 & 3\\ 6 & 1 & 1\\ 2 & -1 & 1\\ \end{vmatrix} [/Tex][Tex]D_3 = \begin{vmatrix} 2 & -1 & 9\\ 1 & 1 & 6\\ 1 & -1 & 2\\ \end{vmatrix} [/Tex]
[x = D1/D = 1], [y = D2/D = 2], [z = D3/D = 3]
Below is the implementation.
C++
Java
Python3
C#
Javascript
// CPP program to calculate solutions of linear// equations using cramer's rule#include <bits/stdc++.h>using namespace std; // This functions finds the determinant of Matrixdouble determinantOfMatrix(double mat[3][3]){ double ans; ans = mat[0][0] * (mat[1][1] * mat[2][2] - mat[2][1] * mat[1][2]) - mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]); return ans;} // This function finds the solution of system of// linear equations using cramer's rulevoid findSolution(double coeff[3][4]){ // Matrix d using coeff as given in cramer's rule double d[3][3] = { { coeff[0][0], coeff[0][1], coeff[0][2] }, { coeff[1][0], coeff[1][1], coeff[1][2] }, { coeff[2][0], coeff[2][1], coeff[2][2] }, }; // Matrix d1 using coeff as given in cramer's rule double d1[3][3] = { { coeff[0][3], coeff[0][1], coeff[0][2] }, { coeff[1][3], coeff[1][1], coeff[1][2] }, { coeff[2][3], coeff[2][1], coeff[2][2] }, }; // Matrix d2 using coeff as given in cramer's rule double d2[3][3] = { { coeff[0][0], coeff[0][3], coeff[0][2] }, { coeff[1][0], coeff[1][3], coeff[1][2] }, { coeff[2][0], coeff[2][3], coeff[2][2] }, }; // Matrix d3 using coeff as given in cramer's rule double d3[3][3] = { { coeff[0][0], coeff[0][1], coeff[0][3] }, { coeff[1][0], coeff[1][1], coeff[1][3] }, { coeff[2][0], coeff[2][1], coeff[2][3] }, }; // Calculating Determinant of Matrices d, d1, d2, d3 double D = determinantOfMatrix(d); double D1 = determinantOfMatrix(d1); double D2 = determinantOfMatrix(d2); double D3 = determinantOfMatrix(d3); printf("D is : %lf \n", D); printf("D1 is : %lf \n", D1); printf("D2 is : %lf \n", D2); printf("D3 is : %lf \n", D3); // Case 1 if (D != 0) { // Coeff have a unique solution. Apply Cramer's Rule double x = D1 / D; double y = D2 / D; double z = D3 / D; // calculating z using cramer's rule printf("Value of x is : %lf\n", x); printf("Value of y is : %lf\n", y); printf("Value of z is : %lf\n", z); } // Case 2 else { if (D1 == 0 && D2 == 0 && D3 == 0) printf("Infinite solutions\n"); else if (D1 != 0 || D2 != 0 || D3 != 0) printf("No solutions\n"); }} // Driver Codeint main(){ // storing coefficients of linear equations in coeff matrix double coeff[3][4] = { { 2, -1, 3, 9 }, { 1, 1, 1, 6 }, { 1, -1, 1, 2 }, }; findSolution(coeff); return 0;}
// Java program to calculate solutions of linear// equations using cramer's ruleclass GFG{ // This functions finds the determinant of Matrixstatic double determinantOfMatrix(double mat[][]){ double ans; ans = mat[0][0] * (mat[1][1] * mat[2][2] - mat[2][1] * mat[1][2]) - mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]); return ans;} // This function finds the solution of system of// linear equations using cramer's rulestatic void findSolution(double coeff[][]){ // Matrix d using coeff as given in cramer's rule double d[][] = { { coeff[0][0], coeff[0][1], coeff[0][2] }, { coeff[1][0], coeff[1][1], coeff[1][2] }, { coeff[2][0], coeff[2][1], coeff[2][2] }, }; // Matrix d1 using coeff as given in cramer's rule double d1[][] = { { coeff[0][3], coeff[0][1], coeff[0][2] }, { coeff[1][3], coeff[1][1], coeff[1][2] }, { coeff[2][3], coeff[2][1], coeff[2][2] }, }; // Matrix d2 using coeff as given in cramer's rule double d2[][] = { { coeff[0][0], coeff[0][3], coeff[0][2] }, { coeff[1][0], coeff[1][3], coeff[1][2] }, { coeff[2][0], coeff[2][3], coeff[2][2] }, }; // Matrix d3 using coeff as given in cramer's rule double d3[][] = { { coeff[0][0], coeff[0][1], coeff[0][3] }, { coeff[1][0], coeff[1][1], coeff[1][3] }, { coeff[2][0], coeff[2][1], coeff[2][3] }, }; // Calculating Determinant of Matrices d, d1, d2, d3 double D = determinantOfMatrix(d); double D1 = determinantOfMatrix(d1); double D2 = determinantOfMatrix(d2); double D3 = determinantOfMatrix(d3); System.out.printf("D is : %.6f \n", D); System.out.printf("D1 is : %.6f \n", D1); System.out.printf("D2 is : %.6f \n", D2); System.out.printf("D3 is : %.6f \n", D3); // Case 1 if (D != 0) { // Coeff have a unique solution. Apply Cramer's Rule double x = D1 / D; double y = D2 / D; double z = D3 / D; // calculating z using cramer's rule System.out.printf("Value of x is : %.6f\n", x); System.out.printf("Value of y is : %.6f\n", y); System.out.printf("Value of z is : %.6f\n", z); } // Case 2 else { if (D1 == 0 && D2 == 0 && D3 == 0) System.out.printf("Infinite solutions\n"); else if (D1 != 0 || D2 != 0 || D3 != 0) System.out.printf("No solutions\n"); }} // Driver Codepublic static void main(String[] args){ // storing coefficients of linear // equations in coeff matrix double coeff[][] = {{ 2, -1, 3, 9 }, { 1, 1, 1, 6 }, { 1, -1, 1, 2 }}; findSolution(coeff); }} // This code is contributed by PrinciRaj1992
# Python3 program to calculate# solutions of linear equations# using cramer's rule # This functions finds the# determinant of Matrixdef determinantOfMatrix(mat): ans = (mat[0][0] * (mat[1][1] * mat[2][2] - mat[2][1] * mat[1][2]) - mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0])) return ans # This function finds the solution of system of# linear equations using cramer's ruledef findSolution(coeff): # Matrix d using coeff as given in # cramer's rule d = [[coeff[0][0], coeff[0][1], coeff[0][2]], [coeff[1][0], coeff[1][1], coeff[1][2]], [coeff[2][0], coeff[2][1], coeff[2][2]]] # Matrix d1 using coeff as given in # cramer's rule d1 = [[coeff[0][3], coeff[0][1], coeff[0][2]], [coeff[1][3], coeff[1][1], coeff[1][2]], [coeff[2][3], coeff[2][1], coeff[2][2]]] # Matrix d2 using coeff as given in # cramer's rule d2 = [[coeff[0][0], coeff[0][3], coeff[0][2]], [coeff[1][0], coeff[1][3], coeff[1][2]], [coeff[2][0], coeff[2][3], coeff[2][2]]] # Matrix d3 using coeff as given in # cramer's rule d3 = [[coeff[0][0], coeff[0][1], coeff[0][3]], [coeff[1][0], coeff[1][1], coeff[1][3]], [coeff[2][0], coeff[2][1], coeff[2][3]]] # Calculating Determinant of Matrices # d, d1, d2, d3 D = determinantOfMatrix(d) D1 = determinantOfMatrix(d1) D2 = determinantOfMatrix(d2) D3 = determinantOfMatrix(d3) print("D is : ", D) print("D1 is : ", D1) print("D2 is : ", D2) print("D3 is : ", D3) # Case 1 if (D != 0): # Coeff have a unique solution. # Apply Cramer's Rule x = D1 / D y = D2 / D # calculating z using cramer's rule z = D3 / D print("Value of x is : ", x) print("Value of y is : ", y) print("Value of z is : ", z) # Case 2 else: if (D1 == 0 and D2 == 0 and D3 == 0): print("Infinite solutions") elif (D1 != 0 or D2 != 0 or D3 != 0): print("No solutions") # Driver Codeif __name__ == "__main__": # storing coefficients of linear # equations in coeff matrix coeff = [[2, -1, 3, 9], [1, 1, 1, 6], [1, -1, 1, 2]] findSolution(coeff) # This code is contributed by Chitranayal
// C# program to calculate solutions of linear// equations using cramer's ruleusing System; class GFG{ // This functions finds the determinant of Matrixstatic double determinantOfMatrix(double [,]mat){ double ans; ans = mat[0,0] * (mat[1,1] * mat[2,2] - mat[2,1] * mat[1,2]) - mat[0,1] * (mat[1,0] * mat[2,2] - mat[1,2] * mat[2,0]) + mat[0,2] * (mat[1,0] * mat[2,1] - mat[1,1] * mat[2,0]); return ans;} // This function finds the solution of system of// linear equations using cramer's rulestatic void findSolution(double [,]coeff){ // Matrix d using coeff as given in cramer's rule double [,]d = { { coeff[0,0], coeff[0,1], coeff[0,2] }, { coeff[1,0], coeff[1,1], coeff[1,2] }, { coeff[2,0], coeff[2,1], coeff[2,2] }, }; // Matrix d1 using coeff as given in cramer's rule double [,]d1 = { { coeff[0,3], coeff[0,1], coeff[0,2] }, { coeff[1,3], coeff[1,1], coeff[1,2] }, { coeff[2,3], coeff[2,1], coeff[2,2] }, }; // Matrix d2 using coeff as given in cramer's rule double [,]d2 = { { coeff[0,0], coeff[0,3], coeff[0,2] }, { coeff[1,0], coeff[1,3], coeff[1,2] }, { coeff[2,0], coeff[2,3], coeff[2,2] }, }; // Matrix d3 using coeff as given in cramer's rule double [,]d3 = { { coeff[0,0], coeff[0,1], coeff[0,3] }, { coeff[1,0], coeff[1,1], coeff[1,3] }, { coeff[2,0], coeff[2,1], coeff[2,3] }, }; // Calculating Determinant of Matrices d, d1, d2, d3 double D = determinantOfMatrix(d); double D1 = determinantOfMatrix(d1); double D2 = determinantOfMatrix(d2); double D3 = determinantOfMatrix(d3); Console.Write("D is : {0:F6} \n", D); Console.Write("D1 is : {0:F6} \n", D1); Console.Write("D2 is : {0:F6} \n", D2); Console.Write("D3 is : {0:F6} \n", D3); // Case 1 if (D != 0) { // Coeff have a unique solution. Apply Cramer's Rule double x = D1 / D; double y = D2 / D; double z = D3 / D; // calculating z using cramer's rule Console.Write("Value of x is : {0:F6}\n", x); Console.Write("Value of y is : {0:F6}\n", y); Console.Write("Value of z is : {0:F6}\n", z); } // Case 2 else { if (D1 == 0 && D2 == 0 && D3 == 0) Console.Write("Infinite solutions\n"); else if (D1 != 0 || D2 != 0 || D3 != 0) Console.Write("No solutions\n"); }} // Driver Codepublic static void Main(){ // storing coefficients of linear // equations in coeff matrix double [,]coeff = {{ 2, -1, 3, 9 }, { 1, 1, 1, 6 }, { 1, -1, 1, 2 }}; findSolution(coeff); }} // This code is contributed by 29AjayKumar
<script>// Javascript program to calculate solutions of linear// equations using cramer's rule // This functions finds the determinant of Matrixfunction determinantOfMatrix(mat){ let ans; ans = mat[0][0] * (mat[1][1] * mat[2][2] - mat[2][1] * mat[1][2]) - mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]); return ans; } // This function finds the solution of system of// linear equations using cramer's rulefunction findSolution(coeff){// Matrix d using coeff as given in cramer's rule let d = [[coeff[0][0], coeff[0][1], coeff[0][2]], [coeff[1][0], coeff[1][1], coeff[1][2]], [coeff[2][0], coeff[2][1], coeff[2][2]]]; // Matrix d1 using coeff as given in cramer's rule let d1 = [[coeff[0][3], coeff[0][1], coeff[0][2]], [coeff[1][3], coeff[1][1], coeff[1][2]], [coeff[2][3], coeff[2][1], coeff[2][2]]]; // Matrix d2 using coeff as given in cramer's rule let d2 = [[coeff[0][0], coeff[0][3], coeff[0][2]], [coeff[1][0], coeff[1][3], coeff[1][2]], [coeff[2][0], coeff[2][3], coeff[2][2]]]; // Matrix d3 using coeff as given in cramer's rule let d3 = [[coeff[0][0], coeff[0][1], coeff[0][3]], [coeff[1][0], coeff[1][1], coeff[1][3]], [coeff[2][0], coeff[2][1], coeff[2][3]]]; // Calculating Determinant of Matrices d, d1, d2, d3 let D = determinantOfMatrix(d); let D1 = determinantOfMatrix(d1); let D2 = determinantOfMatrix(d2); let D3 = determinantOfMatrix(d3); document.write("D is : ", D.toFixed(6)+"<br>"); document.write("D1 is : ", D1.toFixed(6)+"<br>"); document.write("D2 is : ", D2.toFixed(6)+"<br>"); document.write("D3 is : ", D3.toFixed(6)+"<br>"); // Case 1 if (D != 0) { // Coeff have a unique solution. Apply Cramer's Rule let x = D1 / D; let y = D2 / D; let z = D3 / D; // calculating z using cramer's rule document.write("Value of x is : ", x.toFixed(6)+"<br>"); document.write("Value of y is : ", y.toFixed(6)+"<br>"); document.write("Value of z is : ", z.toFixed(6)+"<br>"); } // Case 2 else { if (D1 == 0 && D2 == 0 && D3 == 0) document.write("Infinite solutions\n"); else if (D1 != 0 || D2 != 0 || D3 != 0) document.write("No solutions\n"); }} // Driver Codelet coeff = [[2, -1, 3, 9], [1, 1, 1, 6], [1, -1, 1, 2]] findSolution(coeff); // This code is contributed by avanitrachhadiya2155</script>
Output:
D is : -2.000000
D1 is : -2.000000
D2 is : -4.000000
D3 is : -6.000000
Value of x is : 1.000000
Value of y is : 2.000000
Value of z is : 3.000000
princiraj1992
29AjayKumar
ukasp
avanitrachhadiya2155
Algebra
Mathematical
Matrix
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 702,
"s": 52,
"text": "Cramer’s rule: In linear algebra, Cramer’s rule is an explicit formula for the solution of a system of linear equations with as many equations as unknown variables. It expresses the solution in terms of the determinants of the coefficient matrix and of matrices obtained from it by replacing one column by the column vector of the right-hand-sides of the equations. Cramer’s rule is computationally inefficient for systems of more than two or three equations.Suppose we have to solve these equations: a1x + b1y + c1z = d1 a2x + b2y + c2z = d2 a3x + b3y + c3z = d3 Following the Cramer’s Rule, first find the determinant values of all four matrices. "
},
{
"code": null,
"e": 912,
"s": 702,
"text": "[Tex]D_1 = \\begin{vmatrix} d_1 & b_1 & c_1\\\\ d_2 & b_2 & c_2\\\\ d_3 & b_3 & c_3\\\\ \\end{vmatrix} [/Tex][Tex]D_3 = \\begin{vmatrix} a_1 & b_1 & d_1\\\\ a_2 & b_2 & d_2\\\\ a_3 & b_3 & d_3\\\\ \\end{vmatrix} [/Tex]"
},
{
"code": null,
"e": 1374,
"s": 912,
"text": "There are 2 cases: Case I : When D ≠ 0 In this case we have, x = D1/D y = D2/D z = D3/D Hence unique value of x, y, z will be obtained. Case II : When D = 0 (a) When at least one of D1, D2 and D3 is non zero: Then no solution is possible and hence system of equations will be inconsistent. (b) When D = 0 and D1 = D2 = D3 = 0: Then the system of equations will be consistent and it will have infinitely many solutions. "
},
{
"code": null,
"e": 1386,
"s": 1376,
"text": "Example "
},
{
"code": null,
"e": 1492,
"s": 1388,
"text": "Consider the following system of linear equations. [2x – y + 3z = 9], [x + y + z = 6], [x – y + z = 2] "
},
{
"code": null,
"e": 1672,
"s": 1492,
"text": "[Tex]D_1 = \\begin{vmatrix} 9 & -1 & 3\\\\ 6 & 1 & 1\\\\ 2 & -1 & 1\\\\ \\end{vmatrix} [/Tex][Tex]D_3 = \\begin{vmatrix} 2 & -1 & 9\\\\ 1 & 1 & 6\\\\ 1 & -1 & 2\\\\ \\end{vmatrix} [/Tex] "
},
{
"code": null,
"e": 1720,
"s": 1672,
"text": "[x = D1/D = 1], [y = D2/D = 2], [z = D3/D = 3] "
},
{
"code": null,
"e": 1755,
"s": 1724,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 1761,
"s": 1757,
"text": "C++"
},
{
"code": null,
"e": 1766,
"s": 1761,
"text": "Java"
},
{
"code": null,
"e": 1774,
"s": 1766,
"text": "Python3"
},
{
"code": null,
"e": 1777,
"s": 1774,
"text": "C#"
},
{
"code": null,
"e": 1788,
"s": 1777,
"text": "Javascript"
},
{
"code": "// CPP program to calculate solutions of linear// equations using cramer's rule#include <bits/stdc++.h>using namespace std; // This functions finds the determinant of Matrixdouble determinantOfMatrix(double mat[3][3]){ double ans; ans = mat[0][0] * (mat[1][1] * mat[2][2] - mat[2][1] * mat[1][2]) - mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]); return ans;} // This function finds the solution of system of// linear equations using cramer's rulevoid findSolution(double coeff[3][4]){ // Matrix d using coeff as given in cramer's rule double d[3][3] = { { coeff[0][0], coeff[0][1], coeff[0][2] }, { coeff[1][0], coeff[1][1], coeff[1][2] }, { coeff[2][0], coeff[2][1], coeff[2][2] }, }; // Matrix d1 using coeff as given in cramer's rule double d1[3][3] = { { coeff[0][3], coeff[0][1], coeff[0][2] }, { coeff[1][3], coeff[1][1], coeff[1][2] }, { coeff[2][3], coeff[2][1], coeff[2][2] }, }; // Matrix d2 using coeff as given in cramer's rule double d2[3][3] = { { coeff[0][0], coeff[0][3], coeff[0][2] }, { coeff[1][0], coeff[1][3], coeff[1][2] }, { coeff[2][0], coeff[2][3], coeff[2][2] }, }; // Matrix d3 using coeff as given in cramer's rule double d3[3][3] = { { coeff[0][0], coeff[0][1], coeff[0][3] }, { coeff[1][0], coeff[1][1], coeff[1][3] }, { coeff[2][0], coeff[2][1], coeff[2][3] }, }; // Calculating Determinant of Matrices d, d1, d2, d3 double D = determinantOfMatrix(d); double D1 = determinantOfMatrix(d1); double D2 = determinantOfMatrix(d2); double D3 = determinantOfMatrix(d3); printf(\"D is : %lf \\n\", D); printf(\"D1 is : %lf \\n\", D1); printf(\"D2 is : %lf \\n\", D2); printf(\"D3 is : %lf \\n\", D3); // Case 1 if (D != 0) { // Coeff have a unique solution. Apply Cramer's Rule double x = D1 / D; double y = D2 / D; double z = D3 / D; // calculating z using cramer's rule printf(\"Value of x is : %lf\\n\", x); printf(\"Value of y is : %lf\\n\", y); printf(\"Value of z is : %lf\\n\", z); } // Case 2 else { if (D1 == 0 && D2 == 0 && D3 == 0) printf(\"Infinite solutions\\n\"); else if (D1 != 0 || D2 != 0 || D3 != 0) printf(\"No solutions\\n\"); }} // Driver Codeint main(){ // storing coefficients of linear equations in coeff matrix double coeff[3][4] = { { 2, -1, 3, 9 }, { 1, 1, 1, 6 }, { 1, -1, 1, 2 }, }; findSolution(coeff); return 0;}",
"e": 4421,
"s": 1788,
"text": null
},
{
"code": "// Java program to calculate solutions of linear// equations using cramer's ruleclass GFG{ // This functions finds the determinant of Matrixstatic double determinantOfMatrix(double mat[][]){ double ans; ans = mat[0][0] * (mat[1][1] * mat[2][2] - mat[2][1] * mat[1][2]) - mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]); return ans;} // This function finds the solution of system of// linear equations using cramer's rulestatic void findSolution(double coeff[][]){ // Matrix d using coeff as given in cramer's rule double d[][] = { { coeff[0][0], coeff[0][1], coeff[0][2] }, { coeff[1][0], coeff[1][1], coeff[1][2] }, { coeff[2][0], coeff[2][1], coeff[2][2] }, }; // Matrix d1 using coeff as given in cramer's rule double d1[][] = { { coeff[0][3], coeff[0][1], coeff[0][2] }, { coeff[1][3], coeff[1][1], coeff[1][2] }, { coeff[2][3], coeff[2][1], coeff[2][2] }, }; // Matrix d2 using coeff as given in cramer's rule double d2[][] = { { coeff[0][0], coeff[0][3], coeff[0][2] }, { coeff[1][0], coeff[1][3], coeff[1][2] }, { coeff[2][0], coeff[2][3], coeff[2][2] }, }; // Matrix d3 using coeff as given in cramer's rule double d3[][] = { { coeff[0][0], coeff[0][1], coeff[0][3] }, { coeff[1][0], coeff[1][1], coeff[1][3] }, { coeff[2][0], coeff[2][1], coeff[2][3] }, }; // Calculating Determinant of Matrices d, d1, d2, d3 double D = determinantOfMatrix(d); double D1 = determinantOfMatrix(d1); double D2 = determinantOfMatrix(d2); double D3 = determinantOfMatrix(d3); System.out.printf(\"D is : %.6f \\n\", D); System.out.printf(\"D1 is : %.6f \\n\", D1); System.out.printf(\"D2 is : %.6f \\n\", D2); System.out.printf(\"D3 is : %.6f \\n\", D3); // Case 1 if (D != 0) { // Coeff have a unique solution. Apply Cramer's Rule double x = D1 / D; double y = D2 / D; double z = D3 / D; // calculating z using cramer's rule System.out.printf(\"Value of x is : %.6f\\n\", x); System.out.printf(\"Value of y is : %.6f\\n\", y); System.out.printf(\"Value of z is : %.6f\\n\", z); } // Case 2 else { if (D1 == 0 && D2 == 0 && D3 == 0) System.out.printf(\"Infinite solutions\\n\"); else if (D1 != 0 || D2 != 0 || D3 != 0) System.out.printf(\"No solutions\\n\"); }} // Driver Codepublic static void main(String[] args){ // storing coefficients of linear // equations in coeff matrix double coeff[][] = {{ 2, -1, 3, 9 }, { 1, 1, 1, 6 }, { 1, -1, 1, 2 }}; findSolution(coeff); }} // This code is contributed by PrinciRaj1992",
"e": 7237,
"s": 4421,
"text": null
},
{
"code": "# Python3 program to calculate# solutions of linear equations# using cramer's rule # This functions finds the# determinant of Matrixdef determinantOfMatrix(mat): ans = (mat[0][0] * (mat[1][1] * mat[2][2] - mat[2][1] * mat[1][2]) - mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0])) return ans # This function finds the solution of system of# linear equations using cramer's ruledef findSolution(coeff): # Matrix d using coeff as given in # cramer's rule d = [[coeff[0][0], coeff[0][1], coeff[0][2]], [coeff[1][0], coeff[1][1], coeff[1][2]], [coeff[2][0], coeff[2][1], coeff[2][2]]] # Matrix d1 using coeff as given in # cramer's rule d1 = [[coeff[0][3], coeff[0][1], coeff[0][2]], [coeff[1][3], coeff[1][1], coeff[1][2]], [coeff[2][3], coeff[2][1], coeff[2][2]]] # Matrix d2 using coeff as given in # cramer's rule d2 = [[coeff[0][0], coeff[0][3], coeff[0][2]], [coeff[1][0], coeff[1][3], coeff[1][2]], [coeff[2][0], coeff[2][3], coeff[2][2]]] # Matrix d3 using coeff as given in # cramer's rule d3 = [[coeff[0][0], coeff[0][1], coeff[0][3]], [coeff[1][0], coeff[1][1], coeff[1][3]], [coeff[2][0], coeff[2][1], coeff[2][3]]] # Calculating Determinant of Matrices # d, d1, d2, d3 D = determinantOfMatrix(d) D1 = determinantOfMatrix(d1) D2 = determinantOfMatrix(d2) D3 = determinantOfMatrix(d3) print(\"D is : \", D) print(\"D1 is : \", D1) print(\"D2 is : \", D2) print(\"D3 is : \", D3) # Case 1 if (D != 0): # Coeff have a unique solution. # Apply Cramer's Rule x = D1 / D y = D2 / D # calculating z using cramer's rule z = D3 / D print(\"Value of x is : \", x) print(\"Value of y is : \", y) print(\"Value of z is : \", z) # Case 2 else: if (D1 == 0 and D2 == 0 and D3 == 0): print(\"Infinite solutions\") elif (D1 != 0 or D2 != 0 or D3 != 0): print(\"No solutions\") # Driver Codeif __name__ == \"__main__\": # storing coefficients of linear # equations in coeff matrix coeff = [[2, -1, 3, 9], [1, 1, 1, 6], [1, -1, 1, 2]] findSolution(coeff) # This code is contributed by Chitranayal",
"e": 9732,
"s": 7237,
"text": null
},
{
"code": "// C# program to calculate solutions of linear// equations using cramer's ruleusing System; class GFG{ // This functions finds the determinant of Matrixstatic double determinantOfMatrix(double [,]mat){ double ans; ans = mat[0,0] * (mat[1,1] * mat[2,2] - mat[2,1] * mat[1,2]) - mat[0,1] * (mat[1,0] * mat[2,2] - mat[1,2] * mat[2,0]) + mat[0,2] * (mat[1,0] * mat[2,1] - mat[1,1] * mat[2,0]); return ans;} // This function finds the solution of system of// linear equations using cramer's rulestatic void findSolution(double [,]coeff){ // Matrix d using coeff as given in cramer's rule double [,]d = { { coeff[0,0], coeff[0,1], coeff[0,2] }, { coeff[1,0], coeff[1,1], coeff[1,2] }, { coeff[2,0], coeff[2,1], coeff[2,2] }, }; // Matrix d1 using coeff as given in cramer's rule double [,]d1 = { { coeff[0,3], coeff[0,1], coeff[0,2] }, { coeff[1,3], coeff[1,1], coeff[1,2] }, { coeff[2,3], coeff[2,1], coeff[2,2] }, }; // Matrix d2 using coeff as given in cramer's rule double [,]d2 = { { coeff[0,0], coeff[0,3], coeff[0,2] }, { coeff[1,0], coeff[1,3], coeff[1,2] }, { coeff[2,0], coeff[2,3], coeff[2,2] }, }; // Matrix d3 using coeff as given in cramer's rule double [,]d3 = { { coeff[0,0], coeff[0,1], coeff[0,3] }, { coeff[1,0], coeff[1,1], coeff[1,3] }, { coeff[2,0], coeff[2,1], coeff[2,3] }, }; // Calculating Determinant of Matrices d, d1, d2, d3 double D = determinantOfMatrix(d); double D1 = determinantOfMatrix(d1); double D2 = determinantOfMatrix(d2); double D3 = determinantOfMatrix(d3); Console.Write(\"D is : {0:F6} \\n\", D); Console.Write(\"D1 is : {0:F6} \\n\", D1); Console.Write(\"D2 is : {0:F6} \\n\", D2); Console.Write(\"D3 is : {0:F6} \\n\", D3); // Case 1 if (D != 0) { // Coeff have a unique solution. Apply Cramer's Rule double x = D1 / D; double y = D2 / D; double z = D3 / D; // calculating z using cramer's rule Console.Write(\"Value of x is : {0:F6}\\n\", x); Console.Write(\"Value of y is : {0:F6}\\n\", y); Console.Write(\"Value of z is : {0:F6}\\n\", z); } // Case 2 else { if (D1 == 0 && D2 == 0 && D3 == 0) Console.Write(\"Infinite solutions\\n\"); else if (D1 != 0 || D2 != 0 || D3 != 0) Console.Write(\"No solutions\\n\"); }} // Driver Codepublic static void Main(){ // storing coefficients of linear // equations in coeff matrix double [,]coeff = {{ 2, -1, 3, 9 }, { 1, 1, 1, 6 }, { 1, -1, 1, 2 }}; findSolution(coeff); }} // This code is contributed by 29AjayKumar",
"e": 12465,
"s": 9732,
"text": null
},
{
"code": "<script>// Javascript program to calculate solutions of linear// equations using cramer's rule // This functions finds the determinant of Matrixfunction determinantOfMatrix(mat){ let ans; ans = mat[0][0] * (mat[1][1] * mat[2][2] - mat[2][1] * mat[1][2]) - mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]); return ans; } // This function finds the solution of system of// linear equations using cramer's rulefunction findSolution(coeff){// Matrix d using coeff as given in cramer's rule let d = [[coeff[0][0], coeff[0][1], coeff[0][2]], [coeff[1][0], coeff[1][1], coeff[1][2]], [coeff[2][0], coeff[2][1], coeff[2][2]]]; // Matrix d1 using coeff as given in cramer's rule let d1 = [[coeff[0][3], coeff[0][1], coeff[0][2]], [coeff[1][3], coeff[1][1], coeff[1][2]], [coeff[2][3], coeff[2][1], coeff[2][2]]]; // Matrix d2 using coeff as given in cramer's rule let d2 = [[coeff[0][0], coeff[0][3], coeff[0][2]], [coeff[1][0], coeff[1][3], coeff[1][2]], [coeff[2][0], coeff[2][3], coeff[2][2]]]; // Matrix d3 using coeff as given in cramer's rule let d3 = [[coeff[0][0], coeff[0][1], coeff[0][3]], [coeff[1][0], coeff[1][1], coeff[1][3]], [coeff[2][0], coeff[2][1], coeff[2][3]]]; // Calculating Determinant of Matrices d, d1, d2, d3 let D = determinantOfMatrix(d); let D1 = determinantOfMatrix(d1); let D2 = determinantOfMatrix(d2); let D3 = determinantOfMatrix(d3); document.write(\"D is : \", D.toFixed(6)+\"<br>\"); document.write(\"D1 is : \", D1.toFixed(6)+\"<br>\"); document.write(\"D2 is : \", D2.toFixed(6)+\"<br>\"); document.write(\"D3 is : \", D3.toFixed(6)+\"<br>\"); // Case 1 if (D != 0) { // Coeff have a unique solution. Apply Cramer's Rule let x = D1 / D; let y = D2 / D; let z = D3 / D; // calculating z using cramer's rule document.write(\"Value of x is : \", x.toFixed(6)+\"<br>\"); document.write(\"Value of y is : \", y.toFixed(6)+\"<br>\"); document.write(\"Value of z is : \", z.toFixed(6)+\"<br>\"); } // Case 2 else { if (D1 == 0 && D2 == 0 && D3 == 0) document.write(\"Infinite solutions\\n\"); else if (D1 != 0 || D2 != 0 || D3 != 0) document.write(\"No solutions\\n\"); }} // Driver Codelet coeff = [[2, -1, 3, 9], [1, 1, 1, 6], [1, -1, 1, 2]] findSolution(coeff); // This code is contributed by avanitrachhadiya2155</script>",
"e": 15094,
"s": 12465,
"text": null
},
{
"code": null,
"e": 15252,
"s": 15094,
"text": "Output:\nD is : -2.000000 \nD1 is : -2.000000 \nD2 is : -4.000000 \nD3 is : -6.000000 \nValue of x is : 1.000000\nValue of y is : 2.000000\nValue of z is : 3.000000"
},
{
"code": null,
"e": 15266,
"s": 15252,
"text": "princiraj1992"
},
{
"code": null,
"e": 15278,
"s": 15266,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15284,
"s": 15278,
"text": "ukasp"
},
{
"code": null,
"e": 15305,
"s": 15284,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 15313,
"s": 15305,
"text": "Algebra"
},
{
"code": null,
"e": 15326,
"s": 15313,
"text": "Mathematical"
},
{
"code": null,
"e": 15333,
"s": 15326,
"text": "Matrix"
},
{
"code": null,
"e": 15346,
"s": 15333,
"text": "Mathematical"
},
{
"code": null,
"e": 15353,
"s": 15346,
"text": "Matrix"
}
] |
Python Tkinter – Frameless window | 16 Oct, 2021
Prerequisite: Python GUI – tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python.
To create a Frameless window, we will use the overrideredirect() method.
Syntax:
root.overrideredirect(value)
To create a Frameless Window, we will pass value True or 1 as arguments in over ride redirect() method.
Below is the program that creates a normal tkinter window.
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Execute tkinterroot.mainloop()
Output:
Frame Window
Below is the Program to create a frameless tkinter window in python using the overrideredirect() method.
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Use overrideredirect() methodroot.overrideredirect(True) # Execute tkinterroot.mainloop()
Output:
Frameless Window
ruhelaa48
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 88,
"s": 53,
"text": "Prerequisite: Python GUI – tkinter"
},
{
"code": null,
"e": 313,
"s": 88,
"text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python."
},
{
"code": null,
"e": 386,
"s": 313,
"text": "To create a Frameless window, we will use the overrideredirect() method."
},
{
"code": null,
"e": 394,
"s": 386,
"text": "Syntax:"
},
{
"code": null,
"e": 423,
"s": 394,
"text": "root.overrideredirect(value)"
},
{
"code": null,
"e": 527,
"s": 423,
"text": "To create a Frameless Window, we will pass value True or 1 as arguments in over ride redirect() method."
},
{
"code": null,
"e": 586,
"s": 527,
"text": "Below is the program that creates a normal tkinter window."
},
{
"code": null,
"e": 594,
"s": 586,
"text": "Python3"
},
{
"code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Execute tkinterroot.mainloop()",
"e": 729,
"s": 594,
"text": null
},
{
"code": null,
"e": 737,
"s": 729,
"text": "Output:"
},
{
"code": null,
"e": 750,
"s": 737,
"text": "Frame Window"
},
{
"code": null,
"e": 855,
"s": 750,
"text": "Below is the Program to create a frameless tkinter window in python using the overrideredirect() method."
},
{
"code": null,
"e": 863,
"s": 855,
"text": "Python3"
},
{
"code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Use overrideredirect() methodroot.overrideredirect(True) # Execute tkinterroot.mainloop()",
"e": 1057,
"s": 863,
"text": null
},
{
"code": null,
"e": 1065,
"s": 1057,
"text": "Output:"
},
{
"code": null,
"e": 1082,
"s": 1065,
"text": "Frameless Window"
},
{
"code": null,
"e": 1092,
"s": 1082,
"text": "ruhelaa48"
},
{
"code": null,
"e": 1107,
"s": 1092,
"text": "Python-tkinter"
},
{
"code": null,
"e": 1114,
"s": 1107,
"text": "Python"
}
] |
Check if the given characters is present in Golang String | 26 Aug, 2019
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to check the given characters present in the string using the given functions. These functions are defined under strings package, so you have to import strings package in your program to access these functions:
1. Contains: This function is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false.
Syntax:
func Contains(str, chstr string) bool
Here, str is the original string and chstr is the string which you wants to check. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how to check// the string is present or not in the// specified stringpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing strings str1 := "Welcome to Geeks for Geeks" str2 := "Here! we learn about go strings" fmt.Println("Original strings") fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) // Checking the string present or not // Using Contains() function res1 := strings.Contains(str1, "Geeks") res2 := strings.Contains(str2, "GFG") // Displaying the result fmt.Println("\nResult 1: ", res1) fmt.Println("Result 2: ", res2) }
Output:
Original strings
String 1: Welcome to Geeks for Geeks
String 2: Here! we learn about go strings
Result 1: true
Result 2: false
2. ContainsAny: This function is used to check whether any Unicode code points in chars are present in the given string. If any Unicode code points in chars are available in the given string, then this method returns true, otherwise, return false.
Syntax:
func ContainsAny(str, charstr string) bool
Here, str is the original string and charstr is the Unicode code points in chars. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how to check the// string is present or not in the specified// stringpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing strings str1 := "Welcome to Geeks for Geeks" str2 := "Here! we learn about go strings" // Checking the string present or not // Using ContainsAny() function res1 := strings.ContainsAny(str1, "Geeks") res2 := strings.ContainsAny(str2, "GFG") res3 := strings.ContainsAny("GeeksforGeeks", "G & f") res4 := strings.ContainsAny("GeeksforGeeks", "u | e") res5 := strings.ContainsAny(" ", " ") res6 := strings.ContainsAny("GeeksforGeeks", " ") // Displaying the result fmt.Println("\nResult 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) fmt.Println("Result 4: ", res4) fmt.Println("Result 5: ", res5) fmt.Println("Result 6: ", res6) }
Output:
Result 1: true
Result 2: false
Result 3: true
Result 4: true
Result 5: true
Result 6: false
Golang
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 493,
"s": 28,
"text": "In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to check the given characters present in the string using the given functions. These functions are defined under strings package, so you have to import strings package in your program to access these functions:"
},
{
"code": null,
"e": 688,
"s": 493,
"text": "1. Contains: This function is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false."
},
{
"code": null,
"e": 696,
"s": 688,
"text": "Syntax:"
},
{
"code": null,
"e": 734,
"s": 696,
"text": "func Contains(str, chstr string) bool"
},
{
"code": null,
"e": 874,
"s": 734,
"text": "Here, str is the original string and chstr is the string which you wants to check. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 883,
"s": 874,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to check// the string is present or not in the// specified stringpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing strings str1 := \"Welcome to Geeks for Geeks\" str2 := \"Here! we learn about go strings\" fmt.Println(\"Original strings\") fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2: \", str2) // Checking the string present or not // Using Contains() function res1 := strings.Contains(str1, \"Geeks\") res2 := strings.Contains(str2, \"GFG\") // Displaying the result fmt.Println(\"\\nResult 1: \", res1) fmt.Println(\"Result 2: \", res2) }",
"e": 1556,
"s": 883,
"text": null
},
{
"code": null,
"e": 1564,
"s": 1556,
"text": "Output:"
},
{
"code": null,
"e": 1697,
"s": 1564,
"text": "Original strings\nString 1: Welcome to Geeks for Geeks\nString 2: Here! we learn about go strings\n\nResult 1: true\nResult 2: false\n"
},
{
"code": null,
"e": 1946,
"s": 1697,
"text": " 2. ContainsAny: This function is used to check whether any Unicode code points in chars are present in the given string. If any Unicode code points in chars are available in the given string, then this method returns true, otherwise, return false."
},
{
"code": null,
"e": 1954,
"s": 1946,
"text": "Syntax:"
},
{
"code": null,
"e": 1997,
"s": 1954,
"text": "func ContainsAny(str, charstr string) bool"
},
{
"code": null,
"e": 2136,
"s": 1997,
"text": "Here, str is the original string and charstr is the Unicode code points in chars. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 2145,
"s": 2136,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to check the// string is present or not in the specified// stringpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing strings str1 := \"Welcome to Geeks for Geeks\" str2 := \"Here! we learn about go strings\" // Checking the string present or not // Using ContainsAny() function res1 := strings.ContainsAny(str1, \"Geeks\") res2 := strings.ContainsAny(str2, \"GFG\") res3 := strings.ContainsAny(\"GeeksforGeeks\", \"G & f\") res4 := strings.ContainsAny(\"GeeksforGeeks\", \"u | e\") res5 := strings.ContainsAny(\" \", \" \") res6 := strings.ContainsAny(\"GeeksforGeeks\", \" \") // Displaying the result fmt.Println(\"\\nResult 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) fmt.Println(\"Result 4: \", res4) fmt.Println(\"Result 5: \", res5) fmt.Println(\"Result 6: \", res6) }",
"e": 3067,
"s": 2145,
"text": null
},
{
"code": null,
"e": 3075,
"s": 3067,
"text": "Output:"
},
{
"code": null,
"e": 3174,
"s": 3075,
"text": "Result 1: true\nResult 2: false\nResult 3: true\nResult 4: true\nResult 5: true\nResult 6: false\n"
},
{
"code": null,
"e": 3181,
"s": 3174,
"text": "Golang"
},
{
"code": null,
"e": 3195,
"s": 3181,
"text": "Golang-String"
},
{
"code": null,
"e": 3207,
"s": 3195,
"text": "Go Language"
}
] |
Probabilistic shortest path routing algorithm for optical networks | 16 Jun, 2022
Data transfer operations is a crucial aspect in case of networking and routing. So efficient data transfer operations is a must need, with minimum hardware cost (Optical Cables, WDM Network components, Decoders, Multiplexers) and also in the minimum time possible. Thus, the need is to propose an algorithm that finds the shortest path between two nodes (source node and destination node). Let’s see a completely new algorithm unlike Dijkstra’s Shortest Path or any other algorithm for finding Shortest Path. Given a graph and two nodes (source node and destination node), find the shortest path between them. Let’s Calculate the distance ratio for each link :
Distance of link AB [denoted by d(AB)] = 10 Distance of link AC [denoted by d(AC)] = 12 For link AB, Distance Ratio of AB = d(AB) / (d(AB) + d(AC)) For link AC, Distance Ratio of AC = d(AC) / (d(AB) + d(AC))
Algorithm :
Given a graph and two nodes -
1. Find all the paths connecting the two nodes.
2. For each path calculate probability = (Distance Ratio).
3. After looping over all such paths, find the path for
which the probability turns out to be minimum.
Examples :
Input :
Output : Shortest Path is [A -> B]
Explanation :
All possible paths are
P1 = [A->B]
P2 = [A->C->B]
P3 = [A->D->B]
total distance D = d(P1) + d(P2) + d(P3)
= (3) + (2 + 5) + (4 + 3)
= 17
distance ratio for P1 = d(P1) / D = 3/17
distance ratio for P2 = d(P2) / D = 7/17
distance ratio for P3 = d(P3) / D = 7/17
So the shortest path is P1 = [A->B]
Input :
Output : Shortest Path is [A -> B]
Let’s illustrate the algorithm with a 7-node network and find out the Probabilistic shortest path between node 1 and node 5. Below is the implementation :
Python3
# Python program to find Probabilistic# shortest path routing algorithm for# optical networks # importing random moduleimport random # Number of nodesNODES = 7 # very small invalid# when no link existsINVALID = 0.001 distance_links = [[INVALID for i in range(NODES)] for j in range(NODES)]# distance of each link distance_links[0][1] = 7distance_links[1][0] = 7distance_links[1][2] = 8distance_links[2][1] = 8distance_links[0][2] = 9distance_links[2][0] = 9distance_links[3][0] = 9distance_links[0][3] = 9distance_links[4][3] = 4distance_links[3][4] = 4distance_links[5][4] = 6distance_links[4][5] = 6distance_links[5][2] = 4distance_links[2][5] = 4distance_links[4][6] = 8distance_links[6][4] = 8distance_links[0][6] = 5distance_links[6][0] = 5 # Finds next node from current nodedef next_node(s): nxt = [] for i in range(NODES): if(distance_links[s][i] != INVALID): nxt.append(i) return nxt # Find simple paths for eachdef find_simple_paths(start, end): visited = set() visited.add(start) nodestack = list() indexstack = list() current = start i = 0 while True: # get a list of the neighbors # of the current node neighbors = next_node(current) # Find the next unvisited neighbor # of this node, if any while i < len(neighbors) and neighbors[i] in visited: i += 1 if i >= len(neighbors): visited.remove(current) if len(nodestack) < 1: break current = nodestack.pop() i = indexstack.pop() elif neighbors[i] == end: yield nodestack + [current, end] i += 1 else: nodestack.append(current) indexstack.append(i + 1) visited.add(neighbors[i]) current = neighbors[i] i = 0 # Find the shortest pathdef solution(sour, dest): block = 0 l = [] for path in find_simple_paths(sour, dest): l.append(path) k = 0 for i in range(len(l)): su = 0 for j in range(1, len(l[i])): su += (distance_links[l[i][j-1]] [l[i][j]]) k += su # print k dist_prob = [] probability = [] for i in range(len(l)): s, su = 0, 0 for j in range(1, len(l[i])): su += (distance_links[l[i][j-1]] [l[i][j]]) dist_prob.append(su/(1.0 * k)) for m in range(len(dist_prob)): z = (dist_prob[m]) probability.append(z) for i in range(len(probability)): if(probability[i] == min(probability)): z = l[i] print("Shortest Path is", end = " ") print(z) # Driver Codeif __name__ == '__main__' : source, dest = 1, 5 # Calling the solution function solution(source, dest)
Output :
Shortest Path is [1, 2, 5]
Advantage over common Shortest Path Algorithms : Most of the shortest path algorithms are greedy algorithms. So it is based on the fact that an optimal solution leads to a globally optimal solution. In most of the cases, due to greedy property, it may not always lead to an optimal solution. But using this algorithm, one can always guarantee an optimal solution and hence the accuracy is 100%.
krishna_97
Shortest Path
Computer Networks
Shortest Path
Computer Networks
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, 2022"
},
{
"code": null,
"e": 690,
"s": 28,
"text": "Data transfer operations is a crucial aspect in case of networking and routing. So efficient data transfer operations is a must need, with minimum hardware cost (Optical Cables, WDM Network components, Decoders, Multiplexers) and also in the minimum time possible. Thus, the need is to propose an algorithm that finds the shortest path between two nodes (source node and destination node). Let’s see a completely new algorithm unlike Dijkstra’s Shortest Path or any other algorithm for finding Shortest Path. Given a graph and two nodes (source node and destination node), find the shortest path between them. Let’s Calculate the distance ratio for each link :"
},
{
"code": null,
"e": 898,
"s": 690,
"text": "Distance of link AB [denoted by d(AB)] = 10 Distance of link AC [denoted by d(AC)] = 12 For link AB, Distance Ratio of AB = d(AB) / (d(AB) + d(AC)) For link AC, Distance Ratio of AC = d(AC) / (d(AB) + d(AC))"
},
{
"code": null,
"e": 910,
"s": 898,
"text": "Algorithm :"
},
{
"code": null,
"e": 1155,
"s": 910,
"text": "Given a graph and two nodes -\n\n1. Find all the paths connecting the two nodes.\n2. For each path calculate probability = (Distance Ratio). \n3. After looping over all such paths, find the path for\n which the probability turns out to be minimum."
},
{
"code": null,
"e": 1166,
"s": 1155,
"text": "Examples :"
},
{
"code": null,
"e": 1175,
"s": 1166,
"text": "Input : "
},
{
"code": null,
"e": 1575,
"s": 1175,
"text": "Output : Shortest Path is [A -> B]\n\n\nExplanation :\nAll possible paths are\nP1 = [A->B]\nP2 = [A->C->B]\nP3 = [A->D->B] \n\ntotal distance D = d(P1) + d(P2) + d(P3) \n = (3) + (2 + 5) + (4 + 3)\n = 17\n\ndistance ratio for P1 = d(P1) / D = 3/17\ndistance ratio for P2 = d(P2) / D = 7/17\ndistance ratio for P3 = d(P3) / D = 7/17\n\nSo the shortest path is P1 = [A->B]\n\n\n\n\nInput : "
},
{
"code": null,
"e": 1610,
"s": 1575,
"text": "Output : Shortest Path is [A -> B]"
},
{
"code": null,
"e": 1770,
"s": 1613,
"text": "Let’s illustrate the algorithm with a 7-node network and find out the Probabilistic shortest path between node 1 and node 5. Below is the implementation : "
},
{
"code": null,
"e": 1778,
"s": 1770,
"text": "Python3"
},
{
"code": "# Python program to find Probabilistic# shortest path routing algorithm for# optical networks # importing random moduleimport random # Number of nodesNODES = 7 # very small invalid# when no link existsINVALID = 0.001 distance_links = [[INVALID for i in range(NODES)] for j in range(NODES)]# distance of each link distance_links[0][1] = 7distance_links[1][0] = 7distance_links[1][2] = 8distance_links[2][1] = 8distance_links[0][2] = 9distance_links[2][0] = 9distance_links[3][0] = 9distance_links[0][3] = 9distance_links[4][3] = 4distance_links[3][4] = 4distance_links[5][4] = 6distance_links[4][5] = 6distance_links[5][2] = 4distance_links[2][5] = 4distance_links[4][6] = 8distance_links[6][4] = 8distance_links[0][6] = 5distance_links[6][0] = 5 # Finds next node from current nodedef next_node(s): nxt = [] for i in range(NODES): if(distance_links[s][i] != INVALID): nxt.append(i) return nxt # Find simple paths for eachdef find_simple_paths(start, end): visited = set() visited.add(start) nodestack = list() indexstack = list() current = start i = 0 while True: # get a list of the neighbors # of the current node neighbors = next_node(current) # Find the next unvisited neighbor # of this node, if any while i < len(neighbors) and neighbors[i] in visited: i += 1 if i >= len(neighbors): visited.remove(current) if len(nodestack) < 1: break current = nodestack.pop() i = indexstack.pop() elif neighbors[i] == end: yield nodestack + [current, end] i += 1 else: nodestack.append(current) indexstack.append(i + 1) visited.add(neighbors[i]) current = neighbors[i] i = 0 # Find the shortest pathdef solution(sour, dest): block = 0 l = [] for path in find_simple_paths(sour, dest): l.append(path) k = 0 for i in range(len(l)): su = 0 for j in range(1, len(l[i])): su += (distance_links[l[i][j-1]] [l[i][j]]) k += su # print k dist_prob = [] probability = [] for i in range(len(l)): s, su = 0, 0 for j in range(1, len(l[i])): su += (distance_links[l[i][j-1]] [l[i][j]]) dist_prob.append(su/(1.0 * k)) for m in range(len(dist_prob)): z = (dist_prob[m]) probability.append(z) for i in range(len(probability)): if(probability[i] == min(probability)): z = l[i] print(\"Shortest Path is\", end = \" \") print(z) # Driver Codeif __name__ == '__main__' : source, dest = 1, 5 # Calling the solution function solution(source, dest)",
"e": 4819,
"s": 1778,
"text": null
},
{
"code": null,
"e": 4828,
"s": 4819,
"text": "Output :"
},
{
"code": null,
"e": 4855,
"s": 4828,
"text": "Shortest Path is [1, 2, 5]"
},
{
"code": null,
"e": 5252,
"s": 4855,
"text": " Advantage over common Shortest Path Algorithms : Most of the shortest path algorithms are greedy algorithms. So it is based on the fact that an optimal solution leads to a globally optimal solution. In most of the cases, due to greedy property, it may not always lead to an optimal solution. But using this algorithm, one can always guarantee an optimal solution and hence the accuracy is 100%."
},
{
"code": null,
"e": 5263,
"s": 5252,
"text": "krishna_97"
},
{
"code": null,
"e": 5277,
"s": 5263,
"text": "Shortest Path"
},
{
"code": null,
"e": 5295,
"s": 5277,
"text": "Computer Networks"
},
{
"code": null,
"e": 5309,
"s": 5295,
"text": "Shortest Path"
},
{
"code": null,
"e": 5327,
"s": 5309,
"text": "Computer Networks"
}
] |
C/C++ Program for Finding the vertex, focus and directrix of the parabola? | A set of points on a plain surface that forms a curve such that any point on that curve is equidistant from a point in the center (called focus) is a parabola.
The general equation for the parabola is
y = ax2 + bx + c
The vertex of a parabola is the coordinate from which it takes the sharpest turn whereas a is the straight-line used to generate the curve.
Focus is the point with is equidistant from all points of the parabola.
Here, we will find the vertex, focus, and directrix of a parabola. There is a mathematical formula that finds all these values. And we will make a program using the mathematical formula for it.
Input:
a = 10,
b = 5,
c = 4
Output:
The vertex: (-0.25, 3.375)
The Focus: (-0.25, 3.4)
y-Directrix:-1036
The mathematical formula for find the vertex, focus and y-direction from the given values of the parabolic figure.
Vertex = {(-b/2a) , (4ac-b2/4a)}
Focus = {(-b/2a), (4ac-b2+1/4a)}
Direction = c - (b2 +1)*4a
#include <iostream>
using namespace std;
int main() {
float a = 10, b = 5, c = 4;
cout << "The vertex: (" << (-b / (2 * a)) << ", " << (((4 * a * c) - (b * b)) / (4 * a)) << ")\n";
cout << "The Focus: (" << (-b / (2 * a)) << ", " << (((4 * a * c) - (b * b) + 1) / (4 * a)) << ")\n";
cout << "y-Directrix:" << c - ((b * b) + 1) * 4 * a;
} | [
{
"code": null,
"e": 1222,
"s": 1062,
"text": "A set of points on a plain surface that forms a curve such that any point on that curve is equidistant from a point in the center (called focus) is a parabola."
},
{
"code": null,
"e": 1263,
"s": 1222,
"text": "The general equation for the parabola is"
},
{
"code": null,
"e": 1280,
"s": 1263,
"text": "y = ax2 + bx + c"
},
{
"code": null,
"e": 1420,
"s": 1280,
"text": "The vertex of a parabola is the coordinate from which it takes the sharpest turn whereas a is the straight-line used to generate the curve."
},
{
"code": null,
"e": 1492,
"s": 1420,
"text": "Focus is the point with is equidistant from all points of the parabola."
},
{
"code": null,
"e": 1686,
"s": 1492,
"text": "Here, we will find the vertex, focus, and directrix of a parabola. There is a mathematical formula that finds all these values. And we will make a program using the mathematical formula for it."
},
{
"code": null,
"e": 1791,
"s": 1686,
"text": "Input:\na = 10,\nb = 5,\nc = 4\nOutput:\nThe vertex: (-0.25, 3.375)\nThe Focus: (-0.25, 3.4)\ny-Directrix:-1036"
},
{
"code": null,
"e": 1906,
"s": 1791,
"text": "The mathematical formula for find the vertex, focus and y-direction from the given values of the parabolic figure."
},
{
"code": null,
"e": 1939,
"s": 1906,
"text": "Vertex = {(-b/2a) , (4ac-b2/4a)}"
},
{
"code": null,
"e": 1972,
"s": 1939,
"text": "Focus = {(-b/2a), (4ac-b2+1/4a)}"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Direction = c - (b2 +1)*4a"
},
{
"code": null,
"e": 2349,
"s": 1999,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n float a = 10, b = 5, c = 4;\n cout << \"The vertex: (\" << (-b / (2 * a)) << \", \" << (((4 * a * c) - (b * b)) / (4 * a)) << \")\\n\";\n cout << \"The Focus: (\" << (-b / (2 * a)) << \", \" << (((4 * a * c) - (b * b) + 1) / (4 * a)) << \")\\n\";\n cout << \"y-Directrix:\" << c - ((b * b) + 1) * 4 * a;\n}"
}
] |
Java regex to exclude a specific String constant | regex ^((?!kk).)*$ returns true if a line does not contain kk, otherwise returns false
public class RegTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="tutorials";
boolean i=s.matches("^((?!kk).)*$");
System.out.println(i);
}
} | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "regex ^((?!kk).)*$ returns true if a line does not contain kk, otherwise returns false"
},
{
"code": null,
"e": 1364,
"s": 1149,
"text": "public class RegTest {\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n String s=\"tutorials\";\n boolean i=s.matches(\"^((?!kk).)*$\");\n System.out.println(i);\n }\n}"
}
] |
QlikView - Multi Box | A Multi Box represents the list of all the values from multiple fields as drop down values. Similar to list box, the selection of a value in Multi Box highlights the related values in other sheet objects. This helps in faster visual analysis. It is also very useful to follow a drill down path among various sheet objects.
Let us consider the following input data, which represents the sales figure of different product lines and product categories.
Product_Line,Product_category,Value
Sporting Goods,Outdoor Recreation,5642
Food, Beverages & Tobacco,2514
Apparel & Accessories,Clothing,2365
Apparel & Accessories,Costumes & Accessories,4487
Sporting Goods,Athletics,812
Health & Beauty,Personal Care,6912
Arts & Entertainment,Hobbies & Creative Arts,5201
Arts & Entertainment,Paintings,8451
Arts & Entertainment,Musical Instruments,1245
Hardware,Tool Accessories,456
Home & Garden,Bathroom Accessories,241
Food,Drinks,1247
Home & Garden,Lawn & Garden,5462
Office Supplies,Presentation Supplies,577
Hardware,Blocks,548
Baby & Toddler,Diapering,1247
Baby & Toddler,Toys,257
Home & Garden,Pipes,1241
Office Supplies,Display Board,2177
The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into the QlikView's memory.
LOAD Product_Line,
Product_category,
Value
FROM
[C:\Qlikview\data\product_sales.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
Creation of Multi Box involves navigating through menu Layout → New Sheet Object → Multi Box. The following screen shows these steps.
Next we choose the fields of the Products sales tables to build the Multi Box.
Finishing the above steps brings the following screen, which shows the values of Product category as a Multi box.
Other Sheet Objects automatically get associated with the Multi Box and the association is easily observed by selecting values from the Multi Box.
70 Lectures
5 hours
Arthur Fong
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3243,
"s": 2920,
"text": "A Multi Box represents the list of all the values from multiple fields as drop down values. Similar to list box, the selection of a value in Multi Box highlights the related values in other sheet objects. This helps in faster visual analysis. It is also very useful to follow a drill down path among various sheet objects."
},
{
"code": null,
"e": 3370,
"s": 3243,
"text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories."
},
{
"code": null,
"e": 4054,
"s": 3370,
"text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n"
},
{
"code": null,
"e": 4420,
"s": 4054,
"text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into the QlikView's memory."
},
{
"code": null,
"e": 4582,
"s": 4420,
"text": "LOAD Product_Line, \n Product_category, \n Value\nFROM\n[C:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);"
},
{
"code": null,
"e": 4716,
"s": 4582,
"text": "Creation of Multi Box involves navigating through menu Layout → New Sheet Object → Multi Box. The following screen shows these steps."
},
{
"code": null,
"e": 4795,
"s": 4716,
"text": "Next we choose the fields of the Products sales tables to build the Multi Box."
},
{
"code": null,
"e": 4909,
"s": 4795,
"text": "Finishing the above steps brings the following screen, which shows the values of Product category as a Multi box."
},
{
"code": null,
"e": 5056,
"s": 4909,
"text": "Other Sheet Objects automatically get associated with the Multi Box and the association is easily observed by selecting values from the Multi Box."
},
{
"code": null,
"e": 5089,
"s": 5056,
"text": "\n 70 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5102,
"s": 5089,
"text": " Arthur Fong"
},
{
"code": null,
"e": 5109,
"s": 5102,
"text": " Print"
},
{
"code": null,
"e": 5120,
"s": 5109,
"text": " Add Notes"
}
] |
QTP - Virtual Objects | Sometimes, an application under test may contain standard window object but are not recognized by QTP. Under these circumstances, objects can be defined as virtual object(VO) of type button, link etc. so that user actions can be simulated on the virtual objects during execution.
Let us say we are automating a scenario in Microsoft Word. I activated MS word application and I click on any icon in the ribbon. For example, on the Ribbon, Insert tab is clicked and then the user clicks the "Picture" button. A button is recognized as WinObject; hence, importance of virtual objects is pronounced.
Window("Microsoft Word").WinObject("Ribbon").Click 145,45
Window("Microsoft Word").WinObject("Ribbon").WinObject("Picture...").Click
170,104
Step 1 − In such scenarios, virtual Objects are created using Virtual Object Manager or New Virtual Object from "Tools" >> "Virtual Object" >> "New Virtual Object" and click the "Next" button.
Step 2 − Map the Object against the Class Type and click "Next".
Step 3 − Click "Mark Object" Button. A cross hair cursor would appear and mark the object that you would like to map and click "Next".
Step 4 − Select the parent of the Virtual object and click "Next".
Step 5 − Name the collection in which you would like to store the virtual object and click "Finish".
Virtual object Manager manages the collections of Virtual objects. Testers can add or Delete the Virtual Objects from the Virtual Object manager.
Navigation to Virtual object Manager : "Tools" >> "Virtual Object Manager" as shown below −
After creating the Virtual Objects, the created object can be used as shown below −
Window("Microsoft Word").WinObject("Ribbon").VirtualButton("button").Click
QTP does not support virtual objects for analog or low-level recording.
QTP does not support virtual objects for analog or low-level recording.
Checkpoints cannot be added on Virtual Objects.
Checkpoints cannot be added on Virtual Objects.
Virtual Objects are not controlled by Object Repository.
Virtual Objects are not controlled by Object Repository.
Though we map an object to a particular class (button or List), all the methods of the native objects are not supported by Virtual objects.
Though we map an object to a particular class (button or List), all the methods of the native objects are not supported by Virtual objects.
Object Spy cannot be used on Virtual Object.
Object Spy cannot be used on Virtual Object.
The test execution will fail if the screen resolution changes as the co-ordinates change.
The test execution will fail if the screen resolution changes as the co-ordinates change.
Application Window should be of same screen size so that Virtual objects are captured correctly.
Application Window should be of same screen size so that Virtual objects are captured correctly.
108 Lectures
8 hours
Pavan Lalwani
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2402,
"s": 2122,
"text": "Sometimes, an application under test may contain standard window object but are not recognized by QTP. Under these circumstances, objects can be defined as virtual object(VO) of type button, link etc. so that user actions can be simulated on the virtual objects during execution."
},
{
"code": null,
"e": 2718,
"s": 2402,
"text": "Let us say we are automating a scenario in Microsoft Word. I activated MS word application and I click on any icon in the ribbon. For example, on the Ribbon, Insert tab is clicked and then the user clicks the \"Picture\" button. A button is recognized as WinObject; hence, importance of virtual objects is pronounced."
},
{
"code": null,
"e": 2860,
"s": 2718,
"text": "Window(\"Microsoft Word\").WinObject(\"Ribbon\").Click 145,45\nWindow(\"Microsoft Word\").WinObject(\"Ribbon\").WinObject(\"Picture...\").Click \n170,104"
},
{
"code": null,
"e": 3053,
"s": 2860,
"text": "Step 1 − In such scenarios, virtual Objects are created using Virtual Object Manager or New Virtual Object from \"Tools\" >> \"Virtual Object\" >> \"New Virtual Object\" and click the \"Next\" button."
},
{
"code": null,
"e": 3118,
"s": 3053,
"text": "Step 2 − Map the Object against the Class Type and click \"Next\"."
},
{
"code": null,
"e": 3253,
"s": 3118,
"text": "Step 3 − Click \"Mark Object\" Button. A cross hair cursor would appear and mark the object that you would like to map and click \"Next\"."
},
{
"code": null,
"e": 3320,
"s": 3253,
"text": "Step 4 − Select the parent of the Virtual object and click \"Next\"."
},
{
"code": null,
"e": 3421,
"s": 3320,
"text": "Step 5 − Name the collection in which you would like to store the virtual object and click \"Finish\"."
},
{
"code": null,
"e": 3567,
"s": 3421,
"text": "Virtual object Manager manages the collections of Virtual objects. Testers can add or Delete the Virtual Objects from the Virtual Object manager."
},
{
"code": null,
"e": 3659,
"s": 3567,
"text": "Navigation to Virtual object Manager : \"Tools\" >> \"Virtual Object Manager\" as shown below −"
},
{
"code": null,
"e": 3743,
"s": 3659,
"text": "After creating the Virtual Objects, the created object can be used as shown below −"
},
{
"code": null,
"e": 3819,
"s": 3743,
"text": "Window(\"Microsoft Word\").WinObject(\"Ribbon\").VirtualButton(\"button\").Click\n"
},
{
"code": null,
"e": 3891,
"s": 3819,
"text": "QTP does not support virtual objects for analog or low-level recording."
},
{
"code": null,
"e": 3963,
"s": 3891,
"text": "QTP does not support virtual objects for analog or low-level recording."
},
{
"code": null,
"e": 4011,
"s": 3963,
"text": "Checkpoints cannot be added on Virtual Objects."
},
{
"code": null,
"e": 4059,
"s": 4011,
"text": "Checkpoints cannot be added on Virtual Objects."
},
{
"code": null,
"e": 4116,
"s": 4059,
"text": "Virtual Objects are not controlled by Object Repository."
},
{
"code": null,
"e": 4173,
"s": 4116,
"text": "Virtual Objects are not controlled by Object Repository."
},
{
"code": null,
"e": 4313,
"s": 4173,
"text": "Though we map an object to a particular class (button or List), all the methods of the native objects are not supported by Virtual objects."
},
{
"code": null,
"e": 4453,
"s": 4313,
"text": "Though we map an object to a particular class (button or List), all the methods of the native objects are not supported by Virtual objects."
},
{
"code": null,
"e": 4498,
"s": 4453,
"text": "Object Spy cannot be used on Virtual Object."
},
{
"code": null,
"e": 4543,
"s": 4498,
"text": "Object Spy cannot be used on Virtual Object."
},
{
"code": null,
"e": 4633,
"s": 4543,
"text": "The test execution will fail if the screen resolution changes as the co-ordinates change."
},
{
"code": null,
"e": 4723,
"s": 4633,
"text": "The test execution will fail if the screen resolution changes as the co-ordinates change."
},
{
"code": null,
"e": 4820,
"s": 4723,
"text": "Application Window should be of same screen size so that Virtual objects are captured correctly."
},
{
"code": null,
"e": 4917,
"s": 4820,
"text": "Application Window should be of same screen size so that Virtual objects are captured correctly."
},
{
"code": null,
"e": 4951,
"s": 4917,
"text": "\n 108 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4966,
"s": 4951,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 4973,
"s": 4966,
"text": " Print"
},
{
"code": null,
"e": 4984,
"s": 4973,
"text": " Add Notes"
}
] |
jQuery Tutorial | jQuery is a JavaScript Library.
jQuery greatly simplifies JavaScript programming.
jQuery is easy to learn.
With our online editor, you can edit the code, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Use the correct selector to hide all <p> elements.
$("").hide();
Start the Exercise
Learn by examples! At W3Schools you will find a lot of jQuery examples to edit and test yourself.
Test your jQuery skills at W3Schools!
At W3Schools you will find a complete reference of all jQuery selectors, methods, properties and events.
Get certified by completing the JQUERY course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 32,
"s": 0,
"text": "jQuery is a JavaScript Library."
},
{
"code": null,
"e": 82,
"s": 32,
"text": "jQuery greatly simplifies JavaScript programming."
},
{
"code": null,
"e": 107,
"s": 82,
"text": "jQuery is easy to learn."
},
{
"code": null,
"e": 196,
"s": 107,
"text": "With our online editor, you can edit the code, and click on a button to view the result."
},
{
"code": null,
"e": 255,
"s": 196,
"text": "Click on the \"Try it Yourself\" button to see how it works."
},
{
"code": null,
"e": 306,
"s": 255,
"text": "Use the correct selector to hide all <p> elements."
},
{
"code": null,
"e": 321,
"s": 306,
"text": "$(\"\").hide();\n"
},
{
"code": null,
"e": 340,
"s": 321,
"text": "Start the Exercise"
},
{
"code": null,
"e": 438,
"s": 340,
"text": "Learn by examples! At W3Schools you will find a lot of jQuery examples to edit and test yourself."
},
{
"code": null,
"e": 476,
"s": 438,
"text": "Test your jQuery skills at W3Schools!"
},
{
"code": null,
"e": 581,
"s": 476,
"text": "At W3Schools you will find a complete reference of all jQuery selectors, methods, properties and events."
},
{
"code": null,
"e": 627,
"s": 581,
"text": "Get certified by completing the JQUERY course"
},
{
"code": null,
"e": 660,
"s": 627,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 702,
"s": 660,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 809,
"s": 702,
"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": 828,
"s": 809,
"text": "[email protected]"
}
] |
html.parser — Simple HTML and XHTML parser in Python | The HTMLParser class defined in this module provides functionality to parse HTML and XHMTL documents. This class contains handler methods that can identify tags, data, comments and other HTML elements.
We have to define a new class that inherits HTMLParser class and submit HTML text using feed() method.
from html.parser import HTMLParser
class parser(HTMLParser):
pass
p = parser()
p.feed('<a href = "www.tutorialspoint.com"></a>')
We have to override its following methods
handle_starttag(tag, attrs):
HTML tags normally are in pairs of starting tag and end tag. For example <head> and </head>. This method is called to handle the start of a tag.
Name of the tag converted to lower case. The attrs argument stands for attributes found inside the tag’s <> brackets.
For instance, for the tag <a href = "www.tutorialspoint.com"></a>, is fed to the parser object.
from html.parser import HTMLParser
class parser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Start tag:", tag)
for attr in attrs:
print(" attr:", attr)
p = parser()
p.feed('<a href = "www.tutorialspoint.com">')
Start tag: a
attr: ('href', 'www.tutorialspoint.com')
handle_endtag(tag):
This method is called to handle the end tag of an element.
def handle_endtag(self, tag):
print ("end tag",tag)
handle_data(data):
This method is called to process arbitrary data between tags. For example:
def handle_data(self, data):
print (data)
p = parser()
html = '''
<html>
<body>
<h1>Tutorialspoint</h1>
<b>Python standard library</b>
<p>HTML module</p>
</body>
</html>'''
p.feed(html)
Start tag: h1
Tutorialspoint
end tag h1
Start tag: b
Python standard library
end tag b
Start tag: p
HTML module
end tag p
Other methods in HTMLParser class are as follows:
Return the text of the most recently opened start tag.
Return current line number and offset.
Similar to handle_starttag(), but called when the parser encounters an XHTML-style empty tag (<img ... />).
This method is called when a comment is encountered (e.g. <!--comment-->). | [
{
"code": null,
"e": 1264,
"s": 1062,
"text": "The HTMLParser class defined in this module provides functionality to parse HTML and XHMTL documents. This class contains handler methods that can identify tags, data, comments and other HTML elements."
},
{
"code": null,
"e": 1367,
"s": 1264,
"text": "We have to define a new class that inherits HTMLParser class and submit HTML text using feed() method."
},
{
"code": null,
"e": 1496,
"s": 1367,
"text": "from html.parser import HTMLParser\nclass parser(HTMLParser):\npass\np = parser()\np.feed('<a href = \"www.tutorialspoint.com\"></a>')"
},
{
"code": null,
"e": 1538,
"s": 1496,
"text": "We have to override its following methods"
},
{
"code": null,
"e": 1567,
"s": 1538,
"text": "handle_starttag(tag, attrs):"
},
{
"code": null,
"e": 1712,
"s": 1567,
"text": "HTML tags normally are in pairs of starting tag and end tag. For example <head> and </head>. This method is called to handle the start of a tag."
},
{
"code": null,
"e": 1830,
"s": 1712,
"text": "Name of the tag converted to lower case. The attrs argument stands for attributes found inside the tag’s <> brackets."
},
{
"code": null,
"e": 1926,
"s": 1830,
"text": "For instance, for the tag <a href = \"www.tutorialspoint.com\"></a>, is fed to the parser object."
},
{
"code": null,
"e": 2151,
"s": 1926,
"text": "from html.parser import HTMLParser\nclass parser(HTMLParser):\ndef handle_starttag(self, tag, attrs):\nprint(\"Start tag:\", tag)\nfor attr in attrs:\nprint(\" attr:\", attr)\np = parser()\np.feed('<a href = \"www.tutorialspoint.com\">')"
},
{
"code": null,
"e": 2225,
"s": 2151,
"text": "Start tag: a\nattr: ('href', 'www.tutorialspoint.com')\nhandle_endtag(tag):"
},
{
"code": null,
"e": 2284,
"s": 2225,
"text": "This method is called to handle the end tag of an element."
},
{
"code": null,
"e": 2355,
"s": 2284,
"text": "def handle_endtag(self, tag):\nprint (\"end tag\",tag)\nhandle_data(data):"
},
{
"code": null,
"e": 2430,
"s": 2355,
"text": "This method is called to process arbitrary data between tags. For example:"
},
{
"code": null,
"e": 2640,
"s": 2430,
"text": "def handle_data(self, data):\nprint (data)\np = parser()\nhtml = '''\n<html>\n <body>\n <h1>Tutorialspoint</h1>\n <b>Python standard library</b>\n <p>HTML module</p>\n </body>\n</html>'''\np.feed(html)"
},
{
"code": null,
"e": 2762,
"s": 2640,
"text": "Start tag: h1\nTutorialspoint\nend tag h1\nStart tag: b\nPython standard library\nend tag b\nStart tag: p\nHTML module\nend tag p"
},
{
"code": null,
"e": 2812,
"s": 2762,
"text": "Other methods in HTMLParser class are as follows:"
},
{
"code": null,
"e": 2867,
"s": 2812,
"text": "Return the text of the most recently opened start tag."
},
{
"code": null,
"e": 2906,
"s": 2867,
"text": "Return current line number and offset."
},
{
"code": null,
"e": 3014,
"s": 2906,
"text": "Similar to handle_starttag(), but called when the parser encounters an XHTML-style empty tag (<img ... />)."
},
{
"code": null,
"e": 3089,
"s": 3014,
"text": "This method is called when a comment is encountered (e.g. <!--comment-->)."
}
] |
p5.js | floor() function - GeeksforGeeks | 09 Apr, 2019
The floor() function in p5.js is used to calculate the floor value of a number. This function maps to the Math.floor() of javascript. It calculates the closest int value that is less than or equal to the value of the parameter.
Syntax
floor(number)
Parameters: The function accepts only one parameter as mentioned above and described below:
number : This parameter stores the number to compute.Below program illustrates the floor() function in p5.js:Example:function setup() { //create Canvas of size 270*80 createCanvas(270, 80);} function draw() { background(220); //initialize the parameter let x = 65.67; //call to floor() function let y = floor(x); textSize(16); fill(color('red')); text("Given Number is : " + x, 50, 30); text("Computed Number is : " + y, 50, 50);}Output:Reference: https://p5js.org/reference/#/p5/floorMy Personal Notes
arrow_drop_upSave
Below program illustrates the floor() function in p5.js:Example:
function setup() { //create Canvas of size 270*80 createCanvas(270, 80);} function draw() { background(220); //initialize the parameter let x = 65.67; //call to floor() function let y = floor(x); textSize(16); fill(color('red')); text("Given Number is : " + x, 50, 30); text("Computed Number is : " + y, 50, 50);}
Output:
Reference: https://p5js.org/reference/#/p5/floor
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 43692,
"s": 43664,
"text": "\n09 Apr, 2019"
},
{
"code": null,
"e": 43920,
"s": 43692,
"text": "The floor() function in p5.js is used to calculate the floor value of a number. This function maps to the Math.floor() of javascript. It calculates the closest int value that is less than or equal to the value of the parameter."
},
{
"code": null,
"e": 43927,
"s": 43920,
"text": "Syntax"
},
{
"code": null,
"e": 43942,
"s": 43927,
"text": "floor(number)\n"
},
{
"code": null,
"e": 44034,
"s": 43942,
"text": "Parameters: The function accepts only one parameter as mentioned above and described below:"
},
{
"code": null,
"e": 44597,
"s": 44034,
"text": "number : This parameter stores the number to compute.Below program illustrates the floor() function in p5.js:Example:function setup() { //create Canvas of size 270*80 createCanvas(270, 80);} function draw() { background(220); //initialize the parameter let x = 65.67; //call to floor() function let y = floor(x); textSize(16); fill(color('red')); text(\"Given Number is : \" + x, 50, 30); text(\"Computed Number is : \" + y, 50, 50);}Output:Reference: https://p5js.org/reference/#/p5/floorMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 44662,
"s": 44597,
"text": "Below program illustrates the floor() function in p5.js:Example:"
},
{
"code": "function setup() { //create Canvas of size 270*80 createCanvas(270, 80);} function draw() { background(220); //initialize the parameter let x = 65.67; //call to floor() function let y = floor(x); textSize(16); fill(color('red')); text(\"Given Number is : \" + x, 50, 30); text(\"Computed Number is : \" + y, 50, 50);}",
"e": 45018,
"s": 44662,
"text": null
},
{
"code": null,
"e": 45026,
"s": 45018,
"text": "Output:"
},
{
"code": null,
"e": 45075,
"s": 45026,
"text": "Reference: https://p5js.org/reference/#/p5/floor"
},
{
"code": null,
"e": 45092,
"s": 45075,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 45103,
"s": 45092,
"text": "JavaScript"
},
{
"code": null,
"e": 45120,
"s": 45103,
"text": "Web Technologies"
},
{
"code": null,
"e": 45218,
"s": 45120,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45263,
"s": 45218,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 45324,
"s": 45263,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 45393,
"s": 45324,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 45465,
"s": 45393,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 45517,
"s": 45465,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 45559,
"s": 45517,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 45621,
"s": 45559,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 45664,
"s": 45621,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 45697,
"s": 45664,
"text": "Installation of Node.js on Linux"
}
] |
Getting started with Python environments (using Conda) | by Robert Sandor | Towards Data Science | Whether you want one or have no idea what it is, you’ll have to deal with environments in Python eventually. If you’re a newbie to Python like myselfor a newbie to generally setting up your workspace for any programming language, then you may have dealt with the pain of setting up your environment for the first time.
Between the lack of knowledge of what you’re doing and why it’s necessary, the many different online guides that may not have the exact same instructions and numerous Stack Overflow posts that help with very specific situations, I found it confusing to understand what exactly environments were, when they were needed, and how to set up my own. This guide is to help build an intuition for environments and provide some examples of dealing with them, particularly using conda, the package manager for Anaconda.
Python, like many other programming languages, has different versions. And sometimes when we create software, the software needs to run on a specific version of the language because our software expects a certain behavior that is present in older versions but changes in newer versions. Likewise, we may need to use specific versions of the libraries for similar reasons. But we may have many projects on our computer, perhaps a Flask app that runs on version 0.11 (the first one you made!) and Python 2.7 and even a more modern Flask app that runs on version 0.12 and Python 3.4. If I try running both at once on Python 2 or Python 3, one of them may break because some of the code that runs on Python 2 doesn’t run on Python 3 or vice versa. This is where virtual environments become useful.
Virtual environments keep these dependencies in separate “sandboxes” so you can switch between both applications easily and get them running. For those more familiar with programming, virtual environments are analogous to Docker containers. Additionally, package managers for other languages, like JavaScript’s NPM (Node Package Manager), take care of most of these details for you, but you’ll have to get your hands dirty in Python and deal with the environments yourself.
There are multiple ways of creating an environment, including using virtualenv, venv (built in to the Python 3 standard library), and conda, the package manager associated with Anaconda. There are some arguments as to why you should choose conda over virtualenv as outlined in Myth #5 in this blog post, but I’ll just focus on how to use conda in this guide since that’s a popular tool for data science, which is what I’m focused on right now. This guide will presume that you already have Anaconda or miniconda installed; all the instructions will also be on the bash command line. For reference, I run my commands on the Terminal on Mac OS X.
To quickly create an environment using conda, you can type in the command:
conda create --name your_env_name python=3.7 -y
In this command, the ‘python=3.7’ portion specifies which version of python I want to set up the environment in; you can change the version to whatever suits your needs. In other snippets you see online, you may see ‘-n’ instead of ‘ — name’; they mean exactly the same thing. The ‘-y’ flag essentially tells the command line to say ‘yes’ to all of the prompts that follow; it isn’t strictly necessary but it does save you a little hassle.
conda create --name your_env_name python=3.7 scipy=0.15.0 astroid babel
The ‘conda create’ command will effectively load all of the packages at once, which is preferable to loading them in 1 at a time as that can lead to dependency conflicts. So you could somewhat manually add all of the packages you need, but that may be tedious if you have many packages; besides that, there would be a lot of typing involved on the command line and a slip of the finger may cause you to reenter the command. Even worse, the command may not remain in your shell history and if you wanted to recreate the exact same environment in the future, it would be very tedious if not difficult.
If you didn’t want to create the environment from the command line for those reasons or others, you could create a YAML (YAML Ain’t Markup Language) file, which acts like a configuration file.Your YAML file may look something like this:
name: your_env_namechannels: — defaultsdependencies: — ca-certificates=2018.03.07=0prefix: /Users/your_username/anaconda3/envs/your_env_name
If that file were called ‘environment.yml’, then I could create the environment using the command below:
conda env create -f environment.yml
The ‘-f’ flag stands for file and the filename of the YAML file should immediately follow the ‘-f’ flag.
Now that’s great if you can easily create a YAML file and you know all of the packages you need. But what if you had an existing environment that you would like to duplicate? Perhaps you’d like to duplicate the application onto another server and want the exact same setup for consistency. If that’s the case, then you can run the command below.
conda env export > my_environment.yml
The greater than symbol, ‘>’, indicates that the output is writing to a file called ‘my_environment.yml’. If there were any contents in ‘my_environment.yml’ before this command, they would be overwritten.
As a note, for conda you need a YAML file; if you decide to use virtualenv, a txt file would also suffice for everything done here, but conda specifically needs a YAML file.
So now that you have an environment created and assuming that you’re using conda, let’s quickly verify that it exists using the command:
conda info --envs
This command should display the current environments, which may look something like this:
practice /Users/your_username/anaconda3/envs/practicebase /Users/your_username/anaconda3your_env_name /Users/your_username/anaconda3/envs/your_env_name
After confirming that you created the environment, you can now actually use it. We can accomplish this by typing (assuming your environment is underneath your base):
conda activate your_env_name
At this point, your terminal prompt should look something like this:
(your_env_name) Your_Machine:your_directory username$
If that command doesn’t result in a similar output for whatever reason, you can specify the full path by typing in something similar to the command below:
conda activate /Users/your_username/anaconda3/envs/your_env_name
If, like me, you want to know exactly what is happening when you type in the word ‘activate’, it runs a bash script that exists within a subdirectory of the environment. In my case, the filepath to the script looked something like:
/Users/my_username/anaconda3/envs/my_env_name/lib/python3.6/venv/scripts/common/activate
To stop using the environment, type in
conda deactivate
In a similar fashion to the activate command, the deactivate command runs a function from the activate bash script.
If you would like to update the environment, type in:
conda env update –f environment.yml –n your_env_name
If you would like to get rid of the entire environment, merely type in:
conda remove --name your_env_name --all
The ‘ — all’ flag is to remove all packages from the environment and is necessary to completely clean the environment.
As a quick summary, this guide covered how to create your virtual environment by specifying packages on the command line as well as from within a YAML file, how to get into and out of the virtual environment, how to update it, and how to remove it once you no longer need it.
At this point, you should know enough to independently configure your environment as you see fit and have enough context for why you should create a virtual environment. While this guide didn’t go in depth on the differences between virtualenv, venv, and conda virtual environments, I’ve provided a few links below to get you started.
Please let me know if you have any questions or suggestions on how to make this better. | [
{
"code": null,
"e": 366,
"s": 47,
"text": "Whether you want one or have no idea what it is, you’ll have to deal with environments in Python eventually. If you’re a newbie to Python like myselfor a newbie to generally setting up your workspace for any programming language, then you may have dealt with the pain of setting up your environment for the first time."
},
{
"code": null,
"e": 877,
"s": 366,
"text": "Between the lack of knowledge of what you’re doing and why it’s necessary, the many different online guides that may not have the exact same instructions and numerous Stack Overflow posts that help with very specific situations, I found it confusing to understand what exactly environments were, when they were needed, and how to set up my own. This guide is to help build an intuition for environments and provide some examples of dealing with them, particularly using conda, the package manager for Anaconda."
},
{
"code": null,
"e": 1671,
"s": 877,
"text": "Python, like many other programming languages, has different versions. And sometimes when we create software, the software needs to run on a specific version of the language because our software expects a certain behavior that is present in older versions but changes in newer versions. Likewise, we may need to use specific versions of the libraries for similar reasons. But we may have many projects on our computer, perhaps a Flask app that runs on version 0.11 (the first one you made!) and Python 2.7 and even a more modern Flask app that runs on version 0.12 and Python 3.4. If I try running both at once on Python 2 or Python 3, one of them may break because some of the code that runs on Python 2 doesn’t run on Python 3 or vice versa. This is where virtual environments become useful."
},
{
"code": null,
"e": 2145,
"s": 1671,
"text": "Virtual environments keep these dependencies in separate “sandboxes” so you can switch between both applications easily and get them running. For those more familiar with programming, virtual environments are analogous to Docker containers. Additionally, package managers for other languages, like JavaScript’s NPM (Node Package Manager), take care of most of these details for you, but you’ll have to get your hands dirty in Python and deal with the environments yourself."
},
{
"code": null,
"e": 2790,
"s": 2145,
"text": "There are multiple ways of creating an environment, including using virtualenv, venv (built in to the Python 3 standard library), and conda, the package manager associated with Anaconda. There are some arguments as to why you should choose conda over virtualenv as outlined in Myth #5 in this blog post, but I’ll just focus on how to use conda in this guide since that’s a popular tool for data science, which is what I’m focused on right now. This guide will presume that you already have Anaconda or miniconda installed; all the instructions will also be on the bash command line. For reference, I run my commands on the Terminal on Mac OS X."
},
{
"code": null,
"e": 2865,
"s": 2790,
"text": "To quickly create an environment using conda, you can type in the command:"
},
{
"code": null,
"e": 2913,
"s": 2865,
"text": "conda create --name your_env_name python=3.7 -y"
},
{
"code": null,
"e": 3353,
"s": 2913,
"text": "In this command, the ‘python=3.7’ portion specifies which version of python I want to set up the environment in; you can change the version to whatever suits your needs. In other snippets you see online, you may see ‘-n’ instead of ‘ — name’; they mean exactly the same thing. The ‘-y’ flag essentially tells the command line to say ‘yes’ to all of the prompts that follow; it isn’t strictly necessary but it does save you a little hassle."
},
{
"code": null,
"e": 3425,
"s": 3353,
"text": "conda create --name your_env_name python=3.7 scipy=0.15.0 astroid babel"
},
{
"code": null,
"e": 4025,
"s": 3425,
"text": "The ‘conda create’ command will effectively load all of the packages at once, which is preferable to loading them in 1 at a time as that can lead to dependency conflicts. So you could somewhat manually add all of the packages you need, but that may be tedious if you have many packages; besides that, there would be a lot of typing involved on the command line and a slip of the finger may cause you to reenter the command. Even worse, the command may not remain in your shell history and if you wanted to recreate the exact same environment in the future, it would be very tedious if not difficult."
},
{
"code": null,
"e": 4262,
"s": 4025,
"text": "If you didn’t want to create the environment from the command line for those reasons or others, you could create a YAML (YAML Ain’t Markup Language) file, which acts like a configuration file.Your YAML file may look something like this:"
},
{
"code": null,
"e": 4403,
"s": 4262,
"text": "name: your_env_namechannels: — defaultsdependencies: — ca-certificates=2018.03.07=0prefix: /Users/your_username/anaconda3/envs/your_env_name"
},
{
"code": null,
"e": 4508,
"s": 4403,
"text": "If that file were called ‘environment.yml’, then I could create the environment using the command below:"
},
{
"code": null,
"e": 4544,
"s": 4508,
"text": "conda env create -f environment.yml"
},
{
"code": null,
"e": 4649,
"s": 4544,
"text": "The ‘-f’ flag stands for file and the filename of the YAML file should immediately follow the ‘-f’ flag."
},
{
"code": null,
"e": 4995,
"s": 4649,
"text": "Now that’s great if you can easily create a YAML file and you know all of the packages you need. But what if you had an existing environment that you would like to duplicate? Perhaps you’d like to duplicate the application onto another server and want the exact same setup for consistency. If that’s the case, then you can run the command below."
},
{
"code": null,
"e": 5033,
"s": 4995,
"text": "conda env export > my_environment.yml"
},
{
"code": null,
"e": 5238,
"s": 5033,
"text": "The greater than symbol, ‘>’, indicates that the output is writing to a file called ‘my_environment.yml’. If there were any contents in ‘my_environment.yml’ before this command, they would be overwritten."
},
{
"code": null,
"e": 5412,
"s": 5238,
"text": "As a note, for conda you need a YAML file; if you decide to use virtualenv, a txt file would also suffice for everything done here, but conda specifically needs a YAML file."
},
{
"code": null,
"e": 5549,
"s": 5412,
"text": "So now that you have an environment created and assuming that you’re using conda, let’s quickly verify that it exists using the command:"
},
{
"code": null,
"e": 5567,
"s": 5549,
"text": "conda info --envs"
},
{
"code": null,
"e": 5657,
"s": 5567,
"text": "This command should display the current environments, which may look something like this:"
},
{
"code": null,
"e": 5809,
"s": 5657,
"text": "practice /Users/your_username/anaconda3/envs/practicebase /Users/your_username/anaconda3your_env_name /Users/your_username/anaconda3/envs/your_env_name"
},
{
"code": null,
"e": 5975,
"s": 5809,
"text": "After confirming that you created the environment, you can now actually use it. We can accomplish this by typing (assuming your environment is underneath your base):"
},
{
"code": null,
"e": 6004,
"s": 5975,
"text": "conda activate your_env_name"
},
{
"code": null,
"e": 6073,
"s": 6004,
"text": "At this point, your terminal prompt should look something like this:"
},
{
"code": null,
"e": 6127,
"s": 6073,
"text": "(your_env_name) Your_Machine:your_directory username$"
},
{
"code": null,
"e": 6282,
"s": 6127,
"text": "If that command doesn’t result in a similar output for whatever reason, you can specify the full path by typing in something similar to the command below:"
},
{
"code": null,
"e": 6347,
"s": 6282,
"text": "conda activate /Users/your_username/anaconda3/envs/your_env_name"
},
{
"code": null,
"e": 6579,
"s": 6347,
"text": "If, like me, you want to know exactly what is happening when you type in the word ‘activate’, it runs a bash script that exists within a subdirectory of the environment. In my case, the filepath to the script looked something like:"
},
{
"code": null,
"e": 6668,
"s": 6579,
"text": "/Users/my_username/anaconda3/envs/my_env_name/lib/python3.6/venv/scripts/common/activate"
},
{
"code": null,
"e": 6707,
"s": 6668,
"text": "To stop using the environment, type in"
},
{
"code": null,
"e": 6724,
"s": 6707,
"text": "conda deactivate"
},
{
"code": null,
"e": 6840,
"s": 6724,
"text": "In a similar fashion to the activate command, the deactivate command runs a function from the activate bash script."
},
{
"code": null,
"e": 6894,
"s": 6840,
"text": "If you would like to update the environment, type in:"
},
{
"code": null,
"e": 6947,
"s": 6894,
"text": "conda env update –f environment.yml –n your_env_name"
},
{
"code": null,
"e": 7019,
"s": 6947,
"text": "If you would like to get rid of the entire environment, merely type in:"
},
{
"code": null,
"e": 7059,
"s": 7019,
"text": "conda remove --name your_env_name --all"
},
{
"code": null,
"e": 7178,
"s": 7059,
"text": "The ‘ — all’ flag is to remove all packages from the environment and is necessary to completely clean the environment."
},
{
"code": null,
"e": 7454,
"s": 7178,
"text": "As a quick summary, this guide covered how to create your virtual environment by specifying packages on the command line as well as from within a YAML file, how to get into and out of the virtual environment, how to update it, and how to remove it once you no longer need it."
},
{
"code": null,
"e": 7789,
"s": 7454,
"text": "At this point, you should know enough to independently configure your environment as you see fit and have enough context for why you should create a virtual environment. While this guide didn’t go in depth on the differences between virtualenv, venv, and conda virtual environments, I’ve provided a few links below to get you started."
}
] |
Style Bootstrap 4 card with bg-primary class | Use the bg-primary class in Bootstrap 4, to add important stuff to a card and set blue background color.
Style the Bootstrap 4 card as in the following code snippet −
<div class="card bg-primary text-white">
<div class="card-body">Medical Books</div>
</div>
I have set the body of the card in the card-body class −
<div class="card-body">
Medical Books
</div>
To implement the bg-primary class in Bootstarp 4, you can try to run the following code −
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/4.1.0/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/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Books</h2>
<div class="card bg-info text-white">
<div class="card-body">History Books</div>
</div><br>
<div class="card bg-primary text-white">
<div class="card-body">Medical Books</div>
</div><br>
</div>
</body>
</html> | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "Use the bg-primary class in Bootstrap 4, to add important stuff to a card and set blue background color."
},
{
"code": null,
"e": 1229,
"s": 1167,
"text": "Style the Bootstrap 4 card as in the following code snippet −"
},
{
"code": null,
"e": 1322,
"s": 1229,
"text": "<div class=\"card bg-primary text-white\">\n <div class=\"card-body\">Medical Books</div>\n</div>"
},
{
"code": null,
"e": 1379,
"s": 1322,
"text": "I have set the body of the card in the card-body class −"
},
{
"code": null,
"e": 1426,
"s": 1379,
"text": "<div class=\"card-body\">\n Medical Books\n</div>"
},
{
"code": null,
"e": 1516,
"s": 1426,
"text": "To implement the bg-primary class in Bootstarp 4, you can try to run the following code −"
},
{
"code": null,
"e": 1526,
"s": 1516,
"text": "Live Demo"
},
{
"code": null,
"e": 2303,
"s": 1526,
"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/4.1.0/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/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container\">\n <h2>Books</h2>\n <div class=\"card bg-info text-white\">\n <div class=\"card-body\">History Books</div>\n </div><br>\n <div class=\"card bg-primary text-white\">\n <div class=\"card-body\">Medical Books</div>\n </div><br>\n </div>\n\n</body>\n</html>"
}
] |
Number of subsets with product less than k - GeeksforGeeks | 25 May, 2021
You are given an array of n-elements, you have to find the number of subsets whose product of elements is less than or equal to a given integer k.
Examples:
Input : arr[] = {2, 4, 5, 3}, k = 12
Output : 8
Explanation : All possible subsets whose
products are less than 12 are:
(2), (4), (5), (3), (2, 4), (2, 5), (2, 3), (4, 3)
Input : arr[] = {12, 32, 21 }, k = 1
Output : 0
Explanation : there is not any subset such
that product of elements is less than 1
Approach : If we go through the basic approach to solve this problem, then we have to generate all possible 2n subset and for each of then we have to calculate product of elements of subset and compare products value with given then. But the disadvantage of this approach is that its time complexity is too high i.e. O(n*2n). Now, we can see that it is going to be exponential time complexity which should be avoided in case of competitive codings.Advance Approach : We are going to use the concept of meet in the middle. By, using this concept we can reduce the complexity of our approach to O(n*2n/2).
How to use MEET IN THE MIDDLE Approach :First of all we simply divide the given array into two equal parts and after that we generate all possible subsets for both parts of array and store value of elements product for each subset separately into two vectors (say subset1 & subset2). Now this will cost O(2n/2) time complexity. Now if we sort these two vectors(subset1 & subset2) having (2n/2) elements each then this will cost O(2n/2*log2n/2) ≈ O(n*(2n/2)) Time complexity. In next step we traverse one vector subset1 with 2n/2 elements and find the upper bound of k/subset1[i] in second vector which will tell us the count of total elements whose products will be less than or equal to k. And thus for each element in subset1 we will try to perform a binary search in form of upper_bound in subset2 resulting again a Time complexity of O(n*(2n/2)). So, if we try to compute our overall complexity for this approach we will have O(n*(2n/2) + n*(2n/2) + n*(2n/2)) ≈ O(n*(2n/2)) as our time complexity which is much efficient than our brute force approach.
Algorithm :
Divide array into two equal parts.Generate all subsets and for each subset calculate product of elements and push this to a vector. try this for both part of array.Sort both new vector which contains products of elements for each possible subsets.Traverse any one vector and find upper-bound of element k/vector[i] to find how many subsets are there for vector[i] whose product of elements is less than k.
Divide array into two equal parts.
Generate all subsets and for each subset calculate product of elements and push this to a vector. try this for both part of array.
Sort both new vector which contains products of elements for each possible subsets.
Traverse any one vector and find upper-bound of element k/vector[i] to find how many subsets are there for vector[i] whose product of elements is less than k.
Some key points to improve complexity :
Ignore elements from array if greater than k.
Ignore product of elements to push into vector (subset1 or subset2) if greater than k.YouTubeGeeksforGeeks Practice24.7K subscribersNumber of subsets with product less than or equals to K | Recently Asked in Morgan Stanley8/27InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 15:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=E3vpe9EKoSI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Below is the implementation of the above approach:C++Python3C++// CPP to find the count subset having product// less than k#include <bits/stdc++.h>using namespace std; int findSubset(long long int arr[], int n, long long int k){ // declare four vector for dividing array into // two halves and storing product value of // possible subsets for them vector<long long int> vect1, vect2, subset1, subset2; // ignore element greater than k and divide // array into 2 halves for (int i = 0; i < n; i++) { // ignore element if greater than k if (arr[i] > k) continue; if (i <= n / 2) vect1.push_back(arr[i]); else vect2.push_back(arr[i]); } // generate all subsets for 1st half (vect1) for (int i = 0; i < (1 << vect1.size()); i++) { long long value = 1; for (int j = 0; j < vect1.size(); j++) { if (i & (1 << j)) value *= vect1[j]; } // push only in case subset product is less // than equal to k if (value <= k) subset1.push_back(value); } // generate all subsets for 2nd half (vect2) for (int i = 0; i < (1 << vect2.size()); i++) { long long value = 1; for (int j = 0; j < vect2.size(); j++) { if (i & (1 << j)) value *= vect2[j]; } // push only in case subset product is // less than equal to k if (value <= k) subset2.push_back(value); } // sort subset2 sort(subset2.begin(), subset2.end()); long long count = 0; for (int i = 0; i < subset1.size(); i++) count += upper_bound(subset2.begin(), subset2.end(), (k / subset1[i])) - subset2.begin(); // for null subset decrement the value of count count--; // return count return count;} // driver programint main(){ long long int arr[] = { 4, 2, 3, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); long long int k = 25; cout << findSubset(arr, n, k); return 0;}Python3# Python3 to find the count subset # having product less than k import bisect def findSubset(arr, n, k): # declare four vector for dividing # array into two halves and storing # product value of possible subsets # for them vect1, vect2, subset1, subset2 = [], [], [], [] # ignore element greater than k and # divide array into 2 halves for i in range(0, n): # ignore element if greater than k if arr[i] > k: continue if i <= n // 2: vect1.append(arr[i]) else: vect2.append(arr[i]) # generate all subsets for 1st half (vect1) for i in range(0, (1 << len(vect1))): value = 1 for j in range(0, len(vect1)): if i & (1 << j): value *= vect1[j] # push only in case subset product # is less than equal to k if value <= k: subset1.append(value) # generate all subsets for 2nd half (vect2) for i in range(0, (1 << len(vect2))): value = 1 for j in range(0, len(vect2)): if i & (1 << j): value *= vect2[j] # push only in case subset product # is less than equal to k if value <= k: subset2.append(value) # sort subset2 subset2.sort() count = 0 for i in range(0, len(subset1)): count += bisect.bisect(subset2, (k // subset1[i])) # for null subset decrement the # value of count count -= 1 # return count return count # Driver Codeif __name__ == "__main__": arr = [4, 2, 3, 6, 5] n = len(arr) k = 25 print(findSubset(arr, n, k)) # This code is contributed by Rituraj JainOutput:15
My Personal Notes
arrow_drop_upSave
YouTubeGeeksforGeeks Practice24.7K subscribersNumber of subsets with product less than or equals to K | Recently Asked in Morgan Stanley8/27InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 15:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=E3vpe9EKoSI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Below is the implementation of the above approach:
C++
Python3
// CPP to find the count subset having product// less than k#include <bits/stdc++.h>using namespace std; int findSubset(long long int arr[], int n, long long int k){ // declare four vector for dividing array into // two halves and storing product value of // possible subsets for them vector<long long int> vect1, vect2, subset1, subset2; // ignore element greater than k and divide // array into 2 halves for (int i = 0; i < n; i++) { // ignore element if greater than k if (arr[i] > k) continue; if (i <= n / 2) vect1.push_back(arr[i]); else vect2.push_back(arr[i]); } // generate all subsets for 1st half (vect1) for (int i = 0; i < (1 << vect1.size()); i++) { long long value = 1; for (int j = 0; j < vect1.size(); j++) { if (i & (1 << j)) value *= vect1[j]; } // push only in case subset product is less // than equal to k if (value <= k) subset1.push_back(value); } // generate all subsets for 2nd half (vect2) for (int i = 0; i < (1 << vect2.size()); i++) { long long value = 1; for (int j = 0; j < vect2.size(); j++) { if (i & (1 << j)) value *= vect2[j]; } // push only in case subset product is // less than equal to k if (value <= k) subset2.push_back(value); } // sort subset2 sort(subset2.begin(), subset2.end()); long long count = 0; for (int i = 0; i < subset1.size(); i++) count += upper_bound(subset2.begin(), subset2.end(), (k / subset1[i])) - subset2.begin(); // for null subset decrement the value of count count--; // return count return count;} // driver programint main(){ long long int arr[] = { 4, 2, 3, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); long long int k = 25; cout << findSubset(arr, n, k); return 0;}
# Python3 to find the count subset # having product less than k import bisect def findSubset(arr, n, k): # declare four vector for dividing # array into two halves and storing # product value of possible subsets # for them vect1, vect2, subset1, subset2 = [], [], [], [] # ignore element greater than k and # divide array into 2 halves for i in range(0, n): # ignore element if greater than k if arr[i] > k: continue if i <= n // 2: vect1.append(arr[i]) else: vect2.append(arr[i]) # generate all subsets for 1st half (vect1) for i in range(0, (1 << len(vect1))): value = 1 for j in range(0, len(vect1)): if i & (1 << j): value *= vect1[j] # push only in case subset product # is less than equal to k if value <= k: subset1.append(value) # generate all subsets for 2nd half (vect2) for i in range(0, (1 << len(vect2))): value = 1 for j in range(0, len(vect2)): if i & (1 << j): value *= vect2[j] # push only in case subset product # is less than equal to k if value <= k: subset2.append(value) # sort subset2 subset2.sort() count = 0 for i in range(0, len(subset1)): count += bisect.bisect(subset2, (k // subset1[i])) # for null subset decrement the # value of count count -= 1 # return count return count # Driver Codeif __name__ == "__main__": arr = [4, 2, 3, 6, 5] n = len(arr) k = 25 print(findSubset(arr, n, k)) # This code is contributed by Rituraj Jain
15
rituraj_jain
cpp-vector
subset
Arrays
Technical Scripter
Arrays
subset
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
Write a program to reverse an array or string
Largest Sum Contiguous Subarray
Multidimensional Arrays in Java
Introduction to Arrays | [
{
"code": null,
"e": 41274,
"s": 41246,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 41421,
"s": 41274,
"text": "You are given an array of n-elements, you have to find the number of subsets whose product of elements is less than or equal to a given integer k."
},
{
"code": null,
"e": 41431,
"s": 41421,
"text": "Examples:"
},
{
"code": null,
"e": 41737,
"s": 41431,
"text": "Input : arr[] = {2, 4, 5, 3}, k = 12\nOutput : 8\nExplanation : All possible subsets whose \nproducts are less than 12 are:\n(2), (4), (5), (3), (2, 4), (2, 5), (2, 3), (4, 3)\n\nInput : arr[] = {12, 32, 21 }, k = 1\nOutput : 0\nExplanation : there is not any subset such \nthat product of elements is less than 1\n"
},
{
"code": null,
"e": 42341,
"s": 41737,
"text": "Approach : If we go through the basic approach to solve this problem, then we have to generate all possible 2n subset and for each of then we have to calculate product of elements of subset and compare products value with given then. But the disadvantage of this approach is that its time complexity is too high i.e. O(n*2n). Now, we can see that it is going to be exponential time complexity which should be avoided in case of competitive codings.Advance Approach : We are going to use the concept of meet in the middle. By, using this concept we can reduce the complexity of our approach to O(n*2n/2)."
},
{
"code": null,
"e": 43397,
"s": 42341,
"text": "How to use MEET IN THE MIDDLE Approach :First of all we simply divide the given array into two equal parts and after that we generate all possible subsets for both parts of array and store value of elements product for each subset separately into two vectors (say subset1 & subset2). Now this will cost O(2n/2) time complexity. Now if we sort these two vectors(subset1 & subset2) having (2n/2) elements each then this will cost O(2n/2*log2n/2) ≈ O(n*(2n/2)) Time complexity. In next step we traverse one vector subset1 with 2n/2 elements and find the upper bound of k/subset1[i] in second vector which will tell us the count of total elements whose products will be less than or equal to k. And thus for each element in subset1 we will try to perform a binary search in form of upper_bound in subset2 resulting again a Time complexity of O(n*(2n/2)). So, if we try to compute our overall complexity for this approach we will have O(n*(2n/2) + n*(2n/2) + n*(2n/2)) ≈ O(n*(2n/2)) as our time complexity which is much efficient than our brute force approach."
},
{
"code": null,
"e": 43409,
"s": 43397,
"text": "Algorithm :"
},
{
"code": null,
"e": 43815,
"s": 43409,
"text": "Divide array into two equal parts.Generate all subsets and for each subset calculate product of elements and push this to a vector. try this for both part of array.Sort both new vector which contains products of elements for each possible subsets.Traverse any one vector and find upper-bound of element k/vector[i] to find how many subsets are there for vector[i] whose product of elements is less than k."
},
{
"code": null,
"e": 43850,
"s": 43815,
"text": "Divide array into two equal parts."
},
{
"code": null,
"e": 43981,
"s": 43850,
"text": "Generate all subsets and for each subset calculate product of elements and push this to a vector. try this for both part of array."
},
{
"code": null,
"e": 44065,
"s": 43981,
"text": "Sort both new vector which contains products of elements for each possible subsets."
},
{
"code": null,
"e": 44224,
"s": 44065,
"text": "Traverse any one vector and find upper-bound of element k/vector[i] to find how many subsets are there for vector[i] whose product of elements is less than k."
},
{
"code": null,
"e": 44264,
"s": 44224,
"text": "Some key points to improve complexity :"
},
{
"code": null,
"e": 44310,
"s": 44264,
"text": "Ignore elements from array if greater than k."
},
{
"code": null,
"e": 49136,
"s": 44310,
"text": "Ignore product of elements to push into vector (subset1 or subset2) if greater than k.YouTubeGeeksforGeeks Practice24.7K subscribersNumber of subsets with product less than or equals to K | Recently Asked in Morgan Stanley8/27InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 15:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=E3vpe9EKoSI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Below is the implementation of the above approach:C++Python3C++// CPP to find the count subset having product// less than k#include <bits/stdc++.h>using namespace std; int findSubset(long long int arr[], int n, long long int k){ // declare four vector for dividing array into // two halves and storing product value of // possible subsets for them vector<long long int> vect1, vect2, subset1, subset2; // ignore element greater than k and divide // array into 2 halves for (int i = 0; i < n; i++) { // ignore element if greater than k if (arr[i] > k) continue; if (i <= n / 2) vect1.push_back(arr[i]); else vect2.push_back(arr[i]); } // generate all subsets for 1st half (vect1) for (int i = 0; i < (1 << vect1.size()); i++) { long long value = 1; for (int j = 0; j < vect1.size(); j++) { if (i & (1 << j)) value *= vect1[j]; } // push only in case subset product is less // than equal to k if (value <= k) subset1.push_back(value); } // generate all subsets for 2nd half (vect2) for (int i = 0; i < (1 << vect2.size()); i++) { long long value = 1; for (int j = 0; j < vect2.size(); j++) { if (i & (1 << j)) value *= vect2[j]; } // push only in case subset product is // less than equal to k if (value <= k) subset2.push_back(value); } // sort subset2 sort(subset2.begin(), subset2.end()); long long count = 0; for (int i = 0; i < subset1.size(); i++) count += upper_bound(subset2.begin(), subset2.end(), (k / subset1[i])) - subset2.begin(); // for null subset decrement the value of count count--; // return count return count;} // driver programint main(){ long long int arr[] = { 4, 2, 3, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); long long int k = 25; cout << findSubset(arr, n, k); return 0;}Python3# Python3 to find the count subset # having product less than k import bisect def findSubset(arr, n, k): # declare four vector for dividing # array into two halves and storing # product value of possible subsets # for them vect1, vect2, subset1, subset2 = [], [], [], [] # ignore element greater than k and # divide array into 2 halves for i in range(0, n): # ignore element if greater than k if arr[i] > k: continue if i <= n // 2: vect1.append(arr[i]) else: vect2.append(arr[i]) # generate all subsets for 1st half (vect1) for i in range(0, (1 << len(vect1))): value = 1 for j in range(0, len(vect1)): if i & (1 << j): value *= vect1[j] # push only in case subset product # is less than equal to k if value <= k: subset1.append(value) # generate all subsets for 2nd half (vect2) for i in range(0, (1 << len(vect2))): value = 1 for j in range(0, len(vect2)): if i & (1 << j): value *= vect2[j] # push only in case subset product # is less than equal to k if value <= k: subset2.append(value) # sort subset2 subset2.sort() count = 0 for i in range(0, len(subset1)): count += bisect.bisect(subset2, (k // subset1[i])) # for null subset decrement the # value of count count -= 1 # return count return count # Driver Codeif __name__ == \"__main__\": arr = [4, 2, 3, 6, 5] n = len(arr) k = 25 print(findSubset(arr, n, k)) # This code is contributed by Rituraj JainOutput:15\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 50024,
"s": 49136,
"text": "YouTubeGeeksforGeeks Practice24.7K subscribersNumber of subsets with product less than or equals to K | Recently Asked in Morgan Stanley8/27InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 15:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=E3vpe9EKoSI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 50075,
"s": 50024,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 50079,
"s": 50075,
"text": "C++"
},
{
"code": null,
"e": 50087,
"s": 50079,
"text": "Python3"
},
{
"code": "// CPP to find the count subset having product// less than k#include <bits/stdc++.h>using namespace std; int findSubset(long long int arr[], int n, long long int k){ // declare four vector for dividing array into // two halves and storing product value of // possible subsets for them vector<long long int> vect1, vect2, subset1, subset2; // ignore element greater than k and divide // array into 2 halves for (int i = 0; i < n; i++) { // ignore element if greater than k if (arr[i] > k) continue; if (i <= n / 2) vect1.push_back(arr[i]); else vect2.push_back(arr[i]); } // generate all subsets for 1st half (vect1) for (int i = 0; i < (1 << vect1.size()); i++) { long long value = 1; for (int j = 0; j < vect1.size(); j++) { if (i & (1 << j)) value *= vect1[j]; } // push only in case subset product is less // than equal to k if (value <= k) subset1.push_back(value); } // generate all subsets for 2nd half (vect2) for (int i = 0; i < (1 << vect2.size()); i++) { long long value = 1; for (int j = 0; j < vect2.size(); j++) { if (i & (1 << j)) value *= vect2[j]; } // push only in case subset product is // less than equal to k if (value <= k) subset2.push_back(value); } // sort subset2 sort(subset2.begin(), subset2.end()); long long count = 0; for (int i = 0; i < subset1.size(); i++) count += upper_bound(subset2.begin(), subset2.end(), (k / subset1[i])) - subset2.begin(); // for null subset decrement the value of count count--; // return count return count;} // driver programint main(){ long long int arr[] = { 4, 2, 3, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); long long int k = 25; cout << findSubset(arr, n, k); return 0;}",
"e": 52113,
"s": 50087,
"text": null
},
{
"code": "# Python3 to find the count subset # having product less than k import bisect def findSubset(arr, n, k): # declare four vector for dividing # array into two halves and storing # product value of possible subsets # for them vect1, vect2, subset1, subset2 = [], [], [], [] # ignore element greater than k and # divide array into 2 halves for i in range(0, n): # ignore element if greater than k if arr[i] > k: continue if i <= n // 2: vect1.append(arr[i]) else: vect2.append(arr[i]) # generate all subsets for 1st half (vect1) for i in range(0, (1 << len(vect1))): value = 1 for j in range(0, len(vect1)): if i & (1 << j): value *= vect1[j] # push only in case subset product # is less than equal to k if value <= k: subset1.append(value) # generate all subsets for 2nd half (vect2) for i in range(0, (1 << len(vect2))): value = 1 for j in range(0, len(vect2)): if i & (1 << j): value *= vect2[j] # push only in case subset product # is less than equal to k if value <= k: subset2.append(value) # sort subset2 subset2.sort() count = 0 for i in range(0, len(subset1)): count += bisect.bisect(subset2, (k // subset1[i])) # for null subset decrement the # value of count count -= 1 # return count return count # Driver Codeif __name__ == \"__main__\": arr = [4, 2, 3, 6, 5] n = len(arr) k = 25 print(findSubset(arr, n, k)) # This code is contributed by Rituraj Jain",
"e": 53826,
"s": 52113,
"text": null
},
{
"code": null,
"e": 53830,
"s": 53826,
"text": "15\n"
},
{
"code": null,
"e": 53843,
"s": 53830,
"text": "rituraj_jain"
},
{
"code": null,
"e": 53854,
"s": 53843,
"text": "cpp-vector"
},
{
"code": null,
"e": 53861,
"s": 53854,
"text": "subset"
},
{
"code": null,
"e": 53868,
"s": 53861,
"text": "Arrays"
},
{
"code": null,
"e": 53887,
"s": 53868,
"text": "Technical Scripter"
},
{
"code": null,
"e": 53894,
"s": 53887,
"text": "Arrays"
},
{
"code": null,
"e": 53901,
"s": 53894,
"text": "subset"
},
{
"code": null,
"e": 53999,
"s": 53901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 54008,
"s": 53999,
"text": "Comments"
},
{
"code": null,
"e": 54021,
"s": 54008,
"text": "Old Comments"
},
{
"code": null,
"e": 54036,
"s": 54021,
"text": "Arrays in Java"
},
{
"code": null,
"e": 54052,
"s": 54036,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 54079,
"s": 54052,
"text": "Program for array rotation"
},
{
"code": null,
"e": 54127,
"s": 54079,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 54171,
"s": 54127,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 54217,
"s": 54171,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 54249,
"s": 54217,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 54281,
"s": 54249,
"text": "Multidimensional Arrays in Java"
}
] |
C++ Program to Store Information of a Student in a Structure | A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword.
An example of a structure is as follows.
struct employee {
int empID;
char name[50];
float salary;
};
A program that stores student information in a structure is given as follows.
Live Demo
#include <iostream>
using namespace std;
struct student {
int rollNo;
char name[50];
float marks;
char grade;
};
int main() {
struct student s = { 12 , "Harry" , 90 , 'A' };
cout<<"The student information is given as follows:"<<endl;
cout<<endl;
cout<<"Roll Number: "<<s.rollNo<<endl;
cout<<"Name: "<<s.name<<endl;
cout<<"Marks: "<<s.marks<<endl;
cout<<"Grade: "<<s.grade<<endl;
return 0;
}
The student information is given as follows:
Roll Number: 12
Name: Harry
Marks: 90
Grade: A
In the above program, the structure is defined before the main() function. The structure contains the roll number, name, marks and grade of a student. This is demonstrated in the following code snippet.
struct student {
int rollNo;
char name[50];
float marks;
char grade;
};
In the main() function, an object of type struct student is defined. This contains the roll number, name, marks and grade values. This is shown as follows.
struct student s = { 12 , "Harry" , 90 , 'A' };
The structure values are displayed in the following manner.
cout<<"The student information is given as follows:"<<endl;
cout<<endl;
cout<<"Roll Number: "<<s.rollNo<<endl;
cout<<"Name: "<<s.name<<endl;
cout<<"Marks: "<<s.marks<<endl;
cout<<"Grade: "<<s.grade<<endl; | [
{
"code": null,
"e": 1260,
"s": 1062,
"text": "A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword."
},
{
"code": null,
"e": 1301,
"s": 1260,
"text": "An example of a structure is as follows."
},
{
"code": null,
"e": 1371,
"s": 1301,
"text": "struct employee {\n int empID;\n char name[50];\n float salary;\n};"
},
{
"code": null,
"e": 1449,
"s": 1371,
"text": "A program that stores student information in a structure is given as follows."
},
{
"code": null,
"e": 1460,
"s": 1449,
"text": " Live Demo"
},
{
"code": null,
"e": 1887,
"s": 1460,
"text": "#include <iostream>\nusing namespace std;\nstruct student {\n int rollNo;\n char name[50];\n float marks;\n char grade;\n};\nint main() {\n struct student s = { 12 , \"Harry\" , 90 , 'A' };\n cout<<\"The student information is given as follows:\"<<endl;\n cout<<endl;\n cout<<\"Roll Number: \"<<s.rollNo<<endl;\n cout<<\"Name: \"<<s.name<<endl;\n cout<<\"Marks: \"<<s.marks<<endl;\n cout<<\"Grade: \"<<s.grade<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 1979,
"s": 1887,
"text": "The student information is given as follows:\nRoll Number: 12\nName: Harry\nMarks: 90\nGrade: A"
},
{
"code": null,
"e": 2182,
"s": 1979,
"text": "In the above program, the structure is defined before the main() function. The structure contains the roll number, name, marks and grade of a student. This is demonstrated in the following code snippet."
},
{
"code": null,
"e": 2266,
"s": 2182,
"text": "struct student {\n int rollNo;\n char name[50];\n float marks;\n char grade;\n};"
},
{
"code": null,
"e": 2422,
"s": 2266,
"text": "In the main() function, an object of type struct student is defined. This contains the roll number, name, marks and grade values. This is shown as follows."
},
{
"code": null,
"e": 2470,
"s": 2422,
"text": "struct student s = { 12 , \"Harry\" , 90 , 'A' };"
},
{
"code": null,
"e": 2530,
"s": 2470,
"text": "The structure values are displayed in the following manner."
},
{
"code": null,
"e": 2735,
"s": 2530,
"text": "cout<<\"The student information is given as follows:\"<<endl;\ncout<<endl;\ncout<<\"Roll Number: \"<<s.rollNo<<endl;\ncout<<\"Name: \"<<s.name<<endl;\ncout<<\"Marks: \"<<s.marks<<endl;\ncout<<\"Grade: \"<<s.grade<<endl;"
}
] |
Implementing a Naive Bayes Classifier | by Tarun Gupta | Towards Data Science | In the context of Supervised Learning (Classification), Naive Bayes or rather Bayesian Learning acts as a gold standard for evaluating other learning algorithms along with acting as a powerful probabilistic modelling technique.
In this post, we are going to discuss the workings of Naive Bayes classifier implementationally with Python by applying it to a real world dataset.
The post is divided more broadly into the following parts:
Data Preprocessing
Training the model
Predicting the results
Checking the performance of the model
The above parts can be further divided as follows:
→ Data Preprocessing
Importing the librariesImporting the datasetSplitting the dataset into the training set and testing setFeature Scaling
Importing the libraries
Importing the dataset
Splitting the dataset into the training set and testing set
Feature Scaling
→ Training the model
Training the Naive Bayes model on the training set
Training the Naive Bayes model on the training set
→ Predicting the results
Predicting the test set results
Predicting the test set results
→ Checking the performance of the model
Making the Confusion Matrix
Making the Confusion Matrix
→ Visualisation
Visualising the Confusion Matrix
Visualising the Confusion Matrix
Before we begin to delve into the code itself, we need to talk about the dataset itself. For this implementation, we are going to use The 20 newsgroups text dataset. This dataset is publicly available for the purpose that people can learn and hone their Machine Learning skills.
We are going to use scikit-learn (sklearn) as the Machine Learning library and the repository for the dataset itself. This is what sklearn’s website tells you about the dataset.
The 20 newsgroups dataset comprises around 18000 newsgroups posts on 20 topics split in two subsets: one for training (or development) and the other one for testing (or for performance evaluation). The split between the train and test set is based upon a messages posted before and after a specific date.
Note: Since the raw data is natural language text, we can’t directly work with it. We need to transform the data into numbers before we can start working on it. There are multiple ways to do that, namely:
CountVectorizer
TfIdfVectorizer
HashingVectorizer
It depends on the designer of the solution and the problem itself to choose the Vectorizer. For the purpose of this post, I am going to use CountVectorizer. I have provided the link to sklearn’s documentation for all of the Vectorizers. You can certainly have a detailed look there and over the Internet as well.
Now, that we have talked about the dataset a bit, let’s start with the code itself one step at a time.
Importing the libraries
Importing the libraries
from sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import confusion_matrix, plot_confusion_matriximport matplotlib.pyplot as plt
The above-mentioned libraries are used/required (explained in order) as follows:
a) Importing the dataset from sklearn itself
b) Importing the CountVectorizer to convert raw natural language text to machine understandable numbers
c) Importing the Naive Bayes classifier, in this case we are using Gaussian Naive Bayes
d) Importing the confusion matrix methods to check the performance of the model and visualise it.
e) For visualisation of Confusion Matrix
2 & 3. Importing the dataset and Splitting the dataset into the Training set and Test set
data_train = fetch_20newsgroups(subset='train', categories=None, remove=('headers', 'footers', 'quotes'))data_test = fetch_20newsgroups(subset='test', categories=None, remove=('headers', 'footers', 'quotes'))X_train = data_train.datay_train = data_train.targetX_test = data_test.datay_test = data_test.target
data_train contains the training set from the data itself. The parameters passed in fetch_20newsgroups can be understood as:
i) subset — to define training or test set
ii) categories — The dataset contains 20 categories or class labels. The subset of the dataset can be used by providing a list of categories in the parameter from the following:
from pprint import pprintpprint(list(newsgroups_train.target_names))
The output being:
['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc']
iii) remove — The text in the dataset contains headers, footers and quotes but we want to apply the model on the body of the data.
The independent and dependent variables can be separated by calling .data and .target on the data_train and data_test to get bifurcated training and test data.
The values in the array represents the index of the above mentioned categories list.
4. Feature Scaling
vectorizer = CountVectorizer()X_train = vectorizer.fit_transform(X_train)X_test = vectorizer.transform(X_test)
Making an object of the CountVectorizer class followed by fitting the vectorizer object on both X_train and X_test data.
Training the Naive Bayes model on the training set
Training the Naive Bayes model on the training set
classifier = GaussianNB()classifier.fit(X_train.toarray(), y_train)
Making an object of the GaussianNB class followed by fitting the classifier object on X_train and y_train data. Here .toarray() with X_train is used to convert a sparse matrix to a dense matrix.
Predicting the test set results
Predicting the test set results
y_pred = classifier.predict(X_test.toarray())
Calling the .predict method on the classifier object and passing the X_test to predict the results of the trained model on previously unseen data. Here .toarray() with X_test is used to convert a sparse matrix to a dense matrix.
Making the Confusion Matrix
Making the Confusion Matrix
cm = confusion_matrix(y_test, y_pred)print(cm)
Visualising the Confusion Matrix
Visualising the Confusion Matrix
plot_confusion_matrix(classifier, X_test.toarray(), y_test, display_labels=['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware'], cmap=plt.cm.Blues)
For visualisation purpose I am limiting the number of categories to 4 so that it is properly visible.
Now, that the whole pipeline of a Machine Learning model is finished, I hope I was able to part some knowledge. This is a very basic Machine Learning pipeline but it is rather important in terms of building a foundation when you want to build better and more complex Machine Learning models. I hope to bring more dynamic and complex models in the future so stay tuned.
Here is a link to the complete jupyter notebook.
github.com
I am giving away a free eBook on Consistency. Get your free eBook here.
Thank you for reading.
If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission at no extra cost to you.
tarun-gupta.medium.com
You can read more of my posts here: | [
{
"code": null,
"e": 399,
"s": 171,
"text": "In the context of Supervised Learning (Classification), Naive Bayes or rather Bayesian Learning acts as a gold standard for evaluating other learning algorithms along with acting as a powerful probabilistic modelling technique."
},
{
"code": null,
"e": 547,
"s": 399,
"text": "In this post, we are going to discuss the workings of Naive Bayes classifier implementationally with Python by applying it to a real world dataset."
},
{
"code": null,
"e": 606,
"s": 547,
"text": "The post is divided more broadly into the following parts:"
},
{
"code": null,
"e": 625,
"s": 606,
"text": "Data Preprocessing"
},
{
"code": null,
"e": 644,
"s": 625,
"text": "Training the model"
},
{
"code": null,
"e": 667,
"s": 644,
"text": "Predicting the results"
},
{
"code": null,
"e": 705,
"s": 667,
"text": "Checking the performance of the model"
},
{
"code": null,
"e": 756,
"s": 705,
"text": "The above parts can be further divided as follows:"
},
{
"code": null,
"e": 777,
"s": 756,
"text": "→ Data Preprocessing"
},
{
"code": null,
"e": 896,
"s": 777,
"text": "Importing the librariesImporting the datasetSplitting the dataset into the training set and testing setFeature Scaling"
},
{
"code": null,
"e": 920,
"s": 896,
"text": "Importing the libraries"
},
{
"code": null,
"e": 942,
"s": 920,
"text": "Importing the dataset"
},
{
"code": null,
"e": 1002,
"s": 942,
"text": "Splitting the dataset into the training set and testing set"
},
{
"code": null,
"e": 1018,
"s": 1002,
"text": "Feature Scaling"
},
{
"code": null,
"e": 1039,
"s": 1018,
"text": "→ Training the model"
},
{
"code": null,
"e": 1090,
"s": 1039,
"text": "Training the Naive Bayes model on the training set"
},
{
"code": null,
"e": 1141,
"s": 1090,
"text": "Training the Naive Bayes model on the training set"
},
{
"code": null,
"e": 1166,
"s": 1141,
"text": "→ Predicting the results"
},
{
"code": null,
"e": 1198,
"s": 1166,
"text": "Predicting the test set results"
},
{
"code": null,
"e": 1230,
"s": 1198,
"text": "Predicting the test set results"
},
{
"code": null,
"e": 1270,
"s": 1230,
"text": "→ Checking the performance of the model"
},
{
"code": null,
"e": 1298,
"s": 1270,
"text": "Making the Confusion Matrix"
},
{
"code": null,
"e": 1326,
"s": 1298,
"text": "Making the Confusion Matrix"
},
{
"code": null,
"e": 1342,
"s": 1326,
"text": "→ Visualisation"
},
{
"code": null,
"e": 1375,
"s": 1342,
"text": "Visualising the Confusion Matrix"
},
{
"code": null,
"e": 1408,
"s": 1375,
"text": "Visualising the Confusion Matrix"
},
{
"code": null,
"e": 1687,
"s": 1408,
"text": "Before we begin to delve into the code itself, we need to talk about the dataset itself. For this implementation, we are going to use The 20 newsgroups text dataset. This dataset is publicly available for the purpose that people can learn and hone their Machine Learning skills."
},
{
"code": null,
"e": 1865,
"s": 1687,
"text": "We are going to use scikit-learn (sklearn) as the Machine Learning library and the repository for the dataset itself. This is what sklearn’s website tells you about the dataset."
},
{
"code": null,
"e": 2170,
"s": 1865,
"text": "The 20 newsgroups dataset comprises around 18000 newsgroups posts on 20 topics split in two subsets: one for training (or development) and the other one for testing (or for performance evaluation). The split between the train and test set is based upon a messages posted before and after a specific date."
},
{
"code": null,
"e": 2375,
"s": 2170,
"text": "Note: Since the raw data is natural language text, we can’t directly work with it. We need to transform the data into numbers before we can start working on it. There are multiple ways to do that, namely:"
},
{
"code": null,
"e": 2391,
"s": 2375,
"text": "CountVectorizer"
},
{
"code": null,
"e": 2407,
"s": 2391,
"text": "TfIdfVectorizer"
},
{
"code": null,
"e": 2425,
"s": 2407,
"text": "HashingVectorizer"
},
{
"code": null,
"e": 2738,
"s": 2425,
"text": "It depends on the designer of the solution and the problem itself to choose the Vectorizer. For the purpose of this post, I am going to use CountVectorizer. I have provided the link to sklearn’s documentation for all of the Vectorizers. You can certainly have a detailed look there and over the Internet as well."
},
{
"code": null,
"e": 2841,
"s": 2738,
"text": "Now, that we have talked about the dataset a bit, let’s start with the code itself one step at a time."
},
{
"code": null,
"e": 2865,
"s": 2841,
"text": "Importing the libraries"
},
{
"code": null,
"e": 2889,
"s": 2865,
"text": "Importing the libraries"
},
{
"code": null,
"e": 3136,
"s": 2889,
"text": "from sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import confusion_matrix, plot_confusion_matriximport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 3217,
"s": 3136,
"text": "The above-mentioned libraries are used/required (explained in order) as follows:"
},
{
"code": null,
"e": 3262,
"s": 3217,
"text": "a) Importing the dataset from sklearn itself"
},
{
"code": null,
"e": 3366,
"s": 3262,
"text": "b) Importing the CountVectorizer to convert raw natural language text to machine understandable numbers"
},
{
"code": null,
"e": 3454,
"s": 3366,
"text": "c) Importing the Naive Bayes classifier, in this case we are using Gaussian Naive Bayes"
},
{
"code": null,
"e": 3552,
"s": 3454,
"text": "d) Importing the confusion matrix methods to check the performance of the model and visualise it."
},
{
"code": null,
"e": 3593,
"s": 3552,
"text": "e) For visualisation of Confusion Matrix"
},
{
"code": null,
"e": 3683,
"s": 3593,
"text": "2 & 3. Importing the dataset and Splitting the dataset into the Training set and Test set"
},
{
"code": null,
"e": 4122,
"s": 3683,
"text": "data_train = fetch_20newsgroups(subset='train', categories=None, remove=('headers', 'footers', 'quotes'))data_test = fetch_20newsgroups(subset='test', categories=None, remove=('headers', 'footers', 'quotes'))X_train = data_train.datay_train = data_train.targetX_test = data_test.datay_test = data_test.target"
},
{
"code": null,
"e": 4247,
"s": 4122,
"text": "data_train contains the training set from the data itself. The parameters passed in fetch_20newsgroups can be understood as:"
},
{
"code": null,
"e": 4290,
"s": 4247,
"text": "i) subset — to define training or test set"
},
{
"code": null,
"e": 4468,
"s": 4290,
"text": "ii) categories — The dataset contains 20 categories or class labels. The subset of the dataset can be used by providing a list of categories in the parameter from the following:"
},
{
"code": null,
"e": 4537,
"s": 4468,
"text": "from pprint import pprintpprint(list(newsgroups_train.target_names))"
},
{
"code": null,
"e": 4555,
"s": 4537,
"text": "The output being:"
},
{
"code": null,
"e": 4949,
"s": 4555,
"text": "['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc']"
},
{
"code": null,
"e": 5080,
"s": 4949,
"text": "iii) remove — The text in the dataset contains headers, footers and quotes but we want to apply the model on the body of the data."
},
{
"code": null,
"e": 5240,
"s": 5080,
"text": "The independent and dependent variables can be separated by calling .data and .target on the data_train and data_test to get bifurcated training and test data."
},
{
"code": null,
"e": 5325,
"s": 5240,
"text": "The values in the array represents the index of the above mentioned categories list."
},
{
"code": null,
"e": 5344,
"s": 5325,
"text": "4. Feature Scaling"
},
{
"code": null,
"e": 5455,
"s": 5344,
"text": "vectorizer = CountVectorizer()X_train = vectorizer.fit_transform(X_train)X_test = vectorizer.transform(X_test)"
},
{
"code": null,
"e": 5576,
"s": 5455,
"text": "Making an object of the CountVectorizer class followed by fitting the vectorizer object on both X_train and X_test data."
},
{
"code": null,
"e": 5627,
"s": 5576,
"text": "Training the Naive Bayes model on the training set"
},
{
"code": null,
"e": 5678,
"s": 5627,
"text": "Training the Naive Bayes model on the training set"
},
{
"code": null,
"e": 5746,
"s": 5678,
"text": "classifier = GaussianNB()classifier.fit(X_train.toarray(), y_train)"
},
{
"code": null,
"e": 5941,
"s": 5746,
"text": "Making an object of the GaussianNB class followed by fitting the classifier object on X_train and y_train data. Here .toarray() with X_train is used to convert a sparse matrix to a dense matrix."
},
{
"code": null,
"e": 5973,
"s": 5941,
"text": "Predicting the test set results"
},
{
"code": null,
"e": 6005,
"s": 5973,
"text": "Predicting the test set results"
},
{
"code": null,
"e": 6051,
"s": 6005,
"text": "y_pred = classifier.predict(X_test.toarray())"
},
{
"code": null,
"e": 6280,
"s": 6051,
"text": "Calling the .predict method on the classifier object and passing the X_test to predict the results of the trained model on previously unseen data. Here .toarray() with X_test is used to convert a sparse matrix to a dense matrix."
},
{
"code": null,
"e": 6308,
"s": 6280,
"text": "Making the Confusion Matrix"
},
{
"code": null,
"e": 6336,
"s": 6308,
"text": "Making the Confusion Matrix"
},
{
"code": null,
"e": 6383,
"s": 6336,
"text": "cm = confusion_matrix(y_test, y_pred)print(cm)"
},
{
"code": null,
"e": 6416,
"s": 6383,
"text": "Visualising the Confusion Matrix"
},
{
"code": null,
"e": 6449,
"s": 6416,
"text": "Visualising the Confusion Matrix"
},
{
"code": null,
"e": 6632,
"s": 6449,
"text": "plot_confusion_matrix(classifier, X_test.toarray(), y_test, display_labels=['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware'], cmap=plt.cm.Blues)"
},
{
"code": null,
"e": 6734,
"s": 6632,
"text": "For visualisation purpose I am limiting the number of categories to 4 so that it is properly visible."
},
{
"code": null,
"e": 7103,
"s": 6734,
"text": "Now, that the whole pipeline of a Machine Learning model is finished, I hope I was able to part some knowledge. This is a very basic Machine Learning pipeline but it is rather important in terms of building a foundation when you want to build better and more complex Machine Learning models. I hope to bring more dynamic and complex models in the future so stay tuned."
},
{
"code": null,
"e": 7152,
"s": 7103,
"text": "Here is a link to the complete jupyter notebook."
},
{
"code": null,
"e": 7163,
"s": 7152,
"text": "github.com"
},
{
"code": null,
"e": 7235,
"s": 7163,
"text": "I am giving away a free eBook on Consistency. Get your free eBook here."
},
{
"code": null,
"e": 7258,
"s": 7235,
"text": "Thank you for reading."
},
{
"code": null,
"e": 7532,
"s": 7258,
"text": "If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission at no extra cost to you."
},
{
"code": null,
"e": 7555,
"s": 7532,
"text": "tarun-gupta.medium.com"
}
] |
SAP ABAP - Inheritance | One of the most important concepts in object oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and methods, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class or super class, and the new class is referred to as the derived class or sub class.
An object of one class can acquire the properties of another class.
An object of one class can acquire the properties of another class.
Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods.
Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods.
The main advantage of inheritance is reusability.
The main advantage of inheritance is reusability.
The inheritance relationship is specified using the ‘INHERITING FROM’ addition to the class definition statement.
Following is the syntax −
CLASS <subclass> DEFINITION INHERITING FROM <superclass>.
Report ZINHERITAN_1.
CLASS Parent Definition.
PUBLIC Section.
Data: w_public(25) Value 'This is public data'.
Methods: ParentM.
ENDCLASS.
CLASS Child Definition Inheriting From Parent.
PUBLIC Section.
Methods: ChildM.
ENDCLASS.
CLASS Parent Implementation.
Method ParentM.
Write /: w_public.
EndMethod. ENDCLASS.
CLASS Child Implementation.
Method ChildM.
Skip.
Write /: 'Method in child class', w_public.
EndMethod.
ENDCLASS.
Start-of-selection.
Data: Parent Type Ref To Parent,
Child Type Ref To Child.
Create Object: Parent, Child.
Call Method: Parent→ParentM,
child→ChildM.
The above code produces the following output −
This is public data
Method in child class
This is public data
A derived class can access all the non-private members of its base class. Thus super class members that should not be accessible to the member functions of sub classes should be declared private in the super class. We can summarize the different access types according to who can access them in the following way −
When deriving a class from a super class, it can be inherited through public, protected or private inheritance. The type of inheritance is specified by the access specifier as explained above. We hardly use protected or private inheritance, but public inheritance is commonly used. The following rules are applied while using different types of inheritance.
Public Inheritance − When deriving a class from a public super class, public members of the super class become public members of the sub class and protected members of the super class become protected members of the sub class. Super class's private members are never accessible directly from a sub class, but can be accessed through calls to the public and protected members of the super class.
Public Inheritance − When deriving a class from a public super class, public members of the super class become public members of the sub class and protected members of the super class become protected members of the sub class. Super class's private members are never accessible directly from a sub class, but can be accessed through calls to the public and protected members of the super class.
Protected Inheritance − When deriving from a protected super class, public and protected members of the super class become protected members of the sub class.
Protected Inheritance − When deriving from a protected super class, public and protected members of the super class become protected members of the sub class.
Private Inheritance − When deriving from a private super class, public and protected members of the super class become private members of the sub class.
Private Inheritance − When deriving from a private super class, public and protected members of the super class become private members of the sub class.
The methods of the super class can be re-implemented in the sub class. Few rules of redefining methods −
The redefinition statement for the inherited method must be in the same section as the definition of the original method.
The redefinition statement for the inherited method must be in the same section as the definition of the original method.
If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method.
If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method.
Within the redefined method, you can access components of the direct super class using the super reference.
Within the redefined method, you can access components of the direct super class using the super reference.
The pseudo reference super can only be used in redefined methods.
The pseudo reference super can only be used in redefined methods.
Report Zinheri_Redefine.
CLASS super_class Definition.
Public Section.
Methods: Addition1 importing g_a TYPE I
g_b TYPE I
exporting g_c TYPE I.
ENDCLASS.
CLASS super_class Implementation.
Method Addition1.
g_c = g_a + g_b.
EndMethod.
ENDCLASS.
CLASS sub_class Definition Inheriting From super_class.
Public Section.
METHODS: Addition1 Redefinition.
ENDCLASS.
CLASS sub_class Implementation.
Method Addition1.
g_c = g_a + g_b + 10.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Parameters: P_a Type I, P_b TYPE I.
Data: H_Addition1 TYPE I.
Data: H_Sub TYPE I.
Data: Ref1 TYPE Ref TO sub_class.
Create Object Ref1.
Call Method Ref1→Addition1 exporting g_a = P_a
g_b = P_b
Importing g_c = H_Addition1.
Write:/ H_Addition1.
After executing F8, if we enter the values 9 and 10, the above code produces the following output −
Redefinition Demo
29
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3212,
"s": 2898,
"text": "One of the most important concepts in object oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time."
},
{
"code": null,
"e": 3521,
"s": 3212,
"text": "When creating a class, instead of writing completely new data members and methods, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class or super class, and the new class is referred to as the derived class or sub class."
},
{
"code": null,
"e": 3589,
"s": 3521,
"text": "An object of one class can acquire the properties of another class."
},
{
"code": null,
"e": 3657,
"s": 3589,
"text": "An object of one class can acquire the properties of another class."
},
{
"code": null,
"e": 3781,
"s": 3657,
"text": "Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods."
},
{
"code": null,
"e": 3905,
"s": 3781,
"text": "Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods."
},
{
"code": null,
"e": 3955,
"s": 3905,
"text": "The main advantage of inheritance is reusability."
},
{
"code": null,
"e": 4005,
"s": 3955,
"text": "The main advantage of inheritance is reusability."
},
{
"code": null,
"e": 4119,
"s": 4005,
"text": "The inheritance relationship is specified using the ‘INHERITING FROM’ addition to the class definition statement."
},
{
"code": null,
"e": 4145,
"s": 4119,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 4204,
"s": 4145,
"text": "CLASS <subclass> DEFINITION INHERITING FROM <superclass>.\n"
},
{
"code": null,
"e": 4810,
"s": 4204,
"text": "Report ZINHERITAN_1. \nCLASS Parent Definition. \nPUBLIC Section. \nData: w_public(25) Value 'This is public data'. \nMethods: ParentM. \nENDCLASS. \n\nCLASS Child Definition Inheriting From Parent. \nPUBLIC Section. \nMethods: ChildM. \nENDCLASS. \n\nCLASS Parent Implementation. \nMethod ParentM. \nWrite /: w_public. \nEndMethod. ENDCLASS. \n\nCLASS Child Implementation. \nMethod ChildM. \nSkip. \nWrite /: 'Method in child class', w_public.\nEndMethod. \nENDCLASS. \n\nStart-of-selection. \nData: Parent Type Ref To Parent, \nChild Type Ref To Child. \nCreate Object: Parent, Child. \nCall Method: Parent→ParentM, \nchild→ChildM."
},
{
"code": null,
"e": 4857,
"s": 4810,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 4922,
"s": 4857,
"text": "This is public data \nMethod in child class \nThis is public data\n"
},
{
"code": null,
"e": 5237,
"s": 4922,
"text": "A derived class can access all the non-private members of its base class. Thus super class members that should not be accessible to the member functions of sub classes should be declared private in the super class. We can summarize the different access types according to who can access them in the following way −"
},
{
"code": null,
"e": 5595,
"s": 5237,
"text": "When deriving a class from a super class, it can be inherited through public, protected or private inheritance. The type of inheritance is specified by the access specifier as explained above. We hardly use protected or private inheritance, but public inheritance is commonly used. The following rules are applied while using different types of inheritance."
},
{
"code": null,
"e": 5990,
"s": 5595,
"text": "Public Inheritance − When deriving a class from a public super class, public members of the super class become public members of the sub class and protected members of the super class become protected members of the sub class. Super class's private members are never accessible directly from a sub class, but can be accessed through calls to the public and protected members of the super class."
},
{
"code": null,
"e": 6385,
"s": 5990,
"text": "Public Inheritance − When deriving a class from a public super class, public members of the super class become public members of the sub class and protected members of the super class become protected members of the sub class. Super class's private members are never accessible directly from a sub class, but can be accessed through calls to the public and protected members of the super class."
},
{
"code": null,
"e": 6544,
"s": 6385,
"text": "Protected Inheritance − When deriving from a protected super class, public and protected members of the super class become protected members of the sub class."
},
{
"code": null,
"e": 6703,
"s": 6544,
"text": "Protected Inheritance − When deriving from a protected super class, public and protected members of the super class become protected members of the sub class."
},
{
"code": null,
"e": 6856,
"s": 6703,
"text": "Private Inheritance − When deriving from a private super class, public and protected members of the super class become private members of the sub class."
},
{
"code": null,
"e": 7009,
"s": 6856,
"text": "Private Inheritance − When deriving from a private super class, public and protected members of the super class become private members of the sub class."
},
{
"code": null,
"e": 7114,
"s": 7009,
"text": "The methods of the super class can be re-implemented in the sub class. Few rules of redefining methods −"
},
{
"code": null,
"e": 7236,
"s": 7114,
"text": "The redefinition statement for the inherited method must be in the same section as the definition of the original method."
},
{
"code": null,
"e": 7358,
"s": 7236,
"text": "The redefinition statement for the inherited method must be in the same section as the definition of the original method."
},
{
"code": null,
"e": 7479,
"s": 7358,
"text": "If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method."
},
{
"code": null,
"e": 7600,
"s": 7479,
"text": "If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method."
},
{
"code": null,
"e": 7708,
"s": 7600,
"text": "Within the redefined method, you can access components of the direct super class using the super reference."
},
{
"code": null,
"e": 7816,
"s": 7708,
"text": "Within the redefined method, you can access components of the direct super class using the super reference."
},
{
"code": null,
"e": 7882,
"s": 7816,
"text": "The pseudo reference super can only be used in redefined methods."
},
{
"code": null,
"e": 7948,
"s": 7882,
"text": "The pseudo reference super can only be used in redefined methods."
},
{
"code": null,
"e": 8777,
"s": 7948,
"text": "Report Zinheri_Redefine. \nCLASS super_class Definition. \nPublic Section. \nMethods: Addition1 importing g_a TYPE I\n g_b TYPE I\n\t\t exporting g_c TYPE I.\nENDCLASS. \n\nCLASS super_class Implementation. \nMethod Addition1. \ng_c = g_a + g_b. \nEndMethod. \nENDCLASS. \n\nCLASS sub_class Definition Inheriting From super_class. \nPublic Section. \nMETHODS: Addition1 Redefinition. \nENDCLASS. \n\nCLASS sub_class Implementation. \nMethod Addition1. \ng_c = g_a + g_b + 10. \nEndMethod. \nENDCLASS. \n\nStart-Of-Selection. \nParameters: P_a Type I, P_b TYPE I. \nData: H_Addition1 TYPE I. \nData: H_Sub TYPE I. \nData: Ref1 TYPE Ref TO sub_class. \nCreate Object Ref1. \nCall Method Ref1→Addition1 exporting g_a = P_a \n g_b = P_b\n\t\t Importing g_c = H_Addition1. \nWrite:/ H_Addition1."
},
{
"code": null,
"e": 8877,
"s": 8777,
"text": "After executing F8, if we enter the values 9 and 10, the above code produces the following output −"
},
{
"code": null,
"e": 8900,
"s": 8877,
"text": "Redefinition Demo \n29\n"
},
{
"code": null,
"e": 8933,
"s": 8900,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8947,
"s": 8933,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 8980,
"s": 8947,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8992,
"s": 8980,
"text": " Neha Gupta"
},
{
"code": null,
"e": 9027,
"s": 8992,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9042,
"s": 9027,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 9075,
"s": 9042,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9090,
"s": 9075,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 9125,
"s": 9090,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9137,
"s": 9125,
"text": " Neha Malik"
},
{
"code": null,
"e": 9172,
"s": 9137,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9184,
"s": 9172,
"text": " Neha Malik"
},
{
"code": null,
"e": 9191,
"s": 9184,
"text": " Print"
},
{
"code": null,
"e": 9202,
"s": 9191,
"text": " Add Notes"
}
] |
AWT Event Listeners | The Event listener represent the interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss those which are more frequently used. Every method of an event listener method has a single argument as an object which is subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject.
It is a marker interface which every listener interface has to extend.This class is defined in java.util package.
Following is the declaration for java.util.EventListener interface:
public interface EventListener
Following is the list of commonly used event listeners.
ActionListener
This interface is used for receiving the action events.
ComponentListener
This interface is used for receiving the component events.
ItemListener
This interface is used for receiving the item events.
KeyListener
This interface is used for receiving the key events.
MouseListener
This interface is used for receiving the mouse events.
TextListener
This interface is used for receiving the text events.
WindowListener
This interface is used for receiving the window events.
AdjustmentListener
This interface is used for receiving the adjusmtent events.
ContainerListener
This interface is used for receiving the container events.
MouseMotionListener
This interface is used for receiving the mouse motion events.
FocusListener
This interface is used for receiving the focus events.
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2165,
"s": 1747,
"text": "The Event listener represent the interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss those which are more frequently used. Every method of an event listener method has a single argument as an object which is subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject."
},
{
"code": null,
"e": 2279,
"s": 2165,
"text": "It is a marker interface which every listener interface has to extend.This class is defined in java.util package."
},
{
"code": null,
"e": 2347,
"s": 2279,
"text": "Following is the declaration for java.util.EventListener interface:"
},
{
"code": null,
"e": 2378,
"s": 2347,
"text": "public interface EventListener"
},
{
"code": null,
"e": 2434,
"s": 2378,
"text": "Following is the list of commonly used event listeners."
},
{
"code": null,
"e": 2449,
"s": 2434,
"text": "ActionListener"
},
{
"code": null,
"e": 2505,
"s": 2449,
"text": "This interface is used for receiving the action events."
},
{
"code": null,
"e": 2523,
"s": 2505,
"text": "ComponentListener"
},
{
"code": null,
"e": 2582,
"s": 2523,
"text": "This interface is used for receiving the component events."
},
{
"code": null,
"e": 2595,
"s": 2582,
"text": "ItemListener"
},
{
"code": null,
"e": 2649,
"s": 2595,
"text": "This interface is used for receiving the item events."
},
{
"code": null,
"e": 2661,
"s": 2649,
"text": "KeyListener"
},
{
"code": null,
"e": 2714,
"s": 2661,
"text": "This interface is used for receiving the key events."
},
{
"code": null,
"e": 2728,
"s": 2714,
"text": "MouseListener"
},
{
"code": null,
"e": 2783,
"s": 2728,
"text": "This interface is used for receiving the mouse events."
},
{
"code": null,
"e": 2796,
"s": 2783,
"text": "TextListener"
},
{
"code": null,
"e": 2850,
"s": 2796,
"text": "This interface is used for receiving the text events."
},
{
"code": null,
"e": 2865,
"s": 2850,
"text": "WindowListener"
},
{
"code": null,
"e": 2921,
"s": 2865,
"text": "This interface is used for receiving the window events."
},
{
"code": null,
"e": 2940,
"s": 2921,
"text": "AdjustmentListener"
},
{
"code": null,
"e": 3000,
"s": 2940,
"text": "This interface is used for receiving the adjusmtent events."
},
{
"code": null,
"e": 3018,
"s": 3000,
"text": "ContainerListener"
},
{
"code": null,
"e": 3077,
"s": 3018,
"text": "This interface is used for receiving the container events."
},
{
"code": null,
"e": 3097,
"s": 3077,
"text": "MouseMotionListener"
},
{
"code": null,
"e": 3159,
"s": 3097,
"text": "This interface is used for receiving the mouse motion events."
},
{
"code": null,
"e": 3173,
"s": 3159,
"text": "FocusListener"
},
{
"code": null,
"e": 3228,
"s": 3173,
"text": "This interface is used for receiving the focus events."
},
{
"code": null,
"e": 3261,
"s": 3228,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3269,
"s": 3261,
"text": " EduOLC"
},
{
"code": null,
"e": 3276,
"s": 3269,
"text": " Print"
},
{
"code": null,
"e": 3287,
"s": 3276,
"text": " Add Notes"
}
] |
Generate Contour Plots Using Python’s Matplotlib | by Rashida Nasrin Sucky | Towards Data Science | I am sure you have seen a contour plot before. At least in weather data. It is used a lot in presenting meteorological or geographical data. But it is also used to present density, brightness, and electric potential. It is used a lot in data analysis and machine learning. It shows how a response variable relates to two predictor variables.
It gives a two-dimensional view where all the points having the same response are connected by a line. That line is a contour line.
Three main elements of a contour plot:
x-axis and the y-axis shows the predictorsContour lines to represent the same response valuesColored bands that provide a range of response values
x-axis and the y-axis shows the predictors
Contour lines to represent the same response values
Colored bands that provide a range of response values
First import the necessary packages.
import numpy as npimport matplotlib.pyplot as pltimport pylab
Let’s generate some x and y values
xp = np.arange(-8, 10, 2)yp = np.arange(-8, 10, 2)
You can probably imagine how ‘xp’ and ‘yp’ look like. But still, just have a look.
xp
Output:
array([-8, -6, -4, -2, 0, 2, 4, 6, 8])
Input:
yp
Output:
array([-8, -6, -4, -2, 0, 2, 4, 6, 8])
The length of x and y is 9.
This information is important because we need to generate z using this number.
First, initiate a random z point of the shape 9 x 9
zp = np.ndarray((9,9))zp
Output:
array([[1.20117830e-311, 1.20117830e-311, 1.20120150e-311, 1.20120150e-311, 1.20120150e-311, 1.20120150e-311, 1.20118338e-311, 1.20119781e-311, 1.20120151e-311], [1.20120150e-311, 1.20120151e-311, 1.20117830e-311, 1.20117830e-311, 1.20118045e-311, 1.20120150e-311, 1.20119863e-311, 1.20119863e-311, 1.20117830e-311], [1.20119864e-311, 1.20118316e-311, 1.20117850e-311, 1.20117830e-311, 1.20118500e-311, 1.20118500e-311, 1.20118490e-311, 1.20118488e-311, 1.20118316e-311], [1.20118500e-311, 1.20118493e-311, 1.20118493e-311, 1.20118493e-311, 1.20118493e-311, 1.20118339e-311, 1.20117862e-311, 1.20117835e-311, 1.20118337e-311], [1.20118339e-311, 1.20118338e-311, 1.20118347e-311, 1.20118348e-311, 1.20118339e-311, 1.20118348e-311, 1.20118316e-311, 1.20118338e-311, 1.20118348e-311], [1.20118339e-311, 1.20118348e-311, 1.20118347e-311, 1.20118348e-311, 1.20118348e-311, 1.20118348e-311, 1.20118339e-311, 1.20118339e-311, 1.20118333e-311], [1.20118348e-311, 1.20118348e-311, 1.20118348e-311, 1.20117830e-311, 1.20117830e-311, 1.20117853e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311], [1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311], [1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 0.00000000e+000]])
Now, I will replace these random values with a formula of my choice. you can use the formula you want or you need.
for x in range(0, len(xp)): for y in range(0, len(yp)): zp[x][y] = xp[x]**2 + yp[y]**2zp
Output:
array([[128., 100., 80., 68., 64., 68., 80., 100., 128.], [100., 72., 52., 40., 36., 40., 52., 72., 100.], [ 80., 52., 32., 20., 16., 20., 32., 52., 80.], [ 68., 40., 20., 8., 4., 8., 20., 40., 68.], [ 64., 36., 16., 4., 0., 4., 16., 36., 64.], [ 68., 40., 20., 8., 4., 8., 20., 40., 68.], [ 80., 52., 32., 20., 16., 20., 32., 52., 80.], [100., 72., 52., 40., 36., 40., 52., 72., 100.], [128., 100., 80., 68., 64., 68., 80., 100., 128.]])
So, we have x, y, and z data ready. Here is how to do the contour plot.
plt.figure(figsize=(7, 5))plt.title('Contour Plot')contours = plt.contour(xp, yp, zp)plt.clabel(contours, inline=1, fontsize=12)plt.show()
I will do the exact same procedure with a slightly different formula for z values. So I will not explain step by step this time:
xp = np.arange(-3, 4)yp = np.arange(-3, 4)zp =np.ndarray((7,7))for x in range(0, len(xp)): for y in range(0, len(yp)): zp[x][y] = xp[x]*xp[x] - yp[y]*yp[y]plt.figure(figsize=(8, 6))plt.title('Contour plot for saddle surface - Hyperbolic paraboloid')contours = plt.contour(xp, yp, zp)plt.clabel(contours, inline=1, fontsize=12)plt.show()
This is a density plot. So I will make a different dataset where data points are closer. Here are x and y.
x = np.linspace(0, 5, 60)y = np.linspace(0, 5, 48)
Both x and y are the same. This is how the data look like:
array([0. , 0.08474576, 0.16949153, 0.25423729, 0.33898305, 0.42372881, 0.50847458, 0.59322034, 0.6779661 , 0.76271186, 0.84745763, 0.93220339, 1.01694915, 1.10169492, 1.18644068, 1.27118644, 1.3559322 , 1.44067797, 1.52542373, 1.61016949, 1.69491525, 1.77966102, 1.86440678, 1.94915254, 2.03389831, 2.11864407, 2.20338983, 2.28813559, 2.37288136, 2.45762712, 2.54237288, 2.62711864, 2.71186441, 2.79661017, 2.88135593, 2.96610169, 3.05084746, 3.13559322, 3.22033898, 3.30508475, 3.38983051, 3.47457627, 3.55932203, 3.6440678 , 3.72881356, 3.81355932, 3.89830508, 3.98305085, 4.06779661, 4.15254237, 4.23728814, 4.3220339 , 4.40677966, 4.49152542, 4.57627119, 4.66101695, 4.74576271, 4.83050847, 4.91525424, 5. ])
As before I need a function for z. Here is the function I choose,
def fn(x, y): return np.sin(x)**5 + np.cos(y+17)**8
Now, time to prepare the X, Y, and Z data. I will simply use the np.meshgrid function on x and y which builds two-dimensional grids from one-dimensional arrays.
X, Y = np.meshgrid(x, y)Z = fn(X, Y)
The data is ready. Here is the simplest, black and white density contour plot.
plt.contour(X, Y, Z, colors = 'black')
Let’s add a colormap also specify that we want 15 equally spaced lines drawn within the range.
plt.figure(figsize=(8, 6))contours = plt.contour(X, Y, Z, 15, cmap = 'RdGy')plt.clabel(contours, inline=True, fontsize=12)
There is another function in matplotlib that is contourf. Now, see an example of contourf.
plt.figure(figsize=(14, 10))plt.contourf(X, Y, Z, 20, cmap = 'RdGy')plt.colorbar()
plt.figure(figsize=(14, 10))plt.imshow(Z, extent=[0,6,0,6], origin='upper', cmap='RdGy')plt.colorbar()
We can even place that black and white contour plot on top of this imshow.
plt.figure(figsize=(14, 10))contours = plt.contour(X, Y, Z, 15, colors='black')plt.clabel(contours, inline=True, fontsize=12)plt.imshow(Z, extent=[0,6,0,6], origin='upper', cmap='RdGy', alpha=0.5)plt.colorbar()
I like it! How about you?
If you never made a contour plot before, I hope you will now whenever necessary. It gives a lot of information and also looks nice! If you are a machine learning modeler, use a contour plot to visualize the range in different classes or anomaly in the data.
Feel free to follow me on Twitter and like my Facebook page. | [
{
"code": null,
"e": 388,
"s": 46,
"text": "I am sure you have seen a contour plot before. At least in weather data. It is used a lot in presenting meteorological or geographical data. But it is also used to present density, brightness, and electric potential. It is used a lot in data analysis and machine learning. It shows how a response variable relates to two predictor variables."
},
{
"code": null,
"e": 520,
"s": 388,
"text": "It gives a two-dimensional view where all the points having the same response are connected by a line. That line is a contour line."
},
{
"code": null,
"e": 559,
"s": 520,
"text": "Three main elements of a contour plot:"
},
{
"code": null,
"e": 706,
"s": 559,
"text": "x-axis and the y-axis shows the predictorsContour lines to represent the same response valuesColored bands that provide a range of response values"
},
{
"code": null,
"e": 749,
"s": 706,
"text": "x-axis and the y-axis shows the predictors"
},
{
"code": null,
"e": 801,
"s": 749,
"text": "Contour lines to represent the same response values"
},
{
"code": null,
"e": 855,
"s": 801,
"text": "Colored bands that provide a range of response values"
},
{
"code": null,
"e": 892,
"s": 855,
"text": "First import the necessary packages."
},
{
"code": null,
"e": 954,
"s": 892,
"text": "import numpy as npimport matplotlib.pyplot as pltimport pylab"
},
{
"code": null,
"e": 989,
"s": 954,
"text": "Let’s generate some x and y values"
},
{
"code": null,
"e": 1040,
"s": 989,
"text": "xp = np.arange(-8, 10, 2)yp = np.arange(-8, 10, 2)"
},
{
"code": null,
"e": 1123,
"s": 1040,
"text": "You can probably imagine how ‘xp’ and ‘yp’ look like. But still, just have a look."
},
{
"code": null,
"e": 1126,
"s": 1123,
"text": "xp"
},
{
"code": null,
"e": 1134,
"s": 1126,
"text": "Output:"
},
{
"code": null,
"e": 1178,
"s": 1134,
"text": "array([-8, -6, -4, -2, 0, 2, 4, 6, 8])"
},
{
"code": null,
"e": 1185,
"s": 1178,
"text": "Input:"
},
{
"code": null,
"e": 1188,
"s": 1185,
"text": "yp"
},
{
"code": null,
"e": 1196,
"s": 1188,
"text": "Output:"
},
{
"code": null,
"e": 1240,
"s": 1196,
"text": "array([-8, -6, -4, -2, 0, 2, 4, 6, 8])"
},
{
"code": null,
"e": 1268,
"s": 1240,
"text": "The length of x and y is 9."
},
{
"code": null,
"e": 1347,
"s": 1268,
"text": "This information is important because we need to generate z using this number."
},
{
"code": null,
"e": 1399,
"s": 1347,
"text": "First, initiate a random z point of the shape 9 x 9"
},
{
"code": null,
"e": 1424,
"s": 1399,
"text": "zp = np.ndarray((9,9))zp"
},
{
"code": null,
"e": 1432,
"s": 1424,
"text": "Output:"
},
{
"code": null,
"e": 3009,
"s": 1432,
"text": "array([[1.20117830e-311, 1.20117830e-311, 1.20120150e-311, 1.20120150e-311, 1.20120150e-311, 1.20120150e-311, 1.20118338e-311, 1.20119781e-311, 1.20120151e-311], [1.20120150e-311, 1.20120151e-311, 1.20117830e-311, 1.20117830e-311, 1.20118045e-311, 1.20120150e-311, 1.20119863e-311, 1.20119863e-311, 1.20117830e-311], [1.20119864e-311, 1.20118316e-311, 1.20117850e-311, 1.20117830e-311, 1.20118500e-311, 1.20118500e-311, 1.20118490e-311, 1.20118488e-311, 1.20118316e-311], [1.20118500e-311, 1.20118493e-311, 1.20118493e-311, 1.20118493e-311, 1.20118493e-311, 1.20118339e-311, 1.20117862e-311, 1.20117835e-311, 1.20118337e-311], [1.20118339e-311, 1.20118338e-311, 1.20118347e-311, 1.20118348e-311, 1.20118339e-311, 1.20118348e-311, 1.20118316e-311, 1.20118338e-311, 1.20118348e-311], [1.20118339e-311, 1.20118348e-311, 1.20118347e-311, 1.20118348e-311, 1.20118348e-311, 1.20118348e-311, 1.20118339e-311, 1.20118339e-311, 1.20118333e-311], [1.20118348e-311, 1.20118348e-311, 1.20118348e-311, 1.20117830e-311, 1.20117830e-311, 1.20117853e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311], [1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311], [1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 1.20117830e-311, 0.00000000e+000]])"
},
{
"code": null,
"e": 3124,
"s": 3009,
"text": "Now, I will replace these random values with a formula of my choice. you can use the formula you want or you need."
},
{
"code": null,
"e": 3223,
"s": 3124,
"text": "for x in range(0, len(xp)): for y in range(0, len(yp)): zp[x][y] = xp[x]**2 + yp[y]**2zp"
},
{
"code": null,
"e": 3231,
"s": 3223,
"text": "Output:"
},
{
"code": null,
"e": 3791,
"s": 3231,
"text": "array([[128., 100., 80., 68., 64., 68., 80., 100., 128.], [100., 72., 52., 40., 36., 40., 52., 72., 100.], [ 80., 52., 32., 20., 16., 20., 32., 52., 80.], [ 68., 40., 20., 8., 4., 8., 20., 40., 68.], [ 64., 36., 16., 4., 0., 4., 16., 36., 64.], [ 68., 40., 20., 8., 4., 8., 20., 40., 68.], [ 80., 52., 32., 20., 16., 20., 32., 52., 80.], [100., 72., 52., 40., 36., 40., 52., 72., 100.], [128., 100., 80., 68., 64., 68., 80., 100., 128.]])"
},
{
"code": null,
"e": 3863,
"s": 3791,
"text": "So, we have x, y, and z data ready. Here is how to do the contour plot."
},
{
"code": null,
"e": 4002,
"s": 3863,
"text": "plt.figure(figsize=(7, 5))plt.title('Contour Plot')contours = plt.contour(xp, yp, zp)plt.clabel(contours, inline=1, fontsize=12)plt.show()"
},
{
"code": null,
"e": 4131,
"s": 4002,
"text": "I will do the exact same procedure with a slightly different formula for z values. So I will not explain step by step this time:"
},
{
"code": null,
"e": 4479,
"s": 4131,
"text": "xp = np.arange(-3, 4)yp = np.arange(-3, 4)zp =np.ndarray((7,7))for x in range(0, len(xp)): for y in range(0, len(yp)): zp[x][y] = xp[x]*xp[x] - yp[y]*yp[y]plt.figure(figsize=(8, 6))plt.title('Contour plot for saddle surface - Hyperbolic paraboloid')contours = plt.contour(xp, yp, zp)plt.clabel(contours, inline=1, fontsize=12)plt.show()"
},
{
"code": null,
"e": 4586,
"s": 4479,
"text": "This is a density plot. So I will make a different dataset where data points are closer. Here are x and y."
},
{
"code": null,
"e": 4637,
"s": 4586,
"text": "x = np.linspace(0, 5, 60)y = np.linspace(0, 5, 48)"
},
{
"code": null,
"e": 4696,
"s": 4637,
"text": "Both x and y are the same. This is how the data look like:"
},
{
"code": null,
"e": 5490,
"s": 4696,
"text": "array([0. , 0.08474576, 0.16949153, 0.25423729, 0.33898305, 0.42372881, 0.50847458, 0.59322034, 0.6779661 , 0.76271186, 0.84745763, 0.93220339, 1.01694915, 1.10169492, 1.18644068, 1.27118644, 1.3559322 , 1.44067797, 1.52542373, 1.61016949, 1.69491525, 1.77966102, 1.86440678, 1.94915254, 2.03389831, 2.11864407, 2.20338983, 2.28813559, 2.37288136, 2.45762712, 2.54237288, 2.62711864, 2.71186441, 2.79661017, 2.88135593, 2.96610169, 3.05084746, 3.13559322, 3.22033898, 3.30508475, 3.38983051, 3.47457627, 3.55932203, 3.6440678 , 3.72881356, 3.81355932, 3.89830508, 3.98305085, 4.06779661, 4.15254237, 4.23728814, 4.3220339 , 4.40677966, 4.49152542, 4.57627119, 4.66101695, 4.74576271, 4.83050847, 4.91525424, 5. ])"
},
{
"code": null,
"e": 5556,
"s": 5490,
"text": "As before I need a function for z. Here is the function I choose,"
},
{
"code": null,
"e": 5611,
"s": 5556,
"text": "def fn(x, y): return np.sin(x)**5 + np.cos(y+17)**8"
},
{
"code": null,
"e": 5772,
"s": 5611,
"text": "Now, time to prepare the X, Y, and Z data. I will simply use the np.meshgrid function on x and y which builds two-dimensional grids from one-dimensional arrays."
},
{
"code": null,
"e": 5809,
"s": 5772,
"text": "X, Y = np.meshgrid(x, y)Z = fn(X, Y)"
},
{
"code": null,
"e": 5888,
"s": 5809,
"text": "The data is ready. Here is the simplest, black and white density contour plot."
},
{
"code": null,
"e": 5927,
"s": 5888,
"text": "plt.contour(X, Y, Z, colors = 'black')"
},
{
"code": null,
"e": 6022,
"s": 5927,
"text": "Let’s add a colormap also specify that we want 15 equally spaced lines drawn within the range."
},
{
"code": null,
"e": 6145,
"s": 6022,
"text": "plt.figure(figsize=(8, 6))contours = plt.contour(X, Y, Z, 15, cmap = 'RdGy')plt.clabel(contours, inline=True, fontsize=12)"
},
{
"code": null,
"e": 6236,
"s": 6145,
"text": "There is another function in matplotlib that is contourf. Now, see an example of contourf."
},
{
"code": null,
"e": 6319,
"s": 6236,
"text": "plt.figure(figsize=(14, 10))plt.contourf(X, Y, Z, 20, cmap = 'RdGy')plt.colorbar()"
},
{
"code": null,
"e": 6422,
"s": 6319,
"text": "plt.figure(figsize=(14, 10))plt.imshow(Z, extent=[0,6,0,6], origin='upper', cmap='RdGy')plt.colorbar()"
},
{
"code": null,
"e": 6497,
"s": 6422,
"text": "We can even place that black and white contour plot on top of this imshow."
},
{
"code": null,
"e": 6708,
"s": 6497,
"text": "plt.figure(figsize=(14, 10))contours = plt.contour(X, Y, Z, 15, colors='black')plt.clabel(contours, inline=True, fontsize=12)plt.imshow(Z, extent=[0,6,0,6], origin='upper', cmap='RdGy', alpha=0.5)plt.colorbar()"
},
{
"code": null,
"e": 6734,
"s": 6708,
"text": "I like it! How about you?"
},
{
"code": null,
"e": 6992,
"s": 6734,
"text": "If you never made a contour plot before, I hope you will now whenever necessary. It gives a lot of information and also looks nice! If you are a machine learning modeler, use a contour plot to visualize the range in different classes or anomaly in the data."
}
] |
How to programmatically take a screenshot on iOS? | In this post we will learn how to take screen shot programmatically in iOS.
We will add on textField where we will change the value, take the screen shot by press of a button and then show the screen shot in an imageView which we will place just below the button itself.
Remember that you can add this functionality on long press or any other gesture, and even save the image if you want. But right now we will just focus on capturing the screen shot and showing it on an image view.
So let’s get started
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “TakeScreenShot”
Step 2 − Open Main.storyboard add one UITextField, one button and one UIImageView as shown below
Step 3 − Attach one @IBOutlet for the image view. Name it snapShotImageView. This is the image view where we will sow the captured screen shot.
Step 4 − Add one @IBAction for touchUpInside of ‘Take Snap Shot’ button. Name the function as takeSnapShotClicked.
Step 5 − In viewDidLoad of ViewController class set the border color and width for image the imageView to distinguish it from other part of the view.
self.snapShotImageView.layer.borderColor = UIColor.red.cgColor
self.snapShotImageView.layer.borderWidth = 2.0
Step 6 − We will be using the following method to capture the screenshot.
Start the graphic context.
Capture the current context in a variable.
Int the context variable, render the current views layer.
Get the image from context variable. Note that the context at this point will contain the screen shot of currently whatever is available on the view.
We will set the captured image from context to our imageView
End the graphic context
All of the above we will do in takeSnapShotClicked method. Which now would look like this
@IBAction func takeSnapShotClicked(_ sender: Any) {
UIGraphicsBeginImageContextWithOptions(self.view.layer.frame.size, false, UIScreen.main.scale);
guard let context = UIGraphicsGetCurrentContext() else {return }
self.view.layer.render(in:context)
self.snapShotImageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
Step 7 − Build and run the project. Click on the take snapshot button. You should see the snapshot in the bottom image view. | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "In this post we will learn how to take screen shot programmatically in iOS."
},
{
"code": null,
"e": 1333,
"s": 1138,
"text": "We will add on textField where we will change the value, take the screen shot by press of a button and then show the screen shot in an imageView which we will place just below the button itself."
},
{
"code": null,
"e": 1546,
"s": 1333,
"text": "Remember that you can add this functionality on long press or any other gesture, and even save the image if you want. But right now we will just focus on capturing the screen shot and showing it on an image view."
},
{
"code": null,
"e": 1567,
"s": 1546,
"text": "So let’s get started"
},
{
"code": null,
"e": 1660,
"s": 1567,
"text": "Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “TakeScreenShot”"
},
{
"code": null,
"e": 1758,
"s": 1660,
"text": "Step 2 − Open Main.storyboard add one UITextField, one button and one UIImageView as shown below "
},
{
"code": null,
"e": 1902,
"s": 1758,
"text": "Step 3 − Attach one @IBOutlet for the image view. Name it snapShotImageView. This is the image view where we will sow the captured screen shot."
},
{
"code": null,
"e": 2017,
"s": 1902,
"text": "Step 4 − Add one @IBAction for touchUpInside of ‘Take Snap Shot’ button. Name the function as takeSnapShotClicked."
},
{
"code": null,
"e": 2167,
"s": 2017,
"text": "Step 5 − In viewDidLoad of ViewController class set the border color and width for image the imageView to distinguish it from other part of the view."
},
{
"code": null,
"e": 2277,
"s": 2167,
"text": "self.snapShotImageView.layer.borderColor = UIColor.red.cgColor\nself.snapShotImageView.layer.borderWidth = 2.0"
},
{
"code": null,
"e": 2351,
"s": 2277,
"text": "Step 6 − We will be using the following method to capture the screenshot."
},
{
"code": null,
"e": 2378,
"s": 2351,
"text": "Start the graphic context."
},
{
"code": null,
"e": 2421,
"s": 2378,
"text": "Capture the current context in a variable."
},
{
"code": null,
"e": 2479,
"s": 2421,
"text": "Int the context variable, render the current views layer."
},
{
"code": null,
"e": 2629,
"s": 2479,
"text": "Get the image from context variable. Note that the context at this point will contain the screen shot of currently whatever is available on the view."
},
{
"code": null,
"e": 2690,
"s": 2629,
"text": "We will set the captured image from context to our imageView"
},
{
"code": null,
"e": 2714,
"s": 2690,
"text": "End the graphic context"
},
{
"code": null,
"e": 2804,
"s": 2714,
"text": "All of the above we will do in takeSnapShotClicked method. Which now would look like this"
},
{
"code": null,
"e": 3172,
"s": 2804,
"text": "@IBAction func takeSnapShotClicked(_ sender: Any) {\n UIGraphicsBeginImageContextWithOptions(self.view.layer.frame.size, false, UIScreen.main.scale);\n guard let context = UIGraphicsGetCurrentContext() else {return }\n self.view.layer.render(in:context)\n self.snapShotImageView.image = UIGraphicsGetImageFromCurrentImageContext()\n UIGraphicsEndImageContext()\n}"
},
{
"code": null,
"e": 3297,
"s": 3172,
"text": "Step 7 − Build and run the project. Click on the take snapshot button. You should see the snapshot in the bottom image view."
}
] |
LocalStorage in ReactJS | In this article, we are going to see how to set and retrieve data in the localStorage memory of the user’s browser in a React application.
LocalStorage is a web storage object to store the data on the user’s computer locally, which means the stored data is saved across browser sessions and the data stored has no expiration time.
// To store data
localStorage.setItem('Name', 'Rahul');
// To retrieve data
localStorage.getItem('Name');
// To clear a specific item
localStorage.removeItem('Name');
// To clear the whole data stored in localStorage
localStorage.clear();
In this example, we will build a React application which takes the username and password from the user and stores it as an item in the localStorage of the user’s computer.
App.jsx
import React, { useState } from 'react';
const App = () => {
const [name, setName] = useState('');
const [pwd, setPwd] = useState('');
const handle = () => {
localStorage.setItem('Name', name);
localStorage.setItem('Password', pwd);
};
const remove = () => {
localStorage.removeItem('Name');
localStorage.removeItem('Password');
};
return (
<div className="App">
<h1>Name of the user:</h1>
<input
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<h1>Password of the user:</h1>
<input
type="password"
placeholder="Password"
value={pwd}
onChange={(e) => setPwd(e.target.value)}
/>
<div>
<button onClick={handle}>Done</button>
</div>
{localStorage.getItem('Name') && (
<div>
Name: <p>{localStorage.getItem('Name')}</p>
</div>
)}
{localStorage.getItem('Password') && (
<div>
Password: <p>{localStorage.getItem('Password')}</p>
</div>
)}
<div>
<button onClick={remove}>Remove</button>
</div>
</div>
);
};
export default App;
In the above example, when the Done button is clicked, the handle function is executed which will set the items in the localStorage of the user and display it. But when the Remove button is clicked, the remove function is executed which will remove the items from the localStorage.
This will produce the following result. | [
{
"code": null,
"e": 1201,
"s": 1062,
"text": "In this article, we are going to see how to set and retrieve data in the localStorage memory of the user’s browser in a React application."
},
{
"code": null,
"e": 1393,
"s": 1201,
"text": "LocalStorage is a web storage object to store the data on the user’s computer locally, which means the stored data is saved across browser sessions and the data stored has no expiration time."
},
{
"code": null,
"e": 1635,
"s": 1393,
"text": "// To store data\nlocalStorage.setItem('Name', 'Rahul');\n\n// To retrieve data\nlocalStorage.getItem('Name');\n\n// To clear a specific item\nlocalStorage.removeItem('Name');\n\n// To clear the whole data stored in localStorage\nlocalStorage.clear();"
},
{
"code": null,
"e": 1807,
"s": 1635,
"text": "In this example, we will build a React application which takes the username and password from the user and stores it as an item in the localStorage of the user’s computer."
},
{
"code": null,
"e": 1815,
"s": 1807,
"text": "App.jsx"
},
{
"code": null,
"e": 3138,
"s": 1815,
"text": "import React, { useState } from 'react';\n\nconst App = () => {\n\n const [name, setName] = useState('');\n const [pwd, setPwd] = useState('');\n\n const handle = () => {\n localStorage.setItem('Name', name);\n localStorage.setItem('Password', pwd);\n };\n const remove = () => {\n localStorage.removeItem('Name');\n localStorage.removeItem('Password');\n };\n return (\n <div className=\"App\">\n <h1>Name of the user:</h1>\n <input\n placeholder=\"Name\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n />\n <h1>Password of the user:</h1>\n <input\n type=\"password\"\n placeholder=\"Password\"\n value={pwd}\n onChange={(e) => setPwd(e.target.value)}\n />\n <div>\n <button onClick={handle}>Done</button>\n </div>\n {localStorage.getItem('Name') && (\n <div>\n Name: <p>{localStorage.getItem('Name')}</p>\n </div>\n )}\n {localStorage.getItem('Password') && (\n <div>\n Password: <p>{localStorage.getItem('Password')}</p>\n </div>\n )}\n <div>\n <button onClick={remove}>Remove</button>\n </div>\n </div>\n );\n};\nexport default App;"
},
{
"code": null,
"e": 3420,
"s": 3138,
"text": "In the above example, when the Done button is clicked, the handle function is executed which will set the items in the localStorage of the user and display it. But when the Remove button is clicked, the remove function is executed which will remove the items from the localStorage."
},
{
"code": null,
"e": 3460,
"s": 3420,
"text": "This will produce the following result."
}
] |
Step-by-Step Tutorial: Web Scraping Wikipedia with BeautifulSoup | by Khuyen Tran | Towards Data Science | My roommate and I had a discussion about her observation of the high depression rate in Sweden. We drew the connection between the depression rate and the lack of sunshine. I decided to support my hypothesis by gathering my own data and analyzing it.
I use Beautiful Soup, an easy-to-use Python tool for web scraping. What I love about this tool is that it is easy to use and understand. The documentation for the library can be found here.
Hypothesis: The fewer hours of sunshine in a country, the higher the rate of depression that the country has.
Data to collect:
Names of Countries
Their depression rate
Their sunshine hours
Resources to use:
https://en.wikipedia.org/wiki/Epidemiology_of_depression
https://en.wikipedia.org/wiki/List_of_cities_by_sunshine_duration
import requestsimport urllib.requestimport timefrom bs4 import BeautifulSoupimport numpy as npimport pandas as pdfrom urllib.request import urlopenurl = 'https://en.wikipedia.org/wiki/Epidemiology_of_depression'html = urlopen(url) soup = BeautifulSoup(html, 'html.parser')
Right-click on the page then go to inspect. Click on the icon shown above to choose the element in the website to inspect.
We are interested in extracting the information from the table. This could be done easily with one line of code. By inspection, we find that the table is under <table> tag.
find_all('table') scans the entire document to look for the tag <table>
tables = soup.find_all('table')
find_all() is an easy and effective method that will be used a lot in this tutorial.
Look like the data in theDALY rate column will be a string when collected because of “,”. Create a function to process the string into an integer by using re.sub(), a method to return the substring that matches the regular expression.
import redef process_num(num): return float(re.sub(r'[^\w\s.]','',num))
Test the function
num1 = float(re.sub(r'[^\w\s.]','','1,156.30'))num1
Output: 1156.30
Let’s break this down.
Line 6–7: We pay attention that each row is under <tr> tag. This gives us the idea that we will get the rows by finding all the tag <tr>
Line 9–10: Extract rows by finding all <td> tags
Line 14: Since len(cells) in the first row is 1, we set the condition to skip the first row and extract from the other rows.
Line 15: Because cells is a list of 3 cells, we extract the rank using the first cell, country name using the second cell, and DALY rate using the third cell.
Put the data into a pandas.DataFrame
df1 = pd.DataFrame(ranks, index= countriescolumns = ['Rank'])df1['DALY rate'] = ratesdf1.head(10)
Use the same method as above to collect the sunshine hours from the second website. There are 2 differences between the data of the 2 websites to keep in mind:
There are multiple data about the sunshine hours from the same country. Thus we might want to take the average of these data to get the hours represented for each country. To take the average, we simply use 2 dictionaries, country_suns and countwith the same keys but different values.
Some countries in the second data are not available in the first one. Thus, we just want to collect the data from the countries in the first data, that are stored in the variable countries created above.
Outcome:
789.14 3Country: Benin, Sunshine Hours: 263.05515.99 2Country: Togo, Sunshine Hours: 258.0710.25 3Country: Ghana, Sunshine Hours: 236.75866.0500000000001 4Country: Cameroon, Sunshine Hours: 216.51344.03999999999996 2Country: Gabon, Sunshine Hours: 172.021334.54 5Country: Nigeria, Sunshine Hours: 266.91711.91 2Country: Sudan, Sunshine Hours: 355.95336.1 1...
Use the join method to join the 2 data we collected previously.
df2 = pd.DataFrame.from_dict(country_suns,orient='index', columns = ['Sunshine Hours/Year'])df = df1.join(df2)df.info()
Outcome:
<class 'pandas.core.frame.DataFrame'>Index: 192 entries, United States to JapanData columns (total 3 columns):Rank 192 non-null int64DALY rate 192 non-null float64Sunshine Hours/Year 122 non-null float64dtypes: float64(2), int64(1)memory usage: 11.0+ KB
We realize that there are null values in the last column because some countries in the first source are not in the second source. There are many ways to process missing values. But for now, just drop the rows with the missing values to visualize what we got.
df.dropna(inplace=True)
import matplotlib.pyplot as pltimport seaborn as snssns.scatterplot('Rank', 'Sunshine Hours/Year', data=df)
There seems not to be a strong correlation here. Take a look at the correlation coefficient.
Save the data if you want to work with the data using a different tool.
df.to_csv('wiki-2.csv')
The correlation is not as strong as I thought it would be. But we haven’t taken into account different factors such as the accurateness of the metric to determine to depression rate, the size the countries (the bigger the country, the more variation in sunshine hours/year), GDP, population, etc. More data should be gathered to attain a more accurate result. But before that, feel proud of yourself because you have just learned web scraping, one of the most essential processes in data science.
The Github repository for this tutorial could be found here: https://github.com/khuyentran1401/Web-Scrapping-Wikipedia.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[1] Epidemiology of depression, Wikipedia
[2] List of cities by sunshine duration, Wikipedia
[3]Varun Choudhary, How To Scrape A Website Without Getting Blacklisted (2019), Hackernoon | [
{
"code": null,
"e": 422,
"s": 171,
"text": "My roommate and I had a discussion about her observation of the high depression rate in Sweden. We drew the connection between the depression rate and the lack of sunshine. I decided to support my hypothesis by gathering my own data and analyzing it."
},
{
"code": null,
"e": 612,
"s": 422,
"text": "I use Beautiful Soup, an easy-to-use Python tool for web scraping. What I love about this tool is that it is easy to use and understand. The documentation for the library can be found here."
},
{
"code": null,
"e": 722,
"s": 612,
"text": "Hypothesis: The fewer hours of sunshine in a country, the higher the rate of depression that the country has."
},
{
"code": null,
"e": 739,
"s": 722,
"text": "Data to collect:"
},
{
"code": null,
"e": 758,
"s": 739,
"text": "Names of Countries"
},
{
"code": null,
"e": 780,
"s": 758,
"text": "Their depression rate"
},
{
"code": null,
"e": 801,
"s": 780,
"text": "Their sunshine hours"
},
{
"code": null,
"e": 819,
"s": 801,
"text": "Resources to use:"
},
{
"code": null,
"e": 876,
"s": 819,
"text": "https://en.wikipedia.org/wiki/Epidemiology_of_depression"
},
{
"code": null,
"e": 942,
"s": 876,
"text": "https://en.wikipedia.org/wiki/List_of_cities_by_sunshine_duration"
},
{
"code": null,
"e": 1215,
"s": 942,
"text": "import requestsimport urllib.requestimport timefrom bs4 import BeautifulSoupimport numpy as npimport pandas as pdfrom urllib.request import urlopenurl = 'https://en.wikipedia.org/wiki/Epidemiology_of_depression'html = urlopen(url) soup = BeautifulSoup(html, 'html.parser')"
},
{
"code": null,
"e": 1338,
"s": 1215,
"text": "Right-click on the page then go to inspect. Click on the icon shown above to choose the element in the website to inspect."
},
{
"code": null,
"e": 1511,
"s": 1338,
"text": "We are interested in extracting the information from the table. This could be done easily with one line of code. By inspection, we find that the table is under <table> tag."
},
{
"code": null,
"e": 1583,
"s": 1511,
"text": "find_all('table') scans the entire document to look for the tag <table>"
},
{
"code": null,
"e": 1615,
"s": 1583,
"text": "tables = soup.find_all('table')"
},
{
"code": null,
"e": 1700,
"s": 1615,
"text": "find_all() is an easy and effective method that will be used a lot in this tutorial."
},
{
"code": null,
"e": 1935,
"s": 1700,
"text": "Look like the data in theDALY rate column will be a string when collected because of “,”. Create a function to process the string into an integer by using re.sub(), a method to return the substring that matches the regular expression."
},
{
"code": null,
"e": 2010,
"s": 1935,
"text": "import redef process_num(num): return float(re.sub(r'[^\\w\\s.]','',num))"
},
{
"code": null,
"e": 2028,
"s": 2010,
"text": "Test the function"
},
{
"code": null,
"e": 2080,
"s": 2028,
"text": "num1 = float(re.sub(r'[^\\w\\s.]','','1,156.30'))num1"
},
{
"code": null,
"e": 2096,
"s": 2080,
"text": "Output: 1156.30"
},
{
"code": null,
"e": 2119,
"s": 2096,
"text": "Let’s break this down."
},
{
"code": null,
"e": 2256,
"s": 2119,
"text": "Line 6–7: We pay attention that each row is under <tr> tag. This gives us the idea that we will get the rows by finding all the tag <tr>"
},
{
"code": null,
"e": 2305,
"s": 2256,
"text": "Line 9–10: Extract rows by finding all <td> tags"
},
{
"code": null,
"e": 2430,
"s": 2305,
"text": "Line 14: Since len(cells) in the first row is 1, we set the condition to skip the first row and extract from the other rows."
},
{
"code": null,
"e": 2589,
"s": 2430,
"text": "Line 15: Because cells is a list of 3 cells, we extract the rank using the first cell, country name using the second cell, and DALY rate using the third cell."
},
{
"code": null,
"e": 2626,
"s": 2589,
"text": "Put the data into a pandas.DataFrame"
},
{
"code": null,
"e": 2724,
"s": 2626,
"text": "df1 = pd.DataFrame(ranks, index= countriescolumns = ['Rank'])df1['DALY rate'] = ratesdf1.head(10)"
},
{
"code": null,
"e": 2884,
"s": 2724,
"text": "Use the same method as above to collect the sunshine hours from the second website. There are 2 differences between the data of the 2 websites to keep in mind:"
},
{
"code": null,
"e": 3170,
"s": 2884,
"text": "There are multiple data about the sunshine hours from the same country. Thus we might want to take the average of these data to get the hours represented for each country. To take the average, we simply use 2 dictionaries, country_suns and countwith the same keys but different values."
},
{
"code": null,
"e": 3374,
"s": 3170,
"text": "Some countries in the second data are not available in the first one. Thus, we just want to collect the data from the countries in the first data, that are stored in the variable countries created above."
},
{
"code": null,
"e": 3383,
"s": 3374,
"text": "Outcome:"
},
{
"code": null,
"e": 3743,
"s": 3383,
"text": "789.14 3Country: Benin, Sunshine Hours: 263.05515.99 2Country: Togo, Sunshine Hours: 258.0710.25 3Country: Ghana, Sunshine Hours: 236.75866.0500000000001 4Country: Cameroon, Sunshine Hours: 216.51344.03999999999996 2Country: Gabon, Sunshine Hours: 172.021334.54 5Country: Nigeria, Sunshine Hours: 266.91711.91 2Country: Sudan, Sunshine Hours: 355.95336.1 1..."
},
{
"code": null,
"e": 3807,
"s": 3743,
"text": "Use the join method to join the 2 data we collected previously."
},
{
"code": null,
"e": 3927,
"s": 3807,
"text": "df2 = pd.DataFrame.from_dict(country_suns,orient='index', columns = ['Sunshine Hours/Year'])df = df1.join(df2)df.info()"
},
{
"code": null,
"e": 3936,
"s": 3927,
"text": "Outcome:"
},
{
"code": null,
"e": 4224,
"s": 3936,
"text": "<class 'pandas.core.frame.DataFrame'>Index: 192 entries, United States to JapanData columns (total 3 columns):Rank 192 non-null int64DALY rate 192 non-null float64Sunshine Hours/Year 122 non-null float64dtypes: float64(2), int64(1)memory usage: 11.0+ KB"
},
{
"code": null,
"e": 4483,
"s": 4224,
"text": "We realize that there are null values in the last column because some countries in the first source are not in the second source. There are many ways to process missing values. But for now, just drop the rows with the missing values to visualize what we got."
},
{
"code": null,
"e": 4507,
"s": 4483,
"text": "df.dropna(inplace=True)"
},
{
"code": null,
"e": 4615,
"s": 4507,
"text": "import matplotlib.pyplot as pltimport seaborn as snssns.scatterplot('Rank', 'Sunshine Hours/Year', data=df)"
},
{
"code": null,
"e": 4708,
"s": 4615,
"text": "There seems not to be a strong correlation here. Take a look at the correlation coefficient."
},
{
"code": null,
"e": 4780,
"s": 4708,
"text": "Save the data if you want to work with the data using a different tool."
},
{
"code": null,
"e": 4804,
"s": 4780,
"text": "df.to_csv('wiki-2.csv')"
},
{
"code": null,
"e": 5301,
"s": 4804,
"text": "The correlation is not as strong as I thought it would be. But we haven’t taken into account different factors such as the accurateness of the metric to determine to depression rate, the size the countries (the bigger the country, the more variation in sunshine hours/year), GDP, population, etc. More data should be gathered to attain a more accurate result. But before that, feel proud of yourself because you have just learned web scraping, one of the most essential processes in data science."
},
{
"code": null,
"e": 5421,
"s": 5301,
"text": "The Github repository for this tutorial could be found here: https://github.com/khuyentran1401/Web-Scrapping-Wikipedia."
},
{
"code": null,
"e": 5581,
"s": 5421,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
},
{
"code": null,
"e": 5757,
"s": 5581,
"text": "Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:"
},
{
"code": null,
"e": 5799,
"s": 5757,
"text": "[1] Epidemiology of depression, Wikipedia"
},
{
"code": null,
"e": 5850,
"s": 5799,
"text": "[2] List of cities by sunshine duration, Wikipedia"
}
] |
Common Classification Model Evaluation metrics. | by Oduor George | Towards Data Science | All models are wrong, but some are useful,George E. P. Box.
How accurate is a classification model? Is the model reliable?
These two questions are easily answered by evaluating how well a model performs when subjected to unseen observations. This post illustrates some of the best ways models can be evaluated.
What you will learn from this post:
Jaccard index.Confusion MatrixF-1 ScoreLog loss
Jaccard index.
Confusion Matrix
F-1 Score
Log loss
First I will fit a simple model and use it to illustrate these methods are applied in model performance evaluation. The model predicts whether a cancerous cell is malignant or not.
#quick model fitimport numpy as npimport warningsimport pandaswarnings.filterwarnings("ignore")#not recomended but i have included this for my own convenience.from sklearn.datasets import load_breast_cancerdata = load_breast_cancer()X = pandas.DataFrame(data = data.data,columns=data.feature_names)y = data.target#train test splitfrom sklearn import model_selectionnp.random.seed(2) #to enable you replicate the same thing i am doing here.X_train, X_test, y_train, y_test = model_selection.train_test_split(X,y,test_size=0.30)# I will use logistic regfrom sklearn.linear_model import LogisticRegressionreg = LogisticRegression()reg.fit(X_train,y_train)preds = reg.predict(X_test)predsprob = reg.predict_proba(X_test)
Given predicted values as (y hat)and actual values as y, the Jaccard index can be defined as :
so let us say you have the following set of predicted and actual values.
the Jaccard index will be :
The idea behind this index is that higher the similarity of these two groups the higher the index.
from sklearn.metrics import jaccard_similarity_scorej_index = jaccard_similarity_score(y_true=y_test,y_pred=preds)round(j_index,2)0.94
The confusion matrix is used to describe the performance of a classification model on a set of test data for which true values are known.
From the confusion matrix the following information can be extracted :
True positive(TP).: This shows that a model correctly predicted Positive cases as Positive. eg an illness is diagnosed as present and truly is present.False positive(FP): This shows that a model incorrectly predicted Negative cases as Positive.eg an illness is diagnosed as present and but is absent. (Type I error)False Negative:(FN) This shows that an incorrectly model predicted Positive cases as Negative.eg an illness is diagnosed as absent and but is present. (Type II error)True Negative(TN): This shows that a model correctly predicted Negative cases as Positive. eg an illness is diagnosed as absent and truly is absent.
True positive(TP).: This shows that a model correctly predicted Positive cases as Positive. eg an illness is diagnosed as present and truly is present.
False positive(FP): This shows that a model incorrectly predicted Negative cases as Positive.eg an illness is diagnosed as present and but is absent. (Type I error)
False Negative:(FN) This shows that an incorrectly model predicted Positive cases as Negative.eg an illness is diagnosed as absent and but is present. (Type II error)
True Negative(TN): This shows that a model correctly predicted Negative cases as Positive. eg an illness is diagnosed as absent and truly is absent.
from sklearn.metrics import confusion_matrixprint(confusion_matrix(y_test,preds,labels=[1,0]))import seaborn as snsimport matplotlib.pyplot as pltsns.heatmap(confusion_matrix(y_test,preds),annot=True,lw =2,cbar=False)plt.ylabel("True Values")plt.xlabel("Predicted Values")plt.title("CONFUSSION MATRIX VISUALIZATION")plt.show()
In this case for the breast cancer data, the model correctly predicts 62 cases as benign and 98 cases as malignant.In contrast, it mispredicts a total of 11 cases.
This comes from the confusion matrix. Based on the above confusion matrix above, we can calculate the precision and the recall scores.
Precision score: this is the measure of the accuracy, provided that a class label has been predicted. Simply put, it answers the following question, of all the classes, how many were correctly predicted? The answer to this question should be as high as possible.
It can be calculated as follows:
Recall score(Sensitivity): This is the true positive rate that is if it predicts positive then how often does this take place?
The F1 score is calculated based on the precision and recall of each class. It is the weighted average of the Precision and the recall scores. The F1 score reaches its perfect value at one and worst at 0.It is a very good way to show that a classifies has a good recall and precision values.
We can calculate it using this formula:
from sklearn.metrics import f1_scoref1_score(y_test,preds)0.9468599033816425
F1 score can be calculated for all classes so that an average of the realized scores can be used as shown in the classification report below.
from sklearn.metrics import classification_reportprint(classification_report(y_test,preds))precision recall f1-score support 0 0.91 0.93 0.92 67 1 0.95 0.94 0.95 104 micro avg 0.94 0.94 0.94 171 macro avg 0.93 0.93 0.93 171weighted avg 0.94 0.94 0.94 171
We can use the log loss in cases where the outcome of the classifier is a class probability and not a class label like in cases of logistic regression models.
Log loss measures the performance of a model where the predicted outcome is a probability value between 0 and 1.
In real life when predicting a probability of 0.101 when the true label should be 1 would result in a high log loss. Log loss can be calculated for each row in the data set using the Log loss equation.
The equation simply measures how far each predicted probability is from the actual label. An average of the log loss from all the rows gives the ideal value for the log loss.
A good and model should have a smaller log loss value.
from sklearn.metrics import log_losslog_loss(y_test,predsprob)0.13710589473837184
And there we have a 0.14 log loss which is pretty good!
The choice of evaluation metrics should be well understood based on the model applied.Feature engineering and parameter tuning are recommended for a model in order to get excellent results from the evaluation metrics.
The choice of evaluation metrics should be well understood based on the model applied.
Feature engineering and parameter tuning are recommended for a model in order to get excellent results from the evaluation metrics.
Thanks for reading, any comments and/or additions are welcome. | [
{
"code": null,
"e": 231,
"s": 171,
"text": "All models are wrong, but some are useful,George E. P. Box."
},
{
"code": null,
"e": 294,
"s": 231,
"text": "How accurate is a classification model? Is the model reliable?"
},
{
"code": null,
"e": 482,
"s": 294,
"text": "These two questions are easily answered by evaluating how well a model performs when subjected to unseen observations. This post illustrates some of the best ways models can be evaluated."
},
{
"code": null,
"e": 518,
"s": 482,
"text": "What you will learn from this post:"
},
{
"code": null,
"e": 566,
"s": 518,
"text": "Jaccard index.Confusion MatrixF-1 ScoreLog loss"
},
{
"code": null,
"e": 581,
"s": 566,
"text": "Jaccard index."
},
{
"code": null,
"e": 598,
"s": 581,
"text": "Confusion Matrix"
},
{
"code": null,
"e": 608,
"s": 598,
"text": "F-1 Score"
},
{
"code": null,
"e": 617,
"s": 608,
"text": "Log loss"
},
{
"code": null,
"e": 798,
"s": 617,
"text": "First I will fit a simple model and use it to illustrate these methods are applied in model performance evaluation. The model predicts whether a cancerous cell is malignant or not."
},
{
"code": null,
"e": 1515,
"s": 798,
"text": "#quick model fitimport numpy as npimport warningsimport pandaswarnings.filterwarnings(\"ignore\")#not recomended but i have included this for my own convenience.from sklearn.datasets import load_breast_cancerdata = load_breast_cancer()X = pandas.DataFrame(data = data.data,columns=data.feature_names)y = data.target#train test splitfrom sklearn import model_selectionnp.random.seed(2) #to enable you replicate the same thing i am doing here.X_train, X_test, y_train, y_test = model_selection.train_test_split(X,y,test_size=0.30)# I will use logistic regfrom sklearn.linear_model import LogisticRegressionreg = LogisticRegression()reg.fit(X_train,y_train)preds = reg.predict(X_test)predsprob = reg.predict_proba(X_test)"
},
{
"code": null,
"e": 1610,
"s": 1515,
"text": "Given predicted values as (y hat)and actual values as y, the Jaccard index can be defined as :"
},
{
"code": null,
"e": 1683,
"s": 1610,
"text": "so let us say you have the following set of predicted and actual values."
},
{
"code": null,
"e": 1711,
"s": 1683,
"text": "the Jaccard index will be :"
},
{
"code": null,
"e": 1810,
"s": 1711,
"text": "The idea behind this index is that higher the similarity of these two groups the higher the index."
},
{
"code": null,
"e": 1945,
"s": 1810,
"text": "from sklearn.metrics import jaccard_similarity_scorej_index = jaccard_similarity_score(y_true=y_test,y_pred=preds)round(j_index,2)0.94"
},
{
"code": null,
"e": 2083,
"s": 1945,
"text": "The confusion matrix is used to describe the performance of a classification model on a set of test data for which true values are known."
},
{
"code": null,
"e": 2154,
"s": 2083,
"text": "From the confusion matrix the following information can be extracted :"
},
{
"code": null,
"e": 2784,
"s": 2154,
"text": "True positive(TP).: This shows that a model correctly predicted Positive cases as Positive. eg an illness is diagnosed as present and truly is present.False positive(FP): This shows that a model incorrectly predicted Negative cases as Positive.eg an illness is diagnosed as present and but is absent. (Type I error)False Negative:(FN) This shows that an incorrectly model predicted Positive cases as Negative.eg an illness is diagnosed as absent and but is present. (Type II error)True Negative(TN): This shows that a model correctly predicted Negative cases as Positive. eg an illness is diagnosed as absent and truly is absent."
},
{
"code": null,
"e": 2936,
"s": 2784,
"text": "True positive(TP).: This shows that a model correctly predicted Positive cases as Positive. eg an illness is diagnosed as present and truly is present."
},
{
"code": null,
"e": 3101,
"s": 2936,
"text": "False positive(FP): This shows that a model incorrectly predicted Negative cases as Positive.eg an illness is diagnosed as present and but is absent. (Type I error)"
},
{
"code": null,
"e": 3268,
"s": 3101,
"text": "False Negative:(FN) This shows that an incorrectly model predicted Positive cases as Negative.eg an illness is diagnosed as absent and but is present. (Type II error)"
},
{
"code": null,
"e": 3417,
"s": 3268,
"text": "True Negative(TN): This shows that a model correctly predicted Negative cases as Positive. eg an illness is diagnosed as absent and truly is absent."
},
{
"code": null,
"e": 3744,
"s": 3417,
"text": "from sklearn.metrics import confusion_matrixprint(confusion_matrix(y_test,preds,labels=[1,0]))import seaborn as snsimport matplotlib.pyplot as pltsns.heatmap(confusion_matrix(y_test,preds),annot=True,lw =2,cbar=False)plt.ylabel(\"True Values\")plt.xlabel(\"Predicted Values\")plt.title(\"CONFUSSION MATRIX VISUALIZATION\")plt.show()"
},
{
"code": null,
"e": 3908,
"s": 3744,
"text": "In this case for the breast cancer data, the model correctly predicts 62 cases as benign and 98 cases as malignant.In contrast, it mispredicts a total of 11 cases."
},
{
"code": null,
"e": 4043,
"s": 3908,
"text": "This comes from the confusion matrix. Based on the above confusion matrix above, we can calculate the precision and the recall scores."
},
{
"code": null,
"e": 4306,
"s": 4043,
"text": "Precision score: this is the measure of the accuracy, provided that a class label has been predicted. Simply put, it answers the following question, of all the classes, how many were correctly predicted? The answer to this question should be as high as possible."
},
{
"code": null,
"e": 4339,
"s": 4306,
"text": "It can be calculated as follows:"
},
{
"code": null,
"e": 4466,
"s": 4339,
"text": "Recall score(Sensitivity): This is the true positive rate that is if it predicts positive then how often does this take place?"
},
{
"code": null,
"e": 4758,
"s": 4466,
"text": "The F1 score is calculated based on the precision and recall of each class. It is the weighted average of the Precision and the recall scores. The F1 score reaches its perfect value at one and worst at 0.It is a very good way to show that a classifies has a good recall and precision values."
},
{
"code": null,
"e": 4798,
"s": 4758,
"text": "We can calculate it using this formula:"
},
{
"code": null,
"e": 4875,
"s": 4798,
"text": "from sklearn.metrics import f1_scoref1_score(y_test,preds)0.9468599033816425"
},
{
"code": null,
"e": 5017,
"s": 4875,
"text": "F1 score can be calculated for all classes so that an average of the realized scores can be used as shown in the classification report below."
},
{
"code": null,
"e": 5413,
"s": 5017,
"text": "from sklearn.metrics import classification_reportprint(classification_report(y_test,preds))precision recall f1-score support 0 0.91 0.93 0.92 67 1 0.95 0.94 0.95 104 micro avg 0.94 0.94 0.94 171 macro avg 0.93 0.93 0.93 171weighted avg 0.94 0.94 0.94 171"
},
{
"code": null,
"e": 5572,
"s": 5413,
"text": "We can use the log loss in cases where the outcome of the classifier is a class probability and not a class label like in cases of logistic regression models."
},
{
"code": null,
"e": 5685,
"s": 5572,
"text": "Log loss measures the performance of a model where the predicted outcome is a probability value between 0 and 1."
},
{
"code": null,
"e": 5887,
"s": 5685,
"text": "In real life when predicting a probability of 0.101 when the true label should be 1 would result in a high log loss. Log loss can be calculated for each row in the data set using the Log loss equation."
},
{
"code": null,
"e": 6062,
"s": 5887,
"text": "The equation simply measures how far each predicted probability is from the actual label. An average of the log loss from all the rows gives the ideal value for the log loss."
},
{
"code": null,
"e": 6117,
"s": 6062,
"text": "A good and model should have a smaller log loss value."
},
{
"code": null,
"e": 6199,
"s": 6117,
"text": "from sklearn.metrics import log_losslog_loss(y_test,predsprob)0.13710589473837184"
},
{
"code": null,
"e": 6255,
"s": 6199,
"text": "And there we have a 0.14 log loss which is pretty good!"
},
{
"code": null,
"e": 6473,
"s": 6255,
"text": "The choice of evaluation metrics should be well understood based on the model applied.Feature engineering and parameter tuning are recommended for a model in order to get excellent results from the evaluation metrics."
},
{
"code": null,
"e": 6560,
"s": 6473,
"text": "The choice of evaluation metrics should be well understood based on the model applied."
},
{
"code": null,
"e": 6692,
"s": 6560,
"text": "Feature engineering and parameter tuning are recommended for a model in order to get excellent results from the evaluation metrics."
}
] |
Max sum path in two arrays | Practice | GeeksforGeeks | Given two sorted arrays A and B of size M and N respectively. Each array may have some elements in common with the other array. Find the maximum sum of a path from the beginning of any array to the end of any of the two arrays. We can switch from one array to another array only at the common elements which are present at the same index.
Note: Only one repeated value is considered in the valid path sum.
Example 1:
Input:
M = 5, N = 4
A[] = {2,3,7,10,12}
B[] = {1,5,7,8}
Output: 35
Explanation: The path will be 1+5+7+10+12
= 35.
Example 2:
Input:
M = 3, N = 3
A[] = {1,2,3}
B[] = {3,4,5}
Output: 15
Explanation: The path will be 1+2+3+4+5=15.
Your Task:
You don't need to read input or print anything. Complete the function max_path_sum() which takes the two arrays A and B along with their sizes M and N as input parameters. It returns the maximum path sum.
Expected Time Complexity: O(M + N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= M,N <= 104
1 <= A[i], B[i] <= 104
0
fls70015 days ago
This question is different and the test cases are not designed as per the question asked. Question says same index but according to test cases common elements can be at any index
0
bokonist1 week ago
Don't attempt this question before it's fixed and waste your time. Question is wrong. You should assume that common elements may be at any index.For example, this case:
4 46 7 8 91 2 3 6The answer would be 6+7+8+9 if the switch can happen only at same indices. But, the answer is 36 because the switch can happen at ‘6’ which is at A[0] and at B[3]
0
gautambaddy1 week ago
//please make it correct if possible
int sum1=0; int sum2=0; int sum11=0; int sum22=0; int i=0; int k=0; while((i<n)|(k<m)){ if(arr[i]>arr2[k]){ k++; sum2=sum2+arr2[k]; } else if(arr[i]<arr2[k]){ i++; sum1=sum1+arr[i]; } else if(arr[i]==arr2[k]){ break; } else{ return -1; } } i=i+1; k=k+1; while(i<n){ sum11=sum11+arr[i]; i++; } while(k<m){ sum22=sum22+arr2[k]; } if(sum1>sum2){ if(sum11>sum22){ return(sum1+sum11); } else{ return(sum1+sum22); } } else{ if(sum11>sum22){ return(sum2+sum11); } else{ return(sum2+sum22); } }
0
cshubham4391 week ago
int n = ar1.length;
int m = ar2.length;
int i = 0;
int j = 0;
int sum1 = 0;
int sum2 = 0;
int result = 0;
while(i<n && j<m){
if(ar1[i]<ar2[j]){
sum1+=ar1[i++];
}
else if(ar1[i]>ar2[j]){
sum2+=ar2[j++];
}
else{
result += Math.max(sum1,sum2)+ar1[i];
i++;
j++;
sum1 = 0;
sum2 = 0;
}
}
while(i<n){
sum1+=ar1[i++];
}
while(j<m){
sum2+=ar2[j++];
}
result+=Math.max(sum1,sum2);
return result;
+4
geminicode3 weeks ago
must be medium level.
+2
badgujarsachin833 weeks ago
int max_path_sum(int A[], int B[], int l1, int l2)
{
int i=0,j=0,path1=0,path2=0;
while(i<l1 && j<l2){
if(A[i]<B[j]){
path1+=A[i++];
}else if(A[i]>B[j]){
path2+=B[j++];
}else{
path1+=A[i++];
path2+=B[j++];
path1=max(path1,path2);
path2=max(path1,path2);
}
}
while(i<l1){
path1+=A[i++];
}
while(j<l2){
path2+=B[j++];
}
return max(path1,path2);
}
-1
aniketsaraswat1124 weeks ago
int max_path_sum(int arr1[], int arr2[], int l1, int l2){
int sum1 = 0, sum2 = 0, i = 0, j = 0, result = 0;
while(i < l1 && j < l2){
if(arr1[i] < arr2[j]) sum1 += arr1[i++];
else if(arr2[j] < arr1[i]) sum2 += arr2[j++];
else{
result += max(sum1, sum2) + arr1[i];
sum1 = sum2 = 0;
i++,j++;
}
}
while(i < l1) sum1 += arr1[i++];
while(j < l2) sum2 += arr2[j++];
return result + max(sum1,sum2);
}
+4
siricoolent274 weeks ago
This questions test cases aren't appropriate
+1
rishabhjain169
This comment was deleted.
0
r__________h2 months ago
int max_path_sum(int A[], int B[], int l1, int l2) { int res=0; int i=0,j=0; int asum=0,bsum=0; while(i<l1 && j<l2){ if(A[i]==B[j]){ asum+=A[i++]; bsum+=B[j++]; res+=max(asum,bsum); asum=0; bsum=0; } if(A[i]<B[j]) asum+=A[i++]; if(A[i]>B[j]) bsum+=B[j++]; } while(i<l1){ asum+=A[i++]; } while(j<l2){ bsum+=B[j++]; } res+=max(asum,bsum); return res; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 644,
"s": 238,
"text": "Given two sorted arrays A and B of size M and N respectively. Each array may have some elements in common with the other array. Find the maximum sum of a path from the beginning of any array to the end of any of the two arrays. We can switch from one array to another array only at the common elements which are present at the same index.\nNote: Only one repeated value is considered in the valid path sum."
},
{
"code": null,
"e": 656,
"s": 644,
"text": "\nExample 1:"
},
{
"code": null,
"e": 772,
"s": 656,
"text": "Input:\nM = 5, N = 4\nA[] = {2,3,7,10,12}\nB[] = {1,5,7,8}\nOutput: 35\nExplanation: The path will be 1+5+7+10+12\n= 35.\n"
},
{
"code": null,
"e": 784,
"s": 772,
"text": "\nExample 2:"
},
{
"code": null,
"e": 887,
"s": 784,
"text": "Input:\nM = 3, N = 3\nA[] = {1,2,3}\nB[] = {3,4,5}\nOutput: 15\nExplanation: The path will be 1+2+3+4+5=15."
},
{
"code": null,
"e": 1104,
"s": 887,
"text": "\nYour Task:\nYou don't need to read input or print anything. Complete the function max_path_sum() which takes the two arrays A and B along with their sizes M and N as input parameters. It returns the maximum path sum."
},
{
"code": null,
"e": 1171,
"s": 1104,
"text": "\nExpected Time Complexity: O(M + N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1224,
"s": 1171,
"text": "\nConstraints:\n1 <= M,N <= 104\n1 <= A[i], B[i] <= 104"
},
{
"code": null,
"e": 1226,
"s": 1224,
"text": "0"
},
{
"code": null,
"e": 1244,
"s": 1226,
"text": "fls70015 days ago"
},
{
"code": null,
"e": 1423,
"s": 1244,
"text": "This question is different and the test cases are not designed as per the question asked. Question says same index but according to test cases common elements can be at any index"
},
{
"code": null,
"e": 1425,
"s": 1423,
"text": "0"
},
{
"code": null,
"e": 1444,
"s": 1425,
"text": "bokonist1 week ago"
},
{
"code": null,
"e": 1613,
"s": 1444,
"text": "Don't attempt this question before it's fixed and waste your time. Question is wrong. You should assume that common elements may be at any index.For example, this case:"
},
{
"code": null,
"e": 1793,
"s": 1613,
"text": "4 46 7 8 91 2 3 6The answer would be 6+7+8+9 if the switch can happen only at same indices. But, the answer is 36 because the switch can happen at ‘6’ which is at A[0] and at B[3]"
},
{
"code": null,
"e": 1795,
"s": 1793,
"text": "0"
},
{
"code": null,
"e": 1817,
"s": 1795,
"text": "gautambaddy1 week ago"
},
{
"code": null,
"e": 1854,
"s": 1817,
"text": "//please make it correct if possible"
},
{
"code": null,
"e": 2560,
"s": 1854,
"text": "int sum1=0; int sum2=0; int sum11=0; int sum22=0; int i=0; int k=0; while((i<n)|(k<m)){ if(arr[i]>arr2[k]){ k++; sum2=sum2+arr2[k]; } else if(arr[i]<arr2[k]){ i++; sum1=sum1+arr[i]; } else if(arr[i]==arr2[k]){ break; } else{ return -1; } } i=i+1; k=k+1; while(i<n){ sum11=sum11+arr[i]; i++; } while(k<m){ sum22=sum22+arr2[k]; } if(sum1>sum2){ if(sum11>sum22){ return(sum1+sum11); } else{ return(sum1+sum22); } } else{ if(sum11>sum22){ return(sum2+sum11); } else{ return(sum2+sum22); } }"
},
{
"code": null,
"e": 2562,
"s": 2560,
"text": "0"
},
{
"code": null,
"e": 2584,
"s": 2562,
"text": "cshubham4391 week ago"
},
{
"code": null,
"e": 3289,
"s": 2584,
"text": "int n = ar1.length;\n int m = ar2.length;\n int i = 0;\n int j = 0;\n int sum1 = 0;\n int sum2 = 0;\n int result = 0;\n while(i<n && j<m){\n if(ar1[i]<ar2[j]){\n sum1+=ar1[i++];\n }\n else if(ar1[i]>ar2[j]){\n sum2+=ar2[j++];\n }\n else{\n result += Math.max(sum1,sum2)+ar1[i];\n i++;\n j++;\n sum1 = 0;\n sum2 = 0;\n }\n }\n while(i<n){\n sum1+=ar1[i++];\n }\n while(j<m){\n sum2+=ar2[j++];\n }\n result+=Math.max(sum1,sum2);\n return result;"
},
{
"code": null,
"e": 3292,
"s": 3289,
"text": "+4"
},
{
"code": null,
"e": 3314,
"s": 3292,
"text": "geminicode3 weeks ago"
},
{
"code": null,
"e": 3336,
"s": 3314,
"text": "must be medium level."
},
{
"code": null,
"e": 3339,
"s": 3336,
"text": "+2"
},
{
"code": null,
"e": 3367,
"s": 3339,
"text": "badgujarsachin833 weeks ago"
},
{
"code": null,
"e": 3953,
"s": 3367,
"text": " int max_path_sum(int A[], int B[], int l1, int l2)\n {\n int i=0,j=0,path1=0,path2=0;\n while(i<l1 && j<l2){\n if(A[i]<B[j]){\n path1+=A[i++];\n }else if(A[i]>B[j]){\n path2+=B[j++];\n }else{\n path1+=A[i++];\n path2+=B[j++];\n path1=max(path1,path2);\n path2=max(path1,path2);\n }\n }\n while(i<l1){\n path1+=A[i++];\n }\n while(j<l2){\n path2+=B[j++];\n }\n return max(path1,path2);\n }"
},
{
"code": null,
"e": 3956,
"s": 3953,
"text": "-1"
},
{
"code": null,
"e": 3985,
"s": 3956,
"text": "aniketsaraswat1124 weeks ago"
},
{
"code": null,
"e": 4526,
"s": 3985,
"text": "int max_path_sum(int arr1[], int arr2[], int l1, int l2){\n int sum1 = 0, sum2 = 0, i = 0, j = 0, result = 0;\n while(i < l1 && j < l2){\n if(arr1[i] < arr2[j]) sum1 += arr1[i++];\n else if(arr2[j] < arr1[i]) sum2 += arr2[j++];\n else{\n result += max(sum1, sum2) + arr1[i];\n sum1 = sum2 = 0;\n i++,j++;\n }\n }\n while(i < l1) sum1 += arr1[i++];\n while(j < l2) sum2 += arr2[j++];\n return result + max(sum1,sum2);\n }"
},
{
"code": null,
"e": 4529,
"s": 4526,
"text": "+4"
},
{
"code": null,
"e": 4554,
"s": 4529,
"text": "siricoolent274 weeks ago"
},
{
"code": null,
"e": 4599,
"s": 4554,
"text": "This questions test cases aren't appropriate"
},
{
"code": null,
"e": 4602,
"s": 4599,
"text": "+1"
},
{
"code": null,
"e": 4617,
"s": 4602,
"text": "rishabhjain169"
},
{
"code": null,
"e": 4643,
"s": 4617,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4645,
"s": 4643,
"text": "0"
},
{
"code": null,
"e": 4670,
"s": 4645,
"text": "r__________h2 months ago"
},
{
"code": null,
"e": 5290,
"s": 4670,
"text": " int max_path_sum(int A[], int B[], int l1, int l2) { int res=0; int i=0,j=0; int asum=0,bsum=0; while(i<l1 && j<l2){ if(A[i]==B[j]){ asum+=A[i++]; bsum+=B[j++]; res+=max(asum,bsum); asum=0; bsum=0; } if(A[i]<B[j]) asum+=A[i++]; if(A[i]>B[j]) bsum+=B[j++]; } while(i<l1){ asum+=A[i++]; } while(j<l2){ bsum+=B[j++]; } res+=max(asum,bsum); return res; }"
},
{
"code": null,
"e": 5436,
"s": 5290,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5472,
"s": 5436,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5482,
"s": 5472,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5492,
"s": 5482,
"text": "\nContest\n"
},
{
"code": null,
"e": 5555,
"s": 5492,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5703,
"s": 5555,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5911,
"s": 5703,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6017,
"s": 5911,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
CSS Grid Lines | Grid Lines are columns lines and row lines.
Columns lines are the lines between columns and row lines between rows.
The following is an example of grid lines
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
background-color: green;
grid-template-columns: auto auto;
padding: 20px;
grid-gap: 20px;
}
.container > div {
background-color: orange;
border: 2px solid gray;
padding: 35px;
font-size: 30px;
text-align: center;
}
.ele1 {
grid-row-start: 1;
grid-row-end: 6;
}
</style>
</head>
<body>
<h1>Game Board</h1>
<div class = "container">
<div class = "ele1">1</div>
<div class = "ele2">2</div>
<div class = "ele3">3</div>
<div class = "ele4">4</div>
<div class = "ele5">5</div>
<div class = "ele6">6</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1106,
"s": 1062,
"text": "Grid Lines are columns lines and row lines."
},
{
"code": null,
"e": 1178,
"s": 1106,
"text": "Columns lines are the lines between columns and row lines between rows."
},
{
"code": null,
"e": 1220,
"s": 1178,
"text": "The following is an example of grid lines"
},
{
"code": null,
"e": 1230,
"s": 1220,
"text": "Live Demo"
},
{
"code": null,
"e": 2112,
"s": 1230,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .container {\n display: grid;\n background-color: green;\n grid-template-columns: auto auto;\n padding: 20px;\n grid-gap: 20px;\n }\n .container > div {\n background-color: orange;\n border: 2px solid gray;\n padding: 35px;\n font-size: 30px;\n text-align: center;\n }\n .ele1 {\n grid-row-start: 1;\n grid-row-end: 6;\n }\n </style>\n </head>\n <body>\n <h1>Game Board</h1>\n <div class = \"container\">\n <div class = \"ele1\">1</div>\n <div class = \"ele2\">2</div>\n <div class = \"ele3\">3</div>\n <div class = \"ele4\">4</div>\n <div class = \"ele5\">5</div>\n <div class = \"ele6\">6</div>\n </div>\n </body>\n</html>"
}
] |
Find root of a number using Newton's method - GeeksforGeeks | 06 Feb, 2022
Given an integer N and a tolerance level L, the task is to find the square root of that number using Newton’s Method.Examples:
Input: N = 16, L = 0.0001 Output: 4 42 = 16Input: N = 327, L = 0.00001 Output: 18.0831
Newton’s Method: Let N be any number then the square root of N can be given by the formula:
root = 0.5 * (X + (N / X)) where X is any guess which can be assumed to be N or 1.
In the above formula, X is any assumed square root of N and root is the correct square root of N.
Tolerance limit is the maximum difference between X and root allowed.
Approach: The following steps can be followed to compute the answer:
Assign X to the N itself.Now, start a loop and keep calculating the root which will surely move towards the correct square root of N.Check for the difference between the assumed X and calculated root, if not yet inside tolerance then update root and continue.If the calculated root comes inside the tolerance allowed then break out of the loop.Print the root.
Assign X to the N itself.
Now, start a loop and keep calculating the root which will surely move towards the correct square root of N.
Check for the difference between the assumed X and calculated root, if not yet inside tolerance then update root and continue.
If the calculated root comes inside the tolerance allowed then break out of the loop.
Print the root.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the square root of// a number using Newtons methoddouble squareRoot(double n, float l){ // Assuming the sqrt of n as n only double x = n; // The closed guess will be stored in the root double root; // To count the number of iterations int count = 0; while (1) { count++; // Calculate more closed x root = 0.5 * (x + (n / x)); // Check for closeness if (abs(root - x) < l) break; // Update root x = root; } return root;} // Driver codeint main(){ double n = 327; float l = 0.00001; cout << squareRoot(n, l); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the square root of // a number using Newtons method static double squareRoot(double n, double l) { // Assuming the sqrt of n as n only double x = n; // The closed guess will be stored in the root double root; // To count the number of iterations int count = 0; while (true) { count++; // Calculate more closed x root = 0.5 * (x + (n / x)); // Check for closeness if (Math.abs(root - x) < l) break; // Update root x = root; } return root; } // Driver code public static void main (String[] args) { double n = 327; double l = 0.00001; System.out.println(squareRoot(n, l)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach # Function to return the square root of# a number using Newtons methoddef squareRoot(n, l) : # Assuming the sqrt of n as n only x = n # To count the number of iterations count = 0 while (1) : count += 1 # Calculate more closed x root = 0.5 * (x + (n / x)) # Check for closeness if (abs(root - x) < l) : break # Update root x = root return root # Driver codeif __name__ == "__main__" : n = 327 l = 0.00001 print(squareRoot(n, l)) # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to return the square root of // a number using Newtons method static double squareRoot(double n, double l) { // Assuming the sqrt of n as n only double x = n; // The closed guess will be stored in the root double root; // To count the number of iterations int count = 0; while (true) { count++; // Calculate more closed x root = 0.5 * (x + (n / x)); // Check for closeness if (Math.Abs(root - x) < l) break; // Update root x = root; } return root; } // Driver code public static void Main() { double n = 327; double l = 0.00001; Console.WriteLine(squareRoot(n, l)); }} // This code is contributed by AnkitRai01
<script> // Javascript implementation of the approach // Function to return the square root of // a number using Newtons method function squareRoot(n, l) { // Assuming the sqrt of n as n only let x = n; // The closed guess will be stored in the root let root; // To count the number of iterations let count = 0; while (true) { count++; // Calculate more closed x root = 0.5 * (x + (n / x)); // Check for closeness if (Math.abs(root - x) < l) break; // Update root x = root; } return root.toFixed(4); } let n = 327; let l = 0.00001; document.write(squareRoot(n, l)); // This code is contributed by divyesh072019.</script>
18.0831
Time Complexity: O(log N)
Auxiliary Space: O(1)
ankthon
himangshushekharjha
divyesh072019
subhammahato348
root
Technical Scripter 2019
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Modular multiplicative inverse
Program to multiply two matrices
Program to print prime numbers from 1 to N.
Count ways to reach the n'th stair
Program to convert a given number to words
Fizz Buzz Implementation
Singular Value Decomposition (SVD)
Check if a number is Palindrome
Find first and last digits of a number | [
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n06 Feb, 2022"
},
{
"code": null,
"e": 24845,
"s": 24716,
"text": "Given an integer N and a tolerance level L, the task is to find the square root of that number using Newton’s Method.Examples: "
},
{
"code": null,
"e": 24934,
"s": 24845,
"text": "Input: N = 16, L = 0.0001 Output: 4 42 = 16Input: N = 327, L = 0.00001 Output: 18.0831 "
},
{
"code": null,
"e": 25030,
"s": 24936,
"text": "Newton’s Method: Let N be any number then the square root of N can be given by the formula: "
},
{
"code": null,
"e": 25115,
"s": 25030,
"text": "root = 0.5 * (X + (N / X)) where X is any guess which can be assumed to be N or 1. "
},
{
"code": null,
"e": 25215,
"s": 25117,
"text": "In the above formula, X is any assumed square root of N and root is the correct square root of N."
},
{
"code": null,
"e": 25285,
"s": 25215,
"text": "Tolerance limit is the maximum difference between X and root allowed."
},
{
"code": null,
"e": 25356,
"s": 25285,
"text": "Approach: The following steps can be followed to compute the answer: "
},
{
"code": null,
"e": 25716,
"s": 25356,
"text": "Assign X to the N itself.Now, start a loop and keep calculating the root which will surely move towards the correct square root of N.Check for the difference between the assumed X and calculated root, if not yet inside tolerance then update root and continue.If the calculated root comes inside the tolerance allowed then break out of the loop.Print the root."
},
{
"code": null,
"e": 25742,
"s": 25716,
"text": "Assign X to the N itself."
},
{
"code": null,
"e": 25851,
"s": 25742,
"text": "Now, start a loop and keep calculating the root which will surely move towards the correct square root of N."
},
{
"code": null,
"e": 25978,
"s": 25851,
"text": "Check for the difference between the assumed X and calculated root, if not yet inside tolerance then update root and continue."
},
{
"code": null,
"e": 26064,
"s": 25978,
"text": "If the calculated root comes inside the tolerance allowed then break out of the loop."
},
{
"code": null,
"e": 26080,
"s": 26064,
"text": "Print the root."
},
{
"code": null,
"e": 26133,
"s": 26080,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26137,
"s": 26133,
"text": "C++"
},
{
"code": null,
"e": 26142,
"s": 26137,
"text": "Java"
},
{
"code": null,
"e": 26150,
"s": 26142,
"text": "Python3"
},
{
"code": null,
"e": 26153,
"s": 26150,
"text": "C#"
},
{
"code": null,
"e": 26164,
"s": 26153,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the square root of// a number using Newtons methoddouble squareRoot(double n, float l){ // Assuming the sqrt of n as n only double x = n; // The closed guess will be stored in the root double root; // To count the number of iterations int count = 0; while (1) { count++; // Calculate more closed x root = 0.5 * (x + (n / x)); // Check for closeness if (abs(root - x) < l) break; // Update root x = root; } return root;} // Driver codeint main(){ double n = 327; float l = 0.00001; cout << squareRoot(n, l); return 0;}",
"e": 26894,
"s": 26164,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the square root of // a number using Newtons method static double squareRoot(double n, double l) { // Assuming the sqrt of n as n only double x = n; // The closed guess will be stored in the root double root; // To count the number of iterations int count = 0; while (true) { count++; // Calculate more closed x root = 0.5 * (x + (n / x)); // Check for closeness if (Math.abs(root - x) < l) break; // Update root x = root; } return root; } // Driver code public static void main (String[] args) { double n = 327; double l = 0.00001; System.out.println(squareRoot(n, l)); }} // This code is contributed by AnkitRai01",
"e": 27841,
"s": 26894,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the square root of# a number using Newtons methoddef squareRoot(n, l) : # Assuming the sqrt of n as n only x = n # To count the number of iterations count = 0 while (1) : count += 1 # Calculate more closed x root = 0.5 * (x + (n / x)) # Check for closeness if (abs(root - x) < l) : break # Update root x = root return root # Driver codeif __name__ == \"__main__\" : n = 327 l = 0.00001 print(squareRoot(n, l)) # This code is contributed by AnkitRai01",
"e": 28448,
"s": 27841,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the square root of // a number using Newtons method static double squareRoot(double n, double l) { // Assuming the sqrt of n as n only double x = n; // The closed guess will be stored in the root double root; // To count the number of iterations int count = 0; while (true) { count++; // Calculate more closed x root = 0.5 * (x + (n / x)); // Check for closeness if (Math.Abs(root - x) < l) break; // Update root x = root; } return root; } // Driver code public static void Main() { double n = 327; double l = 0.00001; Console.WriteLine(squareRoot(n, l)); }} // This code is contributed by AnkitRai01",
"e": 29392,
"s": 28448,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the square root of // a number using Newtons method function squareRoot(n, l) { // Assuming the sqrt of n as n only let x = n; // The closed guess will be stored in the root let root; // To count the number of iterations let count = 0; while (true) { count++; // Calculate more closed x root = 0.5 * (x + (n / x)); // Check for closeness if (Math.abs(root - x) < l) break; // Update root x = root; } return root.toFixed(4); } let n = 327; let l = 0.00001; document.write(squareRoot(n, l)); // This code is contributed by divyesh072019.</script>",
"e": 30264,
"s": 29392,
"text": null
},
{
"code": null,
"e": 30272,
"s": 30264,
"text": "18.0831"
},
{
"code": null,
"e": 30300,
"s": 30274,
"text": "Time Complexity: O(log N)"
},
{
"code": null,
"e": 30322,
"s": 30300,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30330,
"s": 30322,
"text": "ankthon"
},
{
"code": null,
"e": 30350,
"s": 30330,
"text": "himangshushekharjha"
},
{
"code": null,
"e": 30364,
"s": 30350,
"text": "divyesh072019"
},
{
"code": null,
"e": 30380,
"s": 30364,
"text": "subhammahato348"
},
{
"code": null,
"e": 30385,
"s": 30380,
"text": "root"
},
{
"code": null,
"e": 30409,
"s": 30385,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 30422,
"s": 30409,
"text": "Mathematical"
},
{
"code": null,
"e": 30435,
"s": 30422,
"text": "Mathematical"
},
{
"code": null,
"e": 30533,
"s": 30435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30542,
"s": 30533,
"text": "Comments"
},
{
"code": null,
"e": 30555,
"s": 30542,
"text": "Old Comments"
},
{
"code": null,
"e": 30587,
"s": 30555,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 30618,
"s": 30587,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30651,
"s": 30618,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30695,
"s": 30651,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30730,
"s": 30695,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 30773,
"s": 30730,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 30798,
"s": 30773,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30833,
"s": 30798,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 30865,
"s": 30833,
"text": "Check if a number is Palindrome"
}
] |
How to use window.location to redirect to a different URL with JavaScript? | You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection.
It is quite simple to do a page redirect using JavaScript on the client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows −
You can try to run the following code to learn how to use window.location to redirect to another URL. Here, we will redirect to the home page
Live Demo
<html>
<head>
<script>
<!--
function Redirect() {
window.location.assign("https://www.tutorialspoint.com");
}
//-->
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>
<input type = "button" value="Redirect Me" onclick="Redirect();" />
</body>
</html> | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection."
},
{
"code": null,
"e": 1417,
"s": 1231,
"text": "It is quite simple to do a page redirect using JavaScript on the client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows −"
},
{
"code": null,
"e": 1559,
"s": 1417,
"text": "You can try to run the following code to learn how to use window.location to redirect to another URL. Here, we will redirect to the home page"
},
{
"code": null,
"e": 1569,
"s": 1559,
"text": "Live Demo"
},
{
"code": null,
"e": 1959,
"s": 1569,
"text": "<html>\n <head>\n <script>\n <!--\n function Redirect() {\n window.location.assign(\"https://www.tutorialspoint.com\");\n }\n //-->\n </script>\n </head>\n <body>\n <p>Click the following button, you will be redirected to home page.</p>\n <input type = \"button\" value=\"Redirect Me\" onclick=\"Redirect();\" />\n </body>\n</html>"
}
] |
Decimal.Compare() Method in C# | The Decimal.Compare() method in C# is used to compare two specified Decimal values.
Following is the syntax −
public static int Compare (decimal val1, decimal val2);
Above, val1 is the first value to compare, whereas Val is the second value to compare.
The return value is less than zero if val1 is less than val2. Return value is 0, if Val = val2, whereas greater than zero, if val1 is greater than val2.
Let us now see an example to implement the Decimal.Compare() method −
using System;
public class Demo {
public static void Main(){
Decimal val1 = 45.85m;
Decimal val2 = 35.45m;
Console.WriteLine("Decimal 1 = "+val1);
Console.WriteLine("Decimal 2 = "+val2);
Console.WriteLine("Comparison Value = "+Decimal.Compare(val1,val2));
}
}
This will produce the following output −
Decimal 1 = 45.85
Decimal 2 = 35.45
Comparison Value = 1
Let us now see another example to implement the Decimal.Compare() method −
using System;
public class Demo {
public static void Main(){
Decimal val1 = 65.15m;
Decimal val2 = 65.15m;
Console.WriteLine("Decimal 1 = "+val1);
Console.WriteLine("Decimal 2 = "+val2);
Console.WriteLine("Comparison Value = "+Decimal.Compare(val1,val2));
}
}
This will produce the following output −
Decimal 1 = 65.15
Decimal 2 = 65.15
Comparison Value = 0 | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "The Decimal.Compare() method in C# is used to compare two specified Decimal values."
},
{
"code": null,
"e": 1172,
"s": 1146,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1228,
"s": 1172,
"text": "public static int Compare (decimal val1, decimal val2);"
},
{
"code": null,
"e": 1315,
"s": 1228,
"text": "Above, val1 is the first value to compare, whereas Val is the second value to compare."
},
{
"code": null,
"e": 1468,
"s": 1315,
"text": "The return value is less than zero if val1 is less than val2. Return value is 0, if Val = val2, whereas greater than zero, if val1 is greater than val2."
},
{
"code": null,
"e": 1538,
"s": 1468,
"text": "Let us now see an example to implement the Decimal.Compare() method −"
},
{
"code": null,
"e": 1834,
"s": 1538,
"text": "using System;\npublic class Demo {\n public static void Main(){\n Decimal val1 = 45.85m;\n Decimal val2 = 35.45m;\n Console.WriteLine(\"Decimal 1 = \"+val1);\n Console.WriteLine(\"Decimal 2 = \"+val2);\n Console.WriteLine(\"Comparison Value = \"+Decimal.Compare(val1,val2));\n }\n}"
},
{
"code": null,
"e": 1875,
"s": 1834,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1932,
"s": 1875,
"text": "Decimal 1 = 45.85\nDecimal 2 = 35.45\nComparison Value = 1"
},
{
"code": null,
"e": 2007,
"s": 1932,
"text": "Let us now see another example to implement the Decimal.Compare() method −"
},
{
"code": null,
"e": 2303,
"s": 2007,
"text": "using System;\npublic class Demo {\n public static void Main(){\n Decimal val1 = 65.15m;\n Decimal val2 = 65.15m;\n Console.WriteLine(\"Decimal 1 = \"+val1);\n Console.WriteLine(\"Decimal 2 = \"+val2);\n Console.WriteLine(\"Comparison Value = \"+Decimal.Compare(val1,val2));\n }\n}"
},
{
"code": null,
"e": 2344,
"s": 2303,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2401,
"s": 2344,
"text": "Decimal 1 = 65.15\nDecimal 2 = 65.15\nComparison Value = 0"
}
] |
Container for form input and label with Bootstrap | Use the .form-group class in Bootstrap to set a container for form input and label &minus
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<form role = "form">
<div class = "form-group">
<label for = "name">Student Name</label>
<input type = "text" class = "form-control" id = "name" placeholder = "Enter Student Name">
</div>
<div class = "form-group">
<label for = "inputfile">Upload Resume</label>
<input type = "file" id = "inputfile">
<p class = "help-block">Example block-level help text here.</p>
</div>
<button type = "submit" class = "btn btn-primary">Next</button>
</form>
</body>
</html> | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "Use the .form-group class in Bootstrap to set a container for form input and label &minus"
},
{
"code": null,
"e": 1162,
"s": 1152,
"text": "Live Demo"
},
{
"code": null,
"e": 2021,
"s": 1162,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <form role = \"form\">\n <div class = \"form-group\">\n <label for = \"name\">Student Name</label>\n <input type = \"text\" class = \"form-control\" id = \"name\" placeholder = \"Enter Student Name\">\n </div>\n <div class = \"form-group\">\n <label for = \"inputfile\">Upload Resume</label>\n <input type = \"file\" id = \"inputfile\">\n <p class = \"help-block\">Example block-level help text here.</p>\n </div>\n <button type = \"submit\" class = \"btn btn-primary\">Next</button>\n </form>\n </body>\n</html>"
}
] |
How to create a random sample with values 0 and 1 in R? | It is known that the random sample can be created by using sample function in R. If we want to create a random sample with values 0 and 1 only then there are three different ways to pass them inside the sample function −
Creating a vector of 0 and 1
Creating a vector of 0 and 1
Using 0:1
Using 0:1
Using c(1,2) directly inside the function.
Using c(1,2) directly inside the function.
Also, we can set replace argument to TRUE or FALSE based on our requirement.
Live Demo
x1<-sample(0:1,size=50,replace=TRUE)
x1
[1] 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 0 0 1 0 1 1 1 0 0 0 0 0 1 1 1 0 1 0 1 1 0 1 1
[39] 0 0 0 0 0 1 1 1 0 1 1 1
Live Demo
x2<-sample(c(0,1),size=100,replace=TRUE)
x2
[1] 0 1 0 0 1 0 1 0 1 0 1 0 1 1 1 0 0 0 1 1 0 0 1 1 0 1 1 0 1 1 0 0 0 1 0 0 1
[38] 1 1 0 1 1 1 1 0 0 0 0 0 1 1 0 1 0 1 1 0 0 0 0 0 0 1 1 1 1 0 0 1 1 1 0 0 0
[75] 0 0 1 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0
Live Demo
x3<-sample(c(0,1),size=150,replace=TRUE)
x3
[1] 0 1 1 0 1 1 0 0 0 0 1 1 0 0 1 1 0 0 1 0 1 0 0 0 1 1 1 1 0 1 0 1 1 1 1 1 0
[38] 1 1 0 1 1 1 0 0 1 0 0 0 1 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 1 1 0 1 0
[75] 1 0 0 1 0 1 1 0 0 0 0 0 1 1 0 0 1 0 1 1 0 0 1 0 1 1 1 0 0 0 0 0 1 0 1 0 0
[112] 1 0 0 0 1 0 0 1 0 1 0 0 1 1 0 1 1 0 0 0 0 1 0 0 1 1 0 0 0 1 1 1 0 1 0 0 0
[149] 1 1
Live Demo
x4<-sample(c(0,1),size=111,replace=TRUE)
x4
[1] 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 0 1 0 0 1 0 1
[38] 0 0 0 1 0 0 1 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0
[75] 0 1 1 1 0 1 1 1 0 0 0 1 1 1 1 1 0 1 0 0 1 0 1 0 1 0 1 1 1 0 0 0 1 1 0 1 1
Live Demo
x5<-sample(c(0,1),size=199,replace=TRUE)
x5
[1] 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1 1 0 0 1 0 1 1 0 0 1 0 0 0 1 1 0 1 1 1 1 0 1
[38] 1 1 1 1 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0 1 1 0 1 1
[75] 0 0 1 0 0 1 1 0 1 0 0 1 1 0 1 0 0 0 0 1 0 1 1 1 1 0 1 1 1 0 0 0 0 1 0 1 1
[112] 1 0 1 1 1 1 1 1 0 1 0 1 0 1 0 0 0 1 1 1 1 1 0 1 1 0 1 1 0 1 0 0 1 1 0 0 0
[149] 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1
[186] 1 1 1 1 0 0 0 1 1 1 0 0 0 1
Live Demo
x6<-sample(c(0,1),size=5,replace=TRUE)
x6
[1] 0 1 1 1 0
Live Demo
x7<-sample(c(0,1),size=49,replace=TRUE)
x7
[1] 0 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 1 0 0 1 0 0 1
[39] 1 1 0 0 0 0 1 1 0 1 1
Live Demo
x8<-sample(c(0,1),size=200,replace=TRUE)
x8
[1] 0 1 0 0 1 0 0 1 0 0 0 0 0 1 1 0 1 0 1 1 0 1 0 1 1 0 0 1 1 0 0 1 0 1 1 0 1
[38] 0 0 0 0 1 1 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 0 0 0 1 1 0 1 1 0 1 0 0 1 1 1 0
[75] 0 1 1 1 1 1 0 0 0 1 1 1 0 1 1 1 1 1 1 0 1 1 0 0 0 1 0 1 0 0 1 0 1 1 0 1 0
[112] 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1 1 0 0 1 1 1 0 1 0 0 0
[149] 0 0 0 0 1 1 1 0 1 0 1 1 1 0 1 0 1 1 1 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1
[186] 1 0 1 0 0 1 1 0 1 1 0 1 1 1 0
Live Demo
x9<-sample(c(0,1),size=175,replace=TRUE)
x9
[1] 1 1 0 1 1 1 1 1 1 1 0 0 0 1 0 1 0 0 0 0 1 0 0 1 0 1 0 1 0 0 1 0 1 1 0 1 1
[38] 0 0 0 1 1 0 1 0 0 1 0 1 0 0 0 0 1 1 1 0 0 0 0 0 1 0 0 1 1 1 0 1 0 1 0 0 1
[75] 1 1 1 1 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 1 1 0 0 1 1 0 1 1
[112] 0 1 0 0 1 1 1 0 1 1 0 0 1 1 1 1 0 0 0 1 1 1 1 1 0 0 1 0 0 1 0 0 0 1 0 0 1
[149] 0 0 0 1 1 1 0 1 1 0 0 1 1 0 1 0 0 1 0 0 1 0 1 0 0 0 0
Live Demo
x10<-sample(c(0,1),size=101,replace=TRUE)
x10
[1] 1 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1
[38] 1 0 1 0 1 0 1 0 1 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 1 1 0 1 0 1 1 1 1 0 1 0 1
[75] 0 0 1 0 1 1 1 1 0 1 1 0 0 1 0 1 0 1 0 1 1 0 0 1 1 0 1 | [
{
"code": null,
"e": 1283,
"s": 1062,
"text": "It is known that the random sample can be created by using sample function in R. If we want to create a random sample with values 0 and 1 only then there are three different ways to pass them inside the sample function −"
},
{
"code": null,
"e": 1312,
"s": 1283,
"text": "Creating a vector of 0 and 1"
},
{
"code": null,
"e": 1341,
"s": 1312,
"text": "Creating a vector of 0 and 1"
},
{
"code": null,
"e": 1351,
"s": 1341,
"text": "Using 0:1"
},
{
"code": null,
"e": 1361,
"s": 1351,
"text": "Using 0:1"
},
{
"code": null,
"e": 1404,
"s": 1361,
"text": "Using c(1,2) directly inside the function."
},
{
"code": null,
"e": 1447,
"s": 1404,
"text": "Using c(1,2) directly inside the function."
},
{
"code": null,
"e": 1524,
"s": 1447,
"text": "Also, we can set replace argument to TRUE or FALSE based on our requirement."
},
{
"code": null,
"e": 1535,
"s": 1524,
"text": " Live Demo"
},
{
"code": null,
"e": 1575,
"s": 1535,
"text": "x1<-sample(0:1,size=50,replace=TRUE)\nx1"
},
{
"code": null,
"e": 1684,
"s": 1575,
"text": "[1] 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 0 0 1 0 1 1 1 0 0 0 0 0 1 1 1 0 1 0 1 1 0 1 1\n[39] 0 0 0 0 0 1 1 1 0 1 1 1"
},
{
"code": null,
"e": 1695,
"s": 1684,
"text": " Live Demo"
},
{
"code": null,
"e": 1739,
"s": 1695,
"text": "x2<-sample(c(0,1),size=100,replace=TRUE)\nx2"
},
{
"code": null,
"e": 1953,
"s": 1739,
"text": "[1] 0 1 0 0 1 0 1 0 1 0 1 0 1 1 1 0 0 0 1 1 0 0 1 1 0 1 1 0 1 1 0 0 0 1 0 0 1\n[38] 1 1 0 1 1 1 1 0 0 0 0 0 1 1 0 1 0 1 1 0 0 0 0 0 0 1 1 1 1 0 0 1 1 1 0 0 0\n[75] 0 0 1 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0"
},
{
"code": null,
"e": 1964,
"s": 1953,
"text": " Live Demo"
},
{
"code": null,
"e": 2008,
"s": 1964,
"text": "x3<-sample(c(0,1),size=150,replace=TRUE)\nx3"
},
{
"code": null,
"e": 2334,
"s": 2008,
"text": "[1] 0 1 1 0 1 1 0 0 0 0 1 1 0 0 1 1 0 0 1 0 1 0 0 0 1 1 1 1 0 1 0 1 1 1 1 1 0\n[38] 1 1 0 1 1 1 0 0 1 0 0 0 1 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 1 1 0 1 0\n[75] 1 0 0 1 0 1 1 0 0 0 0 0 1 1 0 0 1 0 1 1 0 0 1 0 1 1 1 0 0 0 0 0 1 0 1 0 0\n[112] 1 0 0 0 1 0 0 1 0 1 0 0 1 1 0 1 1 0 0 0 0 1 0 0 1 1 0 0 0 1 1 1 0 1 0 0 0\n[149] 1 1"
},
{
"code": null,
"e": 2345,
"s": 2334,
"text": " Live Demo"
},
{
"code": null,
"e": 2389,
"s": 2345,
"text": "x4<-sample(c(0,1),size=111,replace=TRUE)\nx4"
},
{
"code": null,
"e": 2625,
"s": 2389,
"text": "[1] 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 0 1 0 0 1 0 1\n[38] 0 0 0 1 0 0 1 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0\n[75] 0 1 1 1 0 1 1 1 0 0 0 1 1 1 1 1 0 1 0 0 1 0 1 0 1 0 1 1 1 0 0 0 1 1 0 1 1"
},
{
"code": null,
"e": 2636,
"s": 2625,
"text": " Live Demo"
},
{
"code": null,
"e": 2680,
"s": 2636,
"text": "x5<-sample(c(0,1),size=199,replace=TRUE)\nx5"
},
{
"code": null,
"e": 3110,
"s": 2680,
"text": "[1] 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1 1 0 0 1 0 1 1 0 0 1 0 0 0 1 1 0 1 1 1 1 0 1\n[38] 1 1 1 1 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0 1 1 0 1 1\n[75] 0 0 1 0 0 1 1 0 1 0 0 1 1 0 1 0 0 0 0 1 0 1 1 1 1 0 1 1 1 0 0 0 0 1 0 1 1\n[112] 1 0 1 1 1 1 1 1 0 1 0 1 0 1 0 0 0 1 1 1 1 1 0 1 1 0 1 1 0 1 0 0 1 1 0 0 0\n[149] 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1\n[186] 1 1 1 1 0 0 0 1 1 1 0 0 0 1"
},
{
"code": null,
"e": 3121,
"s": 3110,
"text": " Live Demo"
},
{
"code": null,
"e": 3163,
"s": 3121,
"text": "x6<-sample(c(0,1),size=5,replace=TRUE)\nx6"
},
{
"code": null,
"e": 3178,
"s": 3163,
"text": "[1] 0 1 1 1 0\n"
},
{
"code": null,
"e": 3189,
"s": 3178,
"text": " Live Demo"
},
{
"code": null,
"e": 3232,
"s": 3189,
"text": "x7<-sample(c(0,1),size=49,replace=TRUE)\nx7"
},
{
"code": null,
"e": 3339,
"s": 3232,
"text": "[1] 0 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 1 0 0 1 0 0 1\n[39] 1 1 0 0 0 0 1 1 0 1 1"
},
{
"code": null,
"e": 3350,
"s": 3339,
"text": " Live Demo"
},
{
"code": null,
"e": 3394,
"s": 3350,
"text": "x8<-sample(c(0,1),size=200,replace=TRUE)\nx8"
},
{
"code": null,
"e": 3826,
"s": 3394,
"text": "[1] 0 1 0 0 1 0 0 1 0 0 0 0 0 1 1 0 1 0 1 1 0 1 0 1 1 0 0 1 1 0 0 1 0 1 1 0 1\n[38] 0 0 0 0 1 1 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 0 0 0 1 1 0 1 1 0 1 0 0 1 1 1 0\n[75] 0 1 1 1 1 1 0 0 0 1 1 1 0 1 1 1 1 1 1 0 1 1 0 0 0 1 0 1 0 0 1 0 1 1 0 1 0\n[112] 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1 1 0 0 1 1 1 0 1 0 0 0\n[149] 0 0 0 0 1 1 1 0 1 0 1 1 1 0 1 0 1 1 1 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 1 1\n[186] 1 0 1 0 0 1 1 0 1 1 0 1 1 1 0"
},
{
"code": null,
"e": 3837,
"s": 3826,
"text": " Live Demo"
},
{
"code": null,
"e": 3881,
"s": 3837,
"text": "x9<-sample(c(0,1),size=175,replace=TRUE)\nx9"
},
{
"code": null,
"e": 4257,
"s": 3881,
"text": "[1] 1 1 0 1 1 1 1 1 1 1 0 0 0 1 0 1 0 0 0 0 1 0 0 1 0 1 0 1 0 0 1 0 1 1 0 1 1\n[38] 0 0 0 1 1 0 1 0 0 1 0 1 0 0 0 0 1 1 1 0 0 0 0 0 1 0 0 1 1 1 0 1 0 1 0 0 1\n[75] 1 1 1 1 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 1 1 0 0 1 1 0 1 1\n[112] 0 1 0 0 1 1 1 0 1 1 0 0 1 1 1 1 0 0 0 1 1 1 1 1 0 0 1 0 0 1 0 0 0 1 0 0 1\n[149] 0 0 0 1 1 1 0 1 1 0 0 1 1 0 1 0 0 1 0 0 1 0 1 0 0 0 0"
},
{
"code": null,
"e": 4268,
"s": 4257,
"text": " Live Demo"
},
{
"code": null,
"e": 4314,
"s": 4268,
"text": "x10<-sample(c(0,1),size=101,replace=TRUE)\nx10"
},
{
"code": null,
"e": 4530,
"s": 4314,
"text": "[1] 1 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1\n[38] 1 0 1 0 1 0 1 0 1 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 1 1 0 1 0 1 1 1 1 0 1 0 1\n[75] 0 0 1 0 1 1 1 1 0 1 1 0 0 1 0 1 0 1 0 1 1 0 0 1 1 0 1"
}
] |
How to create Microsoft Word paragraphs and insert Images in Python? | Being a Data Engineering specialist, I often receive test results from testers in Microsoft word. Sigh! they put so much information into word document right from capturing screen shots and very big paragraphs.
Other day, I was asked by testing team to help them with a program to insert the tool generated Text and images (taken by automatic screen shots. Not covered in this article).
MS Word document unlike others doesn't have the concept of a page, as it works in paragraphs unfortunately.So we need to use breaks and sections to properly divide a document.
1.
Go ahead and install python-docx.
import docx
# create a new couments
WordDocx = docx.Document()
# My paragraph.
Paragraph = WordDocx.add_paragraph('1. Hello World, Some Sample Text Here...')
run = Paragraph.add_run()
# paragraph with a line break
run.add_break(docx.text.run.WD_BREAK.LINE)
# Add more
Paragraph.add_run('2. I have just written my 2nd line and I can write more..')
# Finally savind the document.
WordDocx.save('My_Amazing_WordDoc.docx')
2.
Now Lets check the content if everything is OK or not. Well you are programmer, so we will do it programatically.
doc = docx.Document('My_Amazing_WordDoc.docx')
print(f"output \n *** Document has {len(doc.paragraphs)} - paragraphs")
for paragraph_number, paragraph in enumerate(doc.paragraphs):
if paragraph.text:
print(f"\n {paragraph.text}")
*** Document has 1 - paragraphs
1. Hello World, Some Sample Text Here...
2. I have just written my 2nd line and I can write more..
3.
Now we will add a image to our document. So, first we need to look for an image. I have downloaded an image from unsplash.com which doen't have any copyright issues. Please make sure what ever you download from internet do with utmost care.
Unsplash had copyright free images we can use for any purpose, appreciate their work.
Ok I have downloaded an image and named it as Tree.img which will be added to our document.
import requests
from docx.shared import Cm
# Download the image from Github
response = requests.get("https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg")
image = open("Tree.jpg", "wb")
image.write(response.content)
image.close()
# add the image
image_to_add = doc.add_picture("Tree.jpg")
print(f"output \n *** MY Image has width = {image_to_add.width} and Height as - {image_to_add.height}")
*** MY Image has width = 43891200 and Height as - 65836800
4.
We need to scale the image properly as my Image is too big. we can use width and height parameter.
image_to_add.width = Cm(10)
image_to_add.height = Cm(10)
print(f" *** My New dimensions Image has width = {image_to_add.width} and Height as - {image_to_add.height}")
# finally save the document
doc.save('report.docx')
*** My New dimensions Image has width = 3600000 and Height as - 3600000
5.
Open the document and you would see the image and the text added.
6.
Putting everything together.
import requests
from docx.shared import Cm
# Download the image from Github
response = requests.get("https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg")
image = open("Tree.jpg", "wb")
image.write(response.content)
image.close()
# add the image
image_to_add = doc.add_picture("Tree.jpg")
print(f"output \n *** MY Image has width = {image_to_add.width} and Height as - {image_to_add.height}")
image_to_add.width = Cm(10)
image_to_add.height = Cm(10)
print(f" *** My New dimensions Image has width = {image_to_add.width} and Height as - {image_to_add.height}")
# finally save the document
doc.save('report.docx')
*** MY Image has width = 43891200 and Height as - 65836800
*** My New dimensions Image has width = 3600000 and Height as - 3600000 | [
{
"code": null,
"e": 1273,
"s": 1062,
"text": "Being a Data Engineering specialist, I often receive test results from testers in Microsoft word. Sigh! they put so much information into word document right from capturing screen shots and very big paragraphs."
},
{
"code": null,
"e": 1449,
"s": 1273,
"text": "Other day, I was asked by testing team to help them with a program to insert the tool generated Text and images (taken by automatic screen shots. Not covered in this article)."
},
{
"code": null,
"e": 1625,
"s": 1449,
"text": "MS Word document unlike others doesn't have the concept of a page, as it works in paragraphs unfortunately.So we need to use breaks and sections to properly divide a document."
},
{
"code": null,
"e": 1662,
"s": 1625,
"text": "1.\nGo ahead and install python-docx."
},
{
"code": null,
"e": 2086,
"s": 1662,
"text": "import docx\n\n# create a new couments\nWordDocx = docx.Document()\n\n# My paragraph.\nParagraph = WordDocx.add_paragraph('1. Hello World, Some Sample Text Here...')\nrun = Paragraph.add_run()\n\n# paragraph with a line break\nrun.add_break(docx.text.run.WD_BREAK.LINE)\n\n# Add more\nParagraph.add_run('2. I have just written my 2nd line and I can write more..')\n\n# Finally savind the document.\nWordDocx.save('My_Amazing_WordDoc.docx')"
},
{
"code": null,
"e": 2203,
"s": 2086,
"text": "2.\nNow Lets check the content if everything is OK or not. Well you are programmer, so we will do it programatically."
},
{
"code": null,
"e": 2433,
"s": 2203,
"text": "doc = docx.Document('My_Amazing_WordDoc.docx')\nprint(f\"output \\n *** Document has {len(doc.paragraphs)} - paragraphs\")\nfor paragraph_number, paragraph in enumerate(doc.paragraphs):\nif paragraph.text:\nprint(f\"\\n {paragraph.text}\")"
},
{
"code": null,
"e": 2565,
"s": 2433,
"text": "*** Document has 1 - paragraphs\n\n1. Hello World, Some Sample Text Here...\n2. I have just written my 2nd line and I can write more.."
},
{
"code": null,
"e": 2809,
"s": 2565,
"text": "3.\nNow we will add a image to our document. So, first we need to look for an image. I have downloaded an image from unsplash.com which doen't have any copyright issues. Please make sure what ever you download from internet do with utmost care."
},
{
"code": null,
"e": 2895,
"s": 2809,
"text": "Unsplash had copyright free images we can use for any purpose, appreciate their work."
},
{
"code": null,
"e": 2987,
"s": 2895,
"text": "Ok I have downloaded an image and named it as Tree.img which will be added to our document."
},
{
"code": null,
"e": 3401,
"s": 2987,
"text": "import requests\nfrom docx.shared import Cm\n\n# Download the image from Github\nresponse = requests.get(\"https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg\")\nimage = open(\"Tree.jpg\", \"wb\")\nimage.write(response.content)\nimage.close()\n\n# add the image\nimage_to_add = doc.add_picture(\"Tree.jpg\")\nprint(f\"output \\n *** MY Image has width = {image_to_add.width} and Height as - {image_to_add.height}\")"
},
{
"code": null,
"e": 3460,
"s": 3401,
"text": "*** MY Image has width = 43891200 and Height as - 65836800"
},
{
"code": null,
"e": 3562,
"s": 3460,
"text": "4.\nWe need to scale the image properly as my Image is too big. we can use width and height parameter."
},
{
"code": null,
"e": 3782,
"s": 3562,
"text": "image_to_add.width = Cm(10)\nimage_to_add.height = Cm(10)\nprint(f\" *** My New dimensions Image has width = {image_to_add.width} and Height as - {image_to_add.height}\")\n\n# finally save the document\ndoc.save('report.docx')"
},
{
"code": null,
"e": 3854,
"s": 3782,
"text": "*** My New dimensions Image has width = 3600000 and Height as - 3600000"
},
{
"code": null,
"e": 3923,
"s": 3854,
"text": "5.\nOpen the document and you would see the image and the text added."
},
{
"code": null,
"e": 3955,
"s": 3923,
"text": "6.\nPutting everything together."
},
{
"code": null,
"e": 4590,
"s": 3955,
"text": "import requests\nfrom docx.shared import Cm\n\n# Download the image from Github\nresponse = requests.get(\"https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg\")\nimage = open(\"Tree.jpg\", \"wb\")\nimage.write(response.content)\nimage.close()\n\n# add the image\nimage_to_add = doc.add_picture(\"Tree.jpg\")\nprint(f\"output \\n *** MY Image has width = {image_to_add.width} and Height as - {image_to_add.height}\")\n\nimage_to_add.width = Cm(10)\nimage_to_add.height = Cm(10)\nprint(f\" *** My New dimensions Image has width = {image_to_add.width} and Height as - {image_to_add.height}\")\n\n# finally save the document\ndoc.save('report.docx')"
},
{
"code": null,
"e": 4721,
"s": 4590,
"text": "*** MY Image has width = 43891200 and Height as - 65836800\n*** My New dimensions Image has width = 3600000 and Height as - 3600000"
}
] |
Draw Spiralling Circles Using Turtle Graphics in Python - GeeksforGeeks | 01 Oct, 2020
Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle, methods defined in the turtle module, and by using some logical loops. To draw something on the screen(cardboard) just move the turtle(pen). To move turtle(pen) there are some functions i.e forward(), backward(), etc.
Approach:
Import and create a turtle instance.Set the graphical visuals as per your needs.Run a for loop for some integer values i.For each value of i, draw a circle with a radius as i.Now rotate the turtle by a fixed degree.
Import and create a turtle instance.
Set the graphical visuals as per your needs.
Run a for loop for some integer values i.
For each value of i, draw a circle with a radius as i.
Now rotate the turtle by a fixed degree.
Below is the implementation of the above approach
Python3
# importing turtleimport turtle # initialise the turtle instanceanimation = turtle.Turtle() #creating animation# changes speed of turtleanimation.speed(0) # hiding turtle animation.hideturtle() # changing background coloranimation.getscreen().bgcolor("black") # color of the animationanimation.color("red") for i in range(100): # drawing circle using circle function # by passing radius i animation.circle(i) # changing turtle face by 5 degree from it's # previous position after drawing a circle animation._rotate(5)
Output:
Python-turtle
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 Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 24596,
"s": 24292,
"text": "Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle, methods defined in the turtle module, and by using some logical loops. To draw something on the screen(cardboard) just move the turtle(pen). To move turtle(pen) there are some functions i.e forward(), backward(), etc."
},
{
"code": null,
"e": 24606,
"s": 24596,
"text": "Approach:"
},
{
"code": null,
"e": 24823,
"s": 24606,
"text": "Import and create a turtle instance.Set the graphical visuals as per your needs.Run a for loop for some integer values i.For each value of i, draw a circle with a radius as i.Now rotate the turtle by a fixed degree. "
},
{
"code": null,
"e": 24860,
"s": 24823,
"text": "Import and create a turtle instance."
},
{
"code": null,
"e": 24905,
"s": 24860,
"text": "Set the graphical visuals as per your needs."
},
{
"code": null,
"e": 24947,
"s": 24905,
"text": "Run a for loop for some integer values i."
},
{
"code": null,
"e": 25002,
"s": 24947,
"text": "For each value of i, draw a circle with a radius as i."
},
{
"code": null,
"e": 25044,
"s": 25002,
"text": "Now rotate the turtle by a fixed degree. "
},
{
"code": null,
"e": 25094,
"s": 25044,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 25102,
"s": 25094,
"text": "Python3"
},
{
"code": "# importing turtleimport turtle # initialise the turtle instanceanimation = turtle.Turtle() #creating animation# changes speed of turtleanimation.speed(0) # hiding turtle animation.hideturtle() # changing background coloranimation.getscreen().bgcolor(\"black\") # color of the animationanimation.color(\"red\") for i in range(100): # drawing circle using circle function # by passing radius i animation.circle(i) # changing turtle face by 5 degree from it's # previous position after drawing a circle animation._rotate(5)",
"e": 25653,
"s": 25102,
"text": null
},
{
"code": null,
"e": 25662,
"s": 25653,
"text": "Output: "
},
{
"code": null,
"e": 25676,
"s": 25662,
"text": "Python-turtle"
},
{
"code": null,
"e": 25683,
"s": 25676,
"text": "Python"
},
{
"code": null,
"e": 25781,
"s": 25683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25813,
"s": 25781,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25855,
"s": 25813,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25911,
"s": 25855,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25953,
"s": 25911,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25975,
"s": 25953,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26006,
"s": 25975,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26061,
"s": 26006,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26100,
"s": 26061,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26129,
"s": 26100,
"text": "Create a directory in Python"
}
] |
Learn Word2Vec by implementing it in tensorflow | by aneesh joshi | Towards Data Science | Hi!
I feel that the best way to understand an algorithm is to implement it. So, in this article I will be teaching you Word Embeddings by implementing it in Tensor Flow.
The idea behind this article is to avoid all the introductions and the usual chatter associated with word embeddings/word2vec and jump straight into the meat of things. So, much of the king-man-woman-queen examples will be skipped.
There are many techniques to get word embeddings, we will discuss one technique which has gained a lot of fame, the one and only, word2vec. Contrary to popular belief, word2vec is not a deep network, it only has 3 layers!
Note : word2vec has a lot of technical details which I will skip over to make the understanding a lot easier.
The idea behind word2vec is that:
Take a 3 layer neural network. (1 input layer + 1 hidden layer + 1 output layer)Feed it a word and train it to predict its neighbouring word.Remove the last (output layer) and keep the input and hidden layer.Now, input a word from within the vocabulary. The output given at the hidden layer is the ‘word embedding’ of the input word.
Take a 3 layer neural network. (1 input layer + 1 hidden layer + 1 output layer)
Feed it a word and train it to predict its neighbouring word.
Remove the last (output layer) and keep the input and hidden layer.
Now, input a word from within the vocabulary. The output given at the hidden layer is the ‘word embedding’ of the input word.
That’s it! Just doing this simple task enables our network to learn interesting representations of words.
Let’s start implementing this to flesh out this understanding.
(the full code is available here . I suggest you understand what’s going on from this article and then use the code from there.)
This is the raw text on which we will be working on:
(I have intentionally spaced out the periods and avoided them in the end to simplify. Once you understand, feel free to use a tokenizer)
import numpy as npimport tensorflow as tfcorpus_raw = 'He is the king . The king is royal . She is the royal queen '# convert to lower casecorpus_raw = corpus_raw.lower()
We need to convert this to an input output pair such that if we input a word, it should it predict that the neighbouring words : the n words before and after it, where n is the parameter window_size Here’s a handy example from this amazing post on word2vec by Chris McCormick.
Note: If the word is at the beginning or ending of sentence, the window ignores the outer words.
Before doing this, we will create a dictionary which translates words to integers and integers to words. This will come in handy later.
words = []for word in corpus_raw.split(): if word != '.': # because we don't want to treat . as a word words.append(word)words = set(words) # so that all duplicate words are removedword2int = {}int2word = {}vocab_size = len(words) # gives the total number of unique wordsfor i,word in enumerate(words): word2int[word] = i int2word[i] = word
What these dictionaries allow us to do is :
print(word2int['queen'])-> 42 (say)print(int2word[42])-> 'queen'
Now, we want a list of our sentences as a list of words:
# raw sentences is a list of sentences.raw_sentences = corpus_raw.split('.')sentences = []for sentence in raw_sentences: sentences.append(sentence.split())
This will give us a list of sentences where each sentence is a list of words.
print(sentences)-> [['he', 'is', 'the', 'king'], ['the', 'king', 'is', 'royal'], ['she', 'is', 'the', 'royal', 'queen']]
Now, we will generate our training data:
(This might get difficult to read within medium. refer to the code link)
data = []WINDOW_SIZE = 2for sentence in sentences: for word_index, word in enumerate(sentence): for nb_word in sentence[max(word_index - WINDOW_SIZE, 0) : min(word_index + WINDOW_SIZE, len(sentence)) + 1] : if nb_word != word: data.append([word, nb_word])
This basically gives a list of word, word pairs. (we are considering a window size of 2)
print(data)[['he', 'is'], ['he', 'the'], ['is', 'he'], ['is', 'the'], ['is', 'king'], ['the', 'he'], ['the', 'is'], ['the', 'king'],...]
We have our training data. But it needs to be represented in a way a computer can understand i.e., with numbers. That’s where our word2int dict comes handy.
Let’s go one step further and convert these numbers into one hot vectors.
i.e., say we have a vocabulary of 3 words : pen, pineapple, applewhere word2int['pen'] -> 0 -> [1 0 0]word2int['pineapple'] -> 1 -> [0 1 0]word2int['apple'] -> 2 -> [0 0 1]
Why one hot vectors? : told later
# function to convert numbers to one hot vectorsdef to_one_hot(data_point_index, vocab_size): temp = np.zeros(vocab_size) temp[data_point_index] = 1 return tempx_train = [] # input wordy_train = [] # output wordfor data_word in data: x_train.append(to_one_hot(word2int[ data_word[0] ], vocab_size)) y_train.append(to_one_hot(word2int[ data_word[1] ], vocab_size))# convert them to numpy arraysx_train = np.asarray(x_train)y_train = np.asarray(y_train)
So now we have x_train and y_train:
print(x_train)->[[ 0. 0. 0. 0. 0. 0. 1.] [ 0. 0. 0. 0. 0. 0. 1.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 0. 0. 1. 0. 0. 0. 0.] [ 0. 0. 1. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 1. 0. 0. 0. 0. 0. 0.] [ 1. 0. 0. 0. 0. 0. 0.]]
Both have the shape:
print(x_train.shape, y_train.shape)->(34, 7) (34, 7)# meaning 34 training points, where each point has 7 dimensions
# making placeholders for x_train and y_trainx = tf.placeholder(tf.float32, shape=(None, vocab_size))y_label = tf.placeholder(tf.float32, shape=(None, vocab_size))
As can be seen in the above diagram, we take our training data and convert into the embedded representation.
EMBEDDING_DIM = 5 # you can choose your own numberW1 = tf.Variable(tf.random_normal([vocab_size, EMBEDDING_DIM]))b1 = tf.Variable(tf.random_normal([EMBEDDING_DIM])) #biashidden_representation = tf.add(tf.matmul(x,W1), b1)
Next, we take what we have in the embedded dimension and make a prediction about the neighbour. To make the prediction we use softmax.
W2 = tf.Variable(tf.random_normal([EMBEDDING_DIM, vocab_size]))b2 = tf.Variable(tf.random_normal([vocab_size]))prediction = tf.nn.softmax(tf.add( tf.matmul(hidden_representation, W2), b2))
So to summarise:
input_one_hot ---> embedded repr. ---> predicted_neighbour_probpredicted_prob will be compared against a one hot vector to correct it.
Now, all that’s left is to train it:
sess = tf.Session()init = tf.global_variables_initializer()sess.run(init) #make sure you do this!# define the loss function:cross_entropy_loss = tf.reduce_mean(-tf.reduce_sum(y_label * tf.log(prediction), reduction_indices=[1]))# define the training step:train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy_loss)n_iters = 10000# train for n_iter iterationsfor _ in range(n_iters): sess.run(train_step, feed_dict={x: x_train, y_label: y_train}) print('loss is : ', sess.run(cross_entropy_loss, feed_dict={x: x_train, y_label: y_train}))
On training, you will get the display of loss:
loss is : 2.73213loss is : 2.30519loss is : 2.11106loss is : 1.9916loss is : 1.90923loss is : 1.84837loss is : 1.80133loss is : 1.76381loss is : 1.73312loss is : 1.70745loss is : 1.68556loss is : 1.66654loss is : 1.64975loss is : 1.63472loss is : 1.62112loss is : 1.6087loss is : 1.59725loss is : 1.58664loss is : 1.57676loss is : 1.56751loss is : 1.55882loss is : 1.55064loss is : 1.54291loss is : 1.53559loss is : 1.52865loss is : 1.52206loss is : 1.51578loss is : 1.50979loss is : 1.50408loss is : 1.49861...
It eventually stabilises on a constant loss. Even though we can’t get high accuracy, we don’t care. All we are interested in is W1 and b1, i.e., the hidden representations.
Let’s have a look at them:
print(sess.run(W1))print('----------')print(sess.run(b1))print('----------')->[[-0.85421133 1.70487809 0.481848 -0.40843448 -0.02236851] [-0.47163373 0.34260952 -2.06743765 -1.43854153 -0.14699034] [-1.06858993 -1.10739779 0.52600187 0.24079895 -0.46390489] [ 0.84426647 0.16476244 -0.72731972 -0.31994426 -0.33553854] [ 0.21508843 -1.21030915 -0.13006891 -0.24056002 -0.30445012] [ 0.17842589 2.08979321 -0.34172744 -1.8842833 -1.14538431] [ 1.61166084 -1.17404735 -0.26805425 0.74437028 -0.81183684]]----------[ 0.57727528 -0.83760375 0.19156453 -0.42394346 1.45631313]----------
When we multiply the one hot vectors with W1 , we basically get access to the row of the of W1 which is in fact the embedded representation of the word represented by the input one hot vector. So W1is essentially acting as a look up table.
In our case we have also included a bias term b1 so you have to add it.
vectors = sess.run(W1 + b1)# if you work it out, you will see that it has the same effect as running the node hidden representationprint(vectors)->[[-0.74829113 -0.48964909 0.54267412 2.34831429 -2.03110814] [-0.92472583 -1.50792813 -1.61014366 -0.88273793 -2.12359881] [-0.69424796 -1.67628145 3.07313657 -1.14802659 -1.2207377 ] [-1.7077738 -0.60641652 2.25586247 1.34536338 -0.83848488] [-0.10080346 -0.90931684 2.8825531 -0.58769202 -1.19922316] [ 1.49428082 -2.55578995 2.01545811 0.31536022 1.52662396] [-1.02735448 0.72176981 -0.03772151 -0.60208392 1.53156447]]
If we want the representation for ‘queen’, all we have to do is:
print(vectors[ word2int['queen'] ])# say here word2int['queen'] is 2-> [-0.69424796 -1.67628145 3.07313657 -1.14802659 -1.2207377 ]
Here’s a quick function to find the closest vector to a given vector. Beware, it’s a dirty implementation.
def euclidean_dist(vec1, vec2): return np.sqrt(np.sum((vec1-vec2)**2))def find_closest(word_index, vectors): min_dist = 10000 # to act like positive infinity min_index = -1 query_vector = vectors[word_index] for index, vector in enumerate(vectors): if euclidean_dist(vector, query_vector) < min_dist and not np.array_equal(vector, query_vector): min_dist = euclidean_dist(vector, query_vector) min_index = index return min_index
We will now query these vectors with ‘king’, ‘queen’ and ‘royal’
print(int2word[find_closest(word2int['king'], vectors)])print(int2word[find_closest(word2int['queen'], vectors)])print(int2word[find_closest(word2int['royal'], vectors)])->queenkinghe
Interesting, our embedding learnt that
king is closest to queenqueen is closest to kingroyal is closest to he
The third one is due to our corpus (It’s still pretty good). A bigger corpus will lead to better results. (Note: due to the random initialisation of the weights, you might get different results. Run it a few times if required)
Let’s plot them vectors!
First let’s reduce the dimensions from 5 to 2 with our favourite dimensionality reduction technique : tSNE (teesnee!)
from sklearn.manifold import TSNEmodel = TSNE(n_components=2, random_state=0)np.set_printoptions(suppress=True)vectors = model.fit_transform(vectors)
Then, we need to normalize the results so that we can view them more comfortably in matplotlib
from sklearn import preprocessingnormalizer = preprocessing.Normalizer()vectors = normalizer.fit_transform(vectors, 'l2')
Finally, we will plot the 2D normalized vectors
import matplotlib.pyplot as pltfig, ax = plt.subplots()for word in words: print(word, vectors[word2int[word]][1]) ax.annotate(word, (vectors[word2int[word]][0],vectors[word2int[word]][1] ))plt.show()
Wow! she is close to queen and king is equally distanced from royal and queen We need a bigger corpus to see some of the more complicated relations.
Note: After publishing this, I realized that this example isn’t correct because to get meaningful convergence of vectors, we need a really large corpus. The small size of the data makes it vulnerable to sudden “jerks”. However, I shall keep this writing intact for pedagogical purposes. For an efficient implementation of word2vec try gensim with some corpus like text8.
We have given the neural network the task of predicting neighbours. But we haven’t specified how the network should predict it. So, the neural network figures out an hidden representation of the words, to aid it in the task of predicting neighbouring words. Predicting neighbouring words is not an interesting task in itself. We care about this hidden representation.
To form these representations, the network is using contexts/neighbours. In our corpus, king and royal appear as neighbours, and royal and queen appear as neighbours.
Well, other task also manage to form a good representation. Predicting whether the word is a valid n-gram as shown here can also lead to good vectors!
We tried to predict a neighbouring words given a word. This is known as the skip gram model. We could have used neighbouring words of a middle word as inputs and asked the network to predict the middle word. This is known as the Continuous Bag of Words Model.
This by no means is a complete understanding of word2vec. Part of w2v’s beauty is in its 2 modifications to what I’ve just talked about. These are:
Negative Sampling
Hierarchical Softmax
Negative Sampling: it suggests that instead of backpropagating all the 0s in the correct output vector (for a vocab size of 10mill there are 10mill minus 1 zeros) we just backpropagate a few of them (say 14)
Hierarchical Softmax: Calculating the softmax for a vocab of 10mill is very time and computation intensive. Hierarchical Softmax suggests a faster way of computing it using Huffman trees
In the interest of keeping the post simple, I have avoided delving much into it. I definitely recommend reading more into it.
Word Vectors are super cool
Don’t use this tensorflow code for actual use. It was just to understand. Use a library like gensim
I hope that helped somebody understand these beauties better. If it did, let me know!
If I’ve made mistakes, please let me know.
I would love to connect with you over twitter , linkedin or/and email. | [
{
"code": null,
"e": 50,
"s": 46,
"text": "Hi!"
},
{
"code": null,
"e": 216,
"s": 50,
"text": "I feel that the best way to understand an algorithm is to implement it. So, in this article I will be teaching you Word Embeddings by implementing it in Tensor Flow."
},
{
"code": null,
"e": 448,
"s": 216,
"text": "The idea behind this article is to avoid all the introductions and the usual chatter associated with word embeddings/word2vec and jump straight into the meat of things. So, much of the king-man-woman-queen examples will be skipped."
},
{
"code": null,
"e": 670,
"s": 448,
"text": "There are many techniques to get word embeddings, we will discuss one technique which has gained a lot of fame, the one and only, word2vec. Contrary to popular belief, word2vec is not a deep network, it only has 3 layers!"
},
{
"code": null,
"e": 780,
"s": 670,
"text": "Note : word2vec has a lot of technical details which I will skip over to make the understanding a lot easier."
},
{
"code": null,
"e": 814,
"s": 780,
"text": "The idea behind word2vec is that:"
},
{
"code": null,
"e": 1148,
"s": 814,
"text": "Take a 3 layer neural network. (1 input layer + 1 hidden layer + 1 output layer)Feed it a word and train it to predict its neighbouring word.Remove the last (output layer) and keep the input and hidden layer.Now, input a word from within the vocabulary. The output given at the hidden layer is the ‘word embedding’ of the input word."
},
{
"code": null,
"e": 1229,
"s": 1148,
"text": "Take a 3 layer neural network. (1 input layer + 1 hidden layer + 1 output layer)"
},
{
"code": null,
"e": 1291,
"s": 1229,
"text": "Feed it a word and train it to predict its neighbouring word."
},
{
"code": null,
"e": 1359,
"s": 1291,
"text": "Remove the last (output layer) and keep the input and hidden layer."
},
{
"code": null,
"e": 1485,
"s": 1359,
"text": "Now, input a word from within the vocabulary. The output given at the hidden layer is the ‘word embedding’ of the input word."
},
{
"code": null,
"e": 1591,
"s": 1485,
"text": "That’s it! Just doing this simple task enables our network to learn interesting representations of words."
},
{
"code": null,
"e": 1654,
"s": 1591,
"text": "Let’s start implementing this to flesh out this understanding."
},
{
"code": null,
"e": 1783,
"s": 1654,
"text": "(the full code is available here . I suggest you understand what’s going on from this article and then use the code from there.)"
},
{
"code": null,
"e": 1836,
"s": 1783,
"text": "This is the raw text on which we will be working on:"
},
{
"code": null,
"e": 1973,
"s": 1836,
"text": "(I have intentionally spaced out the periods and avoided them in the end to simplify. Once you understand, feel free to use a tokenizer)"
},
{
"code": null,
"e": 2145,
"s": 1973,
"text": "import numpy as npimport tensorflow as tfcorpus_raw = 'He is the king . The king is royal . She is the royal queen '# convert to lower casecorpus_raw = corpus_raw.lower()"
},
{
"code": null,
"e": 2422,
"s": 2145,
"text": "We need to convert this to an input output pair such that if we input a word, it should it predict that the neighbouring words : the n words before and after it, where n is the parameter window_size Here’s a handy example from this amazing post on word2vec by Chris McCormick."
},
{
"code": null,
"e": 2519,
"s": 2422,
"text": "Note: If the word is at the beginning or ending of sentence, the window ignores the outer words."
},
{
"code": null,
"e": 2655,
"s": 2519,
"text": "Before doing this, we will create a dictionary which translates words to integers and integers to words. This will come in handy later."
},
{
"code": null,
"e": 3012,
"s": 2655,
"text": "words = []for word in corpus_raw.split(): if word != '.': # because we don't want to treat . as a word words.append(word)words = set(words) # so that all duplicate words are removedword2int = {}int2word = {}vocab_size = len(words) # gives the total number of unique wordsfor i,word in enumerate(words): word2int[word] = i int2word[i] = word"
},
{
"code": null,
"e": 3056,
"s": 3012,
"text": "What these dictionaries allow us to do is :"
},
{
"code": null,
"e": 3121,
"s": 3056,
"text": "print(word2int['queen'])-> 42 (say)print(int2word[42])-> 'queen'"
},
{
"code": null,
"e": 3178,
"s": 3121,
"text": "Now, we want a list of our sentences as a list of words:"
},
{
"code": null,
"e": 3337,
"s": 3178,
"text": "# raw sentences is a list of sentences.raw_sentences = corpus_raw.split('.')sentences = []for sentence in raw_sentences: sentences.append(sentence.split())"
},
{
"code": null,
"e": 3415,
"s": 3337,
"text": "This will give us a list of sentences where each sentence is a list of words."
},
{
"code": null,
"e": 3536,
"s": 3415,
"text": "print(sentences)-> [['he', 'is', 'the', 'king'], ['the', 'king', 'is', 'royal'], ['she', 'is', 'the', 'royal', 'queen']]"
},
{
"code": null,
"e": 3577,
"s": 3536,
"text": "Now, we will generate our training data:"
},
{
"code": null,
"e": 3650,
"s": 3577,
"text": "(This might get difficult to read within medium. refer to the code link)"
},
{
"code": null,
"e": 3943,
"s": 3650,
"text": "data = []WINDOW_SIZE = 2for sentence in sentences: for word_index, word in enumerate(sentence): for nb_word in sentence[max(word_index - WINDOW_SIZE, 0) : min(word_index + WINDOW_SIZE, len(sentence)) + 1] : if nb_word != word: data.append([word, nb_word])"
},
{
"code": null,
"e": 4032,
"s": 3943,
"text": "This basically gives a list of word, word pairs. (we are considering a window size of 2)"
},
{
"code": null,
"e": 4169,
"s": 4032,
"text": "print(data)[['he', 'is'], ['he', 'the'], ['is', 'he'], ['is', 'the'], ['is', 'king'], ['the', 'he'], ['the', 'is'], ['the', 'king'],...]"
},
{
"code": null,
"e": 4326,
"s": 4169,
"text": "We have our training data. But it needs to be represented in a way a computer can understand i.e., with numbers. That’s where our word2int dict comes handy."
},
{
"code": null,
"e": 4400,
"s": 4326,
"text": "Let’s go one step further and convert these numbers into one hot vectors."
},
{
"code": null,
"e": 4573,
"s": 4400,
"text": "i.e., say we have a vocabulary of 3 words : pen, pineapple, applewhere word2int['pen'] -> 0 -> [1 0 0]word2int['pineapple'] -> 1 -> [0 1 0]word2int['apple'] -> 2 -> [0 0 1]"
},
{
"code": null,
"e": 4607,
"s": 4573,
"text": "Why one hot vectors? : told later"
},
{
"code": null,
"e": 5074,
"s": 4607,
"text": "# function to convert numbers to one hot vectorsdef to_one_hot(data_point_index, vocab_size): temp = np.zeros(vocab_size) temp[data_point_index] = 1 return tempx_train = [] # input wordy_train = [] # output wordfor data_word in data: x_train.append(to_one_hot(word2int[ data_word[0] ], vocab_size)) y_train.append(to_one_hot(word2int[ data_word[1] ], vocab_size))# convert them to numpy arraysx_train = np.asarray(x_train)y_train = np.asarray(y_train)"
},
{
"code": null,
"e": 5110,
"s": 5074,
"text": "So now we have x_train and y_train:"
},
{
"code": null,
"e": 6148,
"s": 5110,
"text": "print(x_train)->[[ 0. 0. 0. 0. 0. 0. 1.] [ 0. 0. 0. 0. 0. 0. 1.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 0. 0. 1. 0. 0. 0. 0.] [ 0. 0. 1. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 1. 0. 0. 0. 0. 0. 0.] [ 1. 0. 0. 0. 0. 0. 0.]]"
},
{
"code": null,
"e": 6169,
"s": 6148,
"text": "Both have the shape:"
},
{
"code": null,
"e": 6285,
"s": 6169,
"text": "print(x_train.shape, y_train.shape)->(34, 7) (34, 7)# meaning 34 training points, where each point has 7 dimensions"
},
{
"code": null,
"e": 6449,
"s": 6285,
"text": "# making placeholders for x_train and y_trainx = tf.placeholder(tf.float32, shape=(None, vocab_size))y_label = tf.placeholder(tf.float32, shape=(None, vocab_size))"
},
{
"code": null,
"e": 6558,
"s": 6449,
"text": "As can be seen in the above diagram, we take our training data and convert into the embedded representation."
},
{
"code": null,
"e": 6780,
"s": 6558,
"text": "EMBEDDING_DIM = 5 # you can choose your own numberW1 = tf.Variable(tf.random_normal([vocab_size, EMBEDDING_DIM]))b1 = tf.Variable(tf.random_normal([EMBEDDING_DIM])) #biashidden_representation = tf.add(tf.matmul(x,W1), b1)"
},
{
"code": null,
"e": 6915,
"s": 6780,
"text": "Next, we take what we have in the embedded dimension and make a prediction about the neighbour. To make the prediction we use softmax."
},
{
"code": null,
"e": 7104,
"s": 6915,
"text": "W2 = tf.Variable(tf.random_normal([EMBEDDING_DIM, vocab_size]))b2 = tf.Variable(tf.random_normal([vocab_size]))prediction = tf.nn.softmax(tf.add( tf.matmul(hidden_representation, W2), b2))"
},
{
"code": null,
"e": 7121,
"s": 7104,
"text": "So to summarise:"
},
{
"code": null,
"e": 7258,
"s": 7121,
"text": "input_one_hot ---> embedded repr. ---> predicted_neighbour_probpredicted_prob will be compared against a one hot vector to correct it."
},
{
"code": null,
"e": 7295,
"s": 7258,
"text": "Now, all that’s left is to train it:"
},
{
"code": null,
"e": 7860,
"s": 7295,
"text": "sess = tf.Session()init = tf.global_variables_initializer()sess.run(init) #make sure you do this!# define the loss function:cross_entropy_loss = tf.reduce_mean(-tf.reduce_sum(y_label * tf.log(prediction), reduction_indices=[1]))# define the training step:train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy_loss)n_iters = 10000# train for n_iter iterationsfor _ in range(n_iters): sess.run(train_step, feed_dict={x: x_train, y_label: y_train}) print('loss is : ', sess.run(cross_entropy_loss, feed_dict={x: x_train, y_label: y_train}))"
},
{
"code": null,
"e": 7907,
"s": 7860,
"text": "On training, you will get the display of loss:"
},
{
"code": null,
"e": 8449,
"s": 7907,
"text": "loss is : 2.73213loss is : 2.30519loss is : 2.11106loss is : 1.9916loss is : 1.90923loss is : 1.84837loss is : 1.80133loss is : 1.76381loss is : 1.73312loss is : 1.70745loss is : 1.68556loss is : 1.66654loss is : 1.64975loss is : 1.63472loss is : 1.62112loss is : 1.6087loss is : 1.59725loss is : 1.58664loss is : 1.57676loss is : 1.56751loss is : 1.55882loss is : 1.55064loss is : 1.54291loss is : 1.53559loss is : 1.52865loss is : 1.52206loss is : 1.51578loss is : 1.50979loss is : 1.50408loss is : 1.49861..."
},
{
"code": null,
"e": 8622,
"s": 8449,
"text": "It eventually stabilises on a constant loss. Even though we can’t get high accuracy, we don’t care. All we are interested in is W1 and b1, i.e., the hidden representations."
},
{
"code": null,
"e": 8649,
"s": 8622,
"text": "Let’s have a look at them:"
},
{
"code": null,
"e": 9244,
"s": 8649,
"text": "print(sess.run(W1))print('----------')print(sess.run(b1))print('----------')->[[-0.85421133 1.70487809 0.481848 -0.40843448 -0.02236851] [-0.47163373 0.34260952 -2.06743765 -1.43854153 -0.14699034] [-1.06858993 -1.10739779 0.52600187 0.24079895 -0.46390489] [ 0.84426647 0.16476244 -0.72731972 -0.31994426 -0.33553854] [ 0.21508843 -1.21030915 -0.13006891 -0.24056002 -0.30445012] [ 0.17842589 2.08979321 -0.34172744 -1.8842833 -1.14538431] [ 1.61166084 -1.17404735 -0.26805425 0.74437028 -0.81183684]]----------[ 0.57727528 -0.83760375 0.19156453 -0.42394346 1.45631313]----------"
},
{
"code": null,
"e": 9484,
"s": 9244,
"text": "When we multiply the one hot vectors with W1 , we basically get access to the row of the of W1 which is in fact the embedded representation of the word represented by the input one hot vector. So W1is essentially acting as a look up table."
},
{
"code": null,
"e": 9556,
"s": 9484,
"text": "In our case we have also included a bias term b1 so you have to add it."
},
{
"code": null,
"e": 10139,
"s": 9556,
"text": "vectors = sess.run(W1 + b1)# if you work it out, you will see that it has the same effect as running the node hidden representationprint(vectors)->[[-0.74829113 -0.48964909 0.54267412 2.34831429 -2.03110814] [-0.92472583 -1.50792813 -1.61014366 -0.88273793 -2.12359881] [-0.69424796 -1.67628145 3.07313657 -1.14802659 -1.2207377 ] [-1.7077738 -0.60641652 2.25586247 1.34536338 -0.83848488] [-0.10080346 -0.90931684 2.8825531 -0.58769202 -1.19922316] [ 1.49428082 -2.55578995 2.01545811 0.31536022 1.52662396] [-1.02735448 0.72176981 -0.03772151 -0.60208392 1.53156447]]"
},
{
"code": null,
"e": 10204,
"s": 10139,
"text": "If we want the representation for ‘queen’, all we have to do is:"
},
{
"code": null,
"e": 10337,
"s": 10204,
"text": "print(vectors[ word2int['queen'] ])# say here word2int['queen'] is 2-> [-0.69424796 -1.67628145 3.07313657 -1.14802659 -1.2207377 ]"
},
{
"code": null,
"e": 10444,
"s": 10337,
"text": "Here’s a quick function to find the closest vector to a given vector. Beware, it’s a dirty implementation."
},
{
"code": null,
"e": 10920,
"s": 10444,
"text": "def euclidean_dist(vec1, vec2): return np.sqrt(np.sum((vec1-vec2)**2))def find_closest(word_index, vectors): min_dist = 10000 # to act like positive infinity min_index = -1 query_vector = vectors[word_index] for index, vector in enumerate(vectors): if euclidean_dist(vector, query_vector) < min_dist and not np.array_equal(vector, query_vector): min_dist = euclidean_dist(vector, query_vector) min_index = index return min_index"
},
{
"code": null,
"e": 10985,
"s": 10920,
"text": "We will now query these vectors with ‘king’, ‘queen’ and ‘royal’"
},
{
"code": null,
"e": 11169,
"s": 10985,
"text": "print(int2word[find_closest(word2int['king'], vectors)])print(int2word[find_closest(word2int['queen'], vectors)])print(int2word[find_closest(word2int['royal'], vectors)])->queenkinghe"
},
{
"code": null,
"e": 11208,
"s": 11169,
"text": "Interesting, our embedding learnt that"
},
{
"code": null,
"e": 11279,
"s": 11208,
"text": "king is closest to queenqueen is closest to kingroyal is closest to he"
},
{
"code": null,
"e": 11506,
"s": 11279,
"text": "The third one is due to our corpus (It’s still pretty good). A bigger corpus will lead to better results. (Note: due to the random initialisation of the weights, you might get different results. Run it a few times if required)"
},
{
"code": null,
"e": 11531,
"s": 11506,
"text": "Let’s plot them vectors!"
},
{
"code": null,
"e": 11649,
"s": 11531,
"text": "First let’s reduce the dimensions from 5 to 2 with our favourite dimensionality reduction technique : tSNE (teesnee!)"
},
{
"code": null,
"e": 11799,
"s": 11649,
"text": "from sklearn.manifold import TSNEmodel = TSNE(n_components=2, random_state=0)np.set_printoptions(suppress=True)vectors = model.fit_transform(vectors)"
},
{
"code": null,
"e": 11894,
"s": 11799,
"text": "Then, we need to normalize the results so that we can view them more comfortably in matplotlib"
},
{
"code": null,
"e": 12017,
"s": 11894,
"text": "from sklearn import preprocessingnormalizer = preprocessing.Normalizer()vectors = normalizer.fit_transform(vectors, 'l2')"
},
{
"code": null,
"e": 12065,
"s": 12017,
"text": "Finally, we will plot the 2D normalized vectors"
},
{
"code": null,
"e": 12271,
"s": 12065,
"text": "import matplotlib.pyplot as pltfig, ax = plt.subplots()for word in words: print(word, vectors[word2int[word]][1]) ax.annotate(word, (vectors[word2int[word]][0],vectors[word2int[word]][1] ))plt.show()"
},
{
"code": null,
"e": 12420,
"s": 12271,
"text": "Wow! she is close to queen and king is equally distanced from royal and queen We need a bigger corpus to see some of the more complicated relations."
},
{
"code": null,
"e": 12791,
"s": 12420,
"text": "Note: After publishing this, I realized that this example isn’t correct because to get meaningful convergence of vectors, we need a really large corpus. The small size of the data makes it vulnerable to sudden “jerks”. However, I shall keep this writing intact for pedagogical purposes. For an efficient implementation of word2vec try gensim with some corpus like text8."
},
{
"code": null,
"e": 13159,
"s": 12791,
"text": "We have given the neural network the task of predicting neighbours. But we haven’t specified how the network should predict it. So, the neural network figures out an hidden representation of the words, to aid it in the task of predicting neighbouring words. Predicting neighbouring words is not an interesting task in itself. We care about this hidden representation."
},
{
"code": null,
"e": 13326,
"s": 13159,
"text": "To form these representations, the network is using contexts/neighbours. In our corpus, king and royal appear as neighbours, and royal and queen appear as neighbours."
},
{
"code": null,
"e": 13477,
"s": 13326,
"text": "Well, other task also manage to form a good representation. Predicting whether the word is a valid n-gram as shown here can also lead to good vectors!"
},
{
"code": null,
"e": 13737,
"s": 13477,
"text": "We tried to predict a neighbouring words given a word. This is known as the skip gram model. We could have used neighbouring words of a middle word as inputs and asked the network to predict the middle word. This is known as the Continuous Bag of Words Model."
},
{
"code": null,
"e": 13885,
"s": 13737,
"text": "This by no means is a complete understanding of word2vec. Part of w2v’s beauty is in its 2 modifications to what I’ve just talked about. These are:"
},
{
"code": null,
"e": 13903,
"s": 13885,
"text": "Negative Sampling"
},
{
"code": null,
"e": 13924,
"s": 13903,
"text": "Hierarchical Softmax"
},
{
"code": null,
"e": 14132,
"s": 13924,
"text": "Negative Sampling: it suggests that instead of backpropagating all the 0s in the correct output vector (for a vocab size of 10mill there are 10mill minus 1 zeros) we just backpropagate a few of them (say 14)"
},
{
"code": null,
"e": 14319,
"s": 14132,
"text": "Hierarchical Softmax: Calculating the softmax for a vocab of 10mill is very time and computation intensive. Hierarchical Softmax suggests a faster way of computing it using Huffman trees"
},
{
"code": null,
"e": 14445,
"s": 14319,
"text": "In the interest of keeping the post simple, I have avoided delving much into it. I definitely recommend reading more into it."
},
{
"code": null,
"e": 14473,
"s": 14445,
"text": "Word Vectors are super cool"
},
{
"code": null,
"e": 14573,
"s": 14473,
"text": "Don’t use this tensorflow code for actual use. It was just to understand. Use a library like gensim"
},
{
"code": null,
"e": 14659,
"s": 14573,
"text": "I hope that helped somebody understand these beauties better. If it did, let me know!"
},
{
"code": null,
"e": 14702,
"s": 14659,
"text": "If I’ve made mistakes, please let me know."
}
] |
Geographical plotting using Python plotly | Python provides various libraries to handle geographical and graph data. Python plotly is one of those libraries which are used to draw geographical graphs. Plotly is a free and open source library. Plotly helps to plot various kinds of graphs like Line charts, Horizontal bar charts, bar charts, dashboards, scatter plots, bubble charts, pie charts and many more.
# Import important python geographical libraries.
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
# Must enable in order to use plotly off-line.
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot
# To establish connection
init_notebook_mode()
# type defined is choropleth to
# plot geographical plots
data = dict(type = 'choropleth',
# location: LosAngles, NewJersey, Texas
locations = ['AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL','IN','IA', 'KS', 'KY'],
# States of USA
locationmode = 'USA-states',
# colorscale can be added as per requirement
colorscale = 'Portland',
# text can be given anything you like
text = ['state 1', 'state 2', 'state 3', 'state 4', 'state 5','state 6', 'state 7', 'state 8', 'state 9', 'state 10','state 11', 'state 12', 'state 13', 'state 14', 'state 15','state 16', 'state 17', 'state 18', 'state 19', 'state 20'],
z = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0],
colorbar = {'title': 'USA-states'})
layout = dict(geo ={'scope': 'usa'})
# passing data dictionary as a list
choromap = go.Figure(data = [data], layout = layout)
# plotting graph
iplot(choromap)
With the help of the plot, we can visualize the data (input items) with different ways based on what we want to achieve. We can visualize the different states of India (29) with different colors based on what political party is ruling it or based on food choices (veg/non-veg) which states prefer what kind of food or any other thing you image. Plotly provides a very powerful and interactive library to visualize data in an easily understandable way (graph). | [
{
"code": null,
"e": 1427,
"s": 1062,
"text": "Python provides various libraries to handle geographical and graph data. Python plotly is one of those libraries which are used to draw geographical graphs. Plotly is a free and open source library. Plotly helps to plot various kinds of graphs like Line charts, Horizontal bar charts, bar charts, dashboards, scatter plots, bubble charts, pie charts and many more."
},
{
"code": null,
"e": 2692,
"s": 1427,
"text": "# Import important python geographical libraries.\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport pandas as pd\n# Must enable in order to use plotly off-line.\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot\n# To establish connection\ninit_notebook_mode()\n# type defined is choropleth to\n# plot geographical plots\ndata = dict(type = 'choropleth',\n# location: LosAngles, NewJersey, Texas\nlocations = ['AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL','IN','IA', 'KS', 'KY'],\n# States of USA\nlocationmode = 'USA-states',\n# colorscale can be added as per requirement\ncolorscale = 'Portland',\n# text can be given anything you like\ntext = ['state 1', 'state 2', 'state 3', 'state 4', 'state 5','state 6', 'state 7', 'state 8', 'state 9', 'state 10','state 11', 'state 12', 'state 13', 'state 14', 'state 15','state 16', 'state 17', 'state 18', 'state 19', 'state 20'],\nz = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0],\ncolorbar = {'title': 'USA-states'})\nlayout = dict(geo ={'scope': 'usa'})\n# passing data dictionary as a list\nchoromap = go.Figure(data = [data], layout = layout)\n# plotting graph\niplot(choromap)"
},
{
"code": null,
"e": 3152,
"s": 2692,
"text": "With the help of the plot, we can visualize the data (input items) with different ways based on what we want to achieve. We can visualize the different states of India (29) with different colors based on what political party is ruling it or based on food choices (veg/non-veg) which states prefer what kind of food or any other thing you image. Plotly provides a very powerful and interactive library to visualize data in an easily understandable way (graph)."
}
] |
C++ program to Find Sum of Natural Numbers using Recursion | The natural numbers are the positive integers starting from 1.
The sequence of natural numbers is −
1, 2, 3, 4, 5, 6, 7, 8, 9, 10......
The program to find the sum of first n natural numbers using recursion is as follows.
Live Demo
#include <iostream>
using namespace std;
int sum(int n) {
if(n == 0)
return n;
else
return n + sum(n-1);
}
int main() {
int n = 10;
cout<<"Sum of first "<<n<<" natural numbers is "<<sum(n);
return 0;
}
Sum of first 10 natural numbers is 55
In the above program, the function sum() is a recursive function. If n is 0, it returns 0 as the sum of the first 0 natural numbers is 0. If n is more than 0, then sum recursively calls itself itself with the value n-1 and eventually returns the sum of n, n-1, n-2......2,1. The code snippet that demonstrates this is as follows.
int sum(int n) {
if(n == 0)
return n;
else
return n + sum(n-1);
}
In the function main(), the sum of the first n natural numbers is displayed using cout. This can be seen as follows −
cout<<"Sum of first "<<n<<" natural numbers is "<<sum(n); | [
{
"code": null,
"e": 1125,
"s": 1062,
"text": "The natural numbers are the positive integers starting from 1."
},
{
"code": null,
"e": 1162,
"s": 1125,
"text": "The sequence of natural numbers is −"
},
{
"code": null,
"e": 1198,
"s": 1162,
"text": "1, 2, 3, 4, 5, 6, 7, 8, 9, 10......"
},
{
"code": null,
"e": 1284,
"s": 1198,
"text": "The program to find the sum of first n natural numbers using recursion is as follows."
},
{
"code": null,
"e": 1295,
"s": 1284,
"text": " Live Demo"
},
{
"code": null,
"e": 1518,
"s": 1295,
"text": "#include <iostream>\nusing namespace std;\nint sum(int n) {\n if(n == 0)\n return n;\n else\n return n + sum(n-1);\n}\nint main() {\n int n = 10;\n cout<<\"Sum of first \"<<n<<\" natural numbers is \"<<sum(n);\n return 0;\n}"
},
{
"code": null,
"e": 1556,
"s": 1518,
"text": "Sum of first 10 natural numbers is 55"
},
{
"code": null,
"e": 1886,
"s": 1556,
"text": "In the above program, the function sum() is a recursive function. If n is 0, it returns 0 as the sum of the first 0 natural numbers is 0. If n is more than 0, then sum recursively calls itself itself with the value n-1 and eventually returns the sum of n, n-1, n-2......2,1. The code snippet that demonstrates this is as follows."
},
{
"code": null,
"e": 1964,
"s": 1886,
"text": "int sum(int n) {\n if(n == 0)\n return n;\n else\n return n + sum(n-1);\n}"
},
{
"code": null,
"e": 2082,
"s": 1964,
"text": "In the function main(), the sum of the first n natural numbers is displayed using cout. This can be seen as follows −"
},
{
"code": null,
"e": 2140,
"s": 2082,
"text": "cout<<\"Sum of first \"<<n<<\" natural numbers is \"<<sum(n);"
}
] |
Multiplication of two Matrices in Single line using Numpy in Python | Matrix multiplication is a lengthy process where each element from each row and column of the matrixes are to be multiplied and added in a certain way. For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. The result matrix has the number of rows of the first and the number of columns of the second matrix.
For smaller matrices we may design nested for loops and find the result. For bigger matrices we need some built in functionality in python to tackle this. We will see both approaches below.
We take two matrices of dimension 2x3 and 3x2 (rows x columns). The result of matrix multiplication is a 2x2 matrix. We have a nested for loop designed to go through the columns of A and rows of B and add the products of the values in those rows and columns.
Live Demo
#matrix A with 2 rows
A = ([5,10,15],[20,25,30])
#matrix B with 2 columns
B = ([4,8],[12,10],[14,16])
result = [[0 for x in range(2)] for y in range(2)]
for i in range(len(A)):
# iterate through columns of A
for j in range(len(B[0])):
# iterate through rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
Running the above code gives us the following result:
[350, 380]
[800, 890]
Numpy has a in-built function named dot, that carries out the matrix multiplication. Our number of lines of program becomes very less and the syntax is also very simple.
Live Demo
import numpy as np
#matrix A
matrix_A = ([5,10,15],[20,25,30])
#matrix B
matrix_B = ([4,8],[12,10],[14,16])
result = np.dot(matrix_A,matrix_B)
# Result
print(result)
Running the above code gives us the following result:
[[350 380]
[800 890]] | [
{
"code": null,
"e": 1443,
"s": 1062,
"text": "Matrix multiplication is a lengthy process where each element from each row and column of the matrixes are to be multiplied and added in a certain way. For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. The result matrix has the number of rows of the first and the number of columns of the second matrix."
},
{
"code": null,
"e": 1633,
"s": 1443,
"text": "For smaller matrices we may design nested for loops and find the result. For bigger matrices we need some built in functionality in python to tackle this. We will see both approaches below."
},
{
"code": null,
"e": 1892,
"s": 1633,
"text": "We take two matrices of dimension 2x3 and 3x2 (rows x columns). The result of matrix multiplication is a 2x2 matrix. We have a nested for loop designed to go through the columns of A and rows of B and add the products of the values in those rows and columns."
},
{
"code": null,
"e": 1903,
"s": 1892,
"text": " Live Demo"
},
{
"code": null,
"e": 2284,
"s": 1903,
"text": "#matrix A with 2 rows\nA = ([5,10,15],[20,25,30])\n\n#matrix B with 2 columns\nB = ([4,8],[12,10],[14,16])\n\nresult = [[0 for x in range(2)] for y in range(2)]\n\nfor i in range(len(A)):\n # iterate through columns of A\n for j in range(len(B[0])):\n # iterate through rows of B\n for k in range(len(B)):\n result[i][j] += A[i][k] * B[k][j]\nfor r in result:\n print(r)\n"
},
{
"code": null,
"e": 2338,
"s": 2284,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 2360,
"s": 2338,
"text": "[350, 380]\n[800, 890]"
},
{
"code": null,
"e": 2530,
"s": 2360,
"text": "Numpy has a in-built function named dot, that carries out the matrix multiplication. Our number of lines of program becomes very less and the syntax is also very simple."
},
{
"code": null,
"e": 2541,
"s": 2530,
"text": " Live Demo"
},
{
"code": null,
"e": 2710,
"s": 2541,
"text": "import numpy as np\n\n#matrix A\nmatrix_A = ([5,10,15],[20,25,30])\n\n#matrix B\nmatrix_B = ([4,8],[12,10],[14,16])\nresult = np.dot(matrix_A,matrix_B)\n\n# Result\nprint(result)"
},
{
"code": null,
"e": 2764,
"s": 2710,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 2786,
"s": 2764,
"text": "[[350 380]\n[800 890]]"
}
] |
Delete without head pointer | Practice | GeeksforGeeks | You are given a pointer/ reference to the node which is to be deleted from the linked list of N nodes. The task is to delete the node. Pointer/ reference to head node is not given.
Note: No head reference is given to you. It is guaranteed that the node to be deleted is not a tail node in the linked list.
Example 1:
Input:
N = 2
value[] = {1,2}
node = 1
Output: 2
Explanation: After deleting 1 from the
linked list, we have remaining nodes
as 2.
Example 2:
Input:
N = 4
value[] = {10,20,4,30}
node = 20
Output: 10 4 30
Explanation: After deleting 20 from
the linked list, we have remaining
nodes as 10, 4 and 30.
Your Task:
You only need to complete the function deleteNode that takes reference to the node that needs to be deleted. The printing is done automatically by the driver code.
Expected Time Complexity : O(1)
Expected Auxilliary Space : O(1)
Constraints:
1 <= N <= 103
0
mannukhurana103971 day ago
Java
As we can't delete the current node, copy the data of next node to the current node and point the current node node to the next of the next node;
void deleteNode(Node del)
{ del.data = del.next.data;
del.next = del.next.next;
}
0
aakashsoni24861 week ago
just change the given pointer to next pointer.
// 1 line code class Solution{ public: //Function to delete a node without any reference to head pointer. void deleteNode(Node *del) { // Your code here *del=*del->next; }
};
+1
moonviprant2 weeks ago
Simple SOlution:->
class Solution
{
public:
//Function to delete a node without any reference to head pointer.
void deleteNode(Node *del)
{
// Your code here
del->data=del->next->data;
del->next=del->next->next;
}
};
+1
tarungarg0513 weeks ago
void deleteNode(Node del) { // Your code here del.data = del.next.data; del.next = del.next.next; }
0
adityaraj100mit4 weeks ago
void deleteNode(Node *del) { // Your code here Node* temp=del->next; del->data=temp->data; del->next=temp->next; free(temp); }
+1
swatisingh727774 weeks ago
void deleteNode(Node *del)
{
Node* temp = del->next;
del->data = del->next->data;
del->next = del->next->next;
temp->next=NULL;
}
// O(1) time complexity
+1
umidbaban121 month ago
void deleteNode(Node *del) { del->data=del->next->data; del->next=del->next->next; }
0
amishasahu3281 month ago
void deleteNode(Node *del)
{
// Your code here
Node *temp = del->next;
del->data = temp->data;
del->next = temp->next;
}
0
ahmadsqf1 month ago
What if we only do this ?
void deleteNode(Node *del)
{
del = del -> next;
}
+1
abhishekpanwar6971 month ago
void deleteNode(Node *start) { swap(start->data,start->next->data); start->next=start->next->next; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 545,
"s": 238,
"text": "You are given a pointer/ reference to the node which is to be deleted from the linked list of N nodes. The task is to delete the node. Pointer/ reference to head node is not given. \nNote: No head reference is given to you. It is guaranteed that the node to be deleted is not a tail node in the linked list."
},
{
"code": null,
"e": 556,
"s": 545,
"text": "Example 1:"
},
{
"code": null,
"e": 687,
"s": 556,
"text": "Input:\nN = 2\nvalue[] = {1,2}\nnode = 1\nOutput: 2\nExplanation: After deleting 1 from the\nlinked list, we have remaining nodes\nas 2.\n"
},
{
"code": null,
"e": 698,
"s": 687,
"text": "Example 2:"
},
{
"code": null,
"e": 854,
"s": 698,
"text": "Input:\nN = 4\nvalue[] = {10,20,4,30}\nnode = 20\nOutput: 10 4 30\nExplanation: After deleting 20 from\nthe linked list, we have remaining\nnodes as 10, 4 and 30."
},
{
"code": null,
"e": 1029,
"s": 854,
"text": "Your Task:\nYou only need to complete the function deleteNode that takes reference to the node that needs to be deleted. The printing is done automatically by the driver code."
},
{
"code": null,
"e": 1094,
"s": 1029,
"text": "Expected Time Complexity : O(1)\nExpected Auxilliary Space : O(1)"
},
{
"code": null,
"e": 1121,
"s": 1094,
"text": "Constraints:\n1 <= N <= 103"
},
{
"code": null,
"e": 1123,
"s": 1121,
"text": "0"
},
{
"code": null,
"e": 1150,
"s": 1123,
"text": "mannukhurana103971 day ago"
},
{
"code": null,
"e": 1155,
"s": 1150,
"text": "Java"
},
{
"code": null,
"e": 1301,
"s": 1155,
"text": "As we can't delete the current node, copy the data of next node to the current node and point the current node node to the next of the next node;"
},
{
"code": null,
"e": 1399,
"s": 1303,
"text": "void deleteNode(Node del)\n { del.data = del.next.data;\n del.next = del.next.next;\n }"
},
{
"code": null,
"e": 1401,
"s": 1399,
"text": "0"
},
{
"code": null,
"e": 1426,
"s": 1401,
"text": "aakashsoni24861 week ago"
},
{
"code": null,
"e": 1473,
"s": 1426,
"text": "just change the given pointer to next pointer."
},
{
"code": null,
"e": 1665,
"s": 1473,
"text": "// 1 line code class Solution{ public: //Function to delete a node without any reference to head pointer. void deleteNode(Node *del) { // Your code here *del=*del->next; }"
},
{
"code": null,
"e": 1668,
"s": 1665,
"text": "};"
},
{
"code": null,
"e": 1671,
"s": 1668,
"text": "+1"
},
{
"code": null,
"e": 1694,
"s": 1671,
"text": "moonviprant2 weeks ago"
},
{
"code": null,
"e": 1953,
"s": 1694,
"text": "Simple SOlution:->\nclass Solution\n{\n public:\n //Function to delete a node without any reference to head pointer.\n void deleteNode(Node *del)\n {\n // Your code here\n del->data=del->next->data;\n del->next=del->next->next;\n }\n\n};"
},
{
"code": null,
"e": 1956,
"s": 1953,
"text": "+1"
},
{
"code": null,
"e": 1980,
"s": 1956,
"text": "tarungarg0513 weeks ago"
},
{
"code": null,
"e": 2113,
"s": 1980,
"text": "void deleteNode(Node del) { // Your code here del.data = del.next.data; del.next = del.next.next; }"
},
{
"code": null,
"e": 2115,
"s": 2113,
"text": "0"
},
{
"code": null,
"e": 2142,
"s": 2115,
"text": "adityaraj100mit4 weeks ago"
},
{
"code": null,
"e": 2304,
"s": 2142,
"text": "void deleteNode(Node *del) { // Your code here Node* temp=del->next; del->data=temp->data; del->next=temp->next; free(temp); }"
},
{
"code": null,
"e": 2307,
"s": 2304,
"text": "+1"
},
{
"code": null,
"e": 2334,
"s": 2307,
"text": "swatisingh727774 weeks ago"
},
{
"code": null,
"e": 2538,
"s": 2334,
"text": " void deleteNode(Node *del)\n {\n \n Node* temp = del->next;\n del->data = del->next->data;\n del->next = del->next->next;\n temp->next=NULL;\n }\n // O(1) time complexity"
},
{
"code": null,
"e": 2541,
"s": 2538,
"text": "+1"
},
{
"code": null,
"e": 2564,
"s": 2541,
"text": "umidbaban121 month ago"
},
{
"code": null,
"e": 2663,
"s": 2564,
"text": "void deleteNode(Node *del) { del->data=del->next->data; del->next=del->next->next; }"
},
{
"code": null,
"e": 2665,
"s": 2663,
"text": "0"
},
{
"code": null,
"e": 2690,
"s": 2665,
"text": "amishasahu3281 month ago"
},
{
"code": null,
"e": 2845,
"s": 2690,
"text": " void deleteNode(Node *del)\n {\n // Your code here\n Node *temp = del->next;\n del->data = temp->data;\n del->next = temp->next;\n }"
},
{
"code": null,
"e": 2847,
"s": 2845,
"text": "0"
},
{
"code": null,
"e": 2867,
"s": 2847,
"text": "ahmadsqf1 month ago"
},
{
"code": null,
"e": 2948,
"s": 2867,
"text": "What if we only do this ?\n\nvoid deleteNode(Node *del)\n{\n del = del -> next;\n}"
},
{
"code": null,
"e": 2951,
"s": 2948,
"text": "+1"
},
{
"code": null,
"e": 2980,
"s": 2951,
"text": "abhishekpanwar6971 month ago"
},
{
"code": null,
"e": 3101,
"s": 2980,
"text": "void deleteNode(Node *start) { swap(start->data,start->next->data); start->next=start->next->next; }"
},
{
"code": null,
"e": 3247,
"s": 3101,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 3283,
"s": 3247,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3293,
"s": 3283,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3303,
"s": 3293,
"text": "\nContest\n"
},
{
"code": null,
"e": 3366,
"s": 3303,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3514,
"s": 3366,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 3722,
"s": 3514,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 3828,
"s": 3722,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to detect a new Android notification? | This example demonstrate about How to detect a new Android notification
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to src/MyListener.java
public interface MyListener {
void setValue (String packageName) ;
}
Step 3 − Add the following code to src/MyListener.java
package app.tutorialspoint.com.notifyme ;
import android.content.Context ;
import android.service.notification.NotificationListenerService ;
import android.service.notification.StatusBarNotification ;
import android.util.Log ;
public class NotificationService extends NotificationListenerService {
private String TAG = this .getClass().getSimpleName() ;
Context context ;
static MyListener myListener ;
@Override
public void onCreate () {
super .onCreate() ;
context = getApplicationContext() ;
}
@Override
public void onNotificationPosted (StatusBarNotification sbn) {
Log. i ( TAG , "********** onNotificationPosted" ) ;
Log. i ( TAG , "ID :" + sbn.getId() + " \t " + sbn.getNotification(). tickerText + " \t " + sbn.getPackageName()) ;
myListener .setValue( "Post: " + sbn.getPackageName()) ;
}
@Override
public void onNotificationRemoved (StatusBarNotification sbn) {
Log. i ( TAG , "********** onNotificationRemoved" ) ;
Log. i ( TAG , "ID :" + sbn.getId() + " \t " + sbn.getNotification(). tickerText + " \t " + sbn.getPackageName()) ;
myListener .setValue( "Remove: " + sbn.getPackageName()) ;
}
public void setListener (MyListener myListener) {
NotificationService. myListener = myListener ;
}
}
Step 4 − Add the following code to res/menu/menu_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<menu xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
tools :context = ".MainActivity" >
<item
android :id = "@+id/action_settings"
android :orderInCategory = "100"
android :title = "Settings"
app :showAsAction = "never" />
</menu>
Step 5 − Add the following code to res/layout/activity_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width = "match_parent"
android :layout_height = "match_parent"
android :padding = "16dp"
tools :context = ".MainActivity" >
<Button
android :id = "@+id/btnCreateNotification"
android :layout_width = "wrap_content"
android :layout_height = "wrap_content"
android :layout_alignParentStart = "true"
android :layout_alignParentTop = "true"
android :layout_alignParentEnd = "true"
android :text = "Create Notification" />
<ScrollView
android :layout_width = "match_parent"
android :layout_height = "match_parent"
android :layout_below = "@+id/btnCreateNotification"
android :layout_alignStart = "@+id/btnCreateNotification"
android :layout_alignEnd = "@+id/btnCreateNotification"
android :layout_alignParentBottom = "true" >
<TextView
android :id= "@+id/textView"
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :text= "NotificationListenerService Example"
android :textAppearance= "?android:attr/textAppearanceMedium" />
</ScrollView>
</RelativeLayout>
Step 6 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.content.Intent ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.Menu ;
import android.view.MenuItem ;
import android.view.View ;
import android.widget.Button ;
import android.widget.TextView ;
public class MainActivity extends AppCompatActivity implements MyListener {
private TextView txtView ;
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
new NotificationService().setListener( this ) ;
txtView = findViewById(R.id. textView ) ;
Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;
btnCreateNotification.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick (View v) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
mBuilder.setContentTitle( "My Notification" ) ;
mBuilder.setContentText( "Notification Listener Service Example" ) ;
mBuilder.setTicker( "Notification Listener Service Example" ) ;
mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
mBuilder.setAutoCancel( true ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
}
}) ;
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu. menu_main , menu) ; //Menu Resource, Menu
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id. action_settings :
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS" ) ;
startActivity(intent) ;
return true;
default :
return super .onOptionsItemSelected(item) ;
}
}
@Override
public void setValue (String packageName) {
txtView .append( " \n " + packageName) ;
}
}
Step 7 − Add the following code to AndroidManifest.xml
<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package = "app.tutorialspoint.com.notifyme" >
<uses-permission android :name = "android.permission.VIBRATE" />
<application
android :allowBackup = "true"
android :icon = "@mipmap/ic_launcher"
android :label = "@string/app_name"
android :roundIcon = "@mipmap/ic_launcher_round"
android :supportsRtl = "true"
android :theme = "@style/AppTheme" >
<activity android :name = ".MainActivity" >
<intent-filter>
<action android :name = "android.intent.action.MAIN" />
<category android :name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android :name = ".NotificationService"
android :label = "@string/app_name"
android :permission = "android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
<intent-filter>
<action android :name = "android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "This example demonstrate about How to detect a new Android notification"
},
{
"code": null,
"e": 1263,
"s": 1134,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1318,
"s": 1263,
"text": "Step 2 − Add the following code to src/MyListener.java"
},
{
"code": null,
"e": 1390,
"s": 1318,
"text": "public interface MyListener {\n void setValue (String packageName) ;\n}"
},
{
"code": null,
"e": 1445,
"s": 1390,
"text": "Step 3 − Add the following code to src/MyListener.java"
},
{
"code": null,
"e": 2745,
"s": 1445,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.content.Context ;\nimport android.service.notification.NotificationListenerService ;\nimport android.service.notification.StatusBarNotification ;\nimport android.util.Log ;\npublic class NotificationService extends NotificationListenerService {\n private String TAG = this .getClass().getSimpleName() ;\n Context context ;\n static MyListener myListener ;\n @Override\n public void onCreate () {\n super .onCreate() ;\n context = getApplicationContext() ;\n }\n @Override\n public void onNotificationPosted (StatusBarNotification sbn) {\n Log. i ( TAG , \"********** onNotificationPosted\" ) ;\n Log. i ( TAG , \"ID :\" + sbn.getId() + \" \\t \" + sbn.getNotification(). tickerText + \" \\t \" + sbn.getPackageName()) ;\n myListener .setValue( \"Post: \" + sbn.getPackageName()) ;\n }\n @Override\n public void onNotificationRemoved (StatusBarNotification sbn) {\n Log. i ( TAG , \"********** onNotificationRemoved\" ) ;\n Log. i ( TAG , \"ID :\" + sbn.getId() + \" \\t \" + sbn.getNotification(). tickerText + \" \\t \" + sbn.getPackageName()) ;\n myListener .setValue( \"Remove: \" + sbn.getPackageName()) ;\n }\n public void setListener (MyListener myListener) {\n NotificationService. myListener = myListener ;\n }\n}"
},
{
"code": null,
"e": 2804,
"s": 2745,
"text": "Step 4 − Add the following code to res/menu/menu_main.xml."
},
{
"code": null,
"e": 3236,
"s": 2804,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<menu xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n tools :context = \".MainActivity\" >\n <item\n android :id = \"@+id/action_settings\"\n android :orderInCategory = \"100\"\n android :title = \"Settings\"\n app :showAsAction = \"never\" />\n</menu>"
},
{
"code": null,
"e": 3301,
"s": 3236,
"text": "Step 5 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 4629,
"s": 3301,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :padding = \"16dp\"\n tools :context = \".MainActivity\" >\n <Button\n android :id = \"@+id/btnCreateNotification\"\n android :layout_width = \"wrap_content\"\n android :layout_height = \"wrap_content\"\n android :layout_alignParentStart = \"true\"\n android :layout_alignParentTop = \"true\"\n android :layout_alignParentEnd = \"true\"\n android :text = \"Create Notification\" />\n <ScrollView\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :layout_below = \"@+id/btnCreateNotification\"\n android :layout_alignStart = \"@+id/btnCreateNotification\"\n android :layout_alignEnd = \"@+id/btnCreateNotification\"\n android :layout_alignParentBottom = \"true\" >\n <TextView\n android :id= \"@+id/textView\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :text= \"NotificationListenerService Example\"\n android :textAppearance= \"?android:attr/textAppearanceMedium\" />\n </ScrollView>\n</RelativeLayout>"
},
{
"code": null,
"e": 4686,
"s": 4629,
"text": "Step 6 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 7826,
"s": 4686,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.Menu ;\nimport android.view.MenuItem ;\nimport android.view.View ;\nimport android.widget.Button ;\nimport android.widget.TextView ;\npublic class MainActivity extends AppCompatActivity implements MyListener {\n private TextView txtView ;\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n new NotificationService().setListener( this ) ;\n txtView = findViewById(R.id. textView ) ;\n Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;\n btnCreateNotification.setOnClickListener( new View.OnClickListener() {\n @Override\n public void onClick (View v) {\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setTicker( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n }\n }) ;\n }\n @Override\n public boolean onCreateOptionsMenu (Menu menu) {\n getMenuInflater().inflate(R.menu. menu_main , menu) ; //Menu Resource, Menu\n return true;\n }\n @Override\n public boolean onOptionsItemSelected (MenuItem item) {\n switch (item.getItemId()) {\n case R.id. action_settings :\n Intent intent = new Intent(\"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS\" ) ;\n startActivity(intent) ;\n return true;\n default :\n return super .onOptionsItemSelected(item) ;\n }\n }\n @Override\n public void setValue (String packageName) {\n txtView .append( \" \\n \" + packageName) ;\n }\n}"
},
{
"code": null,
"e": 7881,
"s": 7826,
"text": "Step 7 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 9043,
"s": 7881,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service\n android :name = \".NotificationService\"\n android :label = \"@string/app_name\"\n android :permission = \"android.permission.BIND_NOTIFICATION_LISTENER_SERVICE\" >\n <intent-filter>\n <action android :name = \"android.service.notification.NotificationListenerService\" />\n </intent-filter>\n </service>\n </application>\n</manifest>"
},
{
"code": null,
"e": 9390,
"s": 9043,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 9432,
"s": 9390,
"text": "Click here to download the project code"
}
] |
Easy string | Practice | GeeksforGeeks | You are given the string S . Compress the string when lower and upper cases are the same. In compressed string characters should be in lowercase.
Example 1:
Input: S = "aaABBb"
Output: "3a3b"
Explanation: As 'a' appears 3 times
consecutively and 'b' also 3 times,
and 'b' and 'B' considered as same.
​Example 2:
Input: S = "aaacca"
Output: "3a2c1a"
Explanation: As 'a' appears 3 times
consecutively and 'c' also 2 times,
and then 'a' 1 time.
Your Task:
You don't need to read input or print anything. Your task is to complete the function transform() which takes the string S as inputs and returns the compressed string.
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ |S| ≤ 2 * 105
S contains only lowercase and uppercase characters.
0
csedeepak5 days ago
string transform(string S){ //complete the function here string ans=""; for(int i=0; i<S.length(); i++){ char ch=tolower(S[i]); int cnt=0; while(ch==tolower(S[i])){ cnt++; i++; } i--; ans += to_string(cnt)+ch; } return ans;}
+1
jayanthnalluri3531 month ago
string transform(string S){ //conversion of all the character into lower cases for(int i=0;i<S.length();++i){ S[i]=S[i] | ' '; } stack<pair<char,int>> s; string ans=""; s.push(make_pair(S[0],1)); for(int i=1;i<S.length();++i) { if(S[i]==s.top().first) s.top().second++; else{ ans=ans+to_string(s.top().second)+s.top().first; s.pop(); s.push(make_pair(S[i],1)); } } return ans+to_string(s.top().second)+s.top().first;}
0
arpitkatiyar091972 months ago
USING STACK IN JAVA
Stack<Character> stk=new Stack<>(); StringBuilder strb=new StringBuilder(); S=S.toLowerCase(); // SOLUTION BY arpitkatiyar09197 for(int i=S.length()-1;i>=0;i--) { stk.push(S.charAt(i)); } while(!stk.isEmpty()) { char ch=stk.peek(); stk.pop(); int count=1; while(stk.size()>0 && ch==stk.peek()) { count++; stk.pop(); } strb.append((count+"")+ch); } return strb.toString();
0
arpitkatiyar091972 months ago
Using String Builder
JAVA SOLUTION
class Solution { String transform(String S) { S=S.toLowerCase(); /// Solution by arpitkatiyar09197 int count=1; StringBuilder strb=new StringBuilder(); int i=0; for(i=1;i<S.length();i++) { if(S.charAt(i)==S.charAt(i-1)) { count++; } else { strb.append((count+"")+S.charAt(i-1)); count=1; } } if(i-1==S.length()-1) { strb.append((count+"")+S.charAt(i-1)); } return strb.toString();
0
vrajeshmodi993 months ago
Time=0.4
string transform(string s){
stack<int>sti;
stack<char>stc;
int k=s.size();
for(int i=0;i<k;i++){
int n;
if(s[i]>='a' && s[i]<='z'){
n = s[i] - 'a';
}
else //(s[i]>='A' && s[i]<='Z')
{
n = s[i]-'A';
}
if(stc.empty()){
sti.push(1);
n=n+'a';
stc.push((char)n);
}
else if(stc.top()-'a' == n){
sti.top()++;
}
else //(stc.top()-'a' != n)
{
sti.push(1);
n=n+'a';
stc.push((char)n);
}
}
string str ="";
while(!stc.empty()){
string a = to_string(sti.top());
sti.pop();
str = a+stc.top()+str;
stc.pop();
}
return str;
}
0
snipperwolf3 months ago
def transform(self, S): # code here for i in S: if i.isupper(): S=S.replace(i,i.lower()) stack,l=[],[] for i in range(len(S)): if stack: if stack[-1]!=S[i]: l.append(len(stack)) l.append(stack.pop()) stack=[] stack.append(S[i]) else: stack.append(S[i]) else: stack.append(S[i]) if stack: l.append(len(stack)) l.append(stack.pop()) return "".join([str(i) for i in l])
0
rathoredivya1503 months ago
string transform(string S){int count; stack<char>s; for(int i=S.size()-1;i>=0;i--) { if(S[i]>='A'&&S[i]<='Z') { S[i]=S[i]+32; } s.push(S[i]); }string g; while(s.size()>0) { char ch=s.top(); s.pop(); count=1; if(s.size()>0&&s.top()==ch) { while(s.size()>0&&s.top()==ch) { count++; s.pop(); }
} g+=to_string(count); g+=ch;}
return g;}
0
nrk7863 months ago
string transform(string S){ //complete the function here for(int i=0;i<S.size();i++){ if(S[i]>='A' and S[i]<='Z') S[i]=S[i]+32; } S+=" "; stack<char> s; s.push(S[0]); string x=""; for(int i=1;i<S.length();i++){ if(S[i]==s.top()) s.push(S[i]); else{ char c=s.top(); int k=s.size(); while(!s.empty()) s.pop(); x+=to_string(k); x+=c; s.push(S[i]); } } return x;}
+1
praveenkumar1391523 months ago
def transform(self, S): S=S.lower() k="" l=[] l.append(S[0]) for i in S[1:]: if l[0]==i: l.append(i) else: k=k+str(len(l))+l[0] l.clear() l.append(i) return k+str(len(l))+l[0]
+1
vg714 months ago
string transform(string s){ //complete the function here int n=s.size(); transform(s.begin(), s.end(), s.begin(), ::tolower); string output=""; int i=0; int j=i+1; int count=1; if(n==1){ // string add=to_string(count); output+=to_string(count); output.push_back(s[0]); return output; } while(i<n and j<n){ if(s[i]==s[j]){ count+=1; j++; } else{ // string add=to_string(count); output+=to_string(count); output.push_back(s[i]); i=j; j++; count=1; } } if(i<n and j==n){ //string add=to_string(count); output+=to_string(count); output.push_back(s[i]); } return output;}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 384,
"s": 238,
"text": "You are given the string S . Compress the string when lower and upper cases are the same. In compressed string characters should be in lowercase."
},
{
"code": null,
"e": 395,
"s": 384,
"text": "Example 1:"
},
{
"code": null,
"e": 540,
"s": 395,
"text": "Input: S = \"aaABBb\"\nOutput: \"3a3b\"\nExplanation: As 'a' appears 3 times\nconsecutively and 'b' also 3 times,\nand 'b' and 'B' considered as same. \n"
},
{
"code": null,
"e": 555,
"s": 540,
"text": "​Example 2:"
},
{
"code": null,
"e": 685,
"s": 555,
"text": "Input: S = \"aaacca\"\nOutput: \"3a2c1a\"\nExplanation: As 'a' appears 3 times\nconsecutively and 'c' also 2 times,\nand then 'a' 1 time."
},
{
"code": null,
"e": 866,
"s": 685,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function transform() which takes the string S as inputs and returns the compressed string."
},
{
"code": null,
"e": 963,
"s": 866,
"text": "\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 ≤ |S| ≤ 2 * 105"
},
{
"code": null,
"e": 1015,
"s": 963,
"text": "S contains only lowercase and uppercase characters."
},
{
"code": null,
"e": 1017,
"s": 1015,
"text": "0"
},
{
"code": null,
"e": 1037,
"s": 1017,
"text": "csedeepak5 days ago"
},
{
"code": null,
"e": 1337,
"s": 1037,
"text": "string transform(string S){ //complete the function here string ans=\"\"; for(int i=0; i<S.length(); i++){ char ch=tolower(S[i]); int cnt=0; while(ch==tolower(S[i])){ cnt++; i++; } i--; ans += to_string(cnt)+ch; } return ans;} "
},
{
"code": null,
"e": 1340,
"s": 1337,
"text": "+1"
},
{
"code": null,
"e": 1369,
"s": 1340,
"text": "jayanthnalluri3531 month ago"
},
{
"code": null,
"e": 1858,
"s": 1369,
"text": "string transform(string S){ //conversion of all the character into lower cases for(int i=0;i<S.length();++i){ S[i]=S[i] | ' '; } stack<pair<char,int>> s; string ans=\"\"; s.push(make_pair(S[0],1)); for(int i=1;i<S.length();++i) { if(S[i]==s.top().first) s.top().second++; else{ ans=ans+to_string(s.top().second)+s.top().first; s.pop(); s.push(make_pair(S[i],1)); } } return ans+to_string(s.top().second)+s.top().first;}"
},
{
"code": null,
"e": 1860,
"s": 1858,
"text": "0"
},
{
"code": null,
"e": 1890,
"s": 1860,
"text": "arpitkatiyar091972 months ago"
},
{
"code": null,
"e": 1911,
"s": 1890,
"text": "USING STACK IN JAVA "
},
{
"code": null,
"e": 2494,
"s": 1913,
"text": "Stack<Character> stk=new Stack<>(); StringBuilder strb=new StringBuilder(); S=S.toLowerCase(); // SOLUTION BY arpitkatiyar09197 for(int i=S.length()-1;i>=0;i--) { stk.push(S.charAt(i)); } while(!stk.isEmpty()) { char ch=stk.peek(); stk.pop(); int count=1; while(stk.size()>0 && ch==stk.peek()) { count++; stk.pop(); } strb.append((count+\"\")+ch); } return strb.toString(); "
},
{
"code": null,
"e": 2496,
"s": 2494,
"text": "0"
},
{
"code": null,
"e": 2526,
"s": 2496,
"text": "arpitkatiyar091972 months ago"
},
{
"code": null,
"e": 2547,
"s": 2526,
"text": "Using String Builder"
},
{
"code": null,
"e": 2561,
"s": 2547,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 3156,
"s": 2561,
"text": " class Solution { String transform(String S) { S=S.toLowerCase(); /// Solution by arpitkatiyar09197 int count=1; StringBuilder strb=new StringBuilder(); int i=0; for(i=1;i<S.length();i++) { if(S.charAt(i)==S.charAt(i-1)) { count++; } else { strb.append((count+\"\")+S.charAt(i-1)); count=1; } } if(i-1==S.length()-1) { strb.append((count+\"\")+S.charAt(i-1)); } return strb.toString();"
},
{
"code": null,
"e": 3158,
"s": 3156,
"text": "0"
},
{
"code": null,
"e": 3184,
"s": 3158,
"text": "vrajeshmodi993 months ago"
},
{
"code": null,
"e": 3193,
"s": 3184,
"text": "Time=0.4"
},
{
"code": null,
"e": 4017,
"s": 3195,
"text": "string transform(string s){\n stack<int>sti;\n stack<char>stc;\n int k=s.size();\n \n for(int i=0;i<k;i++){\n int n;\n if(s[i]>='a' && s[i]<='z'){\n n = s[i] - 'a';\n }\n \n else //(s[i]>='A' && s[i]<='Z')\n { \n n = s[i]-'A';\n }\n \n if(stc.empty()){\n sti.push(1);\n n=n+'a';\n stc.push((char)n);\n }\n \n else if(stc.top()-'a' == n){\n sti.top()++;\n }\n else //(stc.top()-'a' != n)\n {\n sti.push(1);\n n=n+'a';\n stc.push((char)n);\n }\n \n }\n \n string str =\"\";\n while(!stc.empty()){\n string a = to_string(sti.top());\n sti.pop();\n str = a+stc.top()+str;\n stc.pop();\n }\n return str;\n}"
},
{
"code": null,
"e": 4019,
"s": 4017,
"text": "0"
},
{
"code": null,
"e": 4043,
"s": 4019,
"text": "snipperwolf3 months ago"
},
{
"code": null,
"e": 4642,
"s": 4043,
"text": "def transform(self, S): # code here for i in S: if i.isupper(): S=S.replace(i,i.lower()) stack,l=[],[] for i in range(len(S)): if stack: if stack[-1]!=S[i]: l.append(len(stack)) l.append(stack.pop()) stack=[] stack.append(S[i]) else: stack.append(S[i]) else: stack.append(S[i]) if stack: l.append(len(stack)) l.append(stack.pop()) return \"\".join([str(i) for i in l])"
},
{
"code": null,
"e": 4644,
"s": 4642,
"text": "0"
},
{
"code": null,
"e": 4672,
"s": 4644,
"text": "rathoredivya1503 months ago"
},
{
"code": null,
"e": 5083,
"s": 4672,
"text": "string transform(string S){int count; stack<char>s; for(int i=S.size()-1;i>=0;i--) { if(S[i]>='A'&&S[i]<='Z') { S[i]=S[i]+32; } s.push(S[i]); }string g; while(s.size()>0) { char ch=s.top(); s.pop(); count=1; if(s.size()>0&&s.top()==ch) { while(s.size()>0&&s.top()==ch) { count++; s.pop(); }"
},
{
"code": null,
"e": 5149,
"s": 5083,
"text": " } g+=to_string(count); g+=ch;}"
},
{
"code": null,
"e": 5170,
"s": 5149,
"text": " return g;} "
},
{
"code": null,
"e": 5172,
"s": 5170,
"text": "0"
},
{
"code": null,
"e": 5191,
"s": 5172,
"text": "nrk7863 months ago"
},
{
"code": null,
"e": 5681,
"s": 5191,
"text": "string transform(string S){ //complete the function here for(int i=0;i<S.size();i++){ if(S[i]>='A' and S[i]<='Z') S[i]=S[i]+32; } S+=\" \"; stack<char> s; s.push(S[0]); string x=\"\"; for(int i=1;i<S.length();i++){ if(S[i]==s.top()) s.push(S[i]); else{ char c=s.top(); int k=s.size(); while(!s.empty()) s.pop(); x+=to_string(k); x+=c; s.push(S[i]); } } return x;}"
},
{
"code": null,
"e": 5684,
"s": 5681,
"text": "+1"
},
{
"code": null,
"e": 5715,
"s": 5684,
"text": "praveenkumar1391523 months ago"
},
{
"code": null,
"e": 6028,
"s": 5715,
"text": " def transform(self, S): S=S.lower() k=\"\" l=[] l.append(S[0]) for i in S[1:]: if l[0]==i: l.append(i) else: k=k+str(len(l))+l[0] l.clear() l.append(i) return k+str(len(l))+l[0] "
},
{
"code": null,
"e": 6031,
"s": 6028,
"text": "+1"
},
{
"code": null,
"e": 6048,
"s": 6031,
"text": "vg714 months ago"
},
{
"code": null,
"e": 6793,
"s": 6048,
"text": "string transform(string s){ //complete the function here int n=s.size(); transform(s.begin(), s.end(), s.begin(), ::tolower); string output=\"\"; int i=0; int j=i+1; int count=1; if(n==1){ // string add=to_string(count); output+=to_string(count); output.push_back(s[0]); return output; } while(i<n and j<n){ if(s[i]==s[j]){ count+=1; j++; } else{ // string add=to_string(count); output+=to_string(count); output.push_back(s[i]); i=j; j++; count=1; } } if(i<n and j==n){ //string add=to_string(count); output+=to_string(count); output.push_back(s[i]); } return output;} "
},
{
"code": null,
"e": 6939,
"s": 6793,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6975,
"s": 6939,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6985,
"s": 6975,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6995,
"s": 6985,
"text": "\nContest\n"
},
{
"code": null,
"e": 7058,
"s": 6995,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7206,
"s": 7058,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7414,
"s": 7206,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 7520,
"s": 7414,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
SQL Query to Get Yesterday and Tomorrow | 08 Apr, 2021
Queries help the users to interact with a database for creating, insertion, deleting, updating data in a database with different queries.
In this article let us see how to get yesterday and tomorrow with respect to the given dates in the database.
Example –
Given date: 2021-03-23Yesterday: 2021-03-22 MondayTomorrow: 2021-03-24 Wednesday
Creating a database calendar:
CREATE DATABASE calendar;
Using the database calendar
USE calendar;
Creating a Table schedule:
CREATE TABLE schedule
(dates date);
Viewing the description of the table:
DESCRIBE schedule;
Inserting rows into the schedule:
INSERT INTO schedule VALUES('2021-03-23');
INSERT INTO schedule VALUES('2020-08-04');
INSERT INTO schedule VALUES('2021-06-08');
INSERT INTO schedule VALUES('2030-04-04');
INSERT INTO schedule VALUES('2025-09-13');
Viewing the data in the table:
SELECT* FROM schedule;
Query to get the yesterday and tomorrow of current date:
To get the yesterday and tomorrow of the current date we can use the CURRDATE() function in MySQL and subtract 1 from it to get yesterday and add 1 to it to get tomorrow.
SELECT CURDATE(),
DATE_SUB(CURDATE(),INTERVAL 1 DAY) AS yesterday,
DATE_ADD(CURDATE(),INTERVAL 1 DAY) AS tomorrow;
Here we can change the default column header to some other name by using AS.
Example1:
Query to get yesterday and tomorrow of dates in the table:
Syntax:SELECT CURDATE(),DATE_SUB(CURDATE(),INTERVAL 1 DAY) AS some_nameDATE_ADD(CURDATE(),INTERVAL 1 DAY) AS some_name;
SELECT dates,
DATE_SUB(dates,INTERVAL 1 DAY) AS yesterday,
DATE_ADD(dates,INTERVAL 1 DAY) AS tomorrow
FROM schedule;
Example2:
Query to get the yesterday and tomorrow dates in the table with weekdays:
Syntax:
SELECT column_name,DATE_SUB(column_name,INTERVAL 1 DAY) AS some_name,DATE_ADD(column_name,INTERVAL 1 DAY) AS some_name,DAYNAME(current_date),DAYNAME(previous_day),DAYNAME(next_day);
SELECT dates,
DATE_SUB(dates,INTERVAL 1 DAY) AS yesterday,
DATE_ADD(dates,INTERVAL 1 DAY) AS tomorrow,
DAYNAME(dates) AS weekdayofdate,
DAYNAME(DATE_SUB(dates,INTERVAL 1 DAY)) AS weekdayofYd,
DAYNAME( DATE_ADD(dates,INTERVAL 1 DAY)) AS weekdayofTm
FROM schedule;
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "Queries help the users to interact with a database for creating, insertion, deleting, updating data in a database with different queries."
},
{
"code": null,
"e": 276,
"s": 166,
"text": "In this article let us see how to get yesterday and tomorrow with respect to the given dates in the database."
},
{
"code": null,
"e": 286,
"s": 276,
"text": "Example –"
},
{
"code": null,
"e": 367,
"s": 286,
"text": "Given date: 2021-03-23Yesterday: 2021-03-22 MondayTomorrow: 2021-03-24 Wednesday"
},
{
"code": null,
"e": 397,
"s": 367,
"text": "Creating a database calendar:"
},
{
"code": null,
"e": 423,
"s": 397,
"text": "CREATE DATABASE calendar;"
},
{
"code": null,
"e": 451,
"s": 423,
"text": "Using the database calendar"
},
{
"code": null,
"e": 465,
"s": 451,
"text": "USE calendar;"
},
{
"code": null,
"e": 492,
"s": 465,
"text": "Creating a Table schedule:"
},
{
"code": null,
"e": 528,
"s": 492,
"text": "CREATE TABLE schedule\n(dates date);"
},
{
"code": null,
"e": 566,
"s": 528,
"text": "Viewing the description of the table:"
},
{
"code": null,
"e": 585,
"s": 566,
"text": "DESCRIBE schedule;"
},
{
"code": null,
"e": 619,
"s": 585,
"text": "Inserting rows into the schedule:"
},
{
"code": null,
"e": 837,
"s": 619,
"text": "INSERT INTO schedule VALUES('2021-03-23');\nINSERT INTO schedule VALUES('2020-08-04');\nINSERT INTO schedule VALUES('2021-06-08');\nINSERT INTO schedule VALUES('2030-04-04');\nINSERT INTO schedule VALUES('2025-09-13');\n "
},
{
"code": null,
"e": 868,
"s": 837,
"text": "Viewing the data in the table:"
},
{
"code": null,
"e": 891,
"s": 868,
"text": "SELECT* FROM schedule;"
},
{
"code": null,
"e": 948,
"s": 891,
"text": "Query to get the yesterday and tomorrow of current date:"
},
{
"code": null,
"e": 1119,
"s": 948,
"text": "To get the yesterday and tomorrow of the current date we can use the CURRDATE() function in MySQL and subtract 1 from it to get yesterday and add 1 to it to get tomorrow."
},
{
"code": null,
"e": 1242,
"s": 1119,
"text": "SELECT CURDATE(),\n DATE_SUB(CURDATE(),INTERVAL 1 DAY) AS yesterday,\n DATE_ADD(CURDATE(),INTERVAL 1 DAY) AS tomorrow;"
},
{
"code": null,
"e": 1319,
"s": 1242,
"text": "Here we can change the default column header to some other name by using AS."
},
{
"code": null,
"e": 1330,
"s": 1319,
"text": "Example1: "
},
{
"code": null,
"e": 1389,
"s": 1330,
"text": "Query to get yesterday and tomorrow of dates in the table:"
},
{
"code": null,
"e": 1509,
"s": 1389,
"text": "Syntax:SELECT CURDATE(),DATE_SUB(CURDATE(),INTERVAL 1 DAY) AS some_nameDATE_ADD(CURDATE(),INTERVAL 1 DAY) AS some_name;"
},
{
"code": null,
"e": 1642,
"s": 1509,
"text": " SELECT dates,\n DATE_SUB(dates,INTERVAL 1 DAY) AS yesterday,\n DATE_ADD(dates,INTERVAL 1 DAY) AS tomorrow\n FROM schedule;"
},
{
"code": null,
"e": 1653,
"s": 1642,
"text": "Example2: "
},
{
"code": null,
"e": 1727,
"s": 1653,
"text": "Query to get the yesterday and tomorrow dates in the table with weekdays:"
},
{
"code": null,
"e": 1735,
"s": 1727,
"text": "Syntax:"
},
{
"code": null,
"e": 1918,
"s": 1735,
"text": "SELECT column_name,DATE_SUB(column_name,INTERVAL 1 DAY) AS some_name,DATE_ADD(column_name,INTERVAL 1 DAY) AS some_name,DAYNAME(current_date),DAYNAME(previous_day),DAYNAME(next_day); "
},
{
"code": null,
"e": 2213,
"s": 1918,
"text": " SELECT dates,\n DATE_SUB(dates,INTERVAL 1 DAY) AS yesterday,\n DATE_ADD(dates,INTERVAL 1 DAY) AS tomorrow,\n DAYNAME(dates) AS weekdayofdate,\n DAYNAME(DATE_SUB(dates,INTERVAL 1 DAY)) AS weekdayofYd,\n DAYNAME( DATE_ADD(dates,INTERVAL 1 DAY)) AS weekdayofTm\n FROM schedule;"
},
{
"code": null,
"e": 2254,
"s": 2245,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2261,
"s": 2254,
"text": "Picked"
},
{
"code": null,
"e": 2265,
"s": 2261,
"text": "SQL"
},
{
"code": null,
"e": 2269,
"s": 2265,
"text": "SQL"
},
{
"code": null,
"e": 2367,
"s": 2269,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2433,
"s": 2367,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2457,
"s": 2433,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2489,
"s": 2457,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2522,
"s": 2489,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2539,
"s": 2522,
"text": "SQL using Python"
},
{
"code": null,
"e": 2569,
"s": 2539,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2647,
"s": 2569,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2683,
"s": 2647,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2714,
"s": 2683,
"text": "SQL Query to Compare Two Dates"
}
] |
How to get the Highlighted/Selected text in JavaScript? | 15 Mar, 2021
There may be a need to find out the text selected/highlighted by the user. It can be done very easily using the window and document objects and their properties. Handling selected text is different for different browsers. The ways to get selected text are shown below:
Example-1: By using window.getSelection property
function selection(){
if (window.getSelection)
return window.getSelection();
}
Example 2: By using document.getSelection property
function selection(){
if (document.getSelection)
return document.getSelection();
}
Example 3: By using document.selection property
function selection(){
if (document.selection)
return document.selection.createRange().text;;
}
Time to try out the code. Run the code, select a text and press the button to show the selected text:Example:
<html> <head> <title>Selected Text</title></head> <body> <center> <h1 style=color:green> GeeksforGeeks </h1> <script> // Function to get the Selected Text function getSelectedText() { var selectedText = ''; // window.getSelection if (window.getSelection) { selectedText = window.getSelection(); } // document.getSelection else if (document.getSelection) { selectedText = document.getSelection(); } // document.selection else if (document.selection) { selectedText = document.selection.createRange().text; } else return; // To write the selected text into the textarea document.testform.selectedtext.value = selectedText; } </script> <p>Select any part of this sentence and press the button</p> <!--Button to invoke the function to get the selected text--> <input type="button" value="Get Selection" onmousedown="getSelectedText()"> <!--Form to show the selected text as output--> <form name="testform"> <textarea name="selectedtext" rows="5" cols="20"></textarea> </form> </center></body> </html>
Output:Before:After:
JavaScript-Misc
Picked
JavaScript
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": "\n15 Mar, 2021"
},
{
"code": null,
"e": 297,
"s": 28,
"text": "There may be a need to find out the text selected/highlighted by the user. It can be done very easily using the window and document objects and their properties. Handling selected text is different for different browsers. The ways to get selected text are shown below:"
},
{
"code": null,
"e": 346,
"s": 297,
"text": "Example-1: By using window.getSelection property"
},
{
"code": null,
"e": 433,
"s": 346,
"text": "function selection(){\nif (window.getSelection)\n return window.getSelection();\n}\n"
},
{
"code": null,
"e": 484,
"s": 433,
"text": "Example 2: By using document.getSelection property"
},
{
"code": null,
"e": 575,
"s": 484,
"text": "function selection(){\nif (document.getSelection)\n return document.getSelection();\n}\n"
},
{
"code": null,
"e": 623,
"s": 575,
"text": "Example 3: By using document.selection property"
},
{
"code": null,
"e": 726,
"s": 623,
"text": "function selection(){\nif (document.selection)\n return document.selection.createRange().text;;\n}\n"
},
{
"code": null,
"e": 836,
"s": 726,
"text": "Time to try out the code. Run the code, select a text and press the button to show the selected text:Example:"
},
{
"code": "<html> <head> <title>Selected Text</title></head> <body> <center> <h1 style=color:green> GeeksforGeeks </h1> <script> // Function to get the Selected Text function getSelectedText() { var selectedText = ''; // window.getSelection if (window.getSelection) { selectedText = window.getSelection(); } // document.getSelection else if (document.getSelection) { selectedText = document.getSelection(); } // document.selection else if (document.selection) { selectedText = document.selection.createRange().text; } else return; // To write the selected text into the textarea document.testform.selectedtext.value = selectedText; } </script> <p>Select any part of this sentence and press the button</p> <!--Button to invoke the function to get the selected text--> <input type=\"button\" value=\"Get Selection\" onmousedown=\"getSelectedText()\"> <!--Form to show the selected text as output--> <form name=\"testform\"> <textarea name=\"selectedtext\" rows=\"5\" cols=\"20\"></textarea> </form> </center></body> </html>",
"e": 2328,
"s": 836,
"text": null
},
{
"code": null,
"e": 2349,
"s": 2328,
"text": "Output:Before:After:"
},
{
"code": null,
"e": 2365,
"s": 2349,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2372,
"s": 2365,
"text": "Picked"
},
{
"code": null,
"e": 2383,
"s": 2372,
"text": "JavaScript"
},
{
"code": null,
"e": 2400,
"s": 2383,
"text": "Web Technologies"
}
] |
Convert a NumPy array to an image | 02 Sep, 2020
NumPy Or numeric python is a popular library for array manipulation. Since images are just an array of pixels carrying various color codes. NumPy can be used to convert an array into image. Apart from NumPy we will be using PIL or Python Image Library also known as Pillow to manipulate and save arrays.
Approach:
Create a numpy array.Reshape the above array to suitable dimensions.Create an image object from the above array using PIL library.Save the image object in a suitable file format.
Create a numpy array.
Reshape the above array to suitable dimensions.
Create an image object from the above array using PIL library.
Save the image object in a suitable file format.
Below is the implementation:
Python3
# Python program to convert# numpy array to image # import required librariesimport numpy as npfrom PIL import Image as im # define a main functiondef main(): # create a numpy array from scratch # using arange function. # 1024x720 = 737280 is the amount # of pixels. # np.uint8 is a data type containing # numbers ranging from 0 to 255 # and no non-negative integers array = np.arange(0, 737280, 1, np.uint8) # check type of array print(type(array)) # our array will be of width # 737280 pixels That means it # will be a long dark line print(array.shape) # Reshape the array into a # familiar resoluition array = np.reshape(array, (1024, 720)) # show the shape of the array print(array.shape) # show the array print(array) # creating image object of # above array data = im.fromarray(array) # saving the final output # as a PNG file data.save('gfg_dummy_pic.png') # driver codeif __name__ == "__main__": # function call main()
Output:
<class 'numpy.ndarray'>
(737280,)
(1024, 720)
[[ 0 1 2 ... 205 206 207]
[208 209 210 ... 157 158 159]
[160 161 162 ... 109 110 111]
...
[144 145 146 ... 93 94 95]
[ 96 97 98 ... 45 46 47]
[ 48 49 50 ... 253 254 255]]
gfg_dummy_pic.png 1024 x 720
Note: Every array can’t be converted into an image because each pixel of an image consist of specific color code and if the given array is not in a suitable format the libraries won’t be able to process it Properly.
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "NumPy Or numeric python is a popular library for array manipulation. Since images are just an array of pixels carrying various color codes. NumPy can be used to convert an array into image. Apart from NumPy we will be using PIL or Python Image Library also known as Pillow to manipulate and save arrays."
},
{
"code": null,
"e": 342,
"s": 332,
"text": "Approach:"
},
{
"code": null,
"e": 521,
"s": 342,
"text": "Create a numpy array.Reshape the above array to suitable dimensions.Create an image object from the above array using PIL library.Save the image object in a suitable file format."
},
{
"code": null,
"e": 543,
"s": 521,
"text": "Create a numpy array."
},
{
"code": null,
"e": 591,
"s": 543,
"text": "Reshape the above array to suitable dimensions."
},
{
"code": null,
"e": 654,
"s": 591,
"text": "Create an image object from the above array using PIL library."
},
{
"code": null,
"e": 703,
"s": 654,
"text": "Save the image object in a suitable file format."
},
{
"code": null,
"e": 732,
"s": 703,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 740,
"s": 732,
"text": "Python3"
},
{
"code": "# Python program to convert# numpy array to image # import required librariesimport numpy as npfrom PIL import Image as im # define a main functiondef main(): # create a numpy array from scratch # using arange function. # 1024x720 = 737280 is the amount # of pixels. # np.uint8 is a data type containing # numbers ranging from 0 to 255 # and no non-negative integers array = np.arange(0, 737280, 1, np.uint8) # check type of array print(type(array)) # our array will be of width # 737280 pixels That means it # will be a long dark line print(array.shape) # Reshape the array into a # familiar resoluition array = np.reshape(array, (1024, 720)) # show the shape of the array print(array.shape) # show the array print(array) # creating image object of # above array data = im.fromarray(array) # saving the final output # as a PNG file data.save('gfg_dummy_pic.png') # driver codeif __name__ == \"__main__\": # function call main()",
"e": 1803,
"s": 740,
"text": null
},
{
"code": null,
"e": 1811,
"s": 1803,
"text": "Output:"
},
{
"code": null,
"e": 2050,
"s": 1811,
"text": "<class 'numpy.ndarray'>\n(737280,)\n(1024, 720)\n[[ 0 1 2 ... 205 206 207]\n [208 209 210 ... 157 158 159]\n [160 161 162 ... 109 110 111]\n ...\n [144 145 146 ... 93 94 95]\n [ 96 97 98 ... 45 46 47]\n [ 48 49 50 ... 253 254 255]]\n"
},
{
"code": null,
"e": 2089,
"s": 2050,
"text": " gfg_dummy_pic.png 1024 x 720 "
},
{
"code": null,
"e": 2305,
"s": 2089,
"text": "Note: Every array can’t be converted into an image because each pixel of an image consist of specific color code and if the given array is not in a suitable format the libraries won’t be able to process it Properly."
},
{
"code": null,
"e": 2336,
"s": 2305,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 2349,
"s": 2336,
"text": "Python-numpy"
},
{
"code": null,
"e": 2356,
"s": 2349,
"text": "Python"
},
{
"code": null,
"e": 2454,
"s": 2356,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2472,
"s": 2454,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2514,
"s": 2472,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2536,
"s": 2514,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2571,
"s": 2536,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2597,
"s": 2571,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2629,
"s": 2597,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2658,
"s": 2629,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2688,
"s": 2658,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2715,
"s": 2688,
"text": "Python Classes and Objects"
}
] |
Implement Various Types of Partitions in Quick Sort in Java | 07 Aug, 2021
Quicksort is a Divide and Conquer Algorithm that is used for sorting the elements. In this algorithm, we choose a pivot and partitions the given array according to the pivot. Quicksort algorithm is a mostly used algorithm because this algorithm is cache-friendly and performs in-place sorting of the elements means no extra space requires for sorting the elements.
Note:
Quicksort algorithm is generally unstable algorithm because quick sort cannot be able to maintain the relative order of the elements.
Three partitions are possible for the Quicksort algorithm:
Naive partition: In this partition helps to maintain the relative order of the elements but this partition takes O(n) extra space.Lomuto partition: In this partition, The last element chooses as a pivot in this partition. The pivot acquires its required position after partition but more comparison takes place in this partition.Hoare’s partition: In this partition, The first element chooses as a pivot in this partition. The pivot displaces its required position after partition but less comparison takes place as compared to the Lomuto partition.
Naive partition: In this partition helps to maintain the relative order of the elements but this partition takes O(n) extra space.
Lomuto partition: In this partition, The last element chooses as a pivot in this partition. The pivot acquires its required position after partition but more comparison takes place in this partition.
Hoare’s partition: In this partition, The first element chooses as a pivot in this partition. The pivot displaces its required position after partition but less comparison takes place as compared to the Lomuto partition.
1. Naive partition
Algorithm:
Naivepartition(arr[],l,r)
1. Make a Temporary array temp[r-l+1] length
2. Choose last element as a pivot element
3. Run two loops:
-> Store all the elements in the temp array that are less than pivot element
-> Store the pivot element
-> Store all the elements in the temp array that are greater than pivot element.
4.Update all the elements of arr[] with the temp[] array
QuickSort(arr[], l, r)
If r > l
1. Find the partition point of the array
m = Naivepartition(a,l,r)
2. Call Quicksort for less than partition point
Call Quicksort(arr, l, m-1)
3. Call Quicksort for greater than the partition point
Call Quicksort(arr, m+1, r)
Java
// Java program to demonstrate the naive partition// in quick sort import java.io.*;import java.util.*;public class GFG { static int partition(int a[], int start, int high) { // Creating temporary int temp[] = new int[(high - start) + 1]; // Choosing a pivot int pivot = a[high]; int index = 0; // smaller number for (int i = start; i <= high; ++i) { if (a[i] < pivot) { temp[index++] = a[i]; } } // pivot position int position = index; // Placing the pivot to its original position temp[index++] = pivot; for (int i = start; i <= high; ++i) { if (a[i] > pivot) { temp[index++] = a[i]; } } // Change the original array for (int i = start; i <= high; ++i) { a[i] = temp[i - start]; } // return the position of the pivot return position; } static void quicksort(int numbers[], int start, int end) { if (start < end) { int point = partition(numbers, start, end); quicksort(numbers, start, point - 1); quicksort(numbers, point + 1, end); } } // Function to print the array static void print(int numbers[]) { for (int a : numbers) { System.out.print(a + " "); } } public static void main(String[] args) { int numbers[] = { 3, 2, 1, 78, 9798, 97 }; // rearrange using naive partition quicksort(numbers, 0, numbers.length - 1); print(numbers); }}
1 2 3 78 97 9798
2. Lomuto partition
Lomuto’s Partition Algorithm (unstable algorithm)
Lomutopartition(arr[], lo, hi)
pivot = arr[hi]
i = lo // place for swapping
for j := lo to hi – 1 do
if arr[j] <= pivot then
swap arr[i] with arr[j]
i = i + 1
swap arr[i] with arr[hi]
return i
QuickSort(arr[], l, r)
If r > l
1. Find the partition point of the array
m =Lomutopartition(a,l,r)
2. Call Quicksort for less than partition point
Call Quicksort(arr, l, m-1)
3. Call Quicksort for greater than the partition point
Call Quicksort(arr, m+1, r)
Java
// Java program to demonstrate the Lomuto partition// in quick sort import java.util.*;public class GFG { static int sort(int numbers[], int start, int last) { int pivot = numbers[last]; int index = start - 1; int temp = 0; for (int i = start; i < last; ++i) { if (numbers[i] < pivot) { ++index; // swap the position temp = numbers[index]; numbers[index] = numbers[i]; numbers[i] = temp; } } int pivotposition = ++index; temp = numbers[index]; numbers[index] = pivot; numbers[last] = temp; return pivotposition; } static void quicksort(int numbers[], int start, int end) { if (start < end) { int pivot_position = sort(numbers, start, end); quicksort(numbers, start, pivot_position - 1); quicksort(numbers, pivot_position + 1, end); } } static void print(int numbers[]) { for (int a : numbers) { System.out.print(a + " "); } } public static void main(String[] args) { int numbers[] = { 4, 5, 1, 2, 4, 5, 6 }; quicksort(numbers, 0, numbers.length - 1); print(numbers); }}
1 2 4 4 5 5 6
3. Hoare’s Partition
Hoare’s Partition Scheme works by initializing two indexes that start at two ends, the two indexes move toward each other until an inversion is (A smaller value on the left side and a greater value on the right side) found. When an inversion is found, two values are swapped and the process is repeated.
Algorithm:
Hoarepartition(arr[], lo, hi)
pivot = arr[lo]
i = lo - 1 // Initialize left index
j = hi + 1 // Initialize right index
// Find a value in left side greater
// than pivot
do
i = i + 1
while arr[i] < pivot
// Find a value in right side smaller
// than pivot
do
j--;
while (arr[j] > pivot);
if i >= j then
return j
swap arr[i] with arr[j]
QuickSort(arr[], l, r)
If r > l
1. Find the partition point of the array
m =Hoarepartition(a,l,r)
2. Call Quicksort for less than partition point
Call Quicksort(arr, l, m)
3. Call Quicksort for greater than the partition point
Call Quicksort(arr, m+1, r)
Java
// Java implementation of QuickSort// using Hoare's partition scheme import java.io.*; class GFG { // This function takes first element as pivot, and // places all the elements smaller than the pivot on the // left side and all the elements greater than the pivot // on the right side. It returns the index of the last // element on the smaller side static int partition(int[] arr, int low, int high) { int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater // than or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller // than or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; // swap(arr[i], arr[j]); int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // The main function that // implements QuickSort // arr[] --> Array to be sorted, // low --> Starting index, // high --> Ending index static void quickSort(int[] arr, int low, int high) { if (low < high) { // pi is partitioning index, // arr[p] is now at right place int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); } } // Function to print an array static void printArray(int[] arr, int n) { for (int i = 0; i < n; ++i) System.out.print(" " + arr[i]); System.out.println(); } // Driver Code static public void main(String[] args) { int[] arr = { 10, 17, 18, 9, 11, 15 }; int n = arr.length; quickSort(arr, 0, n - 1); printArray(arr, n); }}
9 10 11 15 17 18
sagartomar9927
sumitgumber28
gabaa406
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
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": 54,
"s": 26,
"text": "\n07 Aug, 2021"
},
{
"code": null,
"e": 419,
"s": 54,
"text": "Quicksort is a Divide and Conquer Algorithm that is used for sorting the elements. In this algorithm, we choose a pivot and partitions the given array according to the pivot. Quicksort algorithm is a mostly used algorithm because this algorithm is cache-friendly and performs in-place sorting of the elements means no extra space requires for sorting the elements."
},
{
"code": null,
"e": 425,
"s": 419,
"text": "Note:"
},
{
"code": null,
"e": 559,
"s": 425,
"text": "Quicksort algorithm is generally unstable algorithm because quick sort cannot be able to maintain the relative order of the elements."
},
{
"code": null,
"e": 618,
"s": 559,
"text": "Three partitions are possible for the Quicksort algorithm:"
},
{
"code": null,
"e": 1168,
"s": 618,
"text": "Naive partition: In this partition helps to maintain the relative order of the elements but this partition takes O(n) extra space.Lomuto partition: In this partition, The last element chooses as a pivot in this partition. The pivot acquires its required position after partition but more comparison takes place in this partition.Hoare’s partition: In this partition, The first element chooses as a pivot in this partition. The pivot displaces its required position after partition but less comparison takes place as compared to the Lomuto partition."
},
{
"code": null,
"e": 1299,
"s": 1168,
"text": "Naive partition: In this partition helps to maintain the relative order of the elements but this partition takes O(n) extra space."
},
{
"code": null,
"e": 1499,
"s": 1299,
"text": "Lomuto partition: In this partition, The last element chooses as a pivot in this partition. The pivot acquires its required position after partition but more comparison takes place in this partition."
},
{
"code": null,
"e": 1720,
"s": 1499,
"text": "Hoare’s partition: In this partition, The first element chooses as a pivot in this partition. The pivot displaces its required position after partition but less comparison takes place as compared to the Lomuto partition."
},
{
"code": null,
"e": 1740,
"s": 1720,
"text": "1. Naive partition"
},
{
"code": null,
"e": 1751,
"s": 1740,
"text": "Algorithm:"
},
{
"code": null,
"e": 2467,
"s": 1751,
"text": "Naivepartition(arr[],l,r)\n\n1. Make a Temporary array temp[r-l+1] length\n2. Choose last element as a pivot element\n3. Run two loops:\n -> Store all the elements in the temp array that are less than pivot element\n -> Store the pivot element \n -> Store all the elements in the temp array that are greater than pivot element.\n4.Update all the elements of arr[] with the temp[] array \n\n\nQuickSort(arr[], l, r)\n\n\nIf r > l\n 1. Find the partition point of the array \n m = Naivepartition(a,l,r) \n 2. Call Quicksort for less than partition point \n Call Quicksort(arr, l, m-1)\n 3. Call Quicksort for greater than the partition point \n Call Quicksort(arr, m+1, r)"
},
{
"code": null,
"e": 2472,
"s": 2467,
"text": "Java"
},
{
"code": "// Java program to demonstrate the naive partition// in quick sort import java.io.*;import java.util.*;public class GFG { static int partition(int a[], int start, int high) { // Creating temporary int temp[] = new int[(high - start) + 1]; // Choosing a pivot int pivot = a[high]; int index = 0; // smaller number for (int i = start; i <= high; ++i) { if (a[i] < pivot) { temp[index++] = a[i]; } } // pivot position int position = index; // Placing the pivot to its original position temp[index++] = pivot; for (int i = start; i <= high; ++i) { if (a[i] > pivot) { temp[index++] = a[i]; } } // Change the original array for (int i = start; i <= high; ++i) { a[i] = temp[i - start]; } // return the position of the pivot return position; } static void quicksort(int numbers[], int start, int end) { if (start < end) { int point = partition(numbers, start, end); quicksort(numbers, start, point - 1); quicksort(numbers, point + 1, end); } } // Function to print the array static void print(int numbers[]) { for (int a : numbers) { System.out.print(a + \" \"); } } public static void main(String[] args) { int numbers[] = { 3, 2, 1, 78, 9798, 97 }; // rearrange using naive partition quicksort(numbers, 0, numbers.length - 1); print(numbers); }}",
"e": 4162,
"s": 2472,
"text": null
},
{
"code": null,
"e": 4180,
"s": 4162,
"text": "1 2 3 78 97 9798 "
},
{
"code": null,
"e": 4202,
"s": 4180,
"text": "2. Lomuto partition "
},
{
"code": null,
"e": 4252,
"s": 4202,
"text": "Lomuto’s Partition Algorithm (unstable algorithm)"
},
{
"code": null,
"e": 4831,
"s": 4252,
"text": "Lomutopartition(arr[], lo, hi) \n\n pivot = arr[hi]\n i = lo // place for swapping\n for j := lo to hi – 1 do\n if arr[j] <= pivot then\n swap arr[i] with arr[j]\n i = i + 1\n swap arr[i] with arr[hi]\n return i\n\n \nQuickSort(arr[], l, r)\n\nIf r > l\n 1. Find the partition point of the array \n m =Lomutopartition(a,l,r) \n 2. Call Quicksort for less than partition point \n Call Quicksort(arr, l, m-1)\n 3. Call Quicksort for greater than the partition point \n Call Quicksort(arr, m+1, r)"
},
{
"code": null,
"e": 4836,
"s": 4831,
"text": "Java"
},
{
"code": "// Java program to demonstrate the Lomuto partition// in quick sort import java.util.*;public class GFG { static int sort(int numbers[], int start, int last) { int pivot = numbers[last]; int index = start - 1; int temp = 0; for (int i = start; i < last; ++i) { if (numbers[i] < pivot) { ++index; // swap the position temp = numbers[index]; numbers[index] = numbers[i]; numbers[i] = temp; } } int pivotposition = ++index; temp = numbers[index]; numbers[index] = pivot; numbers[last] = temp; return pivotposition; } static void quicksort(int numbers[], int start, int end) { if (start < end) { int pivot_position = sort(numbers, start, end); quicksort(numbers, start, pivot_position - 1); quicksort(numbers, pivot_position + 1, end); } } static void print(int numbers[]) { for (int a : numbers) { System.out.print(a + \" \"); } } public static void main(String[] args) { int numbers[] = { 4, 5, 1, 2, 4, 5, 6 }; quicksort(numbers, 0, numbers.length - 1); print(numbers); }}",
"e": 6169,
"s": 4836,
"text": null
},
{
"code": null,
"e": 6184,
"s": 6169,
"text": "1 2 4 4 5 5 6 "
},
{
"code": null,
"e": 6207,
"s": 6184,
"text": "3. Hoare’s Partition "
},
{
"code": null,
"e": 6511,
"s": 6207,
"text": "Hoare’s Partition Scheme works by initializing two indexes that start at two ends, the two indexes move toward each other until an inversion is (A smaller value on the left side and a greater value on the right side) found. When an inversion is found, two values are swapped and the process is repeated."
},
{
"code": null,
"e": 6523,
"s": 6511,
"text": "Algorithm: "
},
{
"code": null,
"e": 7249,
"s": 6523,
"text": "Hoarepartition(arr[], lo, hi)\n\n pivot = arr[lo]\n i = lo - 1 // Initialize left index\n j = hi + 1 // Initialize right index\n\n // Find a value in left side greater\n // than pivot\n do\n i = i + 1\n while arr[i] < pivot\n\n // Find a value in right side smaller\n // than pivot\n do\n j--;\n while (arr[j] > pivot);\n\n if i >= j then \n return j\n\n swap arr[i] with arr[j]\n\n\n \nQuickSort(arr[], l, r)\n\nIf r > l\n 1. Find the partition point of the array \n m =Hoarepartition(a,l,r) \n 2. Call Quicksort for less than partition point \n Call Quicksort(arr, l, m)\n 3. Call Quicksort for greater than the partition point \n Call Quicksort(arr, m+1, r)"
},
{
"code": null,
"e": 7254,
"s": 7249,
"text": "Java"
},
{
"code": "// Java implementation of QuickSort// using Hoare's partition scheme import java.io.*; class GFG { // This function takes first element as pivot, and // places all the elements smaller than the pivot on the // left side and all the elements greater than the pivot // on the right side. It returns the index of the last // element on the smaller side static int partition(int[] arr, int low, int high) { int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater // than or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller // than or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; // swap(arr[i], arr[j]); int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // The main function that // implements QuickSort // arr[] --> Array to be sorted, // low --> Starting index, // high --> Ending index static void quickSort(int[] arr, int low, int high) { if (low < high) { // pi is partitioning index, // arr[p] is now at right place int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); } } // Function to print an array static void printArray(int[] arr, int n) { for (int i = 0; i < n; ++i) System.out.print(\" \" + arr[i]); System.out.println(); } // Driver Code static public void main(String[] args) { int[] arr = { 10, 17, 18, 9, 11, 15 }; int n = arr.length; quickSort(arr, 0, n - 1); printArray(arr, n); }}",
"e": 9295,
"s": 7254,
"text": null
},
{
"code": null,
"e": 9313,
"s": 9295,
"text": " 9 10 11 15 17 18"
},
{
"code": null,
"e": 9330,
"s": 9315,
"text": "sagartomar9927"
},
{
"code": null,
"e": 9344,
"s": 9330,
"text": "sumitgumber28"
},
{
"code": null,
"e": 9353,
"s": 9344,
"text": "gabaa406"
},
{
"code": null,
"e": 9360,
"s": 9353,
"text": "Picked"
},
{
"code": null,
"e": 9384,
"s": 9360,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 9389,
"s": 9384,
"text": "Java"
},
{
"code": null,
"e": 9403,
"s": 9389,
"text": "Java Programs"
},
{
"code": null,
"e": 9422,
"s": 9403,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9427,
"s": 9422,
"text": "Java"
},
{
"code": null,
"e": 9525,
"s": 9427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9540,
"s": 9525,
"text": "Stream In Java"
},
{
"code": null,
"e": 9561,
"s": 9540,
"text": "Introduction to Java"
},
{
"code": null,
"e": 9582,
"s": 9561,
"text": "Constructors in Java"
},
{
"code": null,
"e": 9601,
"s": 9582,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 9618,
"s": 9601,
"text": "Generics in Java"
},
{
"code": null,
"e": 9644,
"s": 9618,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 9678,
"s": 9644,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 9725,
"s": 9678,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 9763,
"s": 9725,
"text": "Factory method design pattern in Java"
}
] |
PostgreSQL – ALTER DATABASE | 22 Feb, 2021
PostgreSQL has an ALTER DATABASE statement that is used for modifying an existing database. The features of a database, once created can be changed using the ALTER DATABASE statement.
Syntax: ALTER DATABASE target_database action;
As the above syntax depicts, the database where modifications are to be done are mentioned after the ALTER DATABASE statement followed by the action that is to be performed on the database.
Below is the list of actions that PostgreSQL allows:
The ALTER DATABASE RENAME TO statement is used to rename a database as follows:
ALTER DATABASE target_database RENAME TO new_database;
The ALTER DATABASE OWNER TO statement is used to change the owner of a database as follows:
ALTER DATABASE target_database OWNER TO new_owner;
It is important to note that only the superuser or the owner of the database can perform this action.
The ALTER DATABASE SET TABLESPACE statement is used to change the default tablespace of a database as follows:
ALTER DATABASE target_database SET TABLESPACE new_tablespace;
The statement moves tables and indexes from the legacy tablespace to the new one.
By, default, PostgreSQL loads the configuration variable from the postgresql.conf file. This file contains information regarding the database roles and their respective authentication hashing types. These settings or information can be edited using the ALTER DATABASE SET statement as shown below:
ALTER DATABASE target_database SET config_data = value;
It is important to note that only the superuser or the database owner can change the default session variables for a database. Now, let’s look into an example of the implementation of the ALTER DATABASE statement.
Example: Let’s log in as the Postgres user and create a sample database (say, my_test_db) using the below command:
CREATE DATABASE my_test_db;
Now use the below command to rename the database from “my_test_db” to “my_renamed_db“:
ALTER DATABASE my_test_db RENAME TO my_renamed_db;
Now execute the following statement to change the owner of the “my_renamed_db” database from “postgres” to “geeks”, with the assumption that the “geeks” role already exists.
ALTER DATABASE my_renamed_db OWNER TO geeks;
If the “geeks” role does not exist, create it by using the following statement:
CREATE ROLE geeks
VALID UNTIL 'infinity';
Now change the default tablespace of the my_renamed_db from pg_default to geeks_default, with the assumption that the geeks_defaulttablespace already exists.
ALTER DATABASE my_renamed_db
SET TABLESPACE geeks_default;
If the geeks_defaulttablespace does not exist, you can create it by using the following statement:
CREATE TABLESPACE geeks_default
OWNER geeks
LOCATION E'C:\\pgdata\\geeks';
Now set escape_string_warning configuration variable to off using the below commands:
ALTER DATABASE my_renamed_db SET escape_string_warning TO off;
RajuKumar19
postgreSQL-managing-database
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "PostgreSQL has an ALTER DATABASE statement that is used for modifying an existing database. The features of a database, once created can be changed using the ALTER DATABASE statement. "
},
{
"code": null,
"e": 260,
"s": 213,
"text": "Syntax: ALTER DATABASE target_database action;"
},
{
"code": null,
"e": 451,
"s": 260,
"text": "As the above syntax depicts, the database where modifications are to be done are mentioned after the ALTER DATABASE statement followed by the action that is to be performed on the database. "
},
{
"code": null,
"e": 505,
"s": 451,
"text": "Below is the list of actions that PostgreSQL allows: "
},
{
"code": null,
"e": 586,
"s": 505,
"text": "The ALTER DATABASE RENAME TO statement is used to rename a database as follows: "
},
{
"code": null,
"e": 641,
"s": 586,
"text": "ALTER DATABASE target_database RENAME TO new_database;"
},
{
"code": null,
"e": 734,
"s": 641,
"text": "The ALTER DATABASE OWNER TO statement is used to change the owner of a database as follows: "
},
{
"code": null,
"e": 785,
"s": 734,
"text": "ALTER DATABASE target_database OWNER TO new_owner;"
},
{
"code": null,
"e": 888,
"s": 785,
"text": "It is important to note that only the superuser or the owner of the database can perform this action. "
},
{
"code": null,
"e": 1000,
"s": 888,
"text": "The ALTER DATABASE SET TABLESPACE statement is used to change the default tablespace of a database as follows: "
},
{
"code": null,
"e": 1062,
"s": 1000,
"text": "ALTER DATABASE target_database SET TABLESPACE new_tablespace;"
},
{
"code": null,
"e": 1144,
"s": 1062,
"text": "The statement moves tables and indexes from the legacy tablespace to the new one."
},
{
"code": null,
"e": 1442,
"s": 1144,
"text": "By, default, PostgreSQL loads the configuration variable from the postgresql.conf file. This file contains information regarding the database roles and their respective authentication hashing types. These settings or information can be edited using the ALTER DATABASE SET statement as shown below:"
},
{
"code": null,
"e": 1498,
"s": 1442,
"text": "ALTER DATABASE target_database SET config_data = value;"
},
{
"code": null,
"e": 1713,
"s": 1498,
"text": "It is important to note that only the superuser or the database owner can change the default session variables for a database. Now, let’s look into an example of the implementation of the ALTER DATABASE statement. "
},
{
"code": null,
"e": 1828,
"s": 1713,
"text": "Example: Let’s log in as the Postgres user and create a sample database (say, my_test_db) using the below command:"
},
{
"code": null,
"e": 1857,
"s": 1828,
"text": "CREATE DATABASE my_test_db; "
},
{
"code": null,
"e": 1945,
"s": 1857,
"text": "Now use the below command to rename the database from “my_test_db” to “my_renamed_db“: "
},
{
"code": null,
"e": 1996,
"s": 1945,
"text": "ALTER DATABASE my_test_db RENAME TO my_renamed_db;"
},
{
"code": null,
"e": 2171,
"s": 1996,
"text": "Now execute the following statement to change the owner of the “my_renamed_db” database from “postgres” to “geeks”, with the assumption that the “geeks” role already exists. "
},
{
"code": null,
"e": 2216,
"s": 2171,
"text": "ALTER DATABASE my_renamed_db OWNER TO geeks;"
},
{
"code": null,
"e": 2297,
"s": 2216,
"text": "If the “geeks” role does not exist, create it by using the following statement: "
},
{
"code": null,
"e": 2340,
"s": 2297,
"text": "CREATE ROLE geeks\n VALID UNTIL 'infinity';"
},
{
"code": null,
"e": 2499,
"s": 2340,
"text": "Now change the default tablespace of the my_renamed_db from pg_default to geeks_default, with the assumption that the geeks_defaulttablespace already exists. "
},
{
"code": null,
"e": 2558,
"s": 2499,
"text": "ALTER DATABASE my_renamed_db\nSET TABLESPACE geeks_default;"
},
{
"code": null,
"e": 2658,
"s": 2558,
"text": "If the geeks_defaulttablespace does not exist, you can create it by using the following statement: "
},
{
"code": null,
"e": 2735,
"s": 2658,
"text": "CREATE TABLESPACE geeks_default\n OWNER geeks\n LOCATION E'C:\\\\pgdata\\\\geeks';"
},
{
"code": null,
"e": 2822,
"s": 2735,
"text": "Now set escape_string_warning configuration variable to off using the below commands: "
},
{
"code": null,
"e": 2886,
"s": 2822,
"text": "ALTER DATABASE my_renamed_db SET escape_string_warning TO off; "
},
{
"code": null,
"e": 2898,
"s": 2886,
"text": "RajuKumar19"
},
{
"code": null,
"e": 2927,
"s": 2898,
"text": "postgreSQL-managing-database"
},
{
"code": null,
"e": 2938,
"s": 2927,
"text": "PostgreSQL"
},
{
"code": null,
"e": 3036,
"s": 2938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3063,
"s": 3036,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 3095,
"s": 3063,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 3118,
"s": 3095,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 3156,
"s": 3118,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 3196,
"s": 3156,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 3230,
"s": 3196,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 3285,
"s": 3230,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 3309,
"s": 3285,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 3333,
"s": 3309,
"text": "PostgreSQL - Copy Table"
}
] |
How to convert image into base64 string using JavaScript ? | 12 Apr, 2021
Approach :
Here we will create a gfg.js file which will include or JavaScript code and one gfg.html file.
Now we will put onchange on input type and this will execute a function imageUploaded() when you upload an image.
Now we will use file reader and use onload event in file reader than we will get image url and we need to remove some text to get the base64 string and store in variable named base64String and print on console.
And if you want to use this base64 you can write logic on button click like here we will alert this base64 String.
HTML
Javascript
<!DOCTYPE html><html lang="en"> <head> <script src="gfg.js"></script></head> <body> <input type="file" name="" id="fileId" onchange="imageUploaded()"> <br><br> <button onclick="displayString()"> Display String </button></body> </html>
let base64String = ""; function imageUploaded() { var file = document.querySelector( 'input[type=file]')['files'][0]; var reader = new FileReader(); console.log("next"); reader.onload = function () { base64String = reader.result.replace("data:", "") .replace(/^.+,/, ""); imageBase64Stringsep = base64String; // alert(imageBase64Stringsep); console.log(base64String); } reader.readAsDataURL(file);} function displayString() { console.log("Base64String about to be printed"); alert(base64String);}
Output:
JavaScript-Methods
JavaScript-Questions
javascript-string
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 63,
"s": 52,
"text": "Approach :"
},
{
"code": null,
"e": 158,
"s": 63,
"text": "Here we will create a gfg.js file which will include or JavaScript code and one gfg.html file."
},
{
"code": null,
"e": 274,
"s": 158,
"text": "Now we will put onchange on input type and this will execute a function imageUploaded() when you upload an image."
},
{
"code": null,
"e": 485,
"s": 274,
"text": "Now we will use file reader and use onload event in file reader than we will get image url and we need to remove some text to get the base64 string and store in variable named base64String and print on console."
},
{
"code": null,
"e": 600,
"s": 485,
"text": "And if you want to use this base64 you can write logic on button click like here we will alert this base64 String."
},
{
"code": null,
"e": 605,
"s": 600,
"text": "HTML"
},
{
"code": null,
"e": 616,
"s": 605,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"gfg.js\"></script></head> <body> <input type=\"file\" name=\"\" id=\"fileId\" onchange=\"imageUploaded()\"> <br><br> <button onclick=\"displayString()\"> Display String </button></body> </html>",
"e": 886,
"s": 616,
"text": null
},
{
"code": "let base64String = \"\"; function imageUploaded() { var file = document.querySelector( 'input[type=file]')['files'][0]; var reader = new FileReader(); console.log(\"next\"); reader.onload = function () { base64String = reader.result.replace(\"data:\", \"\") .replace(/^.+,/, \"\"); imageBase64Stringsep = base64String; // alert(imageBase64Stringsep); console.log(base64String); } reader.readAsDataURL(file);} function displayString() { console.log(\"Base64String about to be printed\"); alert(base64String);}",
"e": 1467,
"s": 886,
"text": null
},
{
"code": null,
"e": 1475,
"s": 1467,
"text": "Output:"
},
{
"code": null,
"e": 1494,
"s": 1475,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 1515,
"s": 1494,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 1533,
"s": 1515,
"text": "javascript-string"
},
{
"code": null,
"e": 1540,
"s": 1533,
"text": "Picked"
},
{
"code": null,
"e": 1551,
"s": 1540,
"text": "JavaScript"
},
{
"code": null,
"e": 1568,
"s": 1551,
"text": "Web Technologies"
}
] |
Transaction Management | 14 Feb, 2022
Transactions in DBMS : Transactions are a set of operations used to perform a logical set of work. A transaction usually means that the data in the database has changed. One of the major uses of DBMS is to protect the user’s data from system failures. It is done by ensuring that all the data is restored to a consistent state when the computer is restarted after a crash. The transaction is any one execution of the user program in a DBMS. Executing the same program multiple times will generate multiple transactions.
Example – Transaction to be performed to withdraw cash from an ATM vestibule.
Set of Operations : Consider the following example for transaction operations as follows.
Example -ATM transaction steps.
Transaction Start.
Insert your ATM card.
Select language for your transaction.
Select Savings Account option.
Enter the amount you want to withdraw.
Enter your secret pin.
Wait for some time for processing.
Collect your Cash.
Transaction Completed.
Three operations can be performed in a transaction as follows.
Read/Access data (R). Write/Change data (W). Commit.
Read/Access data (R).
Write/Change data (W).
Commit.
Example – Transfer of 50₹ from Account A to Account B. Initially A= 500₹, B= 800₹. This data is brought to RAM from Hard Disk.
R(A) -- 500 // Accessed from RAM.
A = A-50 // Deducting 50₹ from A.
W(A)--450 // Updated in RAM.
R(B) -- 800 // Accessed from RAM.
B=B+50 // 50₹ is added to B's Account.
W(B) --850 // Updated in RAM.
commit // The data in RAM is taken back to Hard Disk.
Note – The updated value of Account A = 450₹ and Account B = 850₹.
All instructions before commit come under a partially committed state and are stored in RAM. When the commit is read the data is fully accepted and is stored in Hard Disk.
If the data is failed anywhere before commit we have to go back and start from the beginning. We can’t continue from the same state. This is known as Roll Back.
Uses of Transaction Management :
The DBMS is used to schedule the access of data concurrently. It means that the user can access multiple data from the database without being interfered with each other. Transactions are used to manage concurrency.
It is also used to satisfy ACID properties.
It is used to solve Read/Write Conflict.
It is used to implement Recoverability, Serializability, and Cascading.
Transaction Management is also used for Concurrency Control Protocols and Locking of data.
Transaction States : Transactions can be implemented using SQL queries and Server. In the below-given diagram, you can see how transaction states works.
Transaction States
Disadvantage of using a Transaction :
It may be difficult to change the information within the transaction database by end-users.
We need to always roll back and start from the beginning rather than continue from the previous state.
gulshankumarar231
arorakashish0911
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
OLAP Guidelines (Codd's Rule)
What is Temporary Table in SQL?
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Introduction of Operating System - Set 1 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 575,
"s": 54,
"text": "Transactions in DBMS : Transactions are a set of operations used to perform a logical set of work. A transaction usually means that the data in the database has changed. One of the major uses of DBMS is to protect the user’s data from system failures. It is done by ensuring that all the data is restored to a consistent state when the computer is restarted after a crash. The transaction is any one execution of the user program in a DBMS. Executing the same program multiple times will generate multiple transactions. "
},
{
"code": null,
"e": 654,
"s": 575,
"text": "Example – Transaction to be performed to withdraw cash from an ATM vestibule. "
},
{
"code": null,
"e": 745,
"s": 654,
"text": "Set of Operations : Consider the following example for transaction operations as follows. "
},
{
"code": null,
"e": 779,
"s": 745,
"text": "Example -ATM transaction steps. "
},
{
"code": null,
"e": 800,
"s": 779,
"text": "Transaction Start. "
},
{
"code": null,
"e": 824,
"s": 800,
"text": "Insert your ATM card. "
},
{
"code": null,
"e": 864,
"s": 824,
"text": "Select language for your transaction. "
},
{
"code": null,
"e": 897,
"s": 864,
"text": "Select Savings Account option. "
},
{
"code": null,
"e": 938,
"s": 897,
"text": "Enter the amount you want to withdraw. "
},
{
"code": null,
"e": 963,
"s": 938,
"text": "Enter your secret pin. "
},
{
"code": null,
"e": 1000,
"s": 963,
"text": "Wait for some time for processing. "
},
{
"code": null,
"e": 1021,
"s": 1000,
"text": "Collect your Cash. "
},
{
"code": null,
"e": 1046,
"s": 1021,
"text": "Transaction Completed. "
},
{
"code": null,
"e": 1111,
"s": 1046,
"text": "Three operations can be performed in a transaction as follows. "
},
{
"code": null,
"e": 1166,
"s": 1111,
"text": "Read/Access data (R). Write/Change data (W). Commit."
},
{
"code": null,
"e": 1190,
"s": 1166,
"text": "Read/Access data (R). "
},
{
"code": null,
"e": 1215,
"s": 1190,
"text": "Write/Change data (W). "
},
{
"code": null,
"e": 1223,
"s": 1215,
"text": "Commit."
},
{
"code": null,
"e": 1352,
"s": 1223,
"text": "Example – Transfer of 50₹ from Account A to Account B. Initially A= 500₹, B= 800₹. This data is brought to RAM from Hard Disk. "
},
{
"code": null,
"e": 1650,
"s": 1352,
"text": "R(A) -- 500 // Accessed from RAM.\nA = A-50 // Deducting 50₹ from A.\nW(A)--450 // Updated in RAM.\nR(B) -- 800 // Accessed from RAM.\nB=B+50 // 50₹ is added to B's Account.\nW(B) --850 // Updated in RAM.\ncommit // The data in RAM is taken back to Hard Disk."
},
{
"code": null,
"e": 1718,
"s": 1650,
"text": "Note – The updated value of Account A = 450₹ and Account B = 850₹. "
},
{
"code": null,
"e": 1891,
"s": 1718,
"text": "All instructions before commit come under a partially committed state and are stored in RAM. When the commit is read the data is fully accepted and is stored in Hard Disk. "
},
{
"code": null,
"e": 2054,
"s": 1891,
"text": "If the data is failed anywhere before commit we have to go back and start from the beginning. We can’t continue from the same state. This is known as Roll Back. "
},
{
"code": null,
"e": 2089,
"s": 2054,
"text": "Uses of Transaction Management : "
},
{
"code": null,
"e": 2306,
"s": 2089,
"text": "The DBMS is used to schedule the access of data concurrently. It means that the user can access multiple data from the database without being interfered with each other. Transactions are used to manage concurrency. "
},
{
"code": null,
"e": 2352,
"s": 2306,
"text": "It is also used to satisfy ACID properties. "
},
{
"code": null,
"e": 2395,
"s": 2352,
"text": "It is used to solve Read/Write Conflict. "
},
{
"code": null,
"e": 2469,
"s": 2395,
"text": "It is used to implement Recoverability, Serializability, and Cascading. "
},
{
"code": null,
"e": 2560,
"s": 2469,
"text": "Transaction Management is also used for Concurrency Control Protocols and Locking of data."
},
{
"code": null,
"e": 2715,
"s": 2560,
"text": "Transaction States : Transactions can be implemented using SQL queries and Server. In the below-given diagram, you can see how transaction states works. "
},
{
"code": null,
"e": 2734,
"s": 2715,
"text": "Transaction States"
},
{
"code": null,
"e": 2774,
"s": 2734,
"text": "Disadvantage of using a Transaction : "
},
{
"code": null,
"e": 2868,
"s": 2774,
"text": "It may be difficult to change the information within the transaction database by end-users. "
},
{
"code": null,
"e": 2971,
"s": 2868,
"text": "We need to always roll back and start from the beginning rather than continue from the previous state."
},
{
"code": null,
"e": 2993,
"s": 2975,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 3010,
"s": 2993,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3015,
"s": 3010,
"text": "DBMS"
},
{
"code": null,
"e": 3023,
"s": 3015,
"text": "GATE CS"
},
{
"code": null,
"e": 3028,
"s": 3023,
"text": "DBMS"
},
{
"code": null,
"e": 3126,
"s": 3028,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3167,
"s": 3126,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 3204,
"s": 3167,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 3245,
"s": 3204,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 3275,
"s": 3245,
"text": "OLAP Guidelines (Codd's Rule)"
},
{
"code": null,
"e": 3307,
"s": 3275,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 3327,
"s": 3307,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 3340,
"s": 3327,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 3367,
"s": 3340,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 3416,
"s": 3367,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
How to Implement Pagination in Android RecyclerView using Volley? | 26 Feb, 2021
Pagination is one of the most important factors which helps to reduce the loading time inside our app and increase the performance of our data which is represented in the form of Lists. In this article, we will take a look at adding pagination in our Android RecyclerView. And to get the data from API we are going to use the Volley library.
Pagination is to load data according to requirement rather than loading complete data at a time. So this helps to reduce the loading time for our data from our API as well as increase the performance of our application.
Many times there is a situation when we have to load a huge amount of the data at a time in our list view or recycler view. So if we load all the data at a time it will take some time to load the data and this will increase the loading time of our Recycler View. Pagination will provide you support with the help of it we can load data in the form of chunks so this will prevent our recycler view from degrading its performance and loading of the data will be faster.
We will be building a simple application in which we will be displaying a list of data in our Android RecyclerView and we will be adding pagination in our RecyclerView to load our data. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL.
// below dependency for using picasso image loading library and volley
implementation ‘com.squareup.picasso:picasso:2.71828’
implementation ‘com.android.volley:volley:1.1.1’
After adding this dependency sync your project and now move towards the AndroidManifest.xml part.
Step 3: Adding permissions to the internet in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml and add the below code to it.
XML
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><!--in this we are displaying a nested scroll view--><androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/idNestedSV" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--linear layout for displaying our recycler view--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!--recycler view for displaying our list of data and we are making nested scroll for our recycler view as false--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVUsers" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:nestedScrollingEnabled="false" tools:listitem="@layout/user_rv_item" /> <!--we are adding progress bar for the purpose of loading--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </androidx.core.widget.NestedScrollView>
Step 5: Creating a Modal class for storing our data
For storing our data we have to create a new java class. For creating a new java class, Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as UserModal and add the below code to it. Comments are added inside the code to understand the code in more detail.
Java
public class UserModal { // variables for our first name, // last name, email and avatar private String first_name; private String last_name; private String email; private String avatar; public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public UserModal(String first_name, String last_name, String email, String avatar) { this.first_name = first_name; this.last_name = last_name; this.email = email; this.avatar = avatar; }}
Step 6: Creating a layout file for each item of our RecyclerView
Navigate to the app > res > layout > Right-click on it > New > layout resource file and give the file name as user_rv_item and add the below code to it. Comments are added in the code to get to know in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:elevation="8dp" app:cardCornerRadius="8dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp"> <!--image view for displaying user image--> <ImageView android:id="@+id/idIVUser" android:layout_width="100dp" android:layout_height="100dp" android:layout_margin="10dp" /> <!--text view for displaying first name--> <TextView android:id="@+id/idTVFirstName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_toEndOf="@id/idIVUser" android:layout_toRightOf="@id/idIVUser" android:text="First Name" android:textColor="@color/black" android:textSize="15sp" /> <!--text view for displaying last name--> <TextView android:id="@+id/idTVLastName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVFirstName" android:layout_marginTop="10dp" android:layout_toEndOf="@id/idIVUser" android:layout_toRightOf="@id/idIVUser" android:text="Last Name" android:textColor="@color/black" android:textSize="15sp" /> <!--text view for displaying user email--> <TextView android:id="@+id/idTVEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVLastName" android:layout_marginTop="10dp" android:layout_toEndOf="@id/idIVUser" android:layout_toRightOf="@id/idIVUser" android:text="Email" android:textColor="@color/black" android:textSize="15sp" /> </RelativeLayout> </androidx.cardview.widget.CardView>
Step 7: Creating an Adapter class for setting data to our RecyclerView item
For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as UserRVAdapter and add the below code to it.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class UserRVAdapter extends RecyclerView.Adapter<UserRVAdapter.ViewHolder> { // variable for our array list and context. private ArrayList<UserModal> userModalArrayList; private Context context; // creating a constructor. public UserRVAdapter(ArrayList<UserModal> userModalArrayList, Context context) { this.userModalArrayList = userModalArrayList; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout file on below line. View view = LayoutInflater.from(context).inflate(R.layout.user_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // getting data from our array list in our modal class. UserModal userModal = userModalArrayList.get(position); // on below line we are setting data to our text view. holder.firstNameTV.setText(userModal.getFirst_name()); holder.lastNameTV.setText(userModal.getLast_name()); holder.emailTV.setText(userModal.getEmail()); // on below line we are loading our image // from url in our image view using picasso. Picasso.get().load(userModal.getAvatar()).into(holder.userIV); } @Override public int getItemCount() { // returning the size of array list. return userModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating a variable for our text view and image view. private TextView firstNameTV, lastNameTV, emailTV; private ImageView userIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our variables. firstNameTV = itemView.findViewById(R.id.idTVFirstName); lastNameTV = itemView.findViewById(R.id.idTVLastName); emailTV = itemView.findViewById(R.id.idTVEmail); userIV = itemView.findViewById(R.id.idIVUser); } }}
Step 8: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.core.widget.NestedScrollView;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating a variable for our array list, adapter class, // recycler view, progressbar, nested scroll view private ArrayList<UserModal> userModalArrayList; private UserRVAdapter userRVAdapter; private RecyclerView userRV; private ProgressBar loadingPB; private NestedScrollView nestedSV; // creating a variable for our page and limit as 2 // as our api is having highest limit as 2 so // we are setting a limit = 2 int page = 0, limit = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating a new array list. userModalArrayList = new ArrayList<>(); // initializing our views. userRV = findViewById(R.id.idRVUsers); loadingPB = findViewById(R.id.idPBLoading); nestedSV = findViewById(R.id.idNestedSV); // calling a method to load our api. getDataFromAPI(page, limit); // adding on scroll change listener method for our nested scroll view. nestedSV.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { // on scroll change we are checking when users scroll as bottom. if (scrollY == v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight()) { // in this method we are incrementing page number, // making progress bar visible and calling get data method. page++; loadingPB.setVisibility(View.VISIBLE); getDataFromAPI(page, limit); } } }); } private void getDataFromAPI(int page, int limit) { if (page > limit) { // checking if the page number is greater than limit. // displaying toast message in this case when page>limit. Toast.makeText(this, "That's all the data..", Toast.LENGTH_SHORT).show(); // hiding our progress bar. loadingPB.setVisibility(View.GONE); return; } // creating a string variable for url . String url = "https://reqres.in/api/users?page=" + page; // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // creating a variable for our json object request and passing our url to it. JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { // on below line we are extracting data from our json array. JSONArray dataArray = response.getJSONArray("data"); // passing data from our json array in our array list. for (int i = 0; i < dataArray.length(); i++) { JSONObject jsonObject = dataArray.getJSONObject(i); // on below line we are extracting data from our json object. userModalArrayList.add(new UserModal(jsonObject.getString("first_name"), jsonObject.getString("last_name"), jsonObject.getString("email"), jsonObject.getString("avatar"))); // passing array list to our adapter class. userRVAdapter = new UserRVAdapter(userModalArrayList, MainActivity.this); // setting layout manager to our recycler view. userRV.setLayoutManager(new LinearLayoutManager(MainActivity.this)); // setting adapter to our recycler view. userRV.setAdapter(userRVAdapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // handling on error listener method. Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show(); } }); // calling a request queue method // and passing our json object queue.add(jsonObjectRequest); }}
Now run your app and see the output of the app.
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Feb, 2021"
},
{
"code": null,
"e": 395,
"s": 52,
"text": "Pagination is one of the most important factors which helps to reduce the loading time inside our app and increase the performance of our data which is represented in the form of Lists. In this article, we will take a look at adding pagination in our Android RecyclerView. And to get the data from API we are going to use the Volley library. "
},
{
"code": null,
"e": 616,
"s": 395,
"text": "Pagination is to load data according to requirement rather than loading complete data at a time. So this helps to reduce the loading time for our data from our API as well as increase the performance of our application. "
},
{
"code": null,
"e": 1084,
"s": 616,
"text": "Many times there is a situation when we have to load a huge amount of the data at a time in our list view or recycler view. So if we load all the data at a time it will take some time to load the data and this will increase the loading time of our Recycler View. Pagination will provide you support with the help of it we can load data in the form of chunks so this will prevent our recycler view from degrading its performance and loading of the data will be faster."
},
{
"code": null,
"e": 1437,
"s": 1084,
"text": "We will be building a simple application in which we will be displaying a list of data in our Android RecyclerView and we will be adding pagination in our RecyclerView to load our data. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 1466,
"s": 1437,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1628,
"s": 1466,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1687,
"s": 1628,
"text": "Step 2: Add the below dependency in your build.gradle file"
},
{
"code": null,
"e": 1984,
"s": 1687,
"text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL. "
},
{
"code": null,
"e": 2055,
"s": 1984,
"text": "// below dependency for using picasso image loading library and volley"
},
{
"code": null,
"e": 2109,
"s": 2055,
"text": "implementation ‘com.squareup.picasso:picasso:2.71828’"
},
{
"code": null,
"e": 2158,
"s": 2109,
"text": "implementation ‘com.android.volley:volley:1.1.1’"
},
{
"code": null,
"e": 2258,
"s": 2158,
"text": "After adding this dependency sync your project and now move towards the AndroidManifest.xml part. "
},
{
"code": null,
"e": 2333,
"s": 2258,
"text": "Step 3: Adding permissions to the internet in the AndroidManifest.xml file"
},
{
"code": null,
"e": 2406,
"s": 2333,
"text": "Navigate to the app > AndroidManifest.xml and add the below code to it. "
},
{
"code": null,
"e": 2410,
"s": 2406,
"text": "XML"
},
{
"code": "<uses-permission android:name=\"android.permission.INTERNET\" />",
"e": 2473,
"s": 2410,
"text": null
},
{
"code": null,
"e": 2521,
"s": 2473,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2664,
"s": 2521,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 2668,
"s": 2664,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--in this we are displaying a nested scroll view--><androidx.core.widget.NestedScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/idNestedSV\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--linear layout for displaying our recycler view--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <!--recycler view for displaying our list of data and we are making nested scroll for our recycler view as false--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVUsers\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" android:layout_weight=\"1\" android:nestedScrollingEnabled=\"false\" tools:listitem=\"@layout/user_rv_item\" /> <!--we are adding progress bar for the purpose of loading--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </LinearLayout> </androidx.core.widget.NestedScrollView>",
"e": 4048,
"s": 2668,
"text": null
},
{
"code": null,
"e": 4100,
"s": 4048,
"text": "Step 5: Creating a Modal class for storing our data"
},
{
"code": null,
"e": 4409,
"s": 4100,
"text": "For storing our data we have to create a new java class. For creating a new java class, Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as UserModal and add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4414,
"s": 4409,
"text": "Java"
},
{
"code": "public class UserModal { // variables for our first name, // last name, email and avatar private String first_name; private String last_name; private String email; private String avatar; public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public UserModal(String first_name, String last_name, String email, String avatar) { this.first_name = first_name; this.last_name = last_name; this.email = email; this.avatar = avatar; }}",
"e": 5432,
"s": 4414,
"text": null
},
{
"code": null,
"e": 5497,
"s": 5432,
"text": "Step 6: Creating a layout file for each item of our RecyclerView"
},
{
"code": null,
"e": 5713,
"s": 5497,
"text": "Navigate to the app > res > layout > Right-click on it > New > layout resource file and give the file name as user_rv_item and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 5717,
"s": 5713,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:elevation=\"8dp\" app:cardCornerRadius=\"8dp\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"2dp\"> <!--image view for displaying user image--> <ImageView android:id=\"@+id/idIVUser\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_margin=\"10dp\" /> <!--text view for displaying first name--> <TextView android:id=\"@+id/idTVFirstName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:layout_toEndOf=\"@id/idIVUser\" android:layout_toRightOf=\"@id/idIVUser\" android:text=\"First Name\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> <!--text view for displaying last name--> <TextView android:id=\"@+id/idTVLastName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVFirstName\" android:layout_marginTop=\"10dp\" android:layout_toEndOf=\"@id/idIVUser\" android:layout_toRightOf=\"@id/idIVUser\" android:text=\"Last Name\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> <!--text view for displaying user email--> <TextView android:id=\"@+id/idTVEmail\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVLastName\" android:layout_marginTop=\"10dp\" android:layout_toEndOf=\"@id/idIVUser\" android:layout_toRightOf=\"@id/idIVUser\" android:text=\"Email\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> </RelativeLayout> </androidx.cardview.widget.CardView>",
"e": 7981,
"s": 5717,
"text": null
},
{
"code": null,
"e": 8057,
"s": 7981,
"text": "Step 7: Creating an Adapter class for setting data to our RecyclerView item"
},
{
"code": null,
"e": 8242,
"s": 8057,
"text": "For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as UserRVAdapter and add the below code to it. "
},
{
"code": null,
"e": 8247,
"s": 8242,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class UserRVAdapter extends RecyclerView.Adapter<UserRVAdapter.ViewHolder> { // variable for our array list and context. private ArrayList<UserModal> userModalArrayList; private Context context; // creating a constructor. public UserRVAdapter(ArrayList<UserModal> userModalArrayList, Context context) { this.userModalArrayList = userModalArrayList; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout file on below line. View view = LayoutInflater.from(context).inflate(R.layout.user_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // getting data from our array list in our modal class. UserModal userModal = userModalArrayList.get(position); // on below line we are setting data to our text view. holder.firstNameTV.setText(userModal.getFirst_name()); holder.lastNameTV.setText(userModal.getLast_name()); holder.emailTV.setText(userModal.getEmail()); // on below line we are loading our image // from url in our image view using picasso. Picasso.get().load(userModal.getAvatar()).into(holder.userIV); } @Override public int getItemCount() { // returning the size of array list. return userModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating a variable for our text view and image view. private TextView firstNameTV, lastNameTV, emailTV; private ImageView userIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our variables. firstNameTV = itemView.findViewById(R.id.idTVFirstName); lastNameTV = itemView.findViewById(R.id.idTVLastName); emailTV = itemView.findViewById(R.id.idTVEmail); userIV = itemView.findViewById(R.id.idIVUser); } }}",
"e": 10723,
"s": 8247,
"text": null
},
{
"code": null,
"e": 10771,
"s": 10723,
"text": "Step 8: Working with the MainActivity.java file"
},
{
"code": null,
"e": 10961,
"s": 10771,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 10966,
"s": 10961,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.core.widget.NestedScrollView;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating a variable for our array list, adapter class, // recycler view, progressbar, nested scroll view private ArrayList<UserModal> userModalArrayList; private UserRVAdapter userRVAdapter; private RecyclerView userRV; private ProgressBar loadingPB; private NestedScrollView nestedSV; // creating a variable for our page and limit as 2 // as our api is having highest limit as 2 so // we are setting a limit = 2 int page = 0, limit = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating a new array list. userModalArrayList = new ArrayList<>(); // initializing our views. userRV = findViewById(R.id.idRVUsers); loadingPB = findViewById(R.id.idPBLoading); nestedSV = findViewById(R.id.idNestedSV); // calling a method to load our api. getDataFromAPI(page, limit); // adding on scroll change listener method for our nested scroll view. nestedSV.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { // on scroll change we are checking when users scroll as bottom. if (scrollY == v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight()) { // in this method we are incrementing page number, // making progress bar visible and calling get data method. page++; loadingPB.setVisibility(View.VISIBLE); getDataFromAPI(page, limit); } } }); } private void getDataFromAPI(int page, int limit) { if (page > limit) { // checking if the page number is greater than limit. // displaying toast message in this case when page>limit. Toast.makeText(this, \"That's all the data..\", Toast.LENGTH_SHORT).show(); // hiding our progress bar. loadingPB.setVisibility(View.GONE); return; } // creating a string variable for url . String url = \"https://reqres.in/api/users?page=\" + page; // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // creating a variable for our json object request and passing our url to it. JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { // on below line we are extracting data from our json array. JSONArray dataArray = response.getJSONArray(\"data\"); // passing data from our json array in our array list. for (int i = 0; i < dataArray.length(); i++) { JSONObject jsonObject = dataArray.getJSONObject(i); // on below line we are extracting data from our json object. userModalArrayList.add(new UserModal(jsonObject.getString(\"first_name\"), jsonObject.getString(\"last_name\"), jsonObject.getString(\"email\"), jsonObject.getString(\"avatar\"))); // passing array list to our adapter class. userRVAdapter = new UserRVAdapter(userModalArrayList, MainActivity.this); // setting layout manager to our recycler view. userRV.setLayoutManager(new LinearLayoutManager(MainActivity.this)); // setting adapter to our recycler view. userRV.setAdapter(userRVAdapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // handling on error listener method. Toast.makeText(MainActivity.this, \"Fail to get data..\", Toast.LENGTH_SHORT).show(); } }); // calling a request queue method // and passing our json object queue.add(jsonObjectRequest); }}",
"e": 16331,
"s": 10966,
"text": null
},
{
"code": null,
"e": 16380,
"s": 16331,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 16404,
"s": 16380,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 16412,
"s": 16404,
"text": "Android"
},
{
"code": null,
"e": 16417,
"s": 16412,
"text": "Java"
},
{
"code": null,
"e": 16436,
"s": 16417,
"text": "Technical Scripter"
},
{
"code": null,
"e": 16441,
"s": 16436,
"text": "Java"
},
{
"code": null,
"e": 16449,
"s": 16441,
"text": "Android"
}
] |
How HashTable Works Internally in Java? | 03 Jun, 2021
Hashtable is a kind of Hash map but is synchronized. Hash map is non–synchronized, permits one null key & multiple null values, not-thread safe i.e. cannot share between many threads without proper synchronization, the key/values pairs are stored in Hashtable. The Hash table does not allow null value/key. When using this you specify an object that is used as a key & the value that you want to associate with the key. It is an array of an index. Each index is known as a bucket/slot. It restrains values based on keys & the place of bucket recognized by calling the Hash code () method. The Hash table of Java holds a class that has unique elements.
Working of Hashtable
Hash table intrinsically contains a slot/bucket in which the storage of key and value pair. It uses the key’s hash code to discover which bucket the key/value of a set should map. To find an item in a list you do the first approach i.e. linear search this involves checking each item, it will take more time. Suppose you have retrieved a value and its index number of an array, then you will look up a value very quickly. In fact, a time will be taken less if you know the index number is independent of the size & position of the array. But how do you know which element of the array contains the value you are looking for. The answer is by calculating the value itself the index number is somewhat related to data.
Let’s proliferate the array, take a name and find its ASCII code, for example, we will take a name say Mia find ASCII code for each letter & add the ASCII code and divide the combined ASCII number with the size of an element in this it is 5, we will take a reminder of the element that is 4 and there we will put the name Mia i.e. in 4th Slot/ Bucket.
Example:
Name = Mia
M 77
i 105
a 97
Sum = 279
Modulus = 279 % 5 = 4
And now we can add more names to the Bucket as shown below:
Mia ⇾ M (77) + i(105) + a(97) = 279 % 5 = 4
Tim ⇾ T (84) + i(105) + m(77) = 298 % 5 = 3
Leo ⇾ L(76) + e(101) + n(110) = 287 % 5 = 2
Som ⇾ S(83) + o(111) + m(77) = 271 % 5 = 1
Beb ⇾ B(66) + e(101) + b(98) = 265 % 5 0
Index number = sum of ASCII codes % Size of array
Let’s retrieve an item say Ada we perform the same calculation,
Find ASCII for Ada = (65+100+97) = 262
262 % 11 = 9
MyData = Array (9)
This is a fast array lookup. Rather than storing individual items or data hash tables are used to store the key-value pairs. For example, Ada would be the key for which want to calculate the Index and DOB of the corresponding value, for this reason, a hash table of key-value pair is sometimes referred to as a hash map in fact if an object-oriented approach is taken each person in an instance of a class and the key would be of many properties, by populating an array with objects you will effectively store much-related data you like for each bucket
A hashing algorithm also is known as a Hash function. The hash function is a function that generates a table when given a key. This is a function to obtain a bucket location from the Key’s hash code. It every time returns a digit for an object. Calculation applied to a key to transforming it into an address.
For numeric keys, divide the key by the number of available addresses, n, and take the remainder
Address = key Mod n
For alphanumeric keys, divide the sum of ASCII codes in a key by the number of available addresses, and take the remainder.
Folding method divides key into equal parts then adds the parts together
Phone No. 018767242947 becomes 01+87+67+24+29+47= 255
Depending on the size of a table, may then divide by some constant and take the remainder.
There are lots of Hash functions some appropriate to another depending on nature.
Collisions in a Hashtable
So far you have seen, there are a lot of a hash table with data that is very conveniently causing any problem say that is unrealistic sometimes if you apply a hash function in two different cases it generates the same index number for both but both items can’t go in the same place this is called Collision. Two identical objects every time have the same digits while two unequal objects might not always have dissimilar digits. Putting an object to the hash table, there is a possibility that dissimilar objects might have an equal hash code called Collision. For rectifying this array of lists is used by a hash table. The set mapped to array index/single bucket and is kept in an index & index reference is stored in array index.
Let’s load up the array again this time with a different set of data. As shown below if Mia is occupying position 4 and Leo to position 2 and if the other names too have the same entry at position 2 then automatically the next bucket will be filled with that entry for avoiding collision as shown below.
Find Rae 280 Mod 11 = 5
myData = Array(5)
As the reminder for an ASCII code of Rae is 5 but is put in slot 8 because due to collision the 2 items figure out to be in the same slot but for avoiding this the Rae is shifted to other slot and as the other slot is again occupied so it is shifted to the 8th position.
Resolving a collision by putting the item somewhere else then its calculated address is called OPEN ADDRESSING because every location is open to an item. This can use a variety of techniques to decide where to place an item this particular addressing technique is called LINEAR PROBING if the calculated address is occupied then the linear search is used to find the next available bucket if the linear probing comes to an end and still cannot find a position it might cycle around the beginning of array & continue searching from there. The more items there are in a hash table the more chances of a collision. One way to deal with this is making the hash table bigger for the total amount of data you are expecting perhaps such that happen 70% of the table is occupied the ratio between the no of items stored and the size of an array is known as Load Factor
Load Factor = Total number of items stored / Size of the array
Another way to do with collisions is known as chains sometimes referred to as CLOSED ADDRESSING. In this, the one slot can form a chain by adding the various item into one bucket.
The objective of a Hash Function
Minimize collisions
Uniform distribution of hash values
Easy to calculate
Resolve any collisions
Methods like hashCode () & equal () to find exact element match
equal(): Object class define equal() as a given language of Java. In which objects indicate whether few objects pass as an argument that is “equal to” the present instance. The different or two objects can be similar only if they are put on an equal memory address.
Syntax:
public boolean equals (Object obj)
// This method checks if some other Object
// passed to it as an argument is equal to
// the Object on which it is invoked.
Should follow the below principles:
Reflexive: For a single object say a, a.equal(a) return true.
Symmetric: For two different objects, a.equal(y) return true if and only if y.equal(a) returns true.
Transitive: For multiple objects a, b, c if a.equal(b) returns true & b.equals(c) returns true then a.equals(c) should return true.
If the object properties are modified means used in equal() method implementation this will result in different and multiple of a.equal(b) will return equal outcome.
Object class equal() will return true only when two references will mark similar objects.
Note: For any non-null reference value a, a.equals(null) should return false.
hashCode(): In this object gives back an integer depiction of an object’s memory address. By using this method a random integer will get returned that is unique for a particular instance. This will return integer hash code data or value of that object.
Syntax:
public int hashCode()
// This method returns the hash code value
// for the object on which this method is invoked.
Example:
Java
import java.util.*; public class HashCodeExample { public static void main(String[] args) { // develop integer object Integer i = new Integer("144"); // Returned hash code value int hashValue = i.hashCode(); System.out.println("Value of Hashcode : " + hashValue); }}
Output
144
Steps
A base class has attributes for objects for user define.
By using @override the override hashCode() function can be predefined.
In a similar way, the override equal() function can be predefined.
Declare an object of the base class and use hash code and equals function so that objects would be equal in the main function.
Contract of hash code() and equal()
During the execution of the application, if hashCode() is invoked more than once on the same Object then it must consistently return the same Integer value, provided no information used in equals(Object) comparison on the Object is modified. It is not necessary that this Integer value remain the same from one execution of the application to another execution of the same application.
If two objects are equal, according to the equals(Object) method, then hashCode() method must produce the same Integer on each of the two Objects.
If two Objects are unequal, according to the equals(Object) method, It is not necessary the Integer value produced by hashCode() method on each of the two Objects will be distinct. It can be the same but producing the distinct Integer on each of the two Objects is better for improving the performance of hashing based Collections like HashMap, HashTable, etc.
Note: Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.
It is a data structure that executes an associative array transcendent data type, a structure that can map keys to values. Here we use the Hash Algorithm to determine a list called hash code into an array of Slots from which desired values can be obtained. Hash table is used to implement an in-memory table, in a programming language like python, PHP, etc., in error checking. An associative array, database indexing, caches, sets, objects representation, unique data representation, Transposition table, etc.
Example 1:
Java
import java.util.*; public class HashtableExample { public static void main(String[] args) { // Create Hashtable Hashtable<Integer, String> hashtable = new Hashtable<>(); // Add mappings to hashtable hashtable.put(1, "X"); hashtable.put(2, "Y"); hashtable.put(3, "Z"); System.out.println(hashtable); // Get a mapping by key String value = hashtable.get(1); System.out.println(value); // Remove a mapping hashtable.remove(3); // Iterate overmapping Iterator<Integer> itr = hashtable.keySet().iterator(); while(itr.hasNext()) { Integer key = itr.next(); String mapped_value = hashtable.get(key); System.out.println( "key: " + key + " value : " + mapped_value); } }}
{3=Z, 2=Y, 1=X}
X
key: 2 value : Y
key: 1 value : X
Example 2:
Java
import java.util.Hashtable;import java.util.Enumeration;public class HashtableExample { public static void main(String[] args) { Enumeration names; String key; // Developing a Hashtable Hashtable<String, String> hashtable = new Hashtable<String, String>(); // Attaching Key and Value sets to Hashtable hashtable.put("Key1", "Madhu"); hashtable.put("Key2", "Girja"); hashtable.put("Key3", "Durgesh"); hashtable.put("Key4", "Richa"); hashtable.put("Key5", "Manisha"); names = hashtable.keys(); while (names.hasMoreElements()) { key = (String)names.nextElement(); System.out.println("Key: " + key + " & Value: " + hashtable.get(key)); } }}
Key: Key4 & Value: Richa
Key: Key3 & Value: Durgesh
Key: Key2 & Value: Girja
Key: Key1 & Value: Madhu
Key: Key5 & Value: Manisha
Conclusion
Used in index large amounts of data
Address of each key calculated using the key itself
Collisions resolved with open or closed addressing
Hashing is widely used in database indexing, compilers, caching, password authentication, and more
Insertion, deletion, and retrieval occur in constant time.
adnanirshad158
Java-HashTable
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 706,
"s": 53,
"text": "Hashtable is a kind of Hash map but is synchronized. Hash map is non–synchronized, permits one null key & multiple null values, not-thread safe i.e. cannot share between many threads without proper synchronization, the key/values pairs are stored in Hashtable. The Hash table does not allow null value/key. When using this you specify an object that is used as a key & the value that you want to associate with the key. It is an array of an index. Each index is known as a bucket/slot. It restrains values based on keys & the place of bucket recognized by calling the Hash code () method. The Hash table of Java holds a class that has unique elements."
},
{
"code": null,
"e": 727,
"s": 706,
"text": "Working of Hashtable"
},
{
"code": null,
"e": 1444,
"s": 727,
"text": "Hash table intrinsically contains a slot/bucket in which the storage of key and value pair. It uses the key’s hash code to discover which bucket the key/value of a set should map. To find an item in a list you do the first approach i.e. linear search this involves checking each item, it will take more time. Suppose you have retrieved a value and its index number of an array, then you will look up a value very quickly. In fact, a time will be taken less if you know the index number is independent of the size & position of the array. But how do you know which element of the array contains the value you are looking for. The answer is by calculating the value itself the index number is somewhat related to data."
},
{
"code": null,
"e": 1796,
"s": 1444,
"text": "Let’s proliferate the array, take a name and find its ASCII code, for example, we will take a name say Mia find ASCII code for each letter & add the ASCII code and divide the combined ASCII number with the size of an element in this it is 5, we will take a reminder of the element that is 4 and there we will put the name Mia i.e. in 4th Slot/ Bucket."
},
{
"code": null,
"e": 1805,
"s": 1796,
"text": "Example:"
},
{
"code": null,
"e": 1818,
"s": 1805,
"text": " Name = Mia "
},
{
"code": null,
"e": 1825,
"s": 1818,
"text": " M 77"
},
{
"code": null,
"e": 1833,
"s": 1825,
"text": " i 105 "
},
{
"code": null,
"e": 1839,
"s": 1833,
"text": "a 97"
},
{
"code": null,
"e": 1850,
"s": 1839,
"text": "Sum = 279 "
},
{
"code": null,
"e": 1872,
"s": 1850,
"text": "Modulus = 279 % 5 = 4"
},
{
"code": null,
"e": 1967,
"s": 1907,
"text": "And now we can add more names to the Bucket as shown below:"
},
{
"code": null,
"e": 2011,
"s": 1967,
"text": "Mia ⇾ M (77) + i(105) + a(97) = 279 % 5 = 4"
},
{
"code": null,
"e": 2055,
"s": 2011,
"text": "Tim ⇾ T (84) + i(105) + m(77) = 298 % 5 = 3"
},
{
"code": null,
"e": 2099,
"s": 2055,
"text": "Leo ⇾ L(76) + e(101) + n(110) = 287 % 5 = 2"
},
{
"code": null,
"e": 2148,
"s": 2099,
"text": "Som ⇾ S(83) + o(111) + m(77) = 271 % 5 = 1 "
},
{
"code": null,
"e": 2189,
"s": 2148,
"text": "Beb ⇾ B(66) + e(101) + b(98) = 265 % 5 0"
},
{
"code": null,
"e": 2239,
"s": 2189,
"text": "Index number = sum of ASCII codes % Size of array"
},
{
"code": null,
"e": 2303,
"s": 2239,
"text": "Let’s retrieve an item say Ada we perform the same calculation,"
},
{
"code": null,
"e": 2347,
"s": 2303,
"text": " Find ASCII for Ada = (65+100+97) = 262"
},
{
"code": null,
"e": 2382,
"s": 2347,
"text": " 262 % 11 = 9"
},
{
"code": null,
"e": 2421,
"s": 2382,
"text": " MyData = Array (9)"
},
{
"code": null,
"e": 3051,
"s": 2498,
"text": "This is a fast array lookup. Rather than storing individual items or data hash tables are used to store the key-value pairs. For example, Ada would be the key for which want to calculate the Index and DOB of the corresponding value, for this reason, a hash table of key-value pair is sometimes referred to as a hash map in fact if an object-oriented approach is taken each person in an instance of a class and the key would be of many properties, by populating an array with objects you will effectively store much-related data you like for each bucket"
},
{
"code": null,
"e": 3406,
"s": 3096,
"text": "A hashing algorithm also is known as a Hash function. The hash function is a function that generates a table when given a key. This is a function to obtain a bucket location from the Key’s hash code. It every time returns a digit for an object. Calculation applied to a key to transforming it into an address."
},
{
"code": null,
"e": 3503,
"s": 3406,
"text": "For numeric keys, divide the key by the number of available addresses, n, and take the remainder"
},
{
"code": null,
"e": 3524,
"s": 3503,
"text": " Address = key Mod n"
},
{
"code": null,
"e": 3648,
"s": 3524,
"text": "For alphanumeric keys, divide the sum of ASCII codes in a key by the number of available addresses, and take the remainder."
},
{
"code": null,
"e": 3721,
"s": 3648,
"text": "Folding method divides key into equal parts then adds the parts together"
},
{
"code": null,
"e": 3775,
"s": 3721,
"text": "Phone No. 018767242947 becomes 01+87+67+24+29+47= 255"
},
{
"code": null,
"e": 3866,
"s": 3775,
"text": "Depending on the size of a table, may then divide by some constant and take the remainder."
},
{
"code": null,
"e": 3948,
"s": 3866,
"text": "There are lots of Hash functions some appropriate to another depending on nature."
},
{
"code": null,
"e": 3974,
"s": 3948,
"text": "Collisions in a Hashtable"
},
{
"code": null,
"e": 4707,
"s": 3974,
"text": "So far you have seen, there are a lot of a hash table with data that is very conveniently causing any problem say that is unrealistic sometimes if you apply a hash function in two different cases it generates the same index number for both but both items can’t go in the same place this is called Collision. Two identical objects every time have the same digits while two unequal objects might not always have dissimilar digits. Putting an object to the hash table, there is a possibility that dissimilar objects might have an equal hash code called Collision. For rectifying this array of lists is used by a hash table. The set mapped to array index/single bucket and is kept in an index & index reference is stored in array index."
},
{
"code": null,
"e": 5011,
"s": 4707,
"text": "Let’s load up the array again this time with a different set of data. As shown below if Mia is occupying position 4 and Leo to position 2 and if the other names too have the same entry at position 2 then automatically the next bucket will be filled with that entry for avoiding collision as shown below."
},
{
"code": null,
"e": 5035,
"s": 5011,
"text": "Find Rae 280 Mod 11 = 5"
},
{
"code": null,
"e": 5053,
"s": 5035,
"text": "myData = Array(5)"
},
{
"code": null,
"e": 5441,
"s": 5170,
"text": "As the reminder for an ASCII code of Rae is 5 but is put in slot 8 because due to collision the 2 items figure out to be in the same slot but for avoiding this the Rae is shifted to other slot and as the other slot is again occupied so it is shifted to the 8th position."
},
{
"code": null,
"e": 6303,
"s": 5441,
"text": "Resolving a collision by putting the item somewhere else then its calculated address is called OPEN ADDRESSING because every location is open to an item. This can use a variety of techniques to decide where to place an item this particular addressing technique is called LINEAR PROBING if the calculated address is occupied then the linear search is used to find the next available bucket if the linear probing comes to an end and still cannot find a position it might cycle around the beginning of array & continue searching from there. The more items there are in a hash table the more chances of a collision. One way to deal with this is making the hash table bigger for the total amount of data you are expecting perhaps such that happen 70% of the table is occupied the ratio between the no of items stored and the size of an array is known as Load Factor"
},
{
"code": null,
"e": 6366,
"s": 6303,
"text": "Load Factor = Total number of items stored / Size of the array"
},
{
"code": null,
"e": 6546,
"s": 6366,
"text": "Another way to do with collisions is known as chains sometimes referred to as CLOSED ADDRESSING. In this, the one slot can form a chain by adding the various item into one bucket."
},
{
"code": null,
"e": 6579,
"s": 6546,
"text": "The objective of a Hash Function"
},
{
"code": null,
"e": 6599,
"s": 6579,
"text": "Minimize collisions"
},
{
"code": null,
"e": 6635,
"s": 6599,
"text": "Uniform distribution of hash values"
},
{
"code": null,
"e": 6653,
"s": 6635,
"text": "Easy to calculate"
},
{
"code": null,
"e": 6676,
"s": 6653,
"text": "Resolve any collisions"
},
{
"code": null,
"e": 6740,
"s": 6676,
"text": "Methods like hashCode () & equal () to find exact element match"
},
{
"code": null,
"e": 7006,
"s": 6740,
"text": "equal(): Object class define equal() as a given language of Java. In which objects indicate whether few objects pass as an argument that is “equal to” the present instance. The different or two objects can be similar only if they are put on an equal memory address."
},
{
"code": null,
"e": 7015,
"s": 7006,
"text": "Syntax: "
},
{
"code": null,
"e": 7177,
"s": 7015,
"text": "public boolean equals (Object obj)\n\n// This method checks if some other Object\n// passed to it as an argument is equal to \n// the Object on which it is invoked."
},
{
"code": null,
"e": 7213,
"s": 7177,
"text": "Should follow the below principles:"
},
{
"code": null,
"e": 7275,
"s": 7213,
"text": "Reflexive: For a single object say a, a.equal(a) return true."
},
{
"code": null,
"e": 7376,
"s": 7275,
"text": "Symmetric: For two different objects, a.equal(y) return true if and only if y.equal(a) returns true."
},
{
"code": null,
"e": 7508,
"s": 7376,
"text": "Transitive: For multiple objects a, b, c if a.equal(b) returns true & b.equals(c) returns true then a.equals(c) should return true."
},
{
"code": null,
"e": 7674,
"s": 7508,
"text": "If the object properties are modified means used in equal() method implementation this will result in different and multiple of a.equal(b) will return equal outcome."
},
{
"code": null,
"e": 7764,
"s": 7674,
"text": "Object class equal() will return true only when two references will mark similar objects."
},
{
"code": null,
"e": 7842,
"s": 7764,
"text": "Note: For any non-null reference value a, a.equals(null) should return false."
},
{
"code": null,
"e": 8097,
"s": 7842,
"text": "hashCode(): In this object gives back an integer depiction of an object’s memory address. By using this method a random integer will get returned that is unique for a particular instance. This will return integer hash code data or value of that object. "
},
{
"code": null,
"e": 8107,
"s": 8097,
"text": "Syntax: "
},
{
"code": null,
"e": 8225,
"s": 8107,
"text": "public int hashCode()\n\n// This method returns the hash code value \n// for the object on which this method is invoked."
},
{
"code": null,
"e": 8234,
"s": 8225,
"text": "Example:"
},
{
"code": null,
"e": 8239,
"s": 8234,
"text": "Java"
},
{
"code": "import java.util.*; public class HashCodeExample { public static void main(String[] args) { // develop integer object Integer i = new Integer(\"144\"); // Returned hash code value int hashValue = i.hashCode(); System.out.println(\"Value of Hashcode : \" + hashValue); }}",
"e": 8578,
"s": 8239,
"text": null
},
{
"code": null,
"e": 8589,
"s": 8582,
"text": "Output"
},
{
"code": null,
"e": 8595,
"s": 8591,
"text": "144"
},
{
"code": null,
"e": 8603,
"s": 8597,
"text": "Steps"
},
{
"code": null,
"e": 8662,
"s": 8605,
"text": "A base class has attributes for objects for user define."
},
{
"code": null,
"e": 8733,
"s": 8662,
"text": "By using @override the override hashCode() function can be predefined."
},
{
"code": null,
"e": 8800,
"s": 8733,
"text": "In a similar way, the override equal() function can be predefined."
},
{
"code": null,
"e": 8927,
"s": 8800,
"text": "Declare an object of the base class and use hash code and equals function so that objects would be equal in the main function."
},
{
"code": null,
"e": 8965,
"s": 8929,
"text": "Contract of hash code() and equal()"
},
{
"code": null,
"e": 9353,
"s": 8967,
"text": "During the execution of the application, if hashCode() is invoked more than once on the same Object then it must consistently return the same Integer value, provided no information used in equals(Object) comparison on the Object is modified. It is not necessary that this Integer value remain the same from one execution of the application to another execution of the same application."
},
{
"code": null,
"e": 9500,
"s": 9353,
"text": "If two objects are equal, according to the equals(Object) method, then hashCode() method must produce the same Integer on each of the two Objects."
},
{
"code": null,
"e": 9861,
"s": 9500,
"text": "If two Objects are unequal, according to the equals(Object) method, It is not necessary the Integer value produced by hashCode() method on each of the two Objects will be distinct. It can be the same but producing the distinct Integer on each of the two Objects is better for improving the performance of hashing based Collections like HashMap, HashTable, etc."
},
{
"code": null,
"e": 10004,
"s": 9863,
"text": "Note: Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes."
},
{
"code": null,
"e": 10519,
"s": 10008,
"text": "It is a data structure that executes an associative array transcendent data type, a structure that can map keys to values. Here we use the Hash Algorithm to determine a list called hash code into an array of Slots from which desired values can be obtained. Hash table is used to implement an in-memory table, in a programming language like python, PHP, etc., in error checking. An associative array, database indexing, caches, sets, objects representation, unique data representation, Transposition table, etc."
},
{
"code": null,
"e": 10532,
"s": 10521,
"text": "Example 1:"
},
{
"code": null,
"e": 10539,
"s": 10534,
"text": "Java"
},
{
"code": "import java.util.*; public class HashtableExample { public static void main(String[] args) { // Create Hashtable Hashtable<Integer, String> hashtable = new Hashtable<>(); // Add mappings to hashtable hashtable.put(1, \"X\"); hashtable.put(2, \"Y\"); hashtable.put(3, \"Z\"); System.out.println(hashtable); // Get a mapping by key String value = hashtable.get(1); System.out.println(value); // Remove a mapping hashtable.remove(3); // Iterate overmapping Iterator<Integer> itr = hashtable.keySet().iterator(); while(itr.hasNext()) { Integer key = itr.next(); String mapped_value = hashtable.get(key); System.out.println( \"key: \" + key + \" value : \" + mapped_value); } }}",
"e": 11408,
"s": 10539,
"text": null
},
{
"code": null,
"e": 11463,
"s": 11411,
"text": "{3=Z, 2=Y, 1=X}\nX\nkey: 2 value : Y\nkey: 1 value : X"
},
{
"code": null,
"e": 11476,
"s": 11465,
"text": "Example 2:"
},
{
"code": null,
"e": 11483,
"s": 11478,
"text": "Java"
},
{
"code": "import java.util.Hashtable;import java.util.Enumeration;public class HashtableExample { public static void main(String[] args) { Enumeration names; String key; // Developing a Hashtable Hashtable<String, String> hashtable = new Hashtable<String, String>(); // Attaching Key and Value sets to Hashtable hashtable.put(\"Key1\", \"Madhu\"); hashtable.put(\"Key2\", \"Girja\"); hashtable.put(\"Key3\", \"Durgesh\"); hashtable.put(\"Key4\", \"Richa\"); hashtable.put(\"Key5\", \"Manisha\"); names = hashtable.keys(); while (names.hasMoreElements()) { key = (String)names.nextElement(); System.out.println(\"Key: \" + key + \" & Value: \" + hashtable.get(key)); } }}",
"e": 12288,
"s": 11483,
"text": null
},
{
"code": null,
"e": 12420,
"s": 12291,
"text": "Key: Key4 & Value: Richa\nKey: Key3 & Value: Durgesh\nKey: Key2 & Value: Girja\nKey: Key1 & Value: Madhu\nKey: Key5 & Value: Manisha"
},
{
"code": null,
"e": 12433,
"s": 12422,
"text": "Conclusion"
},
{
"code": null,
"e": 12471,
"s": 12435,
"text": "Used in index large amounts of data"
},
{
"code": null,
"e": 12523,
"s": 12471,
"text": "Address of each key calculated using the key itself"
},
{
"code": null,
"e": 12574,
"s": 12523,
"text": "Collisions resolved with open or closed addressing"
},
{
"code": null,
"e": 12673,
"s": 12574,
"text": "Hashing is widely used in database indexing, compilers, caching, password authentication, and more"
},
{
"code": null,
"e": 12732,
"s": 12673,
"text": "Insertion, deletion, and retrieval occur in constant time."
},
{
"code": null,
"e": 12749,
"s": 12734,
"text": "adnanirshad158"
},
{
"code": null,
"e": 12764,
"s": 12749,
"text": "Java-HashTable"
},
{
"code": null,
"e": 12771,
"s": 12764,
"text": "Picked"
},
{
"code": null,
"e": 12776,
"s": 12771,
"text": "Java"
},
{
"code": null,
"e": 12781,
"s": 12776,
"text": "Java"
}
] |
Compute Density of the Distribution Function in R Programming – dunif() Function | 30 Jun, 2020
dunif() function in R Language is used to provide the density of the distribution function.
Syntax:dunif(x, min = 0, max = 1, log = FALSE)
Parameters:x: represents vectormin, max: represents lower and upper limits of the distributionlog: represents logical value for probabilities
Example 1:
# Create vector of random deviationu <- runif(20) dunif(u) == u print(dunif(u))
Output:
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Example 2:
# Output to be present as PNG filepng(file = "dunifGFG.png") # Plot densitycurve(dunif(x, min = 2, max = 6), 0, 8, ylim = c(0, 0.5), ylab = "f(x)", main = "Uniform Density f(x)") # Saving the filedev.off()
Output:
R Statistics-Function
R Language
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": 120,
"s": 28,
"text": "dunif() function in R Language is used to provide the density of the distribution function."
},
{
"code": null,
"e": 167,
"s": 120,
"text": "Syntax:dunif(x, min = 0, max = 1, log = FALSE)"
},
{
"code": null,
"e": 309,
"s": 167,
"text": "Parameters:x: represents vectormin, max: represents lower and upper limits of the distributionlog: represents logical value for probabilities"
},
{
"code": null,
"e": 320,
"s": 309,
"text": "Example 1:"
},
{
"code": "# Create vector of random deviationu <- runif(20) dunif(u) == u print(dunif(u))",
"e": 402,
"s": 320,
"text": null
},
{
"code": null,
"e": 410,
"s": 402,
"text": "Output:"
},
{
"code": null,
"e": 586,
"s": 410,
"text": " \n[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n"
},
{
"code": null,
"e": 597,
"s": 586,
"text": "Example 2:"
},
{
"code": "# Output to be present as PNG filepng(file = \"dunifGFG.png\") # Plot densitycurve(dunif(x, min = 2, max = 6), 0, 8, ylim = c(0, 0.5), ylab = \"f(x)\", main = \"Uniform Density f(x)\") # Saving the filedev.off()",
"e": 810,
"s": 597,
"text": null
},
{
"code": null,
"e": 818,
"s": 810,
"text": "Output:"
},
{
"code": null,
"e": 840,
"s": 818,
"text": "R Statistics-Function"
},
{
"code": null,
"e": 851,
"s": 840,
"text": "R Language"
}
] |
Program to count occurrence of a given character in a string | 25 May, 2022
Given a string and a character, the task is to make a function which count occurrence of the given character in the string.
Examples:
Input : str = "geeksforgeeks"
c = 'e'
Output : 4
'e' appears four times in str.
Input : str = "abccdefgaa"
c = 'a'
Output : 3
'a' appears three times in str.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count occurrences of a given// character#include <iostream>#include <string>using namespace std; // Function that return count of the given// character in the stringint count(string s, char c){ // Count variable int res = 0; for (int i=0;i<s.length();i++) // checking character in string if (s[i] == c) res++; return res;} // Driver codeint main(){ string str= "geeksforgeeks"; char c = 'e'; cout << count(str, c) << endl; return 0;}
// JAVA program to count occurrences// of a character class GFG{ // Method that return count of the given // character in the string public static int count(String s, char c) { int res = 0; for (int i=0; i<s.length(); i++) { // checking character in string if (s.charAt(i) == c) res++; } return res; } // Driver method public static void main(String args[]) { String str= "geeksforgeeks"; char c = 'e'; System.out.println(count(str, c)); }}
# Python program to count occurrences# of a given character # Method that return count of the# given character in the stringdef count(s, c) : # Count variable res = 0 for i in range(len(s)) : # Checking character in string if (s[i] == c): res = res + 1 return res # Driver codestr= "geeksforgeeks"c = 'e'print(count(str, c)) # This code is contributed by "rishabh_jain".
// C# program to count occurrences// of a characterusing System; public class GFG { // Method that return count of the given // character in the string public static int count(string s, char c) { int res = 0; for (int i = 0; i < s.Length; i++) { // checking character in string if (s[i] == c) res++; } return res; } // Driver method public static void Main() { string str = "geeksforgeeks"; char c = 'e'; Console.WriteLine(count(str, c)); }} // This code is contributed by Sam007.
<?php// PHP program to count// occurrences of a given// character // Function that return count of// the given character in the stringfunction count($s, $c){ // Count variable $res = 0; for ($i = 0; $i < strlen($s); $i++) // checking character in string if ($s[$i] == $c) $res++; return $res;} // Driver Code $str= "geeksforgeeks"; $c = 'e'; echo count($str, $c) ; return 0; // This code is contributed by nitin mittal.?>
<script>// JAVASCRIPT program to count occurrences// of a character // Method that return count of the given // character in the string function count(s, c) { let res = 0; for (let i = 0; i < s.length; i++) { // checking character in string if (s.charAt(i) == c) res++; } return res; } // Driver method let str= "geeksforgeeks"; let c = 'e'; document.write(count(str, c)); // This code is contributed by shivanisinghss2110 </script>
4
Time Complexity: O(len), where len is the size of the string given.
Auxiliary Space: O(1)Using Direct Function in C++
C++
// CPP program to count occurrences of// a character using library#include<bits/stdc++.h>using namespace std; // Driver codeint main(){ string str = "geeksforgeeks"; char c = 'e'; // Count returns number of occurrences of // c between two given positions provided // as two iterators. cout << count(str.begin(), str.end(), c); return 0;}
Output:
4
Time Complexity: O(len), where len is the size of the string given.
Auxiliary Space: O(1)
Using recursion
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; int countinString(char ch,string s){ // base case; if (s.length() == 0) return 0; int count = 0; // checking if the first character of // the given string is that character // or not if (s[0] == ch) count++; // this will count the occurrence of // given character in the string // from index 1 to the last // index of the string count += countinString(ch, s.substr(1)); return count;} int main(){ string str = "geeksforgeeks"; char c = 'e'; cout<<(countinString(c, str));} // This code is contributed by shinjanpatra
/*package whatever //do not write package name here */ import java.io.*; class GFG { static int countinString(char ch, String s) { //base case; if(s.length()==0) return 0; int count = 0; //checking if the first character of //the given string is that character //or not if(s.charAt(0)==ch) count++; //this will count the occurrence of //given character in the string //from index 1 to the last //index of the string count+=countinString(ch,s.substring(1)); return count; } public static void main (String[] args) { String str= "geeksforgeeks"; char c = 'e'; System.out.println(countinString(c,str)); }}
def countinString(ch, s): # base case; if (len(s) == 0): return 0 count = 0 # checking if the first character of # the given string is that character # or not if (s[0] == ch): count += 1 # this will count the occurrence of # given character in the string # from index 1 to the last # index of the string count += countinString(ch, s[1:]) return count str = "geeksforgeeks"c = 'e'print(countinString(c, str)) # This code is contributed by shinjanpatra
/*package whatever //do not write package name here */using System;public class GFG { static int countinString(char ch, String s) { // base case; if(s.Length == 0) return 0; int count = 0; // checking if the first character of // the given string is that character // or not if(s[0] == ch) count++; // this will count the occurrence of // given character in the string // from index 1 to the last // index of the string count += countinString(ch,s.Substring(1)); return count; } // Driver code public static void Main(String[] args) { String str= "geeksforgeeks"; char c = 'e'; Console.WriteLine(countinString(c,str)); }} // This code is contributed by umadevi9616
<script>/*package whatever //do not write package name here */ function countinString( ch, s) { // base case; if (s.length == 0) return 0; var count = 0; // checking if the first character of // the given string is that character // or not if (s[0] == ch) count++; // this will count the occurrence of // given character in the string // from index 1 to the last // index of the string count += countinString(ch, s.substring(1)); return count; } var str = "geeksforgeeks"; var c = 'e'; document.write(countinString(c, str)); // This code is contributed by gauravrajput1</script>
Output:
4
Time Complexity: O(len), where len is the size of the string given.
Auxiliary Space: O(len), where len is the size of the string given.
This article is contributed by Sahil 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
nitin mittal
le0
sagar0719kumar
shivanisinghss2110
surindertarika1234
GauravRajput1
patildhanu4111999
shinjanpatra
rohitmishra051000
C++
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 178,
"s": 53,
"text": "Given a string and a character, the task is to make a function which count occurrence of the given character in the string. "
},
{
"code": null,
"e": 190,
"s": 178,
"text": "Examples: "
},
{
"code": null,
"e": 369,
"s": 190,
"text": "Input : str = \"geeksforgeeks\"\n c = 'e'\nOutput : 4\n'e' appears four times in str.\n\nInput : str = \"abccdefgaa\"\n c = 'a' \nOutput : 3\n'a' appears three times in str."
},
{
"code": null,
"e": 373,
"s": 369,
"text": "C++"
},
{
"code": null,
"e": 378,
"s": 373,
"text": "Java"
},
{
"code": null,
"e": 386,
"s": 378,
"text": "Python3"
},
{
"code": null,
"e": 389,
"s": 386,
"text": "C#"
},
{
"code": null,
"e": 393,
"s": 389,
"text": "PHP"
},
{
"code": null,
"e": 404,
"s": 393,
"text": "Javascript"
},
{
"code": "// C++ program to count occurrences of a given// character#include <iostream>#include <string>using namespace std; // Function that return count of the given// character in the stringint count(string s, char c){ // Count variable int res = 0; for (int i=0;i<s.length();i++) // checking character in string if (s[i] == c) res++; return res;} // Driver codeint main(){ string str= \"geeksforgeeks\"; char c = 'e'; cout << count(str, c) << endl; return 0;}",
"e": 908,
"s": 404,
"text": null
},
{
"code": "// JAVA program to count occurrences// of a character class GFG{ // Method that return count of the given // character in the string public static int count(String s, char c) { int res = 0; for (int i=0; i<s.length(); i++) { // checking character in string if (s.charAt(i) == c) res++; } return res; } // Driver method public static void main(String args[]) { String str= \"geeksforgeeks\"; char c = 'e'; System.out.println(count(str, c)); }}",
"e": 1471,
"s": 908,
"text": null
},
{
"code": "# Python program to count occurrences# of a given character # Method that return count of the# given character in the stringdef count(s, c) : # Count variable res = 0 for i in range(len(s)) : # Checking character in string if (s[i] == c): res = res + 1 return res # Driver codestr= \"geeksforgeeks\"c = 'e'print(count(str, c)) # This code is contributed by \"rishabh_jain\".",
"e": 1911,
"s": 1471,
"text": null
},
{
"code": "// C# program to count occurrences// of a characterusing System; public class GFG { // Method that return count of the given // character in the string public static int count(string s, char c) { int res = 0; for (int i = 0; i < s.Length; i++) { // checking character in string if (s[i] == c) res++; } return res; } // Driver method public static void Main() { string str = \"geeksforgeeks\"; char c = 'e'; Console.WriteLine(count(str, c)); }} // This code is contributed by Sam007.",
"e": 2558,
"s": 1911,
"text": null
},
{
"code": "<?php// PHP program to count// occurrences of a given// character // Function that return count of// the given character in the stringfunction count($s, $c){ // Count variable $res = 0; for ($i = 0; $i < strlen($s); $i++) // checking character in string if ($s[$i] == $c) $res++; return $res;} // Driver Code $str= \"geeksforgeeks\"; $c = 'e'; echo count($str, $c) ; return 0; // This code is contributed by nitin mittal.?>",
"e": 3045,
"s": 2558,
"text": null
},
{
"code": "<script>// JAVASCRIPT program to count occurrences// of a character // Method that return count of the given // character in the string function count(s, c) { let res = 0; for (let i = 0; i < s.length; i++) { // checking character in string if (s.charAt(i) == c) res++; } return res; } // Driver method let str= \"geeksforgeeks\"; let c = 'e'; document.write(count(str, c)); // This code is contributed by shivanisinghss2110 </script>",
"e": 3608,
"s": 3045,
"text": null
},
{
"code": null,
"e": 3610,
"s": 3608,
"text": "4"
},
{
"code": null,
"e": 3678,
"s": 3610,
"text": "Time Complexity: O(len), where len is the size of the string given."
},
{
"code": null,
"e": 3729,
"s": 3678,
"text": "Auxiliary Space: O(1)Using Direct Function in C++ "
},
{
"code": null,
"e": 3733,
"s": 3729,
"text": "C++"
},
{
"code": "// CPP program to count occurrences of// a character using library#include<bits/stdc++.h>using namespace std; // Driver codeint main(){ string str = \"geeksforgeeks\"; char c = 'e'; // Count returns number of occurrences of // c between two given positions provided // as two iterators. cout << count(str.begin(), str.end(), c); return 0;}",
"e": 4095,
"s": 3733,
"text": null
},
{
"code": null,
"e": 4105,
"s": 4095,
"text": "Output: "
},
{
"code": null,
"e": 4107,
"s": 4105,
"text": "4"
},
{
"code": null,
"e": 4175,
"s": 4107,
"text": "Time Complexity: O(len), where len is the size of the string given."
},
{
"code": null,
"e": 4198,
"s": 4175,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 4214,
"s": 4198,
"text": "Using recursion"
},
{
"code": null,
"e": 4218,
"s": 4214,
"text": "C++"
},
{
"code": null,
"e": 4223,
"s": 4218,
"text": "Java"
},
{
"code": null,
"e": 4231,
"s": 4223,
"text": "Python3"
},
{
"code": null,
"e": 4234,
"s": 4231,
"text": "C#"
},
{
"code": null,
"e": 4245,
"s": 4234,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; int countinString(char ch,string s){ // base case; if (s.length() == 0) return 0; int count = 0; // checking if the first character of // the given string is that character // or not if (s[0] == ch) count++; // this will count the occurrence of // given character in the string // from index 1 to the last // index of the string count += countinString(ch, s.substr(1)); return count;} int main(){ string str = \"geeksforgeeks\"; char c = 'e'; cout<<(countinString(c, str));} // This code is contributed by shinjanpatra",
"e": 4891,
"s": 4245,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { static int countinString(char ch, String s) { //base case; if(s.length()==0) return 0; int count = 0; //checking if the first character of //the given string is that character //or not if(s.charAt(0)==ch) count++; //this will count the occurrence of //given character in the string //from index 1 to the last //index of the string count+=countinString(ch,s.substring(1)); return count; } public static void main (String[] args) { String str= \"geeksforgeeks\"; char c = 'e'; System.out.println(countinString(c,str)); }}",
"e": 5697,
"s": 4891,
"text": null
},
{
"code": "def countinString(ch, s): # base case; if (len(s) == 0): return 0 count = 0 # checking if the first character of # the given string is that character # or not if (s[0] == ch): count += 1 # this will count the occurrence of # given character in the string # from index 1 to the last # index of the string count += countinString(ch, s[1:]) return count str = \"geeksforgeeks\"c = 'e'print(countinString(c, str)) # This code is contributed by shinjanpatra",
"e": 6209,
"s": 5697,
"text": null
},
{
"code": "/*package whatever //do not write package name here */using System;public class GFG { static int countinString(char ch, String s) { // base case; if(s.Length == 0) return 0; int count = 0; // checking if the first character of // the given string is that character // or not if(s[0] == ch) count++; // this will count the occurrence of // given character in the string // from index 1 to the last // index of the string count += countinString(ch,s.Substring(1)); return count; } // Driver code public static void Main(String[] args) { String str= \"geeksforgeeks\"; char c = 'e'; Console.WriteLine(countinString(c,str)); }} // This code is contributed by umadevi9616",
"e": 7081,
"s": 6209,
"text": null
},
{
"code": "<script>/*package whatever //do not write package name here */ function countinString( ch, s) { // base case; if (s.length == 0) return 0; var count = 0; // checking if the first character of // the given string is that character // or not if (s[0] == ch) count++; // this will count the occurrence of // given character in the string // from index 1 to the last // index of the string count += countinString(ch, s.substring(1)); return count; } var str = \"geeksforgeeks\"; var c = 'e'; document.write(countinString(c, str)); // This code is contributed by gauravrajput1</script>",
"e": 7812,
"s": 7081,
"text": null
},
{
"code": null,
"e": 7820,
"s": 7812,
"text": "Output:"
},
{
"code": null,
"e": 7822,
"s": 7820,
"text": "4"
},
{
"code": null,
"e": 7890,
"s": 7822,
"text": "Time Complexity: O(len), where len is the size of the string given."
},
{
"code": null,
"e": 7958,
"s": 7890,
"text": "Auxiliary Space: O(len), where len is the size of the string given."
},
{
"code": null,
"e": 8383,
"s": 7958,
"text": "This article is contributed by Sahil 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8390,
"s": 8383,
"text": "Sam007"
},
{
"code": null,
"e": 8403,
"s": 8390,
"text": "nitin mittal"
},
{
"code": null,
"e": 8407,
"s": 8403,
"text": "le0"
},
{
"code": null,
"e": 8422,
"s": 8407,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 8441,
"s": 8422,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 8460,
"s": 8441,
"text": "surindertarika1234"
},
{
"code": null,
"e": 8474,
"s": 8460,
"text": "GauravRajput1"
},
{
"code": null,
"e": 8492,
"s": 8474,
"text": "patildhanu4111999"
},
{
"code": null,
"e": 8505,
"s": 8492,
"text": "shinjanpatra"
},
{
"code": null,
"e": 8523,
"s": 8505,
"text": "rohitmishra051000"
},
{
"code": null,
"e": 8527,
"s": 8523,
"text": "C++"
},
{
"code": null,
"e": 8535,
"s": 8527,
"text": "Strings"
},
{
"code": null,
"e": 8543,
"s": 8535,
"text": "Strings"
},
{
"code": null,
"e": 8547,
"s": 8543,
"text": "CPP"
},
{
"code": null,
"e": 8645,
"s": 8547,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8699,
"s": 8645,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8733,
"s": 8699,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 8750,
"s": 8733,
"text": "Substring in C++"
},
{
"code": null,
"e": 8774,
"s": 8750,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 8814,
"s": 8774,
"text": "2D Vector In C++ With User Defined Size"
},
{
"code": null,
"e": 8860,
"s": 8814,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 8885,
"s": 8860,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 8945,
"s": 8885,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8960,
"s": 8945,
"text": "C++ Data Types"
}
] |
Encrypt the string – 2 | 28 Jul, 2021
Given a string S consisting of N, lower case English alphabet, it is also given that a string is encrypted by first replacing every substring of the string consisting of the same character with the concatenation of that character and the hexadecimal representation of the size of the substring and then revering the whole string, the task is to find the encrypted string.
Note: All Hexadecimal letters should be converted to Lowercase letters.
Examples:
Input: S = “aaaaaaaaaaa”Output: ba Explanation:
First convert the given string to “a11” i.e. write, character along with its frequency.Then, change “a11” to “ab” because 11 is b in hexadecimal.Then, finally reverse the string i.e “ba”.
First convert the given string to “a11” i.e. write, character along with its frequency.
Then, change “a11” to “ab” because 11 is b in hexadecimal.
Then, finally reverse the string i.e “ba”.
Input: S = “abc”Output: 1c1b1a
Approach: The problem can be solved by iterating over the characters of the string S. Follow the steps below to solve this problem:
Initialize an empty string say, ans to store the answer.
Iterate over the characters of the string S, using the variable i, and perform the following steps:Find the count of a substring with the same character, S[i], starting from index i and store it in a variable, say, count.Now convert the count to hexadecimal representation, and append the character S[i] along with its frequencies hexadecimal representation.
Find the count of a substring with the same character, S[i], starting from index i and store it in a variable, say, count.
Now convert the count to hexadecimal representation, and append the character S[i] along with its frequencies hexadecimal representation.
Finally, reverse the string ans and then print it.
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 convert Decimal to Hexstring convertToHex(int num){ string temp = ""; while (num != 0) { int rem = num % 16; char c; if (rem < 10) { c = rem + 48; } else { c = rem + 87; } temp += c; num = num / 16; } return temp;} // Function to encrypt the stringstring encryptString(string S, int N){ string ans = ""; // Iterate the characters // of the string for (int i = 0; i < N; i++) { char ch = S[i]; int count = 0; string hex; // Iterate until S[i] is equal to ch while (i < N && S[i] == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal // representation hex = convertToHex(count); // Append the character ans += ch; // Append the characters frequency // in hexadecimal representation ans += hex; } // Reverse the obtained answer reverse(ans.begin(), ans.end()); // Return required answer return ans;} // Driver Codeint main(){ // Given Input string S = "abc"; int N = S.size(); // Function Call cout << encryptString(S, N); return 0;}
// Java program for above approachimport java.awt.*;import java.util.*;class GFG{ // Function to convert Decimal to Hex static String convertToHex(int num) { StringBuilder temp = new StringBuilder(); while (num != 0) { int rem = num % 16; char c; if (rem < 10) { c = (char) (rem + 48); } else { c = (char) (rem + 87); } temp.append(c); num = num / 16; } return temp.toString(); } // Function to encrypt the string static String encryptString(String S, int N) { StringBuilder ans = new StringBuilder(); // Iterate the characters // of the string for (int i = 0; i < N; i++) { char ch = S.charAt(i); int count = 0; String hex; // Iterate until S[i] is equal to ch while (i < N && S.charAt(i) == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal // representation hex = convertToHex(count); // Append the character ans.append(ch); // Append the characters frequency // in hexadecimal representation ans.append(hex); } // Reverse the obtained answer ans.reverse(); // Return required answer return ans.toString(); } // Driver Code public static void main(String[] args) { // Given Input String S = "abc"; int N = S.length(); // Function Call System.out.println(encryptString(S, N)); }} // This code is contributed by hritikrommie.
# Python3 program for the above approach # Function to convert Decimal to Hexdef convertToHex(num): temp = "" while (num != 0): rem = num % 16 c = 0 if (rem < 10): c = rem + 48 else: c = rem + 87 temp += chr(c) num = num // 16 return temp # Function to encrypt the stringdef encryptString(S, N): ans = "" # Iterate the characters # of the string for i in range(N): ch = S[i] count = 0 # Iterate until S[i] is equal to ch while (i < N and S[i] == ch): # Update count and i count += 1 i += 1 # Decrement i by 1 i -= 1 # Convert count to hexadecimal # representation hex = convertToHex(count) # Append the character ans += ch # Append the characters frequency # in hexadecimal representation ans += hex # Reverse the obtained answer ans = ans[::-1] # Return required answer return ans # Driver Codeif __name__ == '__main__': # Given Input S = "abc" N = len(S) # Function Call print(encryptString(S, N)) # This code is contributed by mohit kumar 29
// C# program for above approachusing System;class GFG{ // Function to convert Decimal to Hex static string convertToHex(int num) { string temp = ""; while (num != 0) { int rem = num % 16; char c; if (rem < 10) { c = (char) (rem + 48); } else { c = (char) (rem + 87); } temp = temp + c; num = num / 16; } return temp; } // Function to encrypt the string static string encryptString(string S, int N) { string ans = ""; // Iterate the characters // of the string for (int i = 0; i < N; i++) { char ch = S[i]; int count = 0; string hex; // Iterate until S[i] is equal to ch while (i < N && S[i] == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal // representation hex = convertToHex(count); // Append the character ans = ans + ch; // Append the characters frequency // in hexadecimal representation ans = ans + hex; } // Reverse the obtained answer char[] Ans = ans.ToCharArray(); Array.Reverse(Ans); ans = new string(Ans); // Return required answer return ans; } static void Main () { // Given Input string S = "abc"; int N = S.Length; // Function Call Console.WriteLine(encryptString(S, N)); }} // This code is contributed by suresh07.
<script> // JavaScript program for the above approach // Function to convert Decimal to Hexfunction convertToHex(num) { let temp = ""; while (num != 0) { let rem = num % 16; let c = 0; if (rem < 10) { c = rem + 48; } else { c = rem + 87; } temp += String.fromCharCode(c); num = Math.floor(num / 16); } return temp;} // Function to encrypt the stringfunction encryptString(S, N) { let ans = ""; // Iterate the characters // of the string for (let i = 0; i < N; i++) { let ch = S[i]; let count = 0; let hex; // Iterate until S[i] is equal to ch while (i < N && S[i] == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal // representation hex = convertToHex(count); // Append the character ans += ch; // Append the characters frequency // in hexadecimal representation ans += hex; } // Reverse the obtained answer ans = ans.split('').reverse().join(""); // Return required answer return ans;} // Driver Code // Given Inputlet S = "abc";let N = S.length; // Function Calldocument.write(encryptString(S, N)); </script>
1c1b1a
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
_saurabh_jaiswal
hritikrommie
suresh07
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Write a program to reverse an array or string
Reverse a string in Java
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 401,
"s": 28,
"text": "Given a string S consisting of N, lower case English alphabet, it is also given that a string is encrypted by first replacing every substring of the string consisting of the same character with the concatenation of that character and the hexadecimal representation of the size of the substring and then revering the whole string, the task is to find the encrypted string. "
},
{
"code": null,
"e": 473,
"s": 401,
"text": "Note: All Hexadecimal letters should be converted to Lowercase letters."
},
{
"code": null,
"e": 483,
"s": 473,
"text": "Examples:"
},
{
"code": null,
"e": 532,
"s": 483,
"text": "Input: S = “aaaaaaaaaaa”Output: ba Explanation:"
},
{
"code": null,
"e": 720,
"s": 532,
"text": "First convert the given string to “a11” i.e. write, character along with its frequency.Then, change “a11” to “ab” because 11 is b in hexadecimal.Then, finally reverse the string i.e “ba”."
},
{
"code": null,
"e": 808,
"s": 720,
"text": "First convert the given string to “a11” i.e. write, character along with its frequency."
},
{
"code": null,
"e": 867,
"s": 808,
"text": "Then, change “a11” to “ab” because 11 is b in hexadecimal."
},
{
"code": null,
"e": 910,
"s": 867,
"text": "Then, finally reverse the string i.e “ba”."
},
{
"code": null,
"e": 941,
"s": 910,
"text": "Input: S = “abc”Output: 1c1b1a"
},
{
"code": null,
"e": 1073,
"s": 941,
"text": "Approach: The problem can be solved by iterating over the characters of the string S. Follow the steps below to solve this problem:"
},
{
"code": null,
"e": 1130,
"s": 1073,
"text": "Initialize an empty string say, ans to store the answer."
},
{
"code": null,
"e": 1489,
"s": 1130,
"text": "Iterate over the characters of the string S, using the variable i, and perform the following steps:Find the count of a substring with the same character, S[i], starting from index i and store it in a variable, say, count.Now convert the count to hexadecimal representation, and append the character S[i] along with its frequencies hexadecimal representation."
},
{
"code": null,
"e": 1612,
"s": 1489,
"text": "Find the count of a substring with the same character, S[i], starting from index i and store it in a variable, say, count."
},
{
"code": null,
"e": 1750,
"s": 1612,
"text": "Now convert the count to hexadecimal representation, and append the character S[i] along with its frequencies hexadecimal representation."
},
{
"code": null,
"e": 1801,
"s": 1750,
"text": "Finally, reverse the string ans and then print it."
},
{
"code": null,
"e": 1852,
"s": 1801,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1856,
"s": 1852,
"text": "C++"
},
{
"code": null,
"e": 1861,
"s": 1856,
"text": "Java"
},
{
"code": null,
"e": 1869,
"s": 1861,
"text": "Python3"
},
{
"code": null,
"e": 1872,
"s": 1869,
"text": "C#"
},
{
"code": null,
"e": 1883,
"s": 1872,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to convert Decimal to Hexstring convertToHex(int num){ string temp = \"\"; while (num != 0) { int rem = num % 16; char c; if (rem < 10) { c = rem + 48; } else { c = rem + 87; } temp += c; num = num / 16; } return temp;} // Function to encrypt the stringstring encryptString(string S, int N){ string ans = \"\"; // Iterate the characters // of the string for (int i = 0; i < N; i++) { char ch = S[i]; int count = 0; string hex; // Iterate until S[i] is equal to ch while (i < N && S[i] == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal // representation hex = convertToHex(count); // Append the character ans += ch; // Append the characters frequency // in hexadecimal representation ans += hex; } // Reverse the obtained answer reverse(ans.begin(), ans.end()); // Return required answer return ans;} // Driver Codeint main(){ // Given Input string S = \"abc\"; int N = S.size(); // Function Call cout << encryptString(S, N); return 0;}",
"e": 3258,
"s": 1883,
"text": null
},
{
"code": "// Java program for above approachimport java.awt.*;import java.util.*;class GFG{ // Function to convert Decimal to Hex static String convertToHex(int num) { StringBuilder temp = new StringBuilder(); while (num != 0) { int rem = num % 16; char c; if (rem < 10) { c = (char) (rem + 48); } else { c = (char) (rem + 87); } temp.append(c); num = num / 16; } return temp.toString(); } // Function to encrypt the string static String encryptString(String S, int N) { StringBuilder ans = new StringBuilder(); // Iterate the characters // of the string for (int i = 0; i < N; i++) { char ch = S.charAt(i); int count = 0; String hex; // Iterate until S[i] is equal to ch while (i < N && S.charAt(i) == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal // representation hex = convertToHex(count); // Append the character ans.append(ch); // Append the characters frequency // in hexadecimal representation ans.append(hex); } // Reverse the obtained answer ans.reverse(); // Return required answer return ans.toString(); } // Driver Code public static void main(String[] args) { // Given Input String S = \"abc\"; int N = S.length(); // Function Call System.out.println(encryptString(S, N)); }} // This code is contributed by hritikrommie.",
"e": 5065,
"s": 3258,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to convert Decimal to Hexdef convertToHex(num): temp = \"\" while (num != 0): rem = num % 16 c = 0 if (rem < 10): c = rem + 48 else: c = rem + 87 temp += chr(c) num = num // 16 return temp # Function to encrypt the stringdef encryptString(S, N): ans = \"\" # Iterate the characters # of the string for i in range(N): ch = S[i] count = 0 # Iterate until S[i] is equal to ch while (i < N and S[i] == ch): # Update count and i count += 1 i += 1 # Decrement i by 1 i -= 1 # Convert count to hexadecimal # representation hex = convertToHex(count) # Append the character ans += ch # Append the characters frequency # in hexadecimal representation ans += hex # Reverse the obtained answer ans = ans[::-1] # Return required answer return ans # Driver Codeif __name__ == '__main__': # Given Input S = \"abc\" N = len(S) # Function Call print(encryptString(S, N)) # This code is contributed by mohit kumar 29",
"e": 6297,
"s": 5065,
"text": null
},
{
"code": "// C# program for above approachusing System;class GFG{ // Function to convert Decimal to Hex static string convertToHex(int num) { string temp = \"\"; while (num != 0) { int rem = num % 16; char c; if (rem < 10) { c = (char) (rem + 48); } else { c = (char) (rem + 87); } temp = temp + c; num = num / 16; } return temp; } // Function to encrypt the string static string encryptString(string S, int N) { string ans = \"\"; // Iterate the characters // of the string for (int i = 0; i < N; i++) { char ch = S[i]; int count = 0; string hex; // Iterate until S[i] is equal to ch while (i < N && S[i] == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal // representation hex = convertToHex(count); // Append the character ans = ans + ch; // Append the characters frequency // in hexadecimal representation ans = ans + hex; } // Reverse the obtained answer char[] Ans = ans.ToCharArray(); Array.Reverse(Ans); ans = new string(Ans); // Return required answer return ans; } static void Main () { // Given Input string S = \"abc\"; int N = S.Length; // Function Call Console.WriteLine(encryptString(S, N)); }} // This code is contributed by suresh07.",
"e": 8013,
"s": 6297,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to convert Decimal to Hexfunction convertToHex(num) { let temp = \"\"; while (num != 0) { let rem = num % 16; let c = 0; if (rem < 10) { c = rem + 48; } else { c = rem + 87; } temp += String.fromCharCode(c); num = Math.floor(num / 16); } return temp;} // Function to encrypt the stringfunction encryptString(S, N) { let ans = \"\"; // Iterate the characters // of the string for (let i = 0; i < N; i++) { let ch = S[i]; let count = 0; let hex; // Iterate until S[i] is equal to ch while (i < N && S[i] == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal // representation hex = convertToHex(count); // Append the character ans += ch; // Append the characters frequency // in hexadecimal representation ans += hex; } // Reverse the obtained answer ans = ans.split('').reverse().join(\"\"); // Return required answer return ans;} // Driver Code // Given Inputlet S = \"abc\";let N = S.length; // Function Calldocument.write(encryptString(S, N)); </script>",
"e": 9354,
"s": 8013,
"text": null
},
{
"code": null,
"e": 9361,
"s": 9354,
"text": "1c1b1a"
},
{
"code": null,
"e": 9406,
"s": 9363,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9423,
"s": 9408,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 9440,
"s": 9423,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 9453,
"s": 9440,
"text": "hritikrommie"
},
{
"code": null,
"e": 9462,
"s": 9453,
"text": "suresh07"
},
{
"code": null,
"e": 9475,
"s": 9462,
"text": "Mathematical"
},
{
"code": null,
"e": 9483,
"s": 9475,
"text": "Strings"
},
{
"code": null,
"e": 9491,
"s": 9483,
"text": "Strings"
},
{
"code": null,
"e": 9504,
"s": 9491,
"text": "Mathematical"
},
{
"code": null,
"e": 9602,
"s": 9504,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9634,
"s": 9602,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 9680,
"s": 9634,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 9724,
"s": 9680,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 9766,
"s": 9724,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 9828,
"s": 9766,
"text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms"
},
{
"code": null,
"e": 9874,
"s": 9828,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 9899,
"s": 9874,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 9944,
"s": 9899,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 10001,
"s": 9944,
"text": "Python program to check if a string is palindrome or not"
}
] |
Sort string of characters | 06 Jul, 2022
Given a string of lowercase characters from ‘a’ – ‘z’. We need to write a program to print the characters of this string in sorted order.Examples:
Input : bbccdefbbaa
Output : aabbbbccdef
Input : geeksforgeeks
Output : eeeefggkkorss
A simple approach will be to use sorting algorithms like quick sort or merge sort and sort the input string and print it.
C++
Java
Python3
C#
Javascript
// C++ program to sort a string of characters#include<bits/stdc++.h>using namespace std; // function to print string in sorted ordervoid sortString(string &str){ sort(str.begin(), str.end()); cout << str;} // Driver program to test above functionint main(){ string s = "geeksforgeeks"; sortString(s); return 0;}
// Java program to sort a string of characters import java.util.Arrays; class GFG { // function to print string in sorted order static void sortString(String str) { char []arr = str.toCharArray(); Arrays.sort(arr); System.out.print(String.valueOf(arr)); } // Driver program to test above function public static void main(String[] args) { String s = "geeksforgeeks"; sortString(s); }}// This code is contributed by Rajput-Ji
# Python3 program to sort a string# of characters # function to print string in# sorted orderdef sortString(str) : str = ''.join(sorted(str)) print(str) # Driver Codes = "geeksforgeeks"sortString(s) # This code is contributed by Smitha
// C# program to sort a string of charactersusing System; public class GFG { // function to print string in sorted order static void sortString(String str) { char []arr = str.ToCharArray(); Array.Sort(arr); Console.WriteLine(String.Join("",arr)); } // Driver program to test above function public static void Main() { String s = "geeksforgeeks"; sortString(s); }}// This code is contributed by 29AjayKumar
<script> // javascript program to sort a string of characters let MAX_CHAR = 26; // function to print string in sorted order function sortString(str) { // Hash array to keep count of characters. // Initially count of all characters is // initialized to zero. let charCount = new Array(MAX_CHAR); charCount.fill(0); // Traverse string and increment // count of characters for (let i = 0; i < str.length; i++) // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. charCount[str[i].charCodeAt()-'a'.charCodeAt()]++; // Traverse the hash array and print // characters for (let i=0;i<MAX_CHAR;i++) for (let j=0;j<charCount[i];j++) document.write(String.fromCharCode('a'.charCodeAt()+i) ); } let s = "geeksforgeeks"; sortString(s); // This code is contributed by vaibhavrabadiya117.</script>
Output:
eeeefggkkorss
Time Complexity: O(n log n), where n is the length of string.
Auxiliary Space: O( 1 ).An efficient approach will be to observe first that there can be a total of 26 unique characters only. So, we can store the count of occurrences of all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the hashed array will represent character ‘a’, second will represent ‘b’ and so on. Finally, we will simply traverse the hashed array and print the characters from ‘a’ to ‘z’ the number of times they occurred in input string.Below is the implementation of above idea:
C++
Java
Python3
C#
Javascript
// C++ program to sort a string of characters#include<bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // function to print string in sorted ordervoid sortString(string &str){ // Hash array to keep count of characters. // Initially count of all characters is // initialized to zero. int charCount[MAX_CHAR] = {0}; // Traverse string and increment // count of characters for (int i=0; i<str.length(); i++) // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. charCount[str[i]-'a']++; // Traverse the hash array and print // characters for (int i=0;i<MAX_CHAR;i++) for (int j=0;j<charCount[i];j++) cout << (char)('a'+i);} // Driver program to test above functionint main(){ string s = "geeksforgeeks"; sortString(s); return 0;}
// Java program to sort// a string of characterspublic class SortString{ static final int MAX_CHAR = 26; // function to print string in sorted order static void sortString(String str) { // Hash array to keep count of characters. int letters[] = new int[MAX_CHAR]; // Traverse string and increment // count of characters for (char x : str.toCharArray()) { // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. letters[x - 'a']++; } // Traverse the hash array and print // characters for (int i = 0; i < MAX_CHAR; i++) { for (int j = 0; j < letters[i]; j++) { System.out.print((char) (i + 'a')); } } } // Driver program to test above function public static void main(String[] args) { sortString("geeksforgeeks"); }}// This code is contributed// by Sinuhe
# Python 3 program to sort a string# of characters MAX_CHAR = 26 # function to print string in sorted orderdef sortString(str): # Hash array to keep count of characters. # Initially count of all characters is # initialized to zero. charCount = [0 for i in range(MAX_CHAR)] # Traverse string and increment # count of characters for i in range(0, len(str), 1): # 'a'-'a' will be 0, 'b'-'a' will be 1, # so for location of character in count # array we will do str[i]-'a'. charCount[ord(str[i]) - ord('a')] += 1 # Traverse the hash array and print # characters for i in range(0, MAX_CHAR, 1): for j in range(0, charCount[i], 1): print(chr(ord('a') + i), end = "") # Driver Codeif __name__ == '__main__': s = "geeksforgeeks" sortString(s) # This code is contributed by# Sahil_Shelangia
// C# program to sort// a string of charactersusing System; class GFG{ // Method to sort a // string alphabetically public static string sortString(string inputString) { // convert input // string to char array char[] tempArray = inputString.ToCharArray(); // sort tempArray Array.Sort(tempArray); // return new sorted string return new string(tempArray); } // Driver Code public static void Main(string[] args) { string inputString = "geeksforgeeks"; Console.WriteLine(sortString(inputString)); }} // This code is contributed by Shrikant13
<script> // JavaScript program to sort// a string of characters let MAX_CHAR = 26; // function to print string in sorted orderfunction sortString(str){// Hash array to keep count of characters. let letters=new Array(MAX_CHAR); for(let i=0;i<MAX_CHAR;i++) { letters[i]=0; } // Traverse string and increment // count of characters for(let x=0;x<str.length;x++) { // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. letters[str[x].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Traverse the hash array and print // characters for (let i = 0; i < MAX_CHAR; i++) { for (let j = 0; j < letters[i]; j++) { document.write(String.fromCharCode (i + 'a'.charCodeAt(0))); } }} // Driver program to test above functionsortString("geeksforgeeks"); // This code is contributed by rag2127 </script>
Output:
eeeefggkkorss
Time Complexity: O(Max_CHAR*n) which becomes O(n) as MAX_CHAR is constant,So Overall Time Complexity:- O(n) where n is the length of the string. Auxiliary Space: O( 1 ).This article is contributed by Aarti_Rathi and Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prabhat kumar singh
shrikanth13
Rajput-Ji
29AjayKumar
sahilshelangia
Smitha Dinesh Semwal
SinuheVelez
vaibhavrabadiya117
rag2127
sudhanshusingh
codefast
kk9826225
simmytarika5
gulshankumarar231
codewithrathi
Hash
Sorting
Strings
Hash
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 201,
"s": 52,
"text": "Given a string of lowercase characters from ‘a’ – ‘z’. We need to write a program to print the characters of this string in sorted order.Examples: "
},
{
"code": null,
"e": 289,
"s": 201,
"text": "Input : bbccdefbbaa \nOutput : aabbbbccdef\n\nInput : geeksforgeeks\nOutput : eeeefggkkorss"
},
{
"code": null,
"e": 415,
"s": 291,
"text": "A simple approach will be to use sorting algorithms like quick sort or merge sort and sort the input string and print it. "
},
{
"code": null,
"e": 419,
"s": 415,
"text": "C++"
},
{
"code": null,
"e": 424,
"s": 419,
"text": "Java"
},
{
"code": null,
"e": 432,
"s": 424,
"text": "Python3"
},
{
"code": null,
"e": 435,
"s": 432,
"text": "C#"
},
{
"code": null,
"e": 446,
"s": 435,
"text": "Javascript"
},
{
"code": "// C++ program to sort a string of characters#include<bits/stdc++.h>using namespace std; // function to print string in sorted ordervoid sortString(string &str){ sort(str.begin(), str.end()); cout << str;} // Driver program to test above functionint main(){ string s = \"geeksforgeeks\"; sortString(s); return 0;}",
"e": 771,
"s": 446,
"text": null
},
{
"code": "// Java program to sort a string of characters import java.util.Arrays; class GFG { // function to print string in sorted order static void sortString(String str) { char []arr = str.toCharArray(); Arrays.sort(arr); System.out.print(String.valueOf(arr)); } // Driver program to test above function public static void main(String[] args) { String s = \"geeksforgeeks\"; sortString(s); }}// This code is contributed by Rajput-Ji",
"e": 1242,
"s": 771,
"text": null
},
{
"code": "# Python3 program to sort a string# of characters # function to print string in# sorted orderdef sortString(str) : str = ''.join(sorted(str)) print(str) # Driver Codes = \"geeksforgeeks\"sortString(s) # This code is contributed by Smitha",
"e": 1484,
"s": 1242,
"text": null
},
{
"code": "// C# program to sort a string of charactersusing System; public class GFG { // function to print string in sorted order static void sortString(String str) { char []arr = str.ToCharArray(); Array.Sort(arr); Console.WriteLine(String.Join(\"\",arr)); } // Driver program to test above function public static void Main() { String s = \"geeksforgeeks\"; sortString(s); }}// This code is contributed by 29AjayKumar",
"e": 1939,
"s": 1484,
"text": null
},
{
"code": "<script> // javascript program to sort a string of characters let MAX_CHAR = 26; // function to print string in sorted order function sortString(str) { // Hash array to keep count of characters. // Initially count of all characters is // initialized to zero. let charCount = new Array(MAX_CHAR); charCount.fill(0); // Traverse string and increment // count of characters for (let i = 0; i < str.length; i++) // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. charCount[str[i].charCodeAt()-'a'.charCodeAt()]++; // Traverse the hash array and print // characters for (let i=0;i<MAX_CHAR;i++) for (let j=0;j<charCount[i];j++) document.write(String.fromCharCode('a'.charCodeAt()+i) ); } let s = \"geeksforgeeks\"; sortString(s); // This code is contributed by vaibhavrabadiya117.</script>",
"e": 2985,
"s": 1939,
"text": null
},
{
"code": null,
"e": 2995,
"s": 2985,
"text": "Output: "
},
{
"code": null,
"e": 3009,
"s": 2995,
"text": "eeeefggkkorss"
},
{
"code": null,
"e": 3071,
"s": 3009,
"text": "Time Complexity: O(n log n), where n is the length of string."
},
{
"code": null,
"e": 3586,
"s": 3071,
"text": "Auxiliary Space: O( 1 ).An efficient approach will be to observe first that there can be a total of 26 unique characters only. So, we can store the count of occurrences of all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the hashed array will represent character ‘a’, second will represent ‘b’ and so on. Finally, we will simply traverse the hashed array and print the characters from ‘a’ to ‘z’ the number of times they occurred in input string.Below is the implementation of above idea: "
},
{
"code": null,
"e": 3592,
"s": 3588,
"text": "C++"
},
{
"code": null,
"e": 3597,
"s": 3592,
"text": "Java"
},
{
"code": null,
"e": 3605,
"s": 3597,
"text": "Python3"
},
{
"code": null,
"e": 3608,
"s": 3605,
"text": "C#"
},
{
"code": null,
"e": 3619,
"s": 3608,
"text": "Javascript"
},
{
"code": "// C++ program to sort a string of characters#include<bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // function to print string in sorted ordervoid sortString(string &str){ // Hash array to keep count of characters. // Initially count of all characters is // initialized to zero. int charCount[MAX_CHAR] = {0}; // Traverse string and increment // count of characters for (int i=0; i<str.length(); i++) // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. charCount[str[i]-'a']++; // Traverse the hash array and print // characters for (int i=0;i<MAX_CHAR;i++) for (int j=0;j<charCount[i];j++) cout << (char)('a'+i);} // Driver program to test above functionint main(){ string s = \"geeksforgeeks\"; sortString(s); return 0;}",
"e": 4522,
"s": 3619,
"text": null
},
{
"code": "// Java program to sort// a string of characterspublic class SortString{ static final int MAX_CHAR = 26; // function to print string in sorted order static void sortString(String str) { // Hash array to keep count of characters. int letters[] = new int[MAX_CHAR]; // Traverse string and increment // count of characters for (char x : str.toCharArray()) { // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. letters[x - 'a']++; } // Traverse the hash array and print // characters for (int i = 0; i < MAX_CHAR; i++) { for (int j = 0; j < letters[i]; j++) { System.out.print((char) (i + 'a')); } } } // Driver program to test above function public static void main(String[] args) { sortString(\"geeksforgeeks\"); }}// This code is contributed// by Sinuhe",
"e": 5520,
"s": 4522,
"text": null
},
{
"code": "# Python 3 program to sort a string# of characters MAX_CHAR = 26 # function to print string in sorted orderdef sortString(str): # Hash array to keep count of characters. # Initially count of all characters is # initialized to zero. charCount = [0 for i in range(MAX_CHAR)] # Traverse string and increment # count of characters for i in range(0, len(str), 1): # 'a'-'a' will be 0, 'b'-'a' will be 1, # so for location of character in count # array we will do str[i]-'a'. charCount[ord(str[i]) - ord('a')] += 1 # Traverse the hash array and print # characters for i in range(0, MAX_CHAR, 1): for j in range(0, charCount[i], 1): print(chr(ord('a') + i), end = \"\") # Driver Codeif __name__ == '__main__': s = \"geeksforgeeks\" sortString(s) # This code is contributed by# Sahil_Shelangia",
"e": 6412,
"s": 5520,
"text": null
},
{
"code": "// C# program to sort// a string of charactersusing System; class GFG{ // Method to sort a // string alphabetically public static string sortString(string inputString) { // convert input // string to char array char[] tempArray = inputString.ToCharArray(); // sort tempArray Array.Sort(tempArray); // return new sorted string return new string(tempArray); } // Driver Code public static void Main(string[] args) { string inputString = \"geeksforgeeks\"; Console.WriteLine(sortString(inputString)); }} // This code is contributed by Shrikant13",
"e": 7061,
"s": 6412,
"text": null
},
{
"code": "<script> // JavaScript program to sort// a string of characters let MAX_CHAR = 26; // function to print string in sorted orderfunction sortString(str){// Hash array to keep count of characters. let letters=new Array(MAX_CHAR); for(let i=0;i<MAX_CHAR;i++) { letters[i]=0; } // Traverse string and increment // count of characters for(let x=0;x<str.length;x++) { // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. letters[str[x].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Traverse the hash array and print // characters for (let i = 0; i < MAX_CHAR; i++) { for (let j = 0; j < letters[i]; j++) { document.write(String.fromCharCode (i + 'a'.charCodeAt(0))); } }} // Driver program to test above functionsortString(\"geeksforgeeks\"); // This code is contributed by rag2127 </script>",
"e": 8063,
"s": 7061,
"text": null
},
{
"code": null,
"e": 8073,
"s": 8063,
"text": "Output: "
},
{
"code": null,
"e": 8087,
"s": 8073,
"text": "eeeefggkkorss"
},
{
"code": null,
"e": 8696,
"s": 8087,
"text": "Time Complexity: O(Max_CHAR*n) which becomes O(n) as MAX_CHAR is constant,So Overall Time Complexity:- O(n) where n is the length of the string. Auxiliary Space: O( 1 ).This article is contributed by Aarti_Rathi and Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 8716,
"s": 8696,
"text": "prabhat kumar singh"
},
{
"code": null,
"e": 8728,
"s": 8716,
"text": "shrikanth13"
},
{
"code": null,
"e": 8738,
"s": 8728,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8750,
"s": 8738,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8765,
"s": 8750,
"text": "sahilshelangia"
},
{
"code": null,
"e": 8786,
"s": 8765,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 8798,
"s": 8786,
"text": "SinuheVelez"
},
{
"code": null,
"e": 8817,
"s": 8798,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 8825,
"s": 8817,
"text": "rag2127"
},
{
"code": null,
"e": 8840,
"s": 8825,
"text": "sudhanshusingh"
},
{
"code": null,
"e": 8849,
"s": 8840,
"text": "codefast"
},
{
"code": null,
"e": 8859,
"s": 8849,
"text": "kk9826225"
},
{
"code": null,
"e": 8872,
"s": 8859,
"text": "simmytarika5"
},
{
"code": null,
"e": 8890,
"s": 8872,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 8904,
"s": 8890,
"text": "codewithrathi"
},
{
"code": null,
"e": 8909,
"s": 8904,
"text": "Hash"
},
{
"code": null,
"e": 8917,
"s": 8909,
"text": "Sorting"
},
{
"code": null,
"e": 8925,
"s": 8917,
"text": "Strings"
},
{
"code": null,
"e": 8930,
"s": 8925,
"text": "Hash"
},
{
"code": null,
"e": 8938,
"s": 8930,
"text": "Strings"
},
{
"code": null,
"e": 8946,
"s": 8938,
"text": "Sorting"
},
{
"code": null,
"e": 9044,
"s": 8946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9129,
"s": 9044,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 9167,
"s": 9129,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 9203,
"s": 9167,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 9234,
"s": 9203,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 9261,
"s": 9234,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 9272,
"s": 9261,
"text": "Merge Sort"
},
{
"code": null,
"e": 9294,
"s": 9272,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 9304,
"s": 9294,
"text": "QuickSort"
},
{
"code": null,
"e": 9319,
"s": 9304,
"text": "Insertion Sort"
}
] |
How to convert Image to Byte Array in java? | Java provides ImageIO class for reading and writing an image. To convert an image to a byte array –
Read the image using the read() method of the ImageIO class.
Create a ByteArrayOutputStream object.
Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class.
Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageToByteArray {
public static void main(String args[]) throws Exception{
BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
}
} | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "Java provides ImageIO class for reading and writing an image. To convert an image to a byte array –"
},
{
"code": null,
"e": 1223,
"s": 1162,
"text": "Read the image using the read() method of the ImageIO class."
},
{
"code": null,
"e": 1262,
"s": 1223,
"text": "Create a ByteArrayOutputStream object."
},
{
"code": null,
"e": 1375,
"s": 1262,
"text": "Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class."
},
{
"code": null,
"e": 1481,
"s": 1375,
"text": "Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method."
},
{
"code": null,
"e": 1918,
"s": 1481,
"text": "import java.io.ByteArrayOutputStream;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport javax.imageio.ImageIO;\npublic class ImageToByteArray {\n public static void main(String args[]) throws Exception{\n BufferedImage bImage = ImageIO.read(new File(\"sample.jpg\"));\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n ImageIO.write(bImage, \"jpg\", bos );\n byte [] data = bos.toByteArray();\n }\n}"
}
] |
Using pandas crosstab to create a bar plot - GeeksforGeeks | 11 Jan, 2022
In this article, we will discuss how to create a bar plot by using pandas crosstab in Python. First Lets us know more about the crosstab, It is a simple cross-tabulation of two or more variables.
It is a simple cross-tabulation that help us to understand the relationship between two or more variable. It will give a clear understanding of the data and makes analysis easier.
Let us take an example if we take a data set of Handedness of people which includes peoples nationality, sex, age, and name. Suppose if we want to analyze the relationship between nationality and handedness of the peoples. Crosstab gives you the relationship between them.
Before creating the barplot we should create cross-tabulation using pandas.
Syntax: pandas.crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name=’All’, dropna=True, normalize=False
Code:
Python
# importing the pandas libraryimport pandas as pd # Reading the csv file and storing it# in a variabledf = pd.read_csv('Data.csv') # Crosstab function is called# 2 parameters are passed# The table is stored in a variablecrosstb = pd.crosstab(df.Nationality, df.Handedness)
Output:
Bar graphs are most used to compare between different groups or to track changes over time. Using bar plots to the crosstab is one of the efficient ways to conclude the crosstab and analyze them even better.
Syntax: DataFrame.plot.bar(x=None, y=None, **kwargs)
Code:
Python3
# importing the pandas libraryimport pandas as pd # Reading the csv file and storing it in a variabledf = pd.read_csv('Data.csv') # Creating crosstabcrosstb = pd.crosstab(df.Nationality, df.Handedness) # Creating barplotbarplot = crosstb.plot.bar(rot=0)
Output:
Here we will create a stacked barplot through dataframe by passing the stacked parameter as True.
Dataframe.plot(kind=”bar”, stacked = True, rot=0)
Code:
Python
# importing the pandas libraryimport pandas as pd # Reading csv filedf = pd.read_csv('Data.csv') # Creating crosstabcrosstb = pd.crosstab(df.Nationality, df.Handedness) # Creating barplotpl = crosstb.plot(kind="bar", stacked=True, rot=0)
Output:
In the above example, we found the relationship between nationality and the handedness of the people. We can also create a crosstab with more than two values. We will implement this in the following example.
Python3
# importing the moduleimport pandas as pd # reading the csv filedf = pd.read_csv('Data.csv') # Crosstab with three variablescrosstb = pd.crosstab(df.Sex, [df.Nationality, df.Handedness]) # Bar plotinga = crosstb.plot(kind='bar', rot=0)a.legend(title='Handedness', bbox_to_anchor=(1, 1.02), loc='upper left')
Output:
kashishsoda
sumitgumber28
Picked
Python pandas-plotting
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25690,
"s": 25662,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 25886,
"s": 25690,
"text": "In this article, we will discuss how to create a bar plot by using pandas crosstab in Python. First Lets us know more about the crosstab, It is a simple cross-tabulation of two or more variables."
},
{
"code": null,
"e": 26068,
"s": 25886,
"text": "It is a simple cross-tabulation that help us to understand the relationship between two or more variable. It will give a clear understanding of the data and makes analysis easier. "
},
{
"code": null,
"e": 26341,
"s": 26068,
"text": "Let us take an example if we take a data set of Handedness of people which includes peoples nationality, sex, age, and name. Suppose if we want to analyze the relationship between nationality and handedness of the peoples. Crosstab gives you the relationship between them."
},
{
"code": null,
"e": 26417,
"s": 26341,
"text": "Before creating the barplot we should create cross-tabulation using pandas."
},
{
"code": null,
"e": 26578,
"s": 26417,
"text": "Syntax: pandas.crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name=’All’, dropna=True, normalize=False"
},
{
"code": null,
"e": 26584,
"s": 26578,
"text": "Code:"
},
{
"code": null,
"e": 26591,
"s": 26584,
"text": "Python"
},
{
"code": "# importing the pandas libraryimport pandas as pd # Reading the csv file and storing it# in a variabledf = pd.read_csv('Data.csv') # Crosstab function is called# 2 parameters are passed# The table is stored in a variablecrosstb = pd.crosstab(df.Nationality, df.Handedness)",
"e": 26864,
"s": 26591,
"text": null
},
{
"code": null,
"e": 26872,
"s": 26864,
"text": "Output:"
},
{
"code": null,
"e": 27080,
"s": 26872,
"text": "Bar graphs are most used to compare between different groups or to track changes over time. Using bar plots to the crosstab is one of the efficient ways to conclude the crosstab and analyze them even better."
},
{
"code": null,
"e": 27133,
"s": 27080,
"text": "Syntax: DataFrame.plot.bar(x=None, y=None, **kwargs)"
},
{
"code": null,
"e": 27139,
"s": 27133,
"text": "Code:"
},
{
"code": null,
"e": 27147,
"s": 27139,
"text": "Python3"
},
{
"code": "# importing the pandas libraryimport pandas as pd # Reading the csv file and storing it in a variabledf = pd.read_csv('Data.csv') # Creating crosstabcrosstb = pd.crosstab(df.Nationality, df.Handedness) # Creating barplotbarplot = crosstb.plot.bar(rot=0)",
"e": 27401,
"s": 27147,
"text": null
},
{
"code": null,
"e": 27409,
"s": 27401,
"text": "Output:"
},
{
"code": null,
"e": 27507,
"s": 27409,
"text": "Here we will create a stacked barplot through dataframe by passing the stacked parameter as True."
},
{
"code": null,
"e": 27557,
"s": 27507,
"text": "Dataframe.plot(kind=”bar”, stacked = True, rot=0)"
},
{
"code": null,
"e": 27563,
"s": 27557,
"text": "Code:"
},
{
"code": null,
"e": 27570,
"s": 27563,
"text": "Python"
},
{
"code": "# importing the pandas libraryimport pandas as pd # Reading csv filedf = pd.read_csv('Data.csv') # Creating crosstabcrosstb = pd.crosstab(df.Nationality, df.Handedness) # Creating barplotpl = crosstb.plot(kind=\"bar\", stacked=True, rot=0)",
"e": 27808,
"s": 27570,
"text": null
},
{
"code": null,
"e": 27816,
"s": 27808,
"text": "Output:"
},
{
"code": null,
"e": 28025,
"s": 27816,
"text": "In the above example, we found the relationship between nationality and the handedness of the people. We can also create a crosstab with more than two values. We will implement this in the following example. "
},
{
"code": null,
"e": 28033,
"s": 28025,
"text": "Python3"
},
{
"code": "# importing the moduleimport pandas as pd # reading the csv filedf = pd.read_csv('Data.csv') # Crosstab with three variablescrosstb = pd.crosstab(df.Sex, [df.Nationality, df.Handedness]) # Bar plotinga = crosstb.plot(kind='bar', rot=0)a.legend(title='Handedness', bbox_to_anchor=(1, 1.02), loc='upper left')",
"e": 28379,
"s": 28033,
"text": null
},
{
"code": null,
"e": 28387,
"s": 28379,
"text": "Output:"
},
{
"code": null,
"e": 28399,
"s": 28387,
"text": "kashishsoda"
},
{
"code": null,
"e": 28413,
"s": 28399,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28420,
"s": 28413,
"text": "Picked"
},
{
"code": null,
"e": 28443,
"s": 28420,
"text": "Python pandas-plotting"
},
{
"code": null,
"e": 28457,
"s": 28443,
"text": "Python-pandas"
},
{
"code": null,
"e": 28464,
"s": 28457,
"text": "Python"
},
{
"code": null,
"e": 28562,
"s": 28464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28594,
"s": 28562,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28636,
"s": 28594,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28678,
"s": 28636,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28734,
"s": 28678,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28761,
"s": 28734,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28792,
"s": 28761,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28821,
"s": 28792,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28843,
"s": 28821,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28882,
"s": 28843,
"text": "Python | Get unique values from a list"
}
] |
Print pyramid of GeeksforGeeks in PL/SQL - GeeksforGeeks | 30 Jul, 2021
PL/SQL is a block-structured language that enables developers to combine the power of SQL with procedural statements. All the statements of a block are passed to the oracle engine all at once which increases processing speed and decreases the traffic.PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural language that is more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other.
Typically, each block performs a logical action in the program. A block has the following structure:
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
Now write a program in pl/sql which print a pyramid of string “GeeksforGeeks” shown below
Examples –
GeeksforGeeks
GeeksforGeek
GeeksforGee
GeeksforGe
GeeksforG
Geeksfor
Geeksfo
Geeksf
Geeks
Geek
Gee
Ge
G
Code –
C++
--Declaration BlockDECLARE -- declaration of string as Geeksforgeeksstr VARCHAR2(100) := 'GeeksforGeeks'; -- len of string and num for no of rowslen VARCHAR2(100);num NUMBER(15); -- execution part beginBEGIN --calculating length of stringnum:=LENGTH(str); -- starting of while from-- from num to till num>1WHILE num>=1 LOOP len:=SUBSTR(str,1,num); num:=num-1; DBMS_OUTPUT.PUT_LINE(len); --ending of loop here END LOOP; -- end of beginning blockEND; -- End program
Output:
GeeksforGeeks
GeeksforGeek
GeeksforGee
GeeksforGe
GeeksforG
Geeksfor
Geeksfo
Geeksf
Geeks
Geek
Gee
Ge
G
Disadvantages of SQL –
SQL doesn’t provide the programmers with a technique of condition checking, looping, and branching.
SQL statements are passed to the Oracle engine one at a time which increases traffic and decreases speed.
SQL has no facility of error checking during manipulation of data.
Akanksha_Rai
surindertarika1234
surinderdawra388
SQL-PL/SQL
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Characteristics of Internet of Things
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Advantages and Disadvantages of OOP
Introduction to Internet of Things (IoT) | Set 1
Election algorithm and distributed processing
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Activation Functions
Lex Program to count number of words | [
{
"code": null,
"e": 24772,
"s": 24744,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 25280,
"s": 24772,
"text": "PL/SQL is a block-structured language that enables developers to combine the power of SQL with procedural statements. All the statements of a block are passed to the oracle engine all at once which increases processing speed and decreases the traffic.PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural language that is more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other."
},
{
"code": null,
"e": 25381,
"s": 25280,
"text": "Typically, each block performs a logical action in the program. A block has the following structure:"
},
{
"code": null,
"e": 25502,
"s": 25381,
"text": "DECLARE\n declaration statements;\n\nBEGIN\n executable statements\n\nEXCEPTIONS\n exception handling statements\n\nEND;"
},
{
"code": null,
"e": 25592,
"s": 25502,
"text": "Now write a program in pl/sql which print a pyramid of string “GeeksforGeeks” shown below"
},
{
"code": null,
"e": 25604,
"s": 25592,
"text": "Examples – "
},
{
"code": null,
"e": 25708,
"s": 25604,
"text": "GeeksforGeeks\nGeeksforGeek\nGeeksforGee\nGeeksforGe\nGeeksforG\nGeeksfor\nGeeksfo\nGeeksf\nGeeks\nGeek\nGee\nGe\nG"
},
{
"code": null,
"e": 25715,
"s": 25708,
"text": "Code –"
},
{
"code": null,
"e": 25719,
"s": 25715,
"text": "C++"
},
{
"code": "--Declaration BlockDECLARE -- declaration of string as Geeksforgeeksstr VARCHAR2(100) := 'GeeksforGeeks'; -- len of string and num for no of rowslen VARCHAR2(100);num NUMBER(15); -- execution part beginBEGIN --calculating length of stringnum:=LENGTH(str); -- starting of while from-- from num to till num>1WHILE num>=1 LOOP len:=SUBSTR(str,1,num); num:=num-1; DBMS_OUTPUT.PUT_LINE(len); --ending of loop here END LOOP; -- end of beginning blockEND; -- End program",
"e": 26222,
"s": 25719,
"text": null
},
{
"code": null,
"e": 26231,
"s": 26222,
"text": "Output: "
},
{
"code": null,
"e": 26335,
"s": 26231,
"text": "GeeksforGeeks\nGeeksforGeek\nGeeksforGee\nGeeksforGe\nGeeksforG\nGeeksfor\nGeeksfo\nGeeksf\nGeeks\nGeek\nGee\nGe\nG"
},
{
"code": null,
"e": 26359,
"s": 26335,
"text": "Disadvantages of SQL – "
},
{
"code": null,
"e": 26459,
"s": 26359,
"text": "SQL doesn’t provide the programmers with a technique of condition checking, looping, and branching."
},
{
"code": null,
"e": 26565,
"s": 26459,
"text": "SQL statements are passed to the Oracle engine one at a time which increases traffic and decreases speed."
},
{
"code": null,
"e": 26632,
"s": 26565,
"text": "SQL has no facility of error checking during manipulation of data."
},
{
"code": null,
"e": 26645,
"s": 26632,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26664,
"s": 26645,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26681,
"s": 26664,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26692,
"s": 26681,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 26697,
"s": 26692,
"text": "Misc"
},
{
"code": null,
"e": 26702,
"s": 26697,
"text": "Misc"
},
{
"code": null,
"e": 26707,
"s": 26702,
"text": "Misc"
},
{
"code": null,
"e": 26805,
"s": 26707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26843,
"s": 26805,
"text": "Characteristics of Internet of Things"
},
{
"code": null,
"e": 26878,
"s": 26843,
"text": "Sensors in Internet of Things(IoT)"
},
{
"code": null,
"e": 26917,
"s": 26878,
"text": "Challenges in Internet of things (IoT)"
},
{
"code": null,
"e": 26953,
"s": 26917,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 27002,
"s": 26953,
"text": "Introduction to Internet of Things (IoT) | Set 1"
},
{
"code": null,
"e": 27048,
"s": 27002,
"text": "Election algorithm and distributed processing"
},
{
"code": null,
"e": 27080,
"s": 27048,
"text": "Introduction to Electronic Mail"
},
{
"code": null,
"e": 27130,
"s": 27080,
"text": "Communication Models in IoT (Internet of Things )"
},
{
"code": null,
"e": 27151,
"s": 27130,
"text": "Activation Functions"
}
] |
Magical String in C++ | Suppose there is a string. That string is called a magical string S, that consists of only '1' and '2' and obeys the following rules −
The string S is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string S itself.
The first few components of string S is the following − S = "1221121221221121122......"
If we group the consecutive '1's and '2's in S, it will be − 1 22 11 2 1 22 1 22 11 2 11 22 ...... and the occurrences of '1's or '2's in each group are − 1 2 2 1 1 2 1 2 2 1 2 2 ......
Now suppose we have an integer N as input, find the number of '1's in the first N number in the magical string S. So if the input is like 6, then the output will be 3, as first 6 elements in the magical string is “12211”. This contains three 1s, so return 3.
To solve this, we will follow these steps −
if n <= 0, then return 0, if n <= 3, then return 1
ret := 1, make an array arr of size n
arr[0] := 1, arr[1] := 2, arr[2] := 2
head := 2, tail := 3 and num := 1
while tail < nfor i in range 0 to arr[head] – 1arr[tail] := numif num is 1 and tail < n, then increase ret by 1increase tail by 1if tail >= n, then break the loopnum = num XOR 3increase head by 1
for i in range 0 to arr[head] – 1arr[tail] := numif num is 1 and tail < n, then increase ret by 1increase tail by 1if tail >= n, then break the loop
arr[tail] := num
if num is 1 and tail < n, then increase ret by 1
increase tail by 1
if tail >= n, then break the loop
num = num XOR 3
increase head by 1
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int magicalString(int n) {
if(n <= 0) return 0;
if(n <= 3) return 1;
int ret = 1;
vector <int> arr(n);
arr[0] = 1;
arr[1] = 2;
arr[2] = 2;
int head = 2;
int tail = 3;
int num = 1;
while(tail < n){
for(int i = 0; i < arr[head]; i++){
arr[tail] = num;
if(num == 1 && tail < n) ret++;
tail++;
if(tail >= n) break;
}
num ^= 3;
head++;
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.magicalString(6));
}
6
3 | [
{
"code": null,
"e": 1197,
"s": 1062,
"text": "Suppose there is a string. That string is called a magical string S, that consists of only '1' and '2' and obeys the following rules −"
},
{
"code": null,
"e": 1337,
"s": 1197,
"text": "The string S is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string S itself."
},
{
"code": null,
"e": 1425,
"s": 1337,
"text": "The first few components of string S is the following − S = \"1221121221221121122......\""
},
{
"code": null,
"e": 1611,
"s": 1425,
"text": "If we group the consecutive '1's and '2's in S, it will be − 1 22 11 2 1 22 1 22 11 2 11 22 ...... and the occurrences of '1's or '2's in each group are − 1 2 2 1 1 2 1 2 2 1 2 2 ......"
},
{
"code": null,
"e": 1870,
"s": 1611,
"text": "Now suppose we have an integer N as input, find the number of '1's in the first N number in the magical string S. So if the input is like 6, then the output will be 3, as first 6 elements in the magical string is “12211”. This contains three 1s, so return 3."
},
{
"code": null,
"e": 1914,
"s": 1870,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1965,
"s": 1914,
"text": "if n <= 0, then return 0, if n <= 3, then return 1"
},
{
"code": null,
"e": 2003,
"s": 1965,
"text": "ret := 1, make an array arr of size n"
},
{
"code": null,
"e": 2041,
"s": 2003,
"text": "arr[0] := 1, arr[1] := 2, arr[2] := 2"
},
{
"code": null,
"e": 2075,
"s": 2041,
"text": "head := 2, tail := 3 and num := 1"
},
{
"code": null,
"e": 2271,
"s": 2075,
"text": "while tail < nfor i in range 0 to arr[head] – 1arr[tail] := numif num is 1 and tail < n, then increase ret by 1increase tail by 1if tail >= n, then break the loopnum = num XOR 3increase head by 1"
},
{
"code": null,
"e": 2420,
"s": 2271,
"text": "for i in range 0 to arr[head] – 1arr[tail] := numif num is 1 and tail < n, then increase ret by 1increase tail by 1if tail >= n, then break the loop"
},
{
"code": null,
"e": 2437,
"s": 2420,
"text": "arr[tail] := num"
},
{
"code": null,
"e": 2486,
"s": 2437,
"text": "if num is 1 and tail < n, then increase ret by 1"
},
{
"code": null,
"e": 2505,
"s": 2486,
"text": "increase tail by 1"
},
{
"code": null,
"e": 2539,
"s": 2505,
"text": "if tail >= n, then break the loop"
},
{
"code": null,
"e": 2555,
"s": 2539,
"text": "num = num XOR 3"
},
{
"code": null,
"e": 2574,
"s": 2555,
"text": "increase head by 1"
},
{
"code": null,
"e": 2585,
"s": 2574,
"text": "return ret"
},
{
"code": null,
"e": 2655,
"s": 2585,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2666,
"s": 2655,
"text": " Live Demo"
},
{
"code": null,
"e": 3318,
"s": 2666,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int magicalString(int n) {\n if(n <= 0) return 0;\n if(n <= 3) return 1;\n int ret = 1;\n vector <int> arr(n);\n arr[0] = 1;\n arr[1] = 2;\n arr[2] = 2;\n int head = 2;\n int tail = 3;\n int num = 1;\n while(tail < n){\n for(int i = 0; i < arr[head]; i++){\n arr[tail] = num;\n if(num == 1 && tail < n) ret++;\n tail++;\n if(tail >= n) break;\n }\n num ^= 3;\n head++;\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.magicalString(6));\n}"
},
{
"code": null,
"e": 3320,
"s": 3318,
"text": "6"
},
{
"code": null,
"e": 3322,
"s": 3320,
"text": "3"
}
] |
Java catch Keyword | ❮ Java Keywords
If an error occur, use try...catch to catch the error and execute some code to handle it:
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
Try it Yourself »
The catch keyword catches exceptions generated by try statements.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Read more about exceptions in our Java Try..Catch Tutorial.
❮ Java Keywords
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 18,
"s": 0,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 108,
"s": 18,
"text": "If an error occur, use try...catch to catch the error and execute some code to handle it:"
},
{
"code": null,
"e": 256,
"s": 108,
"text": "try {\n int[] myNumbers = {1, 2, 3};\n System.out.println(myNumbers[10]);\n} catch (Exception e) {\n System.out.println(\"Something went wrong.\");\n}\n"
},
{
"code": null,
"e": 276,
"s": 256,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 342,
"s": 276,
"text": "The catch keyword catches exceptions generated by try statements."
},
{
"code": null,
"e": 452,
"s": 342,
"text": "The catch statement allows you to define a block of code to be executed, if an error occurs in the try block."
},
{
"code": null,
"e": 512,
"s": 452,
"text": "Read more about exceptions in our Java Try..Catch Tutorial."
},
{
"code": null,
"e": 530,
"s": 512,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 563,
"s": 530,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 605,
"s": 563,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 712,
"s": 605,
"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": 731,
"s": 712,
"text": "[email protected]"
}
] |
Output of Java Programs | Set 32 - GeeksforGeeks | 11 Sep, 2017
Prerequisite : Arrays in Java
Question 1. What is the output of following program?
class ArrayDemo {public static void main(String[] args) { int arr1[] = { 1, 2, 3, 4, 5 }; int arr2[5] = { 1, 2, 3, 4, 5 }; for (int i = 0; i < 5; i++) System.out.print(arr1[i] + " "); System.out.println(); for (int i = 0; i < 5; i++) System.out.print(arr2[i] + " "); }}
OptionA) 1 2 3 4 51 2 3 4 5B) 1 2 3 4 51 2 3 4C) ErrorD)Exception
Output: C
Explanation : In Java at the time of declaration, we can not specify the size otherwise we will get compile time Error : 1-‘]’ expected, 2- illegal start of expression
Question 2. What is the output of following program?
class ArrayDemo1 {public static void main(String[] args) { int arr1[], arr2[]; int[] arr3, [] arr4; }}
OptionA) Compile time ErrorB) Run time ExceptionC) 4 empty size Array are initializedD) none
Output: A
Explanation : In java, if we want to specify dimension before the variable that facility is applicable only for first variable in a declaration. otherwise we will get compile time error –
1- expected.
2- ';' expected.
Question 3. What is the output of following program?
class ArrayDemo1 {public static void main(String[] args) { int arr1[] = new int[0]; int arr2[] = new int[-1]; System.out.print(arr1.length + " : " + arr2.length); }}
OptionA) 0 : 0B) 0 : -1C) Compiler ErrorD) Run time Exception
Output: D
Explanation : In java, if we are trying to specify Array size with some negative int value then we will get run time exception – NegativeArraySizeException.
Question 4. What is the output of following program?
class ArrayDemo1 {public static void main(String[] args) { int arr1[] = new int[2147483647]; int arr2[] = new int[2147483648]; System.out.println(arr1.length); System.out.println(arr2.length); }}
OptionA) 21474836472147483648B) ErrorC) 2147483647-1D) 21474836472147483646
Output: B
Explanation :In java, maximum allowed array size is 2147483647 which is the maximum value of int.if you will give more than this range then we will get compile time error – integer number too large.
Question 5. What is the output of following program?
class ArrayDemo1 {public static void main(String[] args) { short s = 45; int arr1[] = new int[s]; char ch = 'A'; int arr2[] = new int[ch]; long l = 10; int arr3[] = new int[l]; System.out.println(arr1.length); System.out.println(arr2.length); System.out.println(arr3.length); }}
OptionA)456510B) 45A10C)ErrorD)no output
Output: C
Explanation : In java, we can specify the array size with char, sort, int, byte but we can not with long, double, string and float size. Otherwise we will get compile time error – incompatible types: possible lossy conversion.
This article is contributed by Shivakant Jaiswal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Arrays
Java-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to copy a string in C/C++
Runtime Errors
Output of Python Program | Set 1
C++ Programming Multiple Choice Questions
Output of C Programs | Set 2
unsigned specifier (%u) in C with Examples
Output of C++ programs | Set 50
Output of C++ Program | Set 1
Output of C Programs | Set 3
How to show full column content in a PySpark Dataframe ? | [
{
"code": null,
"e": 24440,
"s": 24412,
"text": "\n11 Sep, 2017"
},
{
"code": null,
"e": 24470,
"s": 24440,
"text": "Prerequisite : Arrays in Java"
},
{
"code": null,
"e": 24523,
"s": 24470,
"text": "Question 1. What is the output of following program?"
},
{
"code": "class ArrayDemo {public static void main(String[] args) { int arr1[] = { 1, 2, 3, 4, 5 }; int arr2[5] = { 1, 2, 3, 4, 5 }; for (int i = 0; i < 5; i++) System.out.print(arr1[i] + \" \"); System.out.println(); for (int i = 0; i < 5; i++) System.out.print(arr2[i] + \" \"); }}",
"e": 24862,
"s": 24523,
"text": null
},
{
"code": null,
"e": 24928,
"s": 24862,
"text": "OptionA) 1 2 3 4 51 2 3 4 5B) 1 2 3 4 51 2 3 4C) ErrorD)Exception"
},
{
"code": null,
"e": 24938,
"s": 24928,
"text": "Output: C"
},
{
"code": null,
"e": 25106,
"s": 24938,
"text": "Explanation : In Java at the time of declaration, we can not specify the size otherwise we will get compile time Error : 1-‘]’ expected, 2- illegal start of expression"
},
{
"code": null,
"e": 25159,
"s": 25106,
"text": "Question 2. What is the output of following program?"
},
{
"code": "class ArrayDemo1 {public static void main(String[] args) { int arr1[], arr2[]; int[] arr3, [] arr4; }}",
"e": 25282,
"s": 25159,
"text": null
},
{
"code": null,
"e": 25375,
"s": 25282,
"text": "OptionA) Compile time ErrorB) Run time ExceptionC) 4 empty size Array are initializedD) none"
},
{
"code": null,
"e": 25385,
"s": 25375,
"text": "Output: A"
},
{
"code": null,
"e": 25573,
"s": 25385,
"text": "Explanation : In java, if we want to specify dimension before the variable that facility is applicable only for first variable in a declaration. otherwise we will get compile time error –"
},
{
"code": null,
"e": 25604,
"s": 25573,
"text": "1- expected.\n2- ';' expected."
},
{
"code": null,
"e": 25657,
"s": 25604,
"text": "Question 3. What is the output of following program?"
},
{
"code": "class ArrayDemo1 {public static void main(String[] args) { int arr1[] = new int[0]; int arr2[] = new int[-1]; System.out.print(arr1.length + \" : \" + arr2.length); }}",
"e": 25852,
"s": 25657,
"text": null
},
{
"code": null,
"e": 25914,
"s": 25852,
"text": "OptionA) 0 : 0B) 0 : -1C) Compiler ErrorD) Run time Exception"
},
{
"code": null,
"e": 25924,
"s": 25914,
"text": "Output: D"
},
{
"code": null,
"e": 26081,
"s": 25924,
"text": "Explanation : In java, if we are trying to specify Array size with some negative int value then we will get run time exception – NegativeArraySizeException."
},
{
"code": null,
"e": 26134,
"s": 26081,
"text": "Question 4. What is the output of following program?"
},
{
"code": "class ArrayDemo1 {public static void main(String[] args) { int arr1[] = new int[2147483647]; int arr2[] = new int[2147483648]; System.out.println(arr1.length); System.out.println(arr2.length); }}",
"e": 26366,
"s": 26134,
"text": null
},
{
"code": null,
"e": 26442,
"s": 26366,
"text": "OptionA) 21474836472147483648B) ErrorC) 2147483647-1D) 21474836472147483646"
},
{
"code": null,
"e": 26452,
"s": 26442,
"text": "Output: B"
},
{
"code": null,
"e": 26651,
"s": 26452,
"text": "Explanation :In java, maximum allowed array size is 2147483647 which is the maximum value of int.if you will give more than this range then we will get compile time error – integer number too large."
},
{
"code": null,
"e": 26704,
"s": 26651,
"text": "Question 5. What is the output of following program?"
},
{
"code": "class ArrayDemo1 {public static void main(String[] args) { short s = 45; int arr1[] = new int[s]; char ch = 'A'; int arr2[] = new int[ch]; long l = 10; int arr3[] = new int[l]; System.out.println(arr1.length); System.out.println(arr2.length); System.out.println(arr3.length); }}",
"e": 27058,
"s": 26704,
"text": null
},
{
"code": null,
"e": 27099,
"s": 27058,
"text": "OptionA)456510B) 45A10C)ErrorD)no output"
},
{
"code": null,
"e": 27109,
"s": 27099,
"text": "Output: C"
},
{
"code": null,
"e": 27336,
"s": 27109,
"text": "Explanation : In java, we can specify the array size with char, sort, int, byte but we can not with long, double, string and float size. Otherwise we will get compile time error – incompatible types: possible lossy conversion."
},
{
"code": null,
"e": 27641,
"s": 27336,
"text": "This article is contributed by Shivakant Jaiswal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27766,
"s": 27641,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27778,
"s": 27766,
"text": "Java-Arrays"
},
{
"code": null,
"e": 27790,
"s": 27778,
"text": "Java-Output"
},
{
"code": null,
"e": 27805,
"s": 27790,
"text": "Program Output"
},
{
"code": null,
"e": 27903,
"s": 27805,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27912,
"s": 27903,
"text": "Comments"
},
{
"code": null,
"e": 27925,
"s": 27912,
"text": "Old Comments"
},
{
"code": null,
"e": 27966,
"s": 27925,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 27981,
"s": 27966,
"text": "Runtime Errors"
},
{
"code": null,
"e": 28014,
"s": 27981,
"text": "Output of Python Program | Set 1"
},
{
"code": null,
"e": 28056,
"s": 28014,
"text": "C++ Programming Multiple Choice Questions"
},
{
"code": null,
"e": 28085,
"s": 28056,
"text": "Output of C Programs | Set 2"
},
{
"code": null,
"e": 28128,
"s": 28085,
"text": "unsigned specifier (%u) in C with Examples"
},
{
"code": null,
"e": 28160,
"s": 28128,
"text": "Output of C++ programs | Set 50"
},
{
"code": null,
"e": 28190,
"s": 28160,
"text": "Output of C++ Program | Set 1"
},
{
"code": null,
"e": 28219,
"s": 28190,
"text": "Output of C Programs | Set 3"
}
] |
PyQt5 – How to change border style of MainWindow ? - GeeksforGeeks | 26 Mar, 2020
When we create a window in PyQt5, by default, there is no special type of border to it. But we change the style, thickness as well as color of the main window by using setStyleSheet() method.
Below is how normal border vs styled border looks like
Syntax : self.setStyleSheet(“border : 3px dashed blue;”)
Argument: It takes string as argument."border : size_of_border type_of_border color_of_border;"
Action performed : It sets the border style.
Code :
# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting geometry self.setGeometry(100, 100, 600, 400) # setting up the style of border self.setStyleSheet("border : 3px dashed blue;") # creating a label widget self.label_1 = QLabel("new border ", self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet("border :3px solid black;") # show all the widgets self.show() # 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.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Selecting rows in pandas DataFrame based on conditions | [
{
"code": null,
"e": 24928,
"s": 24900,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 25120,
"s": 24928,
"text": "When we create a window in PyQt5, by default, there is no special type of border to it. But we change the style, thickness as well as color of the main window by using setStyleSheet() method."
},
{
"code": null,
"e": 25176,
"s": 25120,
"text": "Below is how normal border vs styled border looks like "
},
{
"code": null,
"e": 25233,
"s": 25176,
"text": "Syntax : self.setStyleSheet(“border : 3px dashed blue;”)"
},
{
"code": null,
"e": 25329,
"s": 25233,
"text": "Argument: It takes string as argument.\"border : size_of_border type_of_border color_of_border;\""
},
{
"code": null,
"e": 25374,
"s": 25329,
"text": "Action performed : It sets the border style."
},
{
"code": null,
"e": 25381,
"s": 25374,
"text": "Code :"
},
{
"code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting geometry self.setGeometry(100, 100, 600, 400) # setting up the style of border self.setStyleSheet(\"border : 3px dashed blue;\") # creating a label widget self.label_1 = QLabel(\"new border \", self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet(\"border :3px solid black;\") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 26257,
"s": 25381,
"text": null
},
{
"code": null,
"e": 26266,
"s": 26257,
"text": "Output :"
},
{
"code": null,
"e": 26277,
"s": 26266,
"text": "Python-gui"
},
{
"code": null,
"e": 26289,
"s": 26277,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26296,
"s": 26289,
"text": "Python"
},
{
"code": null,
"e": 26394,
"s": 26296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26403,
"s": 26394,
"text": "Comments"
},
{
"code": null,
"e": 26416,
"s": 26403,
"text": "Old Comments"
},
{
"code": null,
"e": 26434,
"s": 26416,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26469,
"s": 26434,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26491,
"s": 26469,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26523,
"s": 26491,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26553,
"s": 26523,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26595,
"s": 26553,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26621,
"s": 26595,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26658,
"s": 26621,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26701,
"s": 26658,
"text": "Python program to convert a list to string"
}
] |
Class getSuperclass() method in Java with Examples - GeeksforGeeks | 27 Jan, 2022
The getSuperclass() method of java.lang.Class class is used to get the super class of this entity. This entity can be a class, an array, an interface, etc. The method returns the super class of this entity.Syntax:
public Class<T> getSuperclass()
Parameter: This method does not accept any parameter.Return Value: This method returns the super class of this entity.Below programs demonstrate the getSuperclass() method.Example 1:
Java
// Java program to demonstrate getSuperclass() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the super class of myClass // using getSuperclass() method System.out.println("Superclass of myClass: " + myClass.getSuperclass()); }}
Class represented by myClass: class Test
Superclass of myClass: class java.lang.Object
Example 2:
Java
// Java program to demonstrate getSuperclass() method public class Test { class Arr { } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for Arr Class arrClass = Arr.class; // Get the super class of arrClass // using getSuperclass() method System.out.println("Superclass of arrClass: " + arrClass.getSuperclass()); }}
Superclass of arrClass: class java.lang.Object
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getSuperclass–
adnanirshad158
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 24090,
"s": 24062,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 24306,
"s": 24090,
"text": "The getSuperclass() method of java.lang.Class class is used to get the super class of this entity. This entity can be a class, an array, an interface, etc. The method returns the super class of this entity.Syntax: "
},
{
"code": null,
"e": 24338,
"s": 24306,
"text": "public Class<T> getSuperclass()"
},
{
"code": null,
"e": 24522,
"s": 24338,
"text": "Parameter: This method does not accept any parameter.Return Value: This method returns the super class of this entity.Below programs demonstrate the getSuperclass() method.Example 1: "
},
{
"code": null,
"e": 24527,
"s": 24522,
"text": "Java"
},
{
"code": "// Java program to demonstrate getSuperclass() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the super class of myClass // using getSuperclass() method System.out.println(\"Superclass of myClass: \" + myClass.getSuperclass()); }}",
"e": 25084,
"s": 24527,
"text": null
},
{
"code": null,
"e": 25171,
"s": 25084,
"text": "Class represented by myClass: class Test\nSuperclass of myClass: class java.lang.Object"
},
{
"code": null,
"e": 25185,
"s": 25173,
"text": "Example 2: "
},
{
"code": null,
"e": 25190,
"s": 25185,
"text": "Java"
},
{
"code": "// Java program to demonstrate getSuperclass() method public class Test { class Arr { } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for Arr Class arrClass = Arr.class; // Get the super class of arrClass // using getSuperclass() method System.out.println(\"Superclass of arrClass: \" + arrClass.getSuperclass()); }}",
"e": 25644,
"s": 25190,
"text": null
},
{
"code": null,
"e": 25691,
"s": 25644,
"text": "Superclass of arrClass: class java.lang.Object"
},
{
"code": null,
"e": 25783,
"s": 25693,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getSuperclass– "
},
{
"code": null,
"e": 25798,
"s": 25783,
"text": "adnanirshad158"
},
{
"code": null,
"e": 25813,
"s": 25798,
"text": "Java-Functions"
},
{
"code": null,
"e": 25831,
"s": 25813,
"text": "Java-lang package"
},
{
"code": null,
"e": 25847,
"s": 25831,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 25852,
"s": 25847,
"text": "Java"
},
{
"code": null,
"e": 25857,
"s": 25852,
"text": "Java"
},
{
"code": null,
"e": 25955,
"s": 25857,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25970,
"s": 25955,
"text": "Stream In Java"
},
{
"code": null,
"e": 25989,
"s": 25970,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26010,
"s": 25989,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26056,
"s": 26010,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26086,
"s": 26056,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26103,
"s": 26086,
"text": "Generics in Java"
},
{
"code": null,
"e": 26146,
"s": 26103,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26168,
"s": 26146,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 26189,
"s": 26168,
"text": "Introduction to Java"
}
] |
EDA exploratory data analysis R Analytics python | Towards Data Science | While working on a Data Science or Machine Learning project or assignment, we have all felt the urge to fast-forward to the model building and prediction stage. However, as our mentors and experts reiterate, the initial Exploratory Data Analysis (EDA) phase is crucial to get better outcomes from the later stages of training a model and predictions. The estimates of time spent on EDA and data preparation range anywhere from 60–80% of the total time spent on a Data Science project.
Given this, are there packages in R that enable us to speed up our EDA while still doing a thorough job of it? Well, looks like there is !
In this Article, I would like to showcase the capabilities of the R package SmartEDA in making our lives easier in EDA. With just a single line of code using the methods in SmartEDA, we can get each of the following:
Much richer information
Better formatted output for readability
Comprehensive multi-point summary for each feature in the dateset
Visualize uni-variate and bi-variate analysis
All the above features of the SmartEDA come in very handy especially when handling a dataset with large number of features. Try using the traditional str()and summary()` functions with a dataset having over 10 features !
Let us now take SmartEDA for a test drive..
We will use the Titanic dataset from Kaggle. You can download it from here. This contains data on the passengers of the ill-fated Titanic voyage and if they survived the disaster or not.
#install.packages("SmartEDA")library(SmartEDA)data = read.csv("titanic.csv")
Here is a sample of the first few rows of the dataset.
head(data)
The dataset has passenger information including the class of travel, Name, Gender, Age, Number of siblings and spouses onboard, Number of Parents & Children onboard, Fare and Port of embarkation etc.
The ExpData() method gives a top level meta data information about the dataset.
ExpData(data, type=1)
The same method with type = 2 argument gives a neat summary of each feature in the dataset that includes variable type, % missing cases and number of unique values for each feature.
Awesome ! Right? Wait.. it gets better.
Summary of Continuous Features
The ExpNumStat() method generates a comprehensive multi-point statistical summary of all the continuous features in the dataset with a wealth of information including number of negative, zero and positive values, number of missing values and %, min, max, mean, median, standard deviation, coefficient of variation, IQR, Skew, Kurtosis and number of outliers... Whew !!
Also, ExpNumStat()automatically identifies the continuous features in the dataset. Here, below we have taken only a subset of all the summary points available for output. You can view the full output by removing the column index numbers and specify only the column index for the statistic of interest to you.
ExpNumStat(data,by ="A",Outlier=TRUE,round= 2)[,c(1,2,4:6,9:10,12:15,18,23)]
ExpNumStat(data, by = "A", Outlier = TRUE, round = 2)[,c(1,2,9,16:22)]
Further, setting the by argument to G or GA, we can get the summary split by ‘group’ and ‘group plus all’ by specifying a categorical feature in the group argument. This is especially useful in classification problems like the one we have here, where we can get a summary of the continuous features for each level of the categorical response variable (“Survived” in this dataset).
ExpNumStat(data[,-1],by = "GA",Outlier=TRUE,round= 2,gp = "Survived")[,c(1,2,4:6,9:10,12:15,18,23)]
In this case, we can clearly see that the Fare feature plays a big role in whether the passenger survived or not.
Summary of Categorical Features
What about summary of Categorical features? The ExpCatStat() method does the job here.
ExpCatStat(data, Target = "Survived")
The single line of code above not only provides the Chi-squared statistic and p-value between each categorical feature and the target feature, but also provides the information value(IV) for each feature and a useful labelling of its degree of association with the target feature and its predictive power. Talk about going beyond the call of duty !!
Visualization
With SmartEDA,it is not all output in numbers. It delivers in visually exploring data as well be it uni-variate or bi-variate analysis throughExpNumViz and ExpCatViz methods.
Bi-Variate Analysis : Between Pairs of Continuous Features
Passing the scatter = TRUE argument to ExpNumViz() gives a scatter plot between all the pairs of continuous features of the dateset. Here we plot Pclass vs Fare and Age vs SibSp (number of siblings/spouse on board) by selecting the index number of the plots.
ExpNumViz(data[,-1], scatter = TRUE)[4:5]
Passing just the dataset to the method plots the density distribution of each of the continuous features.
Bi-Variate Analysis : Continuous Features vs Categorical Response Feature
Again, all it takes is a single line of code to generate box plots showing the distribution for various levels of the categorical response feature (“survived” encoded by 1 and not survived encoded by 0”). We sample two of them below.
ExpNumViz(data = data,target = "Survived")[4:5]
Categorical Features: Uni-variate Analysis
ExpCatViz without any additional parameters other than the dataset, plots the % bar plots of the count of levels in each categorical feature. We have sampled a couple below.
ExpCatViz(data)
Categorical Features: Bi-Variate Analysis with Target Feature
The ExpCatViz method takes 2 additional arguments target and margin and generates barplots for all categorical features in the dataset vs each level of the target categorical feature “Survived”.
ExpCatViz(data, margin = 2, target = "Survived", col = c("red","green"))[c(1,3:5)]
The above two plots possibly point to the tragic dilemma that was faced by passengers travelling in a larger family group with more siblings, with parents and spouse, that of being unable to leave behind family. Look at the disparity in survival rates !
So, to summarize, we were able to do substantial EDA number crunching as well as visualization with barely half a dozen lines of code. Please give your feedback and comments as well as which is your favourite R package for EDA and why.
Thanks for reading !
No rights reserved
by the author. | [
{
"code": null,
"e": 656,
"s": 171,
"text": "While working on a Data Science or Machine Learning project or assignment, we have all felt the urge to fast-forward to the model building and prediction stage. However, as our mentors and experts reiterate, the initial Exploratory Data Analysis (EDA) phase is crucial to get better outcomes from the later stages of training a model and predictions. The estimates of time spent on EDA and data preparation range anywhere from 60–80% of the total time spent on a Data Science project."
},
{
"code": null,
"e": 795,
"s": 656,
"text": "Given this, are there packages in R that enable us to speed up our EDA while still doing a thorough job of it? Well, looks like there is !"
},
{
"code": null,
"e": 1012,
"s": 795,
"text": "In this Article, I would like to showcase the capabilities of the R package SmartEDA in making our lives easier in EDA. With just a single line of code using the methods in SmartEDA, we can get each of the following:"
},
{
"code": null,
"e": 1036,
"s": 1012,
"text": "Much richer information"
},
{
"code": null,
"e": 1076,
"s": 1036,
"text": "Better formatted output for readability"
},
{
"code": null,
"e": 1142,
"s": 1076,
"text": "Comprehensive multi-point summary for each feature in the dateset"
},
{
"code": null,
"e": 1188,
"s": 1142,
"text": "Visualize uni-variate and bi-variate analysis"
},
{
"code": null,
"e": 1409,
"s": 1188,
"text": "All the above features of the SmartEDA come in very handy especially when handling a dataset with large number of features. Try using the traditional str()and summary()` functions with a dataset having over 10 features !"
},
{
"code": null,
"e": 1453,
"s": 1409,
"text": "Let us now take SmartEDA for a test drive.."
},
{
"code": null,
"e": 1640,
"s": 1453,
"text": "We will use the Titanic dataset from Kaggle. You can download it from here. This contains data on the passengers of the ill-fated Titanic voyage and if they survived the disaster or not."
},
{
"code": null,
"e": 1717,
"s": 1640,
"text": "#install.packages(\"SmartEDA\")library(SmartEDA)data = read.csv(\"titanic.csv\")"
},
{
"code": null,
"e": 1772,
"s": 1717,
"text": "Here is a sample of the first few rows of the dataset."
},
{
"code": null,
"e": 1783,
"s": 1772,
"text": "head(data)"
},
{
"code": null,
"e": 1983,
"s": 1783,
"text": "The dataset has passenger information including the class of travel, Name, Gender, Age, Number of siblings and spouses onboard, Number of Parents & Children onboard, Fare and Port of embarkation etc."
},
{
"code": null,
"e": 2063,
"s": 1983,
"text": "The ExpData() method gives a top level meta data information about the dataset."
},
{
"code": null,
"e": 2085,
"s": 2063,
"text": "ExpData(data, type=1)"
},
{
"code": null,
"e": 2267,
"s": 2085,
"text": "The same method with type = 2 argument gives a neat summary of each feature in the dataset that includes variable type, % missing cases and number of unique values for each feature."
},
{
"code": null,
"e": 2307,
"s": 2267,
"text": "Awesome ! Right? Wait.. it gets better."
},
{
"code": null,
"e": 2338,
"s": 2307,
"text": "Summary of Continuous Features"
},
{
"code": null,
"e": 2707,
"s": 2338,
"text": "The ExpNumStat() method generates a comprehensive multi-point statistical summary of all the continuous features in the dataset with a wealth of information including number of negative, zero and positive values, number of missing values and %, min, max, mean, median, standard deviation, coefficient of variation, IQR, Skew, Kurtosis and number of outliers... Whew !!"
},
{
"code": null,
"e": 3016,
"s": 2707,
"text": "Also, ExpNumStat()automatically identifies the continuous features in the dataset. Here, below we have taken only a subset of all the summary points available for output. You can view the full output by removing the column index numbers and specify only the column index for the statistic of interest to you."
},
{
"code": null,
"e": 3093,
"s": 3016,
"text": "ExpNumStat(data,by =\"A\",Outlier=TRUE,round= 2)[,c(1,2,4:6,9:10,12:15,18,23)]"
},
{
"code": null,
"e": 3164,
"s": 3093,
"text": "ExpNumStat(data, by = \"A\", Outlier = TRUE, round = 2)[,c(1,2,9,16:22)]"
},
{
"code": null,
"e": 3545,
"s": 3164,
"text": "Further, setting the by argument to G or GA, we can get the summary split by ‘group’ and ‘group plus all’ by specifying a categorical feature in the group argument. This is especially useful in classification problems like the one we have here, where we can get a summary of the continuous features for each level of the categorical response variable (“Survived” in this dataset)."
},
{
"code": null,
"e": 3645,
"s": 3545,
"text": "ExpNumStat(data[,-1],by = \"GA\",Outlier=TRUE,round= 2,gp = \"Survived\")[,c(1,2,4:6,9:10,12:15,18,23)]"
},
{
"code": null,
"e": 3759,
"s": 3645,
"text": "In this case, we can clearly see that the Fare feature plays a big role in whether the passenger survived or not."
},
{
"code": null,
"e": 3791,
"s": 3759,
"text": "Summary of Categorical Features"
},
{
"code": null,
"e": 3878,
"s": 3791,
"text": "What about summary of Categorical features? The ExpCatStat() method does the job here."
},
{
"code": null,
"e": 3916,
"s": 3878,
"text": "ExpCatStat(data, Target = \"Survived\")"
},
{
"code": null,
"e": 4266,
"s": 3916,
"text": "The single line of code above not only provides the Chi-squared statistic and p-value between each categorical feature and the target feature, but also provides the information value(IV) for each feature and a useful labelling of its degree of association with the target feature and its predictive power. Talk about going beyond the call of duty !!"
},
{
"code": null,
"e": 4280,
"s": 4266,
"text": "Visualization"
},
{
"code": null,
"e": 4455,
"s": 4280,
"text": "With SmartEDA,it is not all output in numbers. It delivers in visually exploring data as well be it uni-variate or bi-variate analysis throughExpNumViz and ExpCatViz methods."
},
{
"code": null,
"e": 4514,
"s": 4455,
"text": "Bi-Variate Analysis : Between Pairs of Continuous Features"
},
{
"code": null,
"e": 4773,
"s": 4514,
"text": "Passing the scatter = TRUE argument to ExpNumViz() gives a scatter plot between all the pairs of continuous features of the dateset. Here we plot Pclass vs Fare and Age vs SibSp (number of siblings/spouse on board) by selecting the index number of the plots."
},
{
"code": null,
"e": 4815,
"s": 4773,
"text": "ExpNumViz(data[,-1], scatter = TRUE)[4:5]"
},
{
"code": null,
"e": 4921,
"s": 4815,
"text": "Passing just the dataset to the method plots the density distribution of each of the continuous features."
},
{
"code": null,
"e": 4995,
"s": 4921,
"text": "Bi-Variate Analysis : Continuous Features vs Categorical Response Feature"
},
{
"code": null,
"e": 5229,
"s": 4995,
"text": "Again, all it takes is a single line of code to generate box plots showing the distribution for various levels of the categorical response feature (“survived” encoded by 1 and not survived encoded by 0”). We sample two of them below."
},
{
"code": null,
"e": 5277,
"s": 5229,
"text": "ExpNumViz(data = data,target = \"Survived\")[4:5]"
},
{
"code": null,
"e": 5320,
"s": 5277,
"text": "Categorical Features: Uni-variate Analysis"
},
{
"code": null,
"e": 5494,
"s": 5320,
"text": "ExpCatViz without any additional parameters other than the dataset, plots the % bar plots of the count of levels in each categorical feature. We have sampled a couple below."
},
{
"code": null,
"e": 5510,
"s": 5494,
"text": "ExpCatViz(data)"
},
{
"code": null,
"e": 5572,
"s": 5510,
"text": "Categorical Features: Bi-Variate Analysis with Target Feature"
},
{
"code": null,
"e": 5767,
"s": 5572,
"text": "The ExpCatViz method takes 2 additional arguments target and margin and generates barplots for all categorical features in the dataset vs each level of the target categorical feature “Survived”."
},
{
"code": null,
"e": 5860,
"s": 5767,
"text": "ExpCatViz(data, margin = 2, target = \"Survived\", col = c(\"red\",\"green\"))[c(1,3:5)]"
},
{
"code": null,
"e": 6114,
"s": 5860,
"text": "The above two plots possibly point to the tragic dilemma that was faced by passengers travelling in a larger family group with more siblings, with parents and spouse, that of being unable to leave behind family. Look at the disparity in survival rates !"
},
{
"code": null,
"e": 6350,
"s": 6114,
"text": "So, to summarize, we were able to do substantial EDA number crunching as well as visualization with barely half a dozen lines of code. Please give your feedback and comments as well as which is your favourite R package for EDA and why."
},
{
"code": null,
"e": 6371,
"s": 6350,
"text": "Thanks for reading !"
},
{
"code": null,
"e": 6390,
"s": 6371,
"text": "No rights reserved"
}
] |
Converting Row into list RDD in PySpark | 18 Jul, 2021
In this article, we are going to convert Row into a list RDD in Pyspark.
Creating RDD from Row for demonstration:
Python3
# import Row and SparkSessionfrom pyspark.sql import SparkSession, Row # create sparksessionspark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate() # create student data with Row functiondata = [Row(name="sravan kumar", subjects=["Java", "python", "C++"], state="AP"), Row(name="Ojaswi", lang=["Spark", "Java", "C++"], state="Telangana"), Row(name="rohith", subjects=["DS", "PHP", ".net"], state="AP"), Row(name="bobby", lang=["Python", "C", "sql"], state="Delhi"), Row(name="rohith", lang=["CSharp", "VB"], state="Telangana")]rdd = spark.sparkContext.parallelize(data) # display actual rddrdd.collect()
Output:
[Row(name='sravan kumar', subjects=['Java', 'python', 'C++'], state='AP'),
Row(name='Ojaswi', lang=['Spark', 'Java', 'C++'], state='Telangana'),
Row(name='rohith', subjects=['DS', 'PHP', '.net'], state='AP'),
Row(name='bobby', lang=['Python', 'C', 'sql'], state='Delhi'),
Row(name='rohith', lang=['CSharp', 'VB'], state='Telangana')]
Using map() function we can convert into list RDD
Syntax: rdd_data.map(list)
where, rdd_data is the data is of type rdd.
Finally, by using the collect method we can display the data in the list RDD.
Python3
# convert rdd to list by using map() methodb = rdd.map(list) # display the data in b with collect methodfor i in b.collect(): print(i)
Output:
['sravan kumar', ['Java', 'python', 'C++'], 'AP']
['Ojaswi', ['Spark', 'Java', 'C++'], 'Telangana']
['rohith', ['DS', 'PHP', '.net'], 'AP']
['bobby', ['Python', 'C', 'sql'], 'Delhi']
['rohith', ['CSharp', 'VB'], 'Telangana']
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 101,
"s": 28,
"text": "In this article, we are going to convert Row into a list RDD in Pyspark."
},
{
"code": null,
"e": 142,
"s": 101,
"text": "Creating RDD from Row for demonstration:"
},
{
"code": null,
"e": 150,
"s": 142,
"text": "Python3"
},
{
"code": "# import Row and SparkSessionfrom pyspark.sql import SparkSession, Row # create sparksessionspark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate() # create student data with Row functiondata = [Row(name=\"sravan kumar\", subjects=[\"Java\", \"python\", \"C++\"], state=\"AP\"), Row(name=\"Ojaswi\", lang=[\"Spark\", \"Java\", \"C++\"], state=\"Telangana\"), Row(name=\"rohith\", subjects=[\"DS\", \"PHP\", \".net\"], state=\"AP\"), Row(name=\"bobby\", lang=[\"Python\", \"C\", \"sql\"], state=\"Delhi\"), Row(name=\"rohith\", lang=[\"CSharp\", \"VB\"], state=\"Telangana\")]rdd = spark.sparkContext.parallelize(data) # display actual rddrdd.collect()",
"e": 921,
"s": 150,
"text": null
},
{
"code": null,
"e": 929,
"s": 921,
"text": "Output:"
},
{
"code": null,
"e": 1263,
"s": 929,
"text": "[Row(name='sravan kumar', subjects=['Java', 'python', 'C++'], state='AP'),\nRow(name='Ojaswi', lang=['Spark', 'Java', 'C++'], state='Telangana'),\nRow(name='rohith', subjects=['DS', 'PHP', '.net'], state='AP'),\nRow(name='bobby', lang=['Python', 'C', 'sql'], state='Delhi'),\nRow(name='rohith', lang=['CSharp', 'VB'], state='Telangana')]"
},
{
"code": null,
"e": 1313,
"s": 1263,
"text": "Using map() function we can convert into list RDD"
},
{
"code": null,
"e": 1340,
"s": 1313,
"text": "Syntax: rdd_data.map(list)"
},
{
"code": null,
"e": 1384,
"s": 1340,
"text": "where, rdd_data is the data is of type rdd."
},
{
"code": null,
"e": 1462,
"s": 1384,
"text": "Finally, by using the collect method we can display the data in the list RDD."
},
{
"code": null,
"e": 1470,
"s": 1462,
"text": "Python3"
},
{
"code": "# convert rdd to list by using map() methodb = rdd.map(list) # display the data in b with collect methodfor i in b.collect(): print(i)",
"e": 1609,
"s": 1470,
"text": null
},
{
"code": null,
"e": 1617,
"s": 1609,
"text": "Output:"
},
{
"code": null,
"e": 1842,
"s": 1617,
"text": "['sravan kumar', ['Java', 'python', 'C++'], 'AP']\n['Ojaswi', ['Spark', 'Java', 'C++'], 'Telangana']\n['rohith', ['DS', 'PHP', '.net'], 'AP']\n['bobby', ['Python', 'C', 'sql'], 'Delhi']\n['rohith', ['CSharp', 'VB'], 'Telangana']"
},
{
"code": null,
"e": 1849,
"s": 1842,
"text": "Picked"
},
{
"code": null,
"e": 1864,
"s": 1849,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 1871,
"s": 1864,
"text": "Python"
}
] |
How to Build Image Filters like Instagram in Android? | 21 Jan, 2021
Now a day many social media apps provide so many filters that we can use to make our image inside the app more beautiful and attractive. This type of feature is generally seen in Instagram, Snapchat, and many socials media apps. In this article, we will take a look at the implementation of this Instagram-like filter section in Android.
We will be building a simple application in which we will be displaying an ImageView and we will provide different types of image filtering options below. After clicking on each image filter that filter will be applied to our original image. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency and JitPack Repository
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘com.github.mukeshsolanki:photofilter:1.0.2’
Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.
allprojects {
repositories {
...
maven { url “https://jitpack.io” }
}
}
After adding this dependency sync your project and now we will move towards its implementation.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--Imageview for our original image--> <ImageView android:id="@+id/idIVOriginalImage" android:layout_width="match_parent" android:layout_height="300dp" android:layout_centerHorizontal="true" android:layout_margin="20dp" android:padding="5dp" android:src="@drawable/image" /> <!--horizontal scroll view for displaying all our image filters--> <HorizontalScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idIVOriginalImage" android:layout_marginTop="20dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <!--We are creating a linear layout for displaying each item in horizontal scroll view--> <LinearLayout android:id="@+id/idLLVignette" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <!--We are displaying the image view how it will look after applying the filter--> <ImageView android:id="@+id/idIVOne" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <!--Text view for displaying our filter name--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 1" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> <LinearLayout android:id="@+id/idLLTint" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <ImageView android:id="@+id/idIVTwo" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 2" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> <LinearLayout android:id="@+id/idLLTemperature" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <ImageView android:id="@+id/idIVThree" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 3" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> <LinearLayout android:id="@+id/idLLSharpen" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <ImageView android:id="@+id/idIVFour" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 4" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> <LinearLayout android:id="@+id/idLLSepia" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <ImageView android:id="@+id/idIVFive" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 5" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> <LinearLayout android:id="@+id/idLLSaturate" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <ImageView android:id="@+id/idIVSix" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 6" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> <LinearLayout android:id="@+id/idLLRotate" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <ImageView android:id="@+id/idIVSeven" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 7" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> <LinearLayout android:id="@+id/idLLPosterize" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <ImageView android:id="@+id/idIVEight" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 8" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> <LinearLayout android:id="@+id/idLLNone" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <ImageView android:id="@+id/idIVNine" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 9" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> <LinearLayout android:id="@+id/idLLNegative" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="vertical"> <ImageView android:id="@+id/idIVTen" android:layout_width="140dp" android:layout_height="140dp" android:layout_gravity="center" android:src="@drawable/image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp" android:text="Filter 10" android:textAlignment="center" android:textColor="@color/black" /> </LinearLayout> </LinearLayout> </HorizontalScrollView> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.view.View;import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import com.mukesh.image_processing.ImageProcessor; public class MainActivity extends AppCompatActivity { // creating a bitmap for our original // image and all image filters. Bitmap bitmap; // creating a variable for image view. ImageView oneIV, twoIV, threeIV, fourIV, fiveIV, sixIV, sevenIV, eightIV, nineIV, tenIV, originalIV; Bitmap oneBitMap, twoBitMap, threeBitmap, fourBitMap, fiveBitMap, sixBitMap, sevenBitMap, eightBitMap, nineBitMap, tenBitMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating a variable for our image processor. ImageProcessor processor = new ImageProcessor(); // initializing bitmap with our image resource. bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image); // initializing image views for our filters // and original image on which we will // be applying our filters. oneIV = findViewById(R.id.idIVOne); twoIV = findViewById(R.id.idIVTwo); threeIV = findViewById(R.id.idIVThree); fourIV = findViewById(R.id.idIVFour); fiveIV = findViewById(R.id.idIVFive); sixIV = findViewById(R.id.idIVSix); sevenIV = findViewById(R.id.idIVSeven); eightIV = findViewById(R.id.idIVEight); nineIV = findViewById(R.id.idIVNine); tenIV = findViewById(R.id.idIVTen); originalIV = findViewById(R.id.idIVOriginalImage); // below line is use to add tint effect to our original // image bitmap and storing that in one bitmap. oneBitMap = processor.tintImage(bitmap, 90); // after storing it to one bitmap // we are setting it to imageview. oneIV.setImageBitmap(oneBitMap); // below line is use to apply gaussian blur effect // to our original image bitmap. twoBitMap = processor.applyGaussianBlur(bitmap); twoIV.setImageBitmap(twoBitMap); // below line is use to add sepia toing effect // to our original image bitmap. threeBitmap = processor.createSepiaToningEffect(bitmap, 1, 2, 1, 5); threeIV.setImageBitmap(threeBitmap); // below line is use to apply saturation // filter to our original image bitmap. fourBitMap = processor.applySaturationFilter(bitmap, 3); fourIV.setImageBitmap(fourBitMap); // below line is use to apply snow effect // to our original image bitmap. fiveBitMap = processor.applySnowEffect(bitmap); fiveIV.setImageBitmap(fiveBitMap); // below line is use to add gray scale // to our image view. sixBitMap = processor.doGreyScale(bitmap); sixIV.setImageBitmap(sixBitMap); // below line is use to add engrave effect // to our image view. sevenBitMap = processor.engrave(bitmap); sevenIV.setImageBitmap(sevenBitMap); // below line is use to create a contrast // effect to our image view. eightBitMap = processor.createContrast(bitmap, 1.5); eightIV.setImageBitmap(eightBitMap); // below line is use to add shadow effect // to our original bitmap. nineBitMap = processor.createShadow(bitmap); nineIV.setImageBitmap(nineBitMap); // below line is use to add flea // effect to our image view. tenBitMap = processor.applyFleaEffect(bitmap); tenIV.setImageBitmap(tenBitMap); // below line is use to call on click // listener for our all image filters. initializeOnCLickListerns(); } private void initializeOnCLickListerns() { oneIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on clicking on each filter we are // setting that filter to our original image. originalIV.setImageBitmap(oneBitMap); } }); twoIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(twoBitMap); } }); threeIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(threeBitmap); } }); fourIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(fourBitMap); } }); fiveIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(fiveBitMap); } }); sixIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(sixBitMap); } }); sevenIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(sevenBitMap); } }); eightIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(eightBitMap); } }); nineIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(nineBitMap); } }); tenIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(tenBitMap); } }); }}
The image used in this project is added to the drawable folder. For navigating the image, Navigate to the app > res > drawable and you will find the image in that folder. Now run the app and see the output of the code below :
Note: The app will take some time to load though we are using bitmap and it takes time to decode the image to the bitmap.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jan, 2021"
},
{
"code": null,
"e": 393,
"s": 54,
"text": "Now a day many social media apps provide so many filters that we can use to make our image inside the app more beautiful and attractive. This type of feature is generally seen in Instagram, Snapchat, and many socials media apps. In this article, we will take a look at the implementation of this Instagram-like filter section in Android. "
},
{
"code": null,
"e": 800,
"s": 393,
"text": "We will be building a simple application in which we will be displaying an ImageView and we will provide different types of image filtering options below. After clicking on each image filter that filter will be applied to our original image. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 809,
"s": 800,
"text": "Chapters"
},
{
"code": null,
"e": 836,
"s": 809,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 886,
"s": 836,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 909,
"s": 886,
"text": "captions off, selected"
},
{
"code": null,
"e": 917,
"s": 909,
"text": "English"
},
{
"code": null,
"e": 941,
"s": 917,
"text": "This is a modal window."
},
{
"code": null,
"e": 1010,
"s": 941,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1032,
"s": 1010,
"text": "End of dialog window."
},
{
"code": null,
"e": 1061,
"s": 1032,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1223,
"s": 1061,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1269,
"s": 1223,
"text": "Step 2: Add dependency and JitPack Repository"
},
{
"code": null,
"e": 1388,
"s": 1269,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 1448,
"s": 1388,
"text": "implementation ‘com.github.mukeshsolanki:photofilter:1.0.2’"
},
{
"code": null,
"e": 1590,
"s": 1448,
"text": "Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section."
},
{
"code": null,
"e": 1604,
"s": 1590,
"text": "allprojects {"
},
{
"code": null,
"e": 1620,
"s": 1604,
"text": " repositories {"
},
{
"code": null,
"e": 1627,
"s": 1620,
"text": " ..."
},
{
"code": null,
"e": 1665,
"s": 1627,
"text": " maven { url “https://jitpack.io” }"
},
{
"code": null,
"e": 1672,
"s": 1665,
"text": " }"
},
{
"code": null,
"e": 1674,
"s": 1672,
"text": "}"
},
{
"code": null,
"e": 1772,
"s": 1674,
"text": "After adding this dependency sync your project and now we will move towards its implementation. "
},
{
"code": null,
"e": 1820,
"s": 1772,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1963,
"s": 1820,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 1967,
"s": 1963,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Imageview for our original image--> <ImageView android:id=\"@+id/idIVOriginalImage\" android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"20dp\" android:padding=\"5dp\" android:src=\"@drawable/image\" /> <!--horizontal scroll view for displaying all our image filters--> <HorizontalScrollView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idIVOriginalImage\" android:layout_marginTop=\"20dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <!--We are creating a linear layout for displaying each item in horizontal scroll view--> <LinearLayout android:id=\"@+id/idLLVignette\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <!--We are displaying the image view how it will look after applying the filter--> <ImageView android:id=\"@+id/idIVOne\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <!--Text view for displaying our filter name--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 1\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> <LinearLayout android:id=\"@+id/idLLTint\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVTwo\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 2\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> <LinearLayout android:id=\"@+id/idLLTemperature\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVThree\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 3\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> <LinearLayout android:id=\"@+id/idLLSharpen\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVFour\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 4\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> <LinearLayout android:id=\"@+id/idLLSepia\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVFive\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 5\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> <LinearLayout android:id=\"@+id/idLLSaturate\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVSix\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 6\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> <LinearLayout android:id=\"@+id/idLLRotate\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVSeven\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 7\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> <LinearLayout android:id=\"@+id/idLLPosterize\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVEight\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 8\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> <LinearLayout android:id=\"@+id/idLLNone\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVNine\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 9\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> <LinearLayout android:id=\"@+id/idLLNegative\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVTen\" android:layout_width=\"140dp\" android:layout_height=\"140dp\" android:layout_gravity=\"center\" android:src=\"@drawable/image\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"4dp\" android:text=\"Filter 10\" android:textAlignment=\"center\" android:textColor=\"@color/black\" /> </LinearLayout> </LinearLayout> </HorizontalScrollView> </RelativeLayout>",
"e": 12340,
"s": 1967,
"text": null
},
{
"code": null,
"e": 12388,
"s": 12340,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 12578,
"s": 12388,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 12583,
"s": 12578,
"text": "Java"
},
{
"code": "import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.view.View;import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import com.mukesh.image_processing.ImageProcessor; public class MainActivity extends AppCompatActivity { // creating a bitmap for our original // image and all image filters. Bitmap bitmap; // creating a variable for image view. ImageView oneIV, twoIV, threeIV, fourIV, fiveIV, sixIV, sevenIV, eightIV, nineIV, tenIV, originalIV; Bitmap oneBitMap, twoBitMap, threeBitmap, fourBitMap, fiveBitMap, sixBitMap, sevenBitMap, eightBitMap, nineBitMap, tenBitMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating a variable for our image processor. ImageProcessor processor = new ImageProcessor(); // initializing bitmap with our image resource. bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image); // initializing image views for our filters // and original image on which we will // be applying our filters. oneIV = findViewById(R.id.idIVOne); twoIV = findViewById(R.id.idIVTwo); threeIV = findViewById(R.id.idIVThree); fourIV = findViewById(R.id.idIVFour); fiveIV = findViewById(R.id.idIVFive); sixIV = findViewById(R.id.idIVSix); sevenIV = findViewById(R.id.idIVSeven); eightIV = findViewById(R.id.idIVEight); nineIV = findViewById(R.id.idIVNine); tenIV = findViewById(R.id.idIVTen); originalIV = findViewById(R.id.idIVOriginalImage); // below line is use to add tint effect to our original // image bitmap and storing that in one bitmap. oneBitMap = processor.tintImage(bitmap, 90); // after storing it to one bitmap // we are setting it to imageview. oneIV.setImageBitmap(oneBitMap); // below line is use to apply gaussian blur effect // to our original image bitmap. twoBitMap = processor.applyGaussianBlur(bitmap); twoIV.setImageBitmap(twoBitMap); // below line is use to add sepia toing effect // to our original image bitmap. threeBitmap = processor.createSepiaToningEffect(bitmap, 1, 2, 1, 5); threeIV.setImageBitmap(threeBitmap); // below line is use to apply saturation // filter to our original image bitmap. fourBitMap = processor.applySaturationFilter(bitmap, 3); fourIV.setImageBitmap(fourBitMap); // below line is use to apply snow effect // to our original image bitmap. fiveBitMap = processor.applySnowEffect(bitmap); fiveIV.setImageBitmap(fiveBitMap); // below line is use to add gray scale // to our image view. sixBitMap = processor.doGreyScale(bitmap); sixIV.setImageBitmap(sixBitMap); // below line is use to add engrave effect // to our image view. sevenBitMap = processor.engrave(bitmap); sevenIV.setImageBitmap(sevenBitMap); // below line is use to create a contrast // effect to our image view. eightBitMap = processor.createContrast(bitmap, 1.5); eightIV.setImageBitmap(eightBitMap); // below line is use to add shadow effect // to our original bitmap. nineBitMap = processor.createShadow(bitmap); nineIV.setImageBitmap(nineBitMap); // below line is use to add flea // effect to our image view. tenBitMap = processor.applyFleaEffect(bitmap); tenIV.setImageBitmap(tenBitMap); // below line is use to call on click // listener for our all image filters. initializeOnCLickListerns(); } private void initializeOnCLickListerns() { oneIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on clicking on each filter we are // setting that filter to our original image. originalIV.setImageBitmap(oneBitMap); } }); twoIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(twoBitMap); } }); threeIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(threeBitmap); } }); fourIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(fourBitMap); } }); fiveIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(fiveBitMap); } }); sixIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(sixBitMap); } }); sevenIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(sevenBitMap); } }); eightIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(eightBitMap); } }); nineIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(nineBitMap); } }); tenIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { originalIV.setImageBitmap(tenBitMap); } }); }}",
"e": 18772,
"s": 12583,
"text": null
},
{
"code": null,
"e": 18999,
"s": 18772,
"text": "The image used in this project is added to the drawable folder. For navigating the image, Navigate to the app > res > drawable and you will find the image in that folder. Now run the app and see the output of the code below : "
},
{
"code": null,
"e": 19121,
"s": 18999,
"text": "Note: The app will take some time to load though we are using bitmap and it takes time to decode the image to the bitmap."
},
{
"code": null,
"e": 19129,
"s": 19121,
"text": "android"
},
{
"code": null,
"e": 19153,
"s": 19129,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 19161,
"s": 19153,
"text": "Android"
},
{
"code": null,
"e": 19166,
"s": 19161,
"text": "Java"
},
{
"code": null,
"e": 19185,
"s": 19166,
"text": "Technical Scripter"
},
{
"code": null,
"e": 19190,
"s": 19185,
"text": "Java"
},
{
"code": null,
"e": 19198,
"s": 19190,
"text": "Android"
}
] |
LocalTime of() method in Java with Examples | 05 Jun, 2020
The of(int hour, int minute) method of the LocalTime class in Java is used to create an instance of LocalTime from the passed values of hour and minute. In this method, the hour and minute are passed in the Integer format and it returns time-based on these values. The values of second and nanosecond are set to zero by default in this method.Syntax:public static LocalTime of(int hour,
int minute)
Parameters: This method accepts two parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.Return value: This method returns the LocalTime.Exception: This method throws DateTimeException if any parameter value either of hour or minute exceeds the range.Below program illustrates the of(hour, minute) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour,// int minute) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5); // Print time System.out.println("TIME: " + localtime); }}Output:TIME: 06:05
The of(int hour, int minute, int second) method of the LocalTime class in Java is used to create an instance of LocalTime from the passed values of hour, minute and second. In this method, the values of the hour, minute and second are passed in an Integer format and it returns the time on the basis of the passed values. The value of the nanosecond is set to zero by default in this method.Syntax:public static LocalTime of(int hour,
int minute,
int second)
Parameters: This method accepts three parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.Return value: This method returns the LocalTime.Exception: This method throws DateTimeException if any parameter exceeds the range.Below program illustrates the of(hour, minute, second) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour, int minute, int second) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5, 40); // Print time System.out.println("TIME: " + localtime); }}Output:TIME: 06:05:40
The of(int hour, int minute, int second, int nanosecond) method of the LocalTime class in Java is used to create an instance of LocalTime from given values (passed values) of hour, minute, second and nanosecond. In this method, the values of the hour, minute, second and nanosecond os passed in an Integer form and it returns time on the basis of these values. No parameter value is set to zero in this method.Syntax:public static LocalTime of(int hour,
int minute,
int second,
int nanosecond)
Parameters: This method accepts four parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.nanosecond – It is of Integer type and represents the nano of the second. It varies from 0 to 999999999.Return value: The method returns the LocalTime.Exception: The method throws DateTimeException if any parameter value either of hour, minute, second or nanosecond exceeds the range.Below program illustrates the of(hour, minute, second, nanosecond) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour, int minute,// int second, int nanosecond) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of( 6, 5, 40, 50); // Print time System.out.println("TIME: " + localtime); }}Output:TIME: 06:05:40.000000050
The of(int hour, int minute) method of the LocalTime class in Java is used to create an instance of LocalTime from the passed values of hour and minute. In this method, the hour and minute are passed in the Integer format and it returns time-based on these values. The values of second and nanosecond are set to zero by default in this method.Syntax:public static LocalTime of(int hour,
int minute)
Parameters: This method accepts two parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.Return value: This method returns the LocalTime.Exception: This method throws DateTimeException if any parameter value either of hour or minute exceeds the range.Below program illustrates the of(hour, minute) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour,// int minute) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5); // Print time System.out.println("TIME: " + localtime); }}Output:TIME: 06:05
Syntax:
public static LocalTime of(int hour,
int minute)
Parameters: This method accepts two parameters:
hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.
minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.
Return value: This method returns the LocalTime.
Exception: This method throws DateTimeException if any parameter value either of hour or minute exceeds the range.
Below program illustrates the of(hour, minute) method of LocalTime in Java:
Program:
// Java program to demonstrate// LocalTime of(int hour,// int minute) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5); // Print time System.out.println("TIME: " + localtime); }}
TIME: 06:05
The of(int hour, int minute, int second) method of the LocalTime class in Java is used to create an instance of LocalTime from the passed values of hour, minute and second. In this method, the values of the hour, minute and second are passed in an Integer format and it returns the time on the basis of the passed values. The value of the nanosecond is set to zero by default in this method.Syntax:public static LocalTime of(int hour,
int minute,
int second)
Parameters: This method accepts three parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.Return value: This method returns the LocalTime.Exception: This method throws DateTimeException if any parameter exceeds the range.Below program illustrates the of(hour, minute, second) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour, int minute, int second) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5, 40); // Print time System.out.println("TIME: " + localtime); }}Output:TIME: 06:05:40
Syntax:
public static LocalTime of(int hour,
int minute,
int second)
Parameters: This method accepts three parameters:
hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.
minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.
second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.
Return value: This method returns the LocalTime.
Exception: This method throws DateTimeException if any parameter exceeds the range.
Below program illustrates the of(hour, minute, second) method of LocalTime in Java:
Program:
// Java program to demonstrate// LocalTime of(int hour, int minute, int second) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5, 40); // Print time System.out.println("TIME: " + localtime); }}
TIME: 06:05:40
The of(int hour, int minute, int second, int nanosecond) method of the LocalTime class in Java is used to create an instance of LocalTime from given values (passed values) of hour, minute, second and nanosecond. In this method, the values of the hour, minute, second and nanosecond os passed in an Integer form and it returns time on the basis of these values. No parameter value is set to zero in this method.Syntax:public static LocalTime of(int hour,
int minute,
int second,
int nanosecond)
Parameters: This method accepts four parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.nanosecond – It is of Integer type and represents the nano of the second. It varies from 0 to 999999999.Return value: The method returns the LocalTime.Exception: The method throws DateTimeException if any parameter value either of hour, minute, second or nanosecond exceeds the range.Below program illustrates the of(hour, minute, second, nanosecond) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour, int minute,// int second, int nanosecond) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of( 6, 5, 40, 50); // Print time System.out.println("TIME: " + localtime); }}Output:TIME: 06:05:40.000000050
Syntax:
public static LocalTime of(int hour,
int minute,
int second,
int nanosecond)
Parameters: This method accepts four parameters:
hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.
minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.
second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.
nanosecond – It is of Integer type and represents the nano of the second. It varies from 0 to 999999999.
Return value: The method returns the LocalTime.
Exception: The method throws DateTimeException if any parameter value either of hour, minute, second or nanosecond exceeds the range.
Below program illustrates the of(hour, minute, second, nanosecond) method of LocalTime in Java:
Program:
// Java program to demonstrate// LocalTime of(int hour, int minute,// int second, int nanosecond) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of( 6, 5, 40, 50); // Print time System.out.println("TIME: " + localtime); }}
TIME: 06:05:40.000000050
References:
https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#of(int, int)
https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#of(int, int, int)
https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#of(int, int, int, int)
Java-Functions
Java-LocalTime
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 4583,
"s": 28,
"text": "The of(int hour, int minute) method of the LocalTime class in Java is used to create an instance of LocalTime from the passed values of hour and minute. In this method, the hour and minute are passed in the Integer format and it returns time-based on these values. The values of second and nanosecond are set to zero by default in this method.Syntax:public static LocalTime of(int hour,\n int minute)\nParameters: This method accepts two parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.Return value: This method returns the LocalTime.Exception: This method throws DateTimeException if any parameter value either of hour or minute exceeds the range.Below program illustrates the of(hour, minute) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour,// int minute) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5); // Print time System.out.println(\"TIME: \" + localtime); }}Output:TIME: 06:05\nThe of(int hour, int minute, int second) method of the LocalTime class in Java is used to create an instance of LocalTime from the passed values of hour, minute and second. In this method, the values of the hour, minute and second are passed in an Integer format and it returns the time on the basis of the passed values. The value of the nanosecond is set to zero by default in this method.Syntax:public static LocalTime of(int hour,\n int minute,\n int second)\nParameters: This method accepts three parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.Return value: This method returns the LocalTime.Exception: This method throws DateTimeException if any parameter exceeds the range.Below program illustrates the of(hour, minute, second) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour, int minute, int second) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5, 40); // Print time System.out.println(\"TIME: \" + localtime); }}Output:TIME: 06:05:40\nThe of(int hour, int minute, int second, int nanosecond) method of the LocalTime class in Java is used to create an instance of LocalTime from given values (passed values) of hour, minute, second and nanosecond. In this method, the values of the hour, minute, second and nanosecond os passed in an Integer form and it returns time on the basis of these values. No parameter value is set to zero in this method.Syntax:public static LocalTime of(int hour,\n int minute,\n int second,\n int nanosecond)\nParameters: This method accepts four parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.nanosecond – It is of Integer type and represents the nano of the second. It varies from 0 to 999999999.Return value: The method returns the LocalTime.Exception: The method throws DateTimeException if any parameter value either of hour, minute, second or nanosecond exceeds the range.Below program illustrates the of(hour, minute, second, nanosecond) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour, int minute,// int second, int nanosecond) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of( 6, 5, 40, 50); // Print time System.out.println(\"TIME: \" + localtime); }}Output:TIME: 06:05:40.000000050\n"
},
{
"code": null,
"e": 5892,
"s": 4583,
"text": "The of(int hour, int minute) method of the LocalTime class in Java is used to create an instance of LocalTime from the passed values of hour and minute. In this method, the hour and minute are passed in the Integer format and it returns time-based on these values. The values of second and nanosecond are set to zero by default in this method.Syntax:public static LocalTime of(int hour,\n int minute)\nParameters: This method accepts two parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.Return value: This method returns the LocalTime.Exception: This method throws DateTimeException if any parameter value either of hour or minute exceeds the range.Below program illustrates the of(hour, minute) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour,// int minute) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5); // Print time System.out.println(\"TIME: \" + localtime); }}Output:TIME: 06:05\n"
},
{
"code": null,
"e": 5900,
"s": 5892,
"text": "Syntax:"
},
{
"code": null,
"e": 5977,
"s": 5900,
"text": "public static LocalTime of(int hour,\n int minute)\n"
},
{
"code": null,
"e": 6025,
"s": 5977,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 6114,
"s": 6025,
"text": "hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23."
},
{
"code": null,
"e": 6208,
"s": 6114,
"text": "minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59."
},
{
"code": null,
"e": 6257,
"s": 6208,
"text": "Return value: This method returns the LocalTime."
},
{
"code": null,
"e": 6372,
"s": 6257,
"text": "Exception: This method throws DateTimeException if any parameter value either of hour or minute exceeds the range."
},
{
"code": null,
"e": 6448,
"s": 6372,
"text": "Below program illustrates the of(hour, minute) method of LocalTime in Java:"
},
{
"code": null,
"e": 6457,
"s": 6448,
"text": "Program:"
},
{
"code": "// Java program to demonstrate// LocalTime of(int hour,// int minute) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5); // Print time System.out.println(\"TIME: \" + localtime); }}",
"e": 6848,
"s": 6457,
"text": null
},
{
"code": null,
"e": 6861,
"s": 6848,
"text": "TIME: 06:05\n"
},
{
"code": null,
"e": 8348,
"s": 6861,
"text": "The of(int hour, int minute, int second) method of the LocalTime class in Java is used to create an instance of LocalTime from the passed values of hour, minute and second. In this method, the values of the hour, minute and second are passed in an Integer format and it returns the time on the basis of the passed values. The value of the nanosecond is set to zero by default in this method.Syntax:public static LocalTime of(int hour,\n int minute,\n int second)\nParameters: This method accepts three parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.Return value: This method returns the LocalTime.Exception: This method throws DateTimeException if any parameter exceeds the range.Below program illustrates the of(hour, minute, second) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour, int minute, int second) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5, 40); // Print time System.out.println(\"TIME: \" + localtime); }}Output:TIME: 06:05:40\n"
},
{
"code": null,
"e": 8356,
"s": 8348,
"text": "Syntax:"
},
{
"code": null,
"e": 8472,
"s": 8356,
"text": "public static LocalTime of(int hour,\n int minute,\n int second)\n"
},
{
"code": null,
"e": 8522,
"s": 8472,
"text": "Parameters: This method accepts three parameters:"
},
{
"code": null,
"e": 8611,
"s": 8522,
"text": "hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23."
},
{
"code": null,
"e": 8705,
"s": 8611,
"text": "minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59."
},
{
"code": null,
"e": 8801,
"s": 8705,
"text": "second – It is of Integer type and represents the second of the minute. It varies from 0 to 59."
},
{
"code": null,
"e": 8850,
"s": 8801,
"text": "Return value: This method returns the LocalTime."
},
{
"code": null,
"e": 8934,
"s": 8850,
"text": "Exception: This method throws DateTimeException if any parameter exceeds the range."
},
{
"code": null,
"e": 9018,
"s": 8934,
"text": "Below program illustrates the of(hour, minute, second) method of LocalTime in Java:"
},
{
"code": null,
"e": 9027,
"s": 9018,
"text": "Program:"
},
{
"code": "// Java program to demonstrate// LocalTime of(int hour, int minute, int second) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of(6, 5, 40); // Print time System.out.println(\"TIME: \" + localtime); }}",
"e": 9432,
"s": 9027,
"text": null
},
{
"code": null,
"e": 9448,
"s": 9432,
"text": "TIME: 06:05:40\n"
},
{
"code": null,
"e": 11209,
"s": 9448,
"text": "The of(int hour, int minute, int second, int nanosecond) method of the LocalTime class in Java is used to create an instance of LocalTime from given values (passed values) of hour, minute, second and nanosecond. In this method, the values of the hour, minute, second and nanosecond os passed in an Integer form and it returns time on the basis of these values. No parameter value is set to zero in this method.Syntax:public static LocalTime of(int hour,\n int minute,\n int second,\n int nanosecond)\nParameters: This method accepts four parameters:hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23.minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59.second – It is of Integer type and represents the second of the minute. It varies from 0 to 59.nanosecond – It is of Integer type and represents the nano of the second. It varies from 0 to 999999999.Return value: The method returns the LocalTime.Exception: The method throws DateTimeException if any parameter value either of hour, minute, second or nanosecond exceeds the range.Below program illustrates the of(hour, minute, second, nanosecond) method of LocalTime in Java:Program:// Java program to demonstrate// LocalTime of(int hour, int minute,// int second, int nanosecond) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of( 6, 5, 40, 50); // Print time System.out.println(\"TIME: \" + localtime); }}Output:TIME: 06:05:40.000000050\n"
},
{
"code": null,
"e": 11217,
"s": 11209,
"text": "Syntax:"
},
{
"code": null,
"e": 11376,
"s": 11217,
"text": "public static LocalTime of(int hour,\n int minute,\n int second,\n int nanosecond)\n"
},
{
"code": null,
"e": 11425,
"s": 11376,
"text": "Parameters: This method accepts four parameters:"
},
{
"code": null,
"e": 11514,
"s": 11425,
"text": "hour – It is of Integer type and represents the hour of the day. It varies from 0 to 23."
},
{
"code": null,
"e": 11608,
"s": 11514,
"text": "minute – It is of Integer type and represents the minute of the hour. It varies from 0 to 59."
},
{
"code": null,
"e": 11704,
"s": 11608,
"text": "second – It is of Integer type and represents the second of the minute. It varies from 0 to 59."
},
{
"code": null,
"e": 11809,
"s": 11704,
"text": "nanosecond – It is of Integer type and represents the nano of the second. It varies from 0 to 999999999."
},
{
"code": null,
"e": 11857,
"s": 11809,
"text": "Return value: The method returns the LocalTime."
},
{
"code": null,
"e": 11991,
"s": 11857,
"text": "Exception: The method throws DateTimeException if any parameter value either of hour, minute, second or nanosecond exceeds the range."
},
{
"code": null,
"e": 12087,
"s": 11991,
"text": "Below program illustrates the of(hour, minute, second, nanosecond) method of LocalTime in Java:"
},
{
"code": null,
"e": 12096,
"s": 12087,
"text": "Program:"
},
{
"code": "// Java program to demonstrate// LocalTime of(int hour, int minute,// int second, int nanosecond) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalTime object LocalTime localtime = LocalTime.of( 6, 5, 40, 50); // Print time System.out.println(\"TIME: \" + localtime); }}",
"e": 12539,
"s": 12096,
"text": null
},
{
"code": null,
"e": 12565,
"s": 12539,
"text": "TIME: 06:05:40.000000050\n"
},
{
"code": null,
"e": 12577,
"s": 12565,
"text": "References:"
},
{
"code": null,
"e": 12658,
"s": 12577,
"text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#of(int, int)"
},
{
"code": null,
"e": 12744,
"s": 12658,
"text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#of(int, int, int)"
},
{
"code": null,
"e": 12835,
"s": 12744,
"text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#of(int, int, int, int)"
},
{
"code": null,
"e": 12850,
"s": 12835,
"text": "Java-Functions"
},
{
"code": null,
"e": 12865,
"s": 12850,
"text": "Java-LocalTime"
},
{
"code": null,
"e": 12870,
"s": 12865,
"text": "Java"
},
{
"code": null,
"e": 12875,
"s": 12870,
"text": "Java"
}
] |
jQuery UI Button icon Option | 22 Mar, 2021
jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Button icon option is used to add an icon inside button element.
Syntax:
$( ".selector" ).button({
icon: "ui-icon-gear"
});
CDN Link: First, add jQuery UI scripts needed for your project.
<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>
Example:
HTML
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href= "//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"></script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script></head> <body> <h1 style="color: green;">GeeksforGeeks</h1> <h3>jQuery UI Button icon option</h3> <button>GFG Button</button> <script> $("button").button({ icon: "ui-icon-circle-arrow-e" }); </script></body> </html>
Output:
HTML-Tags
jQuery-Methods
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to add options to a select element using jQuery?
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 fetch data from an API in ReactJS ?
Roadmap to Learn JavaScript For Beginners | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 274,
"s": 28,
"text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Button icon option is used to add an icon inside button element."
},
{
"code": null,
"e": 282,
"s": 274,
"text": "Syntax:"
},
{
"code": null,
"e": 335,
"s": 282,
"text": "$( \".selector\" ).button({\n icon: \"ui-icon-gear\"\n});"
},
{
"code": null,
"e": 399,
"s": 335,
"text": "CDN Link: First, add jQuery UI scripts needed for your project."
},
{
"code": null,
"e": 612,
"s": 399,
"text": "<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>"
},
{
"code": null,
"e": 621,
"s": 612,
"text": "Example:"
},
{
"code": null,
"e": 626,
"s": 621,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link rel=\"stylesheet\" href= \"//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css\"> <script src=\"//code.jquery.com/jquery-1.12.4.js\"></script> <script src=\"//code.jquery.com/ui/1.12.1/jquery-ui.js\"></script></head> <body> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h3>jQuery UI Button icon option</h3> <button>GFG Button</button> <script> $(\"button\").button({ icon: \"ui-icon-circle-arrow-e\" }); </script></body> </html>",
"e": 1183,
"s": 626,
"text": null
},
{
"code": null,
"e": 1191,
"s": 1183,
"text": "Output:"
},
{
"code": null,
"e": 1201,
"s": 1191,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1216,
"s": 1201,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 1226,
"s": 1216,
"text": "jQuery-UI"
},
{
"code": null,
"e": 1233,
"s": 1226,
"text": "JQuery"
},
{
"code": null,
"e": 1250,
"s": 1233,
"text": "Web Technologies"
},
{
"code": null,
"e": 1348,
"s": 1250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1394,
"s": 1348,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 1457,
"s": 1394,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 1486,
"s": 1457,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 1542,
"s": 1486,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 1595,
"s": 1542,
"text": "How to add options to a select element using jQuery?"
},
{
"code": null,
"e": 1628,
"s": 1595,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1690,
"s": 1628,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1751,
"s": 1690,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1794,
"s": 1751,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
ZonedDateTime truncatedTo() method in Java with Examples | 17 Dec, 2018
The truncatedTo() method of a ZonedDateTime class is used to return the value of this ZonedDateTime in the specified unit. This method takes a parameter Unit, which is the Unit in which this ZonedDateTime is to be truncated to. It returns a truncated immutable ZonedDateTime with the value in the specified unit.
Syntax:
public ZonedDateTime truncatedTo(TemporalUnit unit)
Parameters: This method accepts one single parameter unit which is the unit in which this ZonedDateTime is to be truncated to. It should not be null.
Return value: This method returns a immutable truncated ZonedDateTime with the value in the specified unit.
Exception: This method throws following Exceptions:
DateTimeException: if unable to truncate.
UnsupportedTemporalTypeException: if the unit is not supported.
Below programs illustrate the truncatedTo() method:
Program 1:
// Java program to demonstrate// ZonedDateTime.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a ZonedDateTime object ZonedDateTime zonedDT = ZonedDateTime .parse( "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); // print ZonedDateTime System.out.println("ZonedDateTime before" + " truncate: " + zonedDT); // truncate to ChronoUnit.HOURS // means unit smaller than Hour // will be Zero ZonedDateTime returnvalue = zonedDT.truncatedTo(ChronoUnit.HOURS); // print result System.out.println("ZonedDateTime after " + " truncate: " + returnvalue); }}
ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after truncate: 2018-12-06T19:00+05:30[Asia/Calcutta]
Program 2:
// Java program to demonstrate// ZonedDateTime.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a ZonedDateTime object ZonedDateTime zonedDT = ZonedDateTime .parse( "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); // print ZonedDateTime System.out.println("ZonedDateTime before" + " truncate: " + zonedDT); // truncate to ChronoUnit.DAYS // means unit smaller than DAY // will be Zero ZonedDateTime returnvalue = zonedDT.truncatedTo(ChronoUnit.DAYS); // print result System.out.println("ZonedDateTime after " + " truncate: " + returnvalue); }}
ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after truncate: 2018-12-06T00:00+05:30[Asia/Calcutta]
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#withZoneSameInstant(java.time.ZoneId)
Java-Functions
Java-time package
Java-ZonedDateTime
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2018"
},
{
"code": null,
"e": 341,
"s": 28,
"text": "The truncatedTo() method of a ZonedDateTime class is used to return the value of this ZonedDateTime in the specified unit. This method takes a parameter Unit, which is the Unit in which this ZonedDateTime is to be truncated to. It returns a truncated immutable ZonedDateTime with the value in the specified unit."
},
{
"code": null,
"e": 349,
"s": 341,
"text": "Syntax:"
},
{
"code": null,
"e": 402,
"s": 349,
"text": "public ZonedDateTime truncatedTo(TemporalUnit unit)\n"
},
{
"code": null,
"e": 552,
"s": 402,
"text": "Parameters: This method accepts one single parameter unit which is the unit in which this ZonedDateTime is to be truncated to. It should not be null."
},
{
"code": null,
"e": 660,
"s": 552,
"text": "Return value: This method returns a immutable truncated ZonedDateTime with the value in the specified unit."
},
{
"code": null,
"e": 712,
"s": 660,
"text": "Exception: This method throws following Exceptions:"
},
{
"code": null,
"e": 754,
"s": 712,
"text": "DateTimeException: if unable to truncate."
},
{
"code": null,
"e": 818,
"s": 754,
"text": "UnsupportedTemporalTypeException: if the unit is not supported."
},
{
"code": null,
"e": 870,
"s": 818,
"text": "Below programs illustrate the truncatedTo() method:"
},
{
"code": null,
"e": 881,
"s": 870,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// ZonedDateTime.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a ZonedDateTime object ZonedDateTime zonedDT = ZonedDateTime .parse( \"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); // print ZonedDateTime System.out.println(\"ZonedDateTime before\" + \" truncate: \" + zonedDT); // truncate to ChronoUnit.HOURS // means unit smaller than Hour // will be Zero ZonedDateTime returnvalue = zonedDT.truncatedTo(ChronoUnit.HOURS); // print result System.out.println(\"ZonedDateTime after \" + \" truncate: \" + returnvalue); }}",
"e": 1780,
"s": 881,
"text": null
},
{
"code": null,
"e": 1926,
"s": 1780,
"text": "ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\nZonedDateTime after truncate: 2018-12-06T19:00+05:30[Asia/Calcutta]\n"
},
{
"code": null,
"e": 1937,
"s": 1926,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// ZonedDateTime.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a ZonedDateTime object ZonedDateTime zonedDT = ZonedDateTime .parse( \"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); // print ZonedDateTime System.out.println(\"ZonedDateTime before\" + \" truncate: \" + zonedDT); // truncate to ChronoUnit.DAYS // means unit smaller than DAY // will be Zero ZonedDateTime returnvalue = zonedDT.truncatedTo(ChronoUnit.DAYS); // print result System.out.println(\"ZonedDateTime after \" + \" truncate: \" + returnvalue); }}",
"e": 2833,
"s": 1937,
"text": null
},
{
"code": null,
"e": 2979,
"s": 2833,
"text": "ZonedDateTime before truncate: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\nZonedDateTime after truncate: 2018-12-06T00:00+05:30[Asia/Calcutta]\n"
},
{
"code": null,
"e": 3100,
"s": 2979,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#withZoneSameInstant(java.time.ZoneId)"
},
{
"code": null,
"e": 3115,
"s": 3100,
"text": "Java-Functions"
},
{
"code": null,
"e": 3133,
"s": 3115,
"text": "Java-time package"
},
{
"code": null,
"e": 3152,
"s": 3133,
"text": "Java-ZonedDateTime"
},
{
"code": null,
"e": 3157,
"s": 3152,
"text": "Java"
},
{
"code": null,
"e": 3162,
"s": 3157,
"text": "Java"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.