title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to insert DATE into a MySQL column value using Java?
|
For this, you can use PreparedStatement from Java. Let us first create a table wherein one of the columns is ArrivalDate with DATE type −
mysql> create table DemoTable(
PassengerId int,
PassengerName varchar(40),
ArrivalDate date
);
Query OK, 0 rows affected (0.82 sec)
The JAVA code is as follows to insert date −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertDateFromJava {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
try {
java.util.Date javaDate = new java.util.Date();
java.sql.Date mySQLDate = new java.sql.Date(javaDate.getTime());
con = DriverManager.getConnection("jdbc :mysql ://localhost :3306/web?useSSL=false", "root","123456");
String query = "insert into DemoTable(PassengerId,PassengerName,ArrivalDate) values(?,?,?) ";
ps = con.prepareStatement(query);
ps.setInt(1, 101);
ps.setString(2, "Adam");
ps.setDate(3, mySQLDate);
ps.executeUpdate();
System.out.println("Record is inserted with current Date......");
} catch (Exception e) {
e.printStackTrace();
}
}
}
This will produce the following output of Java −
Record is inserted with current Date......
Following is the screenshot of the output −
Let us check the records of the table again −
mysql> select * from DemoTable;
This will produce the following output −
+-------------+---------------+-------------+
| PassengerId | PassengerName | ArrivalDate |
+-------------+---------------+-------------+
| 101 | Adam | 2019-09-07 |
+-------------+---------------+-------------+
1 row in set (0.00 sec)
The screenshot is as follows −
|
[
{
"code": null,
"e": 1200,
"s": 1062,
"text": "For this, you can use PreparedStatement from Java. Let us first create a table wherein one of the columns is ArrivalDate with DATE type −"
},
{
"code": null,
"e": 1341,
"s": 1200,
"text": "mysql> create table DemoTable(\n PassengerId int,\n PassengerName varchar(40),\n ArrivalDate date\n);\nQuery OK, 0 rows affected (0.82 sec)"
},
{
"code": null,
"e": 1386,
"s": 1341,
"text": "The JAVA code is as follows to insert date −"
},
{
"code": null,
"e": 2299,
"s": 1386,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\npublic class InsertDateFromJava {\n public static void main(String[] args) {\n Connection con = null;\n PreparedStatement ps = null;\n try {\n java.util.Date javaDate = new java.util.Date();\n java.sql.Date mySQLDate = new java.sql.Date(javaDate.getTime());\n con = DriverManager.getConnection(\"jdbc :mysql ://localhost :3306/web?useSSL=false\", \"root\",\"123456\");\n String query = \"insert into DemoTable(PassengerId,PassengerName,ArrivalDate) values(?,?,?) \";\n ps = con.prepareStatement(query);\n ps.setInt(1, 101);\n ps.setString(2, \"Adam\");\n ps.setDate(3, mySQLDate);\n ps.executeUpdate();\n System.out.println(\"Record is inserted with current Date......\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2348,
"s": 2299,
"text": "This will produce the following output of Java −"
},
{
"code": null,
"e": 2391,
"s": 2348,
"text": "Record is inserted with current Date......"
},
{
"code": null,
"e": 2435,
"s": 2391,
"text": "Following is the screenshot of the output −"
},
{
"code": null,
"e": 2481,
"s": 2435,
"text": "Let us check the records of the table again −"
},
{
"code": null,
"e": 2513,
"s": 2481,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 2554,
"s": 2513,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2808,
"s": 2554,
"text": "+-------------+---------------+-------------+\n| PassengerId | PassengerName | ArrivalDate |\n+-------------+---------------+-------------+\n| 101 | Adam | 2019-09-07 |\n+-------------+---------------+-------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2839,
"s": 2808,
"text": "The screenshot is as follows −"
}
] |
How to find only Monday's date with Python?
|
You can find the next Monday's date easily with Python's datetime library and the timedelta object. You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday). Finally add one week to this date using a timedelta object and voila you get the next monday's date.
import datetime
today = datetime.date.today()
next_monday = today + datetime.timedelta(days=-today.weekday(), weeks=1)
print(next_monday)
This will give the output −
2018-01-08
|
[
{
"code": null,
"e": 1394,
"s": 1062,
"text": "You can find the next Monday's date easily with Python's datetime library and the timedelta object. You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday). Finally add one week to this date using a timedelta object and voila you get the next monday's date."
},
{
"code": null,
"e": 1532,
"s": 1394,
"text": "import datetime\ntoday = datetime.date.today()\nnext_monday = today + datetime.timedelta(days=-today.weekday(), weeks=1)\nprint(next_monday)"
},
{
"code": null,
"e": 1560,
"s": 1532,
"text": "This will give the output −"
},
{
"code": null,
"e": 1571,
"s": 1560,
"text": "2018-01-08"
}
] |
Extracting email addresses using regular expressions in Python
|
Email addresses are pretty complex and do not have a standard being followed all over the world which makes it difficult to identify an email in a regex. The RFC 5322 specifies the format of an email address. We'll use this format to extract email addresses from the text.
For example, for a given input string −
Hi my name is John and email address is john.doe@somecompany.co.uk and my friend's email is jane_doe124@gmail.com
We should get the output −
john.doe@somecompany.co.uk
jane_doe124@gmail.com
We can use the following regex for exatraction −
[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+
We can extract the email addresses using the find all method from re module. For example,
import re
my_str = "Hi my name is John and email address is john.doe@somecompany.co.uk and my friend's email is jane_doe124@gmail.com"
emails = re.findall("([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)", my_str)
for mail in an email:
print(mail)
This will give the output −
john.doe@somecompany.co.uk
jane_doe124@gmail.com
|
[
{
"code": null,
"e": 1335,
"s": 1062,
"text": "Email addresses are pretty complex and do not have a standard being followed all over the world which makes it difficult to identify an email in a regex. The RFC 5322 specifies the format of an email address. We'll use this format to extract email addresses from the text."
},
{
"code": null,
"e": 1375,
"s": 1335,
"text": "For example, for a given input string −"
},
{
"code": null,
"e": 1489,
"s": 1375,
"text": "Hi my name is John and email address is john.doe@somecompany.co.uk and my friend's email is jane_doe124@gmail.com"
},
{
"code": null,
"e": 1516,
"s": 1489,
"text": "We should get the output −"
},
{
"code": null,
"e": 1565,
"s": 1516,
"text": "john.doe@somecompany.co.uk\njane_doe124@gmail.com"
},
{
"code": null,
"e": 1614,
"s": 1565,
"text": "We can use the following regex for exatraction −"
},
{
"code": null,
"e": 1661,
"s": 1614,
"text": "[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+"
},
{
"code": null,
"e": 1751,
"s": 1661,
"text": "We can extract the email addresses using the find all method from re module. For example,"
},
{
"code": null,
"e": 2002,
"s": 1751,
"text": "import re\n\nmy_str = \"Hi my name is John and email address is john.doe@somecompany.co.uk and my friend's email is jane_doe124@gmail.com\"\nemails = re.findall(\"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)\", my_str)\n\nfor mail in an email:\nprint(mail)"
},
{
"code": null,
"e": 2030,
"s": 2002,
"text": "This will give the output −"
},
{
"code": null,
"e": 2079,
"s": 2030,
"text": "john.doe@somecompany.co.uk\njane_doe124@gmail.com"
}
] |
Modelling tabular data with CatBoost and NODE | by Mikael Huss | Towards Data Science
|
CatBoost from Yandex, a Russian online search company, is fast and easy to use, but recently researchers from the same company released a new neural network based package, NODE, that they claim outperforms CatBoost and all other gradient boosting methods. Can this be true? Let’s find out how to use both CatBoost and NODE!
Who is this blog post for?
Although I wrote this blog post for anyone who is interested in machine learning and in particular tabular data, it is helpful if you are familiar with Python and the scikit-learn library if you want to follow along with the code. If you aren’t, hopefully, you will find the theoretical and conceptual parts interesting anyway!
CatBoost is my go-to package for modelling tabular data. It is an implementation of gradient boosted decision trees with a few tweaks that make it slightly different from e.g. xgboost or LightGBM. It works for both classification and regression problems.
Some nice things about CatBoost:
It handles categorical features (get it?) out of the box, so you don’t need to worry about how to encode them.
It typically requires very little parameter tuning.
It avoids certain subtle types of data leakage that other methods may suffer from.
It is fast, and can be run on GPU if you want it to go even faster.
These factors make CatBoost, for me, a no-brainer as the first thing to reach for when I need to analyze a new tabular dataset.
Skip this section if you just want to use CatBoost!
On a more technical level, there are some interesting things about how CatBoost is implemented. I highly recommend the paper Catboost: unbiased boosting with categorical features if you are interested in the details. I just want to highlight two things.
In the paper, the authors show that standard gradient boosting algorithms are affected by subtle types of data leakage which result from the way that the models are iteratively fitted. In a similar manner, the most effective ways to encode categorical features numerically (like target encoding) are prone to data leakage and overfitting. To avoid this leakage, CatBoost introduces an artificial timeline according to which the training examples arrive so that only “previously seen” examples can be used when calculating statistics.CatBoost actually doesn’t use regular decision trees, but oblivious decision trees. These are trees where, at each level of the tree, the same feature and the same splitting criterion is used everywhere! This sounds weird, but has some nice properties. Let’s look at what is meant by this.
In the paper, the authors show that standard gradient boosting algorithms are affected by subtle types of data leakage which result from the way that the models are iteratively fitted. In a similar manner, the most effective ways to encode categorical features numerically (like target encoding) are prone to data leakage and overfitting. To avoid this leakage, CatBoost introduces an artificial timeline according to which the training examples arrive so that only “previously seen” examples can be used when calculating statistics.
CatBoost actually doesn’t use regular decision trees, but oblivious decision trees. These are trees where, at each level of the tree, the same feature and the same splitting criterion is used everywhere! This sounds weird, but has some nice properties. Let’s look at what is meant by this.
In a normal decision tree, feature to split on and the cutoff value both depend on what path you have taken so far in the tree. This makes sense because we can use the information we already have to decide the most informative next question (like in the “20 questions” game). With oblivious decision trees, the history doesn’t matter; we pose the same question no matter what. The trees are called “oblivious” because they keep “forgetting” what has happened before.
Why is this useful? One nice property of oblivious decision trees is that an example can be classified or scored really quickly — it is always the same N binary questions that are posed (where N is the depth of the tree). This can easily be done in parallel for many examples. That is one reason why CatBoost is fast. Another thing to keep in mind is that we are dealing with a tree ensemble here. As a stand-alone algorithm, the oblivious decision tree might not work so well, but the idea of tree ensembles is that a coalition of weak learners often works well because errors and biases are “washed out”. Normally, the weak learner is a standard decision tree, and here it is something even weaker, namely the oblivious decision tree. The CatBoost authors argue that this particular weak base learner works well for generalization.
Although installing CatBoost should be a simple matter of typing
pip install catboost
I’ve sometimes encountered problems with that when on a Mac. On Linux systems such as the Ubuntu system I am typing on now, or on Google Colaboratory, it should “just work”. If you keep having problems installing it, consider using a Docker image, e.g.
docker pull yandex/tutorial-catboost-clickhousedocker run -it yandex/tutorial-catboost-clickhouse
Link to Colab notebook with code
Let’s have a look at how to use CatBoost on a tabular dataset. We start by downloading a lightly preprocessed version of the Adult/Census Income dataset which is, in the following, assumed to be located in datasets/adult.csv. I chose this dataset because it has a mix of categorical and numerical features, a nice manageable size in the tens of thousands of examples and not too many features. It is often used to exemplify algorithms, for instance in Google’s What-If Tool and many other places.
The adult census dataset has the columns ‘age’, ‘workclass’, ‘education’, ‘education-num’, ‘marital-status’, ‘occupation’, ‘relationship’, ‘race’, ‘sex’, ‘capital-gain’, ‘capital-loss’, ‘hours-per-week’, ‘native-country’, and ‘<=50K’. The task is to predict the value of the last column, ‘<=50K’, which indicates if the person in question earns 50,000 USD or less per year (the dataset is from 1994). We regard the following features as categorical rather than numerical: ‘workclass’, ‘education’, ‘marital-status’, ‘occupation’, ‘relationship’, ‘race’, ‘sex’, ‘native-country’.
The code is pretty similar to scikit-learn except for the Pool datatype that CatBoost uses to bundle feature and target values for a dataset while keeping them conceptually separate. (I have to admit I don’t really know why Pool is there — I just use it, and it seems to work fine.)
The code is available on Colab, but I will copy it here for reference. CatBoost needs to know which features are categorical and will then handle them automatically. In this code snippet, I also use 5-fold (stratified) cross-validation to estimate the prediction accuracy.
from catboost import CatBoostClassifier, Poolfrom hyperopt import fmin, hp, tpeimport pandas as pdfrom sklearn.model_selection import StratifiedKFolddf = pd.read_csv('https://docs.google.com/uc?' + 'id=10eFO2rVlsQBUffn0b7UCAp28n0mkLCy7&' + 'export=download')labels = df.pop('<=50K')categorical_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country'] categoricals = [df.columns.get_loc(i) for i in categorical_names]nfolds = 5skf = StratifiedKFold(n_splits=nfolds, shuffle=True)acc = []for train_index, test_index in skf.split(df, labels): X_train, X_test = df.iloc[train_index].copy(), \ df.iloc[test_index].copy() y_train, y_test = labels.iloc[train_index], \ labels.iloc[test_index] train_pool = Pool(X_train, y_train, cat_features = categoricals) test_pool = Pool(X_test, y_test, cat_features = categoricals) model = CatBoostClassifier(iterations=100, depth=8, learning_rate=1, loss_function='MultiClass') model.fit(train_pool) predictions = model.predict(test_pool) accuracy = sum(predictions.squeeze() == y_test) / len(predictions) acc.append(accuracy)mean_acc = sum(acc) / nfoldsprint(f'Mean accuracy based on {nfolds} folds: {mean_acc:.3f}')print(acc)
What we tend to get from running this (CatBoost without hyperparameter optimization) is a mean accuracy between 85% and 86%. In my last run, I got about 85.7%.
If we want to try to optimize the hyperparameters, we can use hyperopt (if you don’t have it, install it with pip install hyperopt). In order to use it, you need to define a function that hyperopt tries to minimize. We will just try to optimize the accuracy here. Perhaps it would be better to optimize e.g. log loss, but that is left as an exercise to the reader ;)
The main parameters to optimize are probably the number of iterations, the learning rate, and the tree depth. There are also many other parameters related to over-fitting, for instance early stopping rounds and so on. Feel free to explore on your own!
# Optimize between 10 and 1000 iterations and depth between 2 and 12search_space = {'iterations': hp.quniform('iterations', 10, 1000, 10), 'depth': hp.quniform('depth', 2, 12, 1), 'lr': hp.uniform('lr', 0.01, 1) }def opt_fn(search_space): nfolds = 5 skf = StratifiedKFold(n_splits=nfolds, shuffle=True) acc = [] for train_index, test_index in skf.split(df, labels): X_train, X_test = df.iloc[train_index].copy(), \ df.iloc[test_index].copy() y_train, y_test = labels.iloc[train_index], \ labels.iloc[test_index] train_pool = Pool(X_train, y_train, cat_features = categoricals) test_pool = Pool(X_test, y_test, cat_features = categoricals) model = CatBoostClassifier(iterations=search_space['iterations'], depth=search_space['depth'], learning_rate=search_space['lr'], loss_function='MultiClass', od_type='Iter') model.fit(train_pool, logging_level='Silent') predictions = model.predict(test_pool) accuracy = sum(predictions.squeeze() == y_test) / len(predictions) acc.append(accuracy) mean_acc = sum(acc) / nfolds return -1*mean_accbest = fmin(fn=opt_fn, space=search_space, algo=tpe.suggest, max_evals=100)
When I last ran this code, it took over 5 hours but resulted in a mean accuracy of 87.3%, which is on par with the best results I got when trying the Auger.ai AutoML platform.
At this point, we should ask ourselves if these fancy new-fangled methods are really needed. How would a good old logistic regression perform out of the box and after hyperparameter optimization?
I’ll omit reproducing the code here for brevity’s sake, but it is available in the same Colab notebook as before. One detail with the logistic regression implementation is that it doesn’t handle categorical variables out of the box like CatBoost does, so I decided to code them using target encoding, specifically leave-one-out target encoding, which is the approach taken in NODE and a fairly close though not identical analogue of what happens in CatBoost.
Long story short, untuned logistic regression with this type of encoding yields around 80% accuracy, and around 81% (80.7% in my latest run) after hyperparameter tuning. Here, an interesting alternative is to try automated preprocessing libraries such as vtreat and Automunge, but I will save those for an upcoming blog post!
What do we have so far, before trying NODE?
Logistic regression, untuned: 80.0%
Logistic regression, tuned: 80.7%
CatBoost, untuned: 85.7%
CatBoost, tuned: 87.2%
A recent manuscript from Yandex researchers describes an interesting neural network version of CatBoost, or at least a neural network take on oblivious decision tree ensembles (see the technical section above if you want to remind yourself what “oblivious” means here.) This architecture, called NODE, can be used for either classification or regression.
One of the claims from the abstract reads: “With an extensive experimental comparison to the leading GBDT packages on a large number of tabular datasets, we demonstrate the advantage of the proposed NODE architecture, which outperforms the competitors on most of the tasks.” This naturally piqued my interest. Could this tool be better than CatBoost?
You should go to the paper for the full story, but some relevant details are:
The entmax activation function is used as a soft version of a split in a regular decision tree. As the paper puts it, “The entmax is capable to produce sparse probability distributions, where the majority of probabilities are exactly equal to 0. In this work, we argue that entmax is also an appropriate inductive bias in our model, which allows differentiable split decision construction in the internal tree nodes. Intuitively, entmax can learn splitting decisions based on a small subset of data features (up to one, as in classical decision trees), avoiding undesired influence from others.” The entmax functions allows a neural network to mimic a decision tree-type system while keeping the model differentiable (weights can be updated based on the gradients).
The authors present a new type of layer, a “node layer”, which you can use in a neural network (their implementation is in PyTorch). A node layer represents a tree ensemble.
Several node layers can be stacked, yielding a hierarchical model where the input is fed through one tree ensemble at a time. Successive concatenation of input representations can be used to give a model which is reminiscent of the popular DenseNet model for image processing, just specialized in tabular data.
The parameters of a NODE model are:
Learning rate (always 0.001 in the paper)
The number of node layers (k)
The number of trees in each layer (m)
The depth of the trees in each layer (d)
To get a feeling for how the analogy between this neural network architecture and decision tree ensembles looks, Figure 1 is reproduced here.
There is not much guidance in the manuscript; the authors suggest using hyperparameter optimization. They do mention that they optimize over the following space:
num layers: {2, 4, 8}
total tree count: {1024, 2048}
tree depth: {6, 8}
tree output dim: {2, 3}
In my code, I don’t do grid search but rather let hyperopt sample values within certain ranges. The way I thought about it (which could be wrong) is that each layer represents a tree ensemble (a single instance of CatBoost, let’s say). For each layer that you add, you may add some representation power, but you also make the model much heavier to train and potentially risk overfitting. The total tree count seems roughly analogous to the number of trees in CatBoost/xgboost/random forests, and has the same tradeoffs: with many trees, you can express more complicated functions, but the model will take much longer to train and risk overfitting. The tree depth, again, has the same type of tradeoff. As for the output dimensionality, frankly, I don’t quite understand why it is a parameter. Reading the paper, it seems it should be equal to one for regression and equal to the number of classes for classification.
The authors have made code available on GitHub. They do not provide a command-line interface but rather suggest that users run their models in the provided Jupyter notebooks. One classification example and one regression example is provided in those notebooks.
The repo README page also strongly suggests using a GPU to train NODE models. (This is a factor in favor of CatBoost.)
I have prepared a Colaboratory notebook with some example code on how to run classification on NODE and how to optimize hyperparameters with hyperopt.
Please move to the Colaboratory notebook right now to keep following along!
Here I will just highlight some parts of the code.
The problems I encountered when adapting the authors’ code were mainly related to data types. It’s important that the input datasets (X_train and X_val) are arrays (numpy or torch) in float32 format; not float64 or a mix of float and int. The labels need to be encoded as long (int64) for classification, and float32 for regression. (You can see this handled in the cell titled “Load, split and preprocess the data”.)
Other problems were related to memory. The models can quickly blow up the GPU memory, especially with the large batch sizes used in the authors’ example notebooks. I solved this simply by using the maximum batch size I could get away with on my laptop (and later, on Colab).
In general, though, it was not that hard to get the code to work. The documentation was a bit sparse, but sufficient.
Unlike CatBoost, NODE does not support categorical variables, so you have to prepare those yourself into a numerical format. We do it for the Adult Census dataset in the same way the NODE authors do it, using LeaveOneOutEncoder from the category_encoders library. Here we just use a regular train/test split instead of 5-fold CV out of convenience, as it takes a long time to train NODE (especially with hyperparameter optimization).
from category_encoders import LeaveOneOutEncoderimport numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitdf = pd.read_csv('https://docs.google.com/uc' + '?id=10eFO2rVlsQBUffn0b7UCAp28n0mkLCy7&' + 'export=download')labels = df.pop('<=50K')X_train, X_val, y_train, y_val = train_test_split(df, labels, test_size=0.2)class_to_int = {c: i for i, c in enumerate(y_train.unique())} y_train_int = [class_to_int[v] for v in y_train] y_val_int = [class_to_int[v] for v in y_val] cat_features = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country'] cat_encoder = LeaveOneOutEncoder()cat_encoder.fit(X_train[cat_features], y_train_int)X_train[cat_features] = cat_encoder.transform(X_train[cat_features])X_val[cat_features] = cat_encoder.transform(X_val[cat_features])# Node is going to want to have the values as float32 at some pointsX_train = X_train.values.astype('float32')X_val = X_val.values.astype('float32')y_train = np.array(y_train_int)y_val = np.array(y_val_int)
Now we have a fully numeric dataset.
The rest of the code is essentially the same as in the authors’ repo (except for the hyperopt part). They created a Pytorch layer called DenseBlock, which implements the NODE architecture. A class called Trainer holds information about the experiment, and there is a straightforward training loop that keeps track of the best metrics seen so far and plots updated loss curves.
With some minimal trial and error, I was able to find a model with around 86% validation accuracy. After hyperparameter optimization with hyperopt (which was supposed to run overnight on a GPU in Colab, but in fact, timed out after about 40 iterations), the best performance was 87.2%. In other runs, I have achieved 87.4%. In other words, NODE did outperform CatBoost, albeit slightly, after hyperopt tuning.
However, accuracy is not everything. It is not convenient to have to do costly optimization for every dataset.
It seems that slightly better results can be obtained (based on the NODE paper and this test; I will be sure to try many other datasets!)
Much faster
Less need for hyperparameter optimization
Runs fine without GPU
Has support for categorical variables
Which one would I use for my next projects? Probably CatBoost will still be my go-to tool, but I will keep NODE in mind and maybe try it just in case...
It’s also important to realize that performance is dataset-dependent and that the Adult Census Income dataset is not representative of all scenarios. Perhaps more importantly, the preprocessing of categorical features is likely rather important in NODE. I’ll return to the subject of preprocessing in a future post!
|
[
{
"code": null,
"e": 496,
"s": 172,
"text": "CatBoost from Yandex, a Russian online search company, is fast and easy to use, but recently researchers from the same company released a new neural network based package, NODE, that they claim outperforms CatBoost and all other gradient boosting methods. Can this be true? Let’s find out how to use both CatBoost and NODE!"
},
{
"code": null,
"e": 523,
"s": 496,
"text": "Who is this blog post for?"
},
{
"code": null,
"e": 851,
"s": 523,
"text": "Although I wrote this blog post for anyone who is interested in machine learning and in particular tabular data, it is helpful if you are familiar with Python and the scikit-learn library if you want to follow along with the code. If you aren’t, hopefully, you will find the theoretical and conceptual parts interesting anyway!"
},
{
"code": null,
"e": 1106,
"s": 851,
"text": "CatBoost is my go-to package for modelling tabular data. It is an implementation of gradient boosted decision trees with a few tweaks that make it slightly different from e.g. xgboost or LightGBM. It works for both classification and regression problems."
},
{
"code": null,
"e": 1139,
"s": 1106,
"text": "Some nice things about CatBoost:"
},
{
"code": null,
"e": 1250,
"s": 1139,
"text": "It handles categorical features (get it?) out of the box, so you don’t need to worry about how to encode them."
},
{
"code": null,
"e": 1302,
"s": 1250,
"text": "It typically requires very little parameter tuning."
},
{
"code": null,
"e": 1385,
"s": 1302,
"text": "It avoids certain subtle types of data leakage that other methods may suffer from."
},
{
"code": null,
"e": 1453,
"s": 1385,
"text": "It is fast, and can be run on GPU if you want it to go even faster."
},
{
"code": null,
"e": 1581,
"s": 1453,
"text": "These factors make CatBoost, for me, a no-brainer as the first thing to reach for when I need to analyze a new tabular dataset."
},
{
"code": null,
"e": 1633,
"s": 1581,
"text": "Skip this section if you just want to use CatBoost!"
},
{
"code": null,
"e": 1887,
"s": 1633,
"text": "On a more technical level, there are some interesting things about how CatBoost is implemented. I highly recommend the paper Catboost: unbiased boosting with categorical features if you are interested in the details. I just want to highlight two things."
},
{
"code": null,
"e": 2710,
"s": 1887,
"text": "In the paper, the authors show that standard gradient boosting algorithms are affected by subtle types of data leakage which result from the way that the models are iteratively fitted. In a similar manner, the most effective ways to encode categorical features numerically (like target encoding) are prone to data leakage and overfitting. To avoid this leakage, CatBoost introduces an artificial timeline according to which the training examples arrive so that only “previously seen” examples can be used when calculating statistics.CatBoost actually doesn’t use regular decision trees, but oblivious decision trees. These are trees where, at each level of the tree, the same feature and the same splitting criterion is used everywhere! This sounds weird, but has some nice properties. Let’s look at what is meant by this."
},
{
"code": null,
"e": 3244,
"s": 2710,
"text": "In the paper, the authors show that standard gradient boosting algorithms are affected by subtle types of data leakage which result from the way that the models are iteratively fitted. In a similar manner, the most effective ways to encode categorical features numerically (like target encoding) are prone to data leakage and overfitting. To avoid this leakage, CatBoost introduces an artificial timeline according to which the training examples arrive so that only “previously seen” examples can be used when calculating statistics."
},
{
"code": null,
"e": 3534,
"s": 3244,
"text": "CatBoost actually doesn’t use regular decision trees, but oblivious decision trees. These are trees where, at each level of the tree, the same feature and the same splitting criterion is used everywhere! This sounds weird, but has some nice properties. Let’s look at what is meant by this."
},
{
"code": null,
"e": 4001,
"s": 3534,
"text": "In a normal decision tree, feature to split on and the cutoff value both depend on what path you have taken so far in the tree. This makes sense because we can use the information we already have to decide the most informative next question (like in the “20 questions” game). With oblivious decision trees, the history doesn’t matter; we pose the same question no matter what. The trees are called “oblivious” because they keep “forgetting” what has happened before."
},
{
"code": null,
"e": 4835,
"s": 4001,
"text": "Why is this useful? One nice property of oblivious decision trees is that an example can be classified or scored really quickly — it is always the same N binary questions that are posed (where N is the depth of the tree). This can easily be done in parallel for many examples. That is one reason why CatBoost is fast. Another thing to keep in mind is that we are dealing with a tree ensemble here. As a stand-alone algorithm, the oblivious decision tree might not work so well, but the idea of tree ensembles is that a coalition of weak learners often works well because errors and biases are “washed out”. Normally, the weak learner is a standard decision tree, and here it is something even weaker, namely the oblivious decision tree. The CatBoost authors argue that this particular weak base learner works well for generalization."
},
{
"code": null,
"e": 4900,
"s": 4835,
"text": "Although installing CatBoost should be a simple matter of typing"
},
{
"code": null,
"e": 4921,
"s": 4900,
"text": "pip install catboost"
},
{
"code": null,
"e": 5174,
"s": 4921,
"text": "I’ve sometimes encountered problems with that when on a Mac. On Linux systems such as the Ubuntu system I am typing on now, or on Google Colaboratory, it should “just work”. If you keep having problems installing it, consider using a Docker image, e.g."
},
{
"code": null,
"e": 5272,
"s": 5174,
"text": "docker pull yandex/tutorial-catboost-clickhousedocker run -it yandex/tutorial-catboost-clickhouse"
},
{
"code": null,
"e": 5305,
"s": 5272,
"text": "Link to Colab notebook with code"
},
{
"code": null,
"e": 5802,
"s": 5305,
"text": "Let’s have a look at how to use CatBoost on a tabular dataset. We start by downloading a lightly preprocessed version of the Adult/Census Income dataset which is, in the following, assumed to be located in datasets/adult.csv. I chose this dataset because it has a mix of categorical and numerical features, a nice manageable size in the tens of thousands of examples and not too many features. It is often used to exemplify algorithms, for instance in Google’s What-If Tool and many other places."
},
{
"code": null,
"e": 6381,
"s": 5802,
"text": "The adult census dataset has the columns ‘age’, ‘workclass’, ‘education’, ‘education-num’, ‘marital-status’, ‘occupation’, ‘relationship’, ‘race’, ‘sex’, ‘capital-gain’, ‘capital-loss’, ‘hours-per-week’, ‘native-country’, and ‘<=50K’. The task is to predict the value of the last column, ‘<=50K’, which indicates if the person in question earns 50,000 USD or less per year (the dataset is from 1994). We regard the following features as categorical rather than numerical: ‘workclass’, ‘education’, ‘marital-status’, ‘occupation’, ‘relationship’, ‘race’, ‘sex’, ‘native-country’."
},
{
"code": null,
"e": 6664,
"s": 6381,
"text": "The code is pretty similar to scikit-learn except for the Pool datatype that CatBoost uses to bundle feature and target values for a dataset while keeping them conceptually separate. (I have to admit I don’t really know why Pool is there — I just use it, and it seems to work fine.)"
},
{
"code": null,
"e": 6937,
"s": 6664,
"text": "The code is available on Colab, but I will copy it here for reference. CatBoost needs to know which features are categorical and will then handle them automatically. In this code snippet, I also use 5-fold (stratified) cross-validation to estimate the prediction accuracy."
},
{
"code": null,
"e": 8363,
"s": 6937,
"text": "from catboost import CatBoostClassifier, Poolfrom hyperopt import fmin, hp, tpeimport pandas as pdfrom sklearn.model_selection import StratifiedKFolddf = pd.read_csv('https://docs.google.com/uc?' + 'id=10eFO2rVlsQBUffn0b7UCAp28n0mkLCy7&' + 'export=download')labels = df.pop('<=50K')categorical_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country'] categoricals = [df.columns.get_loc(i) for i in categorical_names]nfolds = 5skf = StratifiedKFold(n_splits=nfolds, shuffle=True)acc = []for train_index, test_index in skf.split(df, labels): X_train, X_test = df.iloc[train_index].copy(), \\ df.iloc[test_index].copy() y_train, y_test = labels.iloc[train_index], \\ labels.iloc[test_index] train_pool = Pool(X_train, y_train, cat_features = categoricals) test_pool = Pool(X_test, y_test, cat_features = categoricals) model = CatBoostClassifier(iterations=100, depth=8, learning_rate=1, loss_function='MultiClass') model.fit(train_pool) predictions = model.predict(test_pool) accuracy = sum(predictions.squeeze() == y_test) / len(predictions) acc.append(accuracy)mean_acc = sum(acc) / nfoldsprint(f'Mean accuracy based on {nfolds} folds: {mean_acc:.3f}')print(acc)"
},
{
"code": null,
"e": 8523,
"s": 8363,
"text": "What we tend to get from running this (CatBoost without hyperparameter optimization) is a mean accuracy between 85% and 86%. In my last run, I got about 85.7%."
},
{
"code": null,
"e": 8890,
"s": 8523,
"text": "If we want to try to optimize the hyperparameters, we can use hyperopt (if you don’t have it, install it with pip install hyperopt). In order to use it, you need to define a function that hyperopt tries to minimize. We will just try to optimize the accuracy here. Perhaps it would be better to optimize e.g. log loss, but that is left as an exercise to the reader ;)"
},
{
"code": null,
"e": 9142,
"s": 8890,
"text": "The main parameters to optimize are probably the number of iterations, the learning rate, and the tree depth. There are also many other parameters related to over-fitting, for instance early stopping rounds and so on. Feel free to explore on your own!"
},
{
"code": null,
"e": 10517,
"s": 9142,
"text": "# Optimize between 10 and 1000 iterations and depth between 2 and 12search_space = {'iterations': hp.quniform('iterations', 10, 1000, 10), 'depth': hp.quniform('depth', 2, 12, 1), 'lr': hp.uniform('lr', 0.01, 1) }def opt_fn(search_space): nfolds = 5 skf = StratifiedKFold(n_splits=nfolds, shuffle=True) acc = [] for train_index, test_index in skf.split(df, labels): X_train, X_test = df.iloc[train_index].copy(), \\ df.iloc[test_index].copy() y_train, y_test = labels.iloc[train_index], \\ labels.iloc[test_index] train_pool = Pool(X_train, y_train, cat_features = categoricals) test_pool = Pool(X_test, y_test, cat_features = categoricals) model = CatBoostClassifier(iterations=search_space['iterations'], depth=search_space['depth'], learning_rate=search_space['lr'], loss_function='MultiClass', od_type='Iter') model.fit(train_pool, logging_level='Silent') predictions = model.predict(test_pool) accuracy = sum(predictions.squeeze() == y_test) / len(predictions) acc.append(accuracy) mean_acc = sum(acc) / nfolds return -1*mean_accbest = fmin(fn=opt_fn, space=search_space, algo=tpe.suggest, max_evals=100)"
},
{
"code": null,
"e": 10693,
"s": 10517,
"text": "When I last ran this code, it took over 5 hours but resulted in a mean accuracy of 87.3%, which is on par with the best results I got when trying the Auger.ai AutoML platform."
},
{
"code": null,
"e": 10889,
"s": 10693,
"text": "At this point, we should ask ourselves if these fancy new-fangled methods are really needed. How would a good old logistic regression perform out of the box and after hyperparameter optimization?"
},
{
"code": null,
"e": 11348,
"s": 10889,
"text": "I’ll omit reproducing the code here for brevity’s sake, but it is available in the same Colab notebook as before. One detail with the logistic regression implementation is that it doesn’t handle categorical variables out of the box like CatBoost does, so I decided to code them using target encoding, specifically leave-one-out target encoding, which is the approach taken in NODE and a fairly close though not identical analogue of what happens in CatBoost."
},
{
"code": null,
"e": 11674,
"s": 11348,
"text": "Long story short, untuned logistic regression with this type of encoding yields around 80% accuracy, and around 81% (80.7% in my latest run) after hyperparameter tuning. Here, an interesting alternative is to try automated preprocessing libraries such as vtreat and Automunge, but I will save those for an upcoming blog post!"
},
{
"code": null,
"e": 11718,
"s": 11674,
"text": "What do we have so far, before trying NODE?"
},
{
"code": null,
"e": 11754,
"s": 11718,
"text": "Logistic regression, untuned: 80.0%"
},
{
"code": null,
"e": 11788,
"s": 11754,
"text": "Logistic regression, tuned: 80.7%"
},
{
"code": null,
"e": 11813,
"s": 11788,
"text": "CatBoost, untuned: 85.7%"
},
{
"code": null,
"e": 11836,
"s": 11813,
"text": "CatBoost, tuned: 87.2%"
},
{
"code": null,
"e": 12191,
"s": 11836,
"text": "A recent manuscript from Yandex researchers describes an interesting neural network version of CatBoost, or at least a neural network take on oblivious decision tree ensembles (see the technical section above if you want to remind yourself what “oblivious” means here.) This architecture, called NODE, can be used for either classification or regression."
},
{
"code": null,
"e": 12542,
"s": 12191,
"text": "One of the claims from the abstract reads: “With an extensive experimental comparison to the leading GBDT packages on a large number of tabular datasets, we demonstrate the advantage of the proposed NODE architecture, which outperforms the competitors on most of the tasks.” This naturally piqued my interest. Could this tool be better than CatBoost?"
},
{
"code": null,
"e": 12620,
"s": 12542,
"text": "You should go to the paper for the full story, but some relevant details are:"
},
{
"code": null,
"e": 13386,
"s": 12620,
"text": "The entmax activation function is used as a soft version of a split in a regular decision tree. As the paper puts it, “The entmax is capable to produce sparse probability distributions, where the majority of probabilities are exactly equal to 0. In this work, we argue that entmax is also an appropriate inductive bias in our model, which allows differentiable split decision construction in the internal tree nodes. Intuitively, entmax can learn splitting decisions based on a small subset of data features (up to one, as in classical decision trees), avoiding undesired influence from others.” The entmax functions allows a neural network to mimic a decision tree-type system while keeping the model differentiable (weights can be updated based on the gradients)."
},
{
"code": null,
"e": 13560,
"s": 13386,
"text": "The authors present a new type of layer, a “node layer”, which you can use in a neural network (their implementation is in PyTorch). A node layer represents a tree ensemble."
},
{
"code": null,
"e": 13871,
"s": 13560,
"text": "Several node layers can be stacked, yielding a hierarchical model where the input is fed through one tree ensemble at a time. Successive concatenation of input representations can be used to give a model which is reminiscent of the popular DenseNet model for image processing, just specialized in tabular data."
},
{
"code": null,
"e": 13907,
"s": 13871,
"text": "The parameters of a NODE model are:"
},
{
"code": null,
"e": 13949,
"s": 13907,
"text": "Learning rate (always 0.001 in the paper)"
},
{
"code": null,
"e": 13979,
"s": 13949,
"text": "The number of node layers (k)"
},
{
"code": null,
"e": 14017,
"s": 13979,
"text": "The number of trees in each layer (m)"
},
{
"code": null,
"e": 14058,
"s": 14017,
"text": "The depth of the trees in each layer (d)"
},
{
"code": null,
"e": 14200,
"s": 14058,
"text": "To get a feeling for how the analogy between this neural network architecture and decision tree ensembles looks, Figure 1 is reproduced here."
},
{
"code": null,
"e": 14362,
"s": 14200,
"text": "There is not much guidance in the manuscript; the authors suggest using hyperparameter optimization. They do mention that they optimize over the following space:"
},
{
"code": null,
"e": 14384,
"s": 14362,
"text": "num layers: {2, 4, 8}"
},
{
"code": null,
"e": 14415,
"s": 14384,
"text": "total tree count: {1024, 2048}"
},
{
"code": null,
"e": 14434,
"s": 14415,
"text": "tree depth: {6, 8}"
},
{
"code": null,
"e": 14458,
"s": 14434,
"text": "tree output dim: {2, 3}"
},
{
"code": null,
"e": 15375,
"s": 14458,
"text": "In my code, I don’t do grid search but rather let hyperopt sample values within certain ranges. The way I thought about it (which could be wrong) is that each layer represents a tree ensemble (a single instance of CatBoost, let’s say). For each layer that you add, you may add some representation power, but you also make the model much heavier to train and potentially risk overfitting. The total tree count seems roughly analogous to the number of trees in CatBoost/xgboost/random forests, and has the same tradeoffs: with many trees, you can express more complicated functions, but the model will take much longer to train and risk overfitting. The tree depth, again, has the same type of tradeoff. As for the output dimensionality, frankly, I don’t quite understand why it is a parameter. Reading the paper, it seems it should be equal to one for regression and equal to the number of classes for classification."
},
{
"code": null,
"e": 15636,
"s": 15375,
"text": "The authors have made code available on GitHub. They do not provide a command-line interface but rather suggest that users run their models in the provided Jupyter notebooks. One classification example and one regression example is provided in those notebooks."
},
{
"code": null,
"e": 15755,
"s": 15636,
"text": "The repo README page also strongly suggests using a GPU to train NODE models. (This is a factor in favor of CatBoost.)"
},
{
"code": null,
"e": 15906,
"s": 15755,
"text": "I have prepared a Colaboratory notebook with some example code on how to run classification on NODE and how to optimize hyperparameters with hyperopt."
},
{
"code": null,
"e": 15982,
"s": 15906,
"text": "Please move to the Colaboratory notebook right now to keep following along!"
},
{
"code": null,
"e": 16033,
"s": 15982,
"text": "Here I will just highlight some parts of the code."
},
{
"code": null,
"e": 16451,
"s": 16033,
"text": "The problems I encountered when adapting the authors’ code were mainly related to data types. It’s important that the input datasets (X_train and X_val) are arrays (numpy or torch) in float32 format; not float64 or a mix of float and int. The labels need to be encoded as long (int64) for classification, and float32 for regression. (You can see this handled in the cell titled “Load, split and preprocess the data”.)"
},
{
"code": null,
"e": 16726,
"s": 16451,
"text": "Other problems were related to memory. The models can quickly blow up the GPU memory, especially with the large batch sizes used in the authors’ example notebooks. I solved this simply by using the maximum batch size I could get away with on my laptop (and later, on Colab)."
},
{
"code": null,
"e": 16844,
"s": 16726,
"text": "In general, though, it was not that hard to get the code to work. The documentation was a bit sparse, but sufficient."
},
{
"code": null,
"e": 17278,
"s": 16844,
"text": "Unlike CatBoost, NODE does not support categorical variables, so you have to prepare those yourself into a numerical format. We do it for the Adult Census dataset in the same way the NODE authors do it, using LeaveOneOutEncoder from the category_encoders library. Here we just use a regular train/test split instead of 5-fold CV out of convenience, as it takes a long time to train NODE (especially with hyperparameter optimization)."
},
{
"code": null,
"e": 18723,
"s": 17278,
"text": "from category_encoders import LeaveOneOutEncoderimport numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitdf = pd.read_csv('https://docs.google.com/uc' + '?id=10eFO2rVlsQBUffn0b7UCAp28n0mkLCy7&' + 'export=download')labels = df.pop('<=50K')X_train, X_val, y_train, y_val = train_test_split(df, labels, test_size=0.2)class_to_int = {c: i for i, c in enumerate(y_train.unique())} y_train_int = [class_to_int[v] for v in y_train] y_val_int = [class_to_int[v] for v in y_val] cat_features = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country'] cat_encoder = LeaveOneOutEncoder()cat_encoder.fit(X_train[cat_features], y_train_int)X_train[cat_features] = cat_encoder.transform(X_train[cat_features])X_val[cat_features] = cat_encoder.transform(X_val[cat_features])# Node is going to want to have the values as float32 at some pointsX_train = X_train.values.astype('float32')X_val = X_val.values.astype('float32')y_train = np.array(y_train_int)y_val = np.array(y_val_int)"
},
{
"code": null,
"e": 18760,
"s": 18723,
"text": "Now we have a fully numeric dataset."
},
{
"code": null,
"e": 19137,
"s": 18760,
"text": "The rest of the code is essentially the same as in the authors’ repo (except for the hyperopt part). They created a Pytorch layer called DenseBlock, which implements the NODE architecture. A class called Trainer holds information about the experiment, and there is a straightforward training loop that keeps track of the best metrics seen so far and plots updated loss curves."
},
{
"code": null,
"e": 19547,
"s": 19137,
"text": "With some minimal trial and error, I was able to find a model with around 86% validation accuracy. After hyperparameter optimization with hyperopt (which was supposed to run overnight on a GPU in Colab, but in fact, timed out after about 40 iterations), the best performance was 87.2%. In other runs, I have achieved 87.4%. In other words, NODE did outperform CatBoost, albeit slightly, after hyperopt tuning."
},
{
"code": null,
"e": 19658,
"s": 19547,
"text": "However, accuracy is not everything. It is not convenient to have to do costly optimization for every dataset."
},
{
"code": null,
"e": 19796,
"s": 19658,
"text": "It seems that slightly better results can be obtained (based on the NODE paper and this test; I will be sure to try many other datasets!)"
},
{
"code": null,
"e": 19808,
"s": 19796,
"text": "Much faster"
},
{
"code": null,
"e": 19850,
"s": 19808,
"text": "Less need for hyperparameter optimization"
},
{
"code": null,
"e": 19872,
"s": 19850,
"text": "Runs fine without GPU"
},
{
"code": null,
"e": 19910,
"s": 19872,
"text": "Has support for categorical variables"
},
{
"code": null,
"e": 20063,
"s": 19910,
"text": "Which one would I use for my next projects? Probably CatBoost will still be my go-to tool, but I will keep NODE in mind and maybe try it just in case..."
}
] |
Reverse all the word in a String represented as a Linked List - GeeksforGeeks
|
23 Jun, 2021
Given a Linked List which represents a sentence S such that each node represents a letter, the task is to reverse the sentence without reversing individual words. For example, for a given sentence “I love Geeks for Geeks”, the Linked List representation is given as: I-> ->l->o->v->e-> ->G->e->e->k->s-> ->f->o->r-> ->G->e->e->k->s
Examples:
Input: I love Geeks for Geeks Output: Geeks for Geeks love I
Input: practice makes a man perfect Output: perfect man a makes practice
Approach: The idea is to navigate the linked list from the beginning. Every time space is encountered, swap the space to the beginning of that word. Repeat this step until the last node is reached. Finally set the first words last letter to point null which will become the last node and keep changing the pointers.
Below is the implementation of the approach:
Java
C#
// Linked List Implementationpublic class Node { public Node(char data, Node next) { Data = data; Next = next; } public char Data; public Node Next;}class GFG { // Function to create a linked list // from the given String private static Node CreateLinkedList(String s) { Node header = null; Node temp = null; // Generates characters from the given string for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); Node node = new Node(c, null); if (header == null) { header = node; temp = header; } else { temp.Next = node; temp = temp.Next; } } return header; } // Function to reverse the words // Assume str = "practice makes man perfect" // to understand proper understanding of the code private static Node Reverse(Node header) { if (header == null) return header; Node wordStartPosition = null; Node endOfSentence = null; Node sentenceStartPosition = null; // Initialize wordStartPosition to header // ie. node 'p' first letter of the word 'practice' wordStartPosition = header; // Navigate the linked list until // a space(' ') is found or header is null //(this is for handing if there is // only one word in the given sentence) while (header != null && header.Data != ' ') { // Keep track the previous node. // This will become the // last node of the linked list endOfSentence = header; // Keep moving to the next node header = header.Next; } // After the above while loop, // endOfSentence points to // the last letter 'e'of word 'practice' // header points to the space(' ') // which is next to word 'practice' // If header is null then there is only // one word in the given sentence // so set header to the // first/wordStartPosition node and return. if (header == null) { header = wordStartPosition; return header; } do { // Swapping the space ie. // convert 'practice<space>' to //'<space>practice' // store the node which is next to space(' ') // 'm' which is the first letter of the word 'make' Node temp = header.Next; header.Next = wordStartPosition; wordStartPosition = header; header = temp; Node prev = null; // Setting sentenceStartPosition to node 'm' //(first letter of the word 'make') sentenceStartPosition = header; // Again Navigate the linked list until // a space(' ') is found or // header == null end of the linked list while (header != null && header.Data != ' ') { prev = header; header = header.Next; } // When the next space is found, // change the pointer to point the previous space // ie. the word is being converted to // "m->a->k->e->s-> ->p->r->a->c->t->i->c->e" prev.Next = wordStartPosition; // Newly found space will point to //'m' first letter of the word 'make' wordStartPosition = sentenceStartPosition; if (header == null) break; // Repeat the loop until // the end of the linked list is reached } while (header != null); header = sentenceStartPosition; // Set the last node's next to null // ie. ->m->a->k->e->s-> ->p->r->a->->c->t->i->c->e->null endOfSentence.Next = null; return header; } // Function to print the Linked List private static void PrintList(Node Header) { Node temp = Header; // Navigate till the end and print the data in each node while (temp != null) { System.out.print(temp.Data); temp = temp.Next; } } // Driver code public static void main(String[] args) { String s = "practice makes a man perfect"; // Convert given string to a linked list // with character as data in each node Node header = CreateLinkedList(s); System.out.println("Before:"); PrintList(header); header = Reverse(header); System.out.println("\nAfter:"); PrintList(header); }}
using System; // Linked List Implementationpublic class Node{ public Node(char data, Node next) { Data = data; Next = next; } public char Data; public Node Next;} class GFG{ // Function to create a linked list // from the given String private static Node CreateList(String s) { Node header = null; Node temp = null; // Generates characters from the given string for (int i = 0; i < s.Length; i++) { char c = s[i]; Node node = new Node(c, null); if (header == null) { header = node; temp = header; } else { temp.Next = node; temp = temp.Next; } } return header; } // Function to reverse the words // Assume str = "practice makes man perfect" // to understand proper understanding of the code private static Node Reverse(Node header) { if (header == null) return header; Node wordStartPosition = null; Node endOfSentence = null; Node sentenceStartPosition = null; // Initialize wordStartPosition to header // ie. node 'p' first letter of the word 'practice' wordStartPosition = header; // Navigate the linked list until // a space(' ') is found or header is null //(this is for handing if there is // only one word in the given sentence) while (header != null && header.Data != ' ') { // Keep track the previous node. // This will become the // last node of the linked list endOfSentence = header; // Keep moving to the next node header = header.Next; } // After the above while loop, // endOfSentence points to // the last letter 'e'of word 'practice' // header points to the space(' ') // which is next to word 'practice' // If header is null then there is only // one word in the given sentance // so set header to the // first/wordStartPosition node and return. if (header == null) { header = wordStartPosition; return header; } do { // Swapping the space ie. // convert 'practice<space>' to //'<space>practice' // store the node which is next to space(' ') // 'm' which is the first letter of the word 'make' Node temp = header.Next; header.Next = wordStartPosition; wordStartPosition = header; header = temp; Node prev = null; // Setting sentenceStartPosition to node 'm' //(first letter of the word 'make') sentenceStartPosition = header; // Again Navigate the linked list until // a space(' ') is found or // header == null end of the linked list while (header != null && header.Data != ' ') { prev = header; header = header.Next; } // When the next space is found, // change the pointer to point the previous space // ie. the word is being converted to // "m->a->k->e->s-> ->p->r->a->c->t->i->c->e" prev.Next = wordStartPosition; // Newly found space will point to //'m' first letter of the word 'make' wordStartPosition = sentenceStartPosition; if (header == null) break; // Repeat the loop until // the end of the linked list is reached } while (header != null); header = sentenceStartPosition; // Set the last node's next to null // ie. ->m->a->k->e->s-> ->p->r->a->->c->t->i->c->e->null endOfSentence.Next = null; return header; } // Function to print the Linked List private static void PrintList(Node Header) { Node temp = Header; // Navigate till the end and print // the data in each node while (temp != null) { Console.Write(temp.Data); temp = temp.Next; } } // Driver code public static void Main(String[] args) { String s = "practice makes a man perfect"; // Convert given string to a linked list // with character as data in each node Node header = CreateList(s); Console.WriteLine("Before:"); PrintList(header); header = Reverse(header); Console.WriteLine("\nAfter:"); PrintList(header); }} // This code is contributed by Rajput-Ji
Before:
practice makes a man perfect
After:
perfect man a makes practice
Rajput-Ji
clintra
Reverse
Linked List
Strings
Linked List
Strings
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Delete a node in a Doubly Linked List
Given a linked list which is sorted, how will you insert in sorted way
Insert a node at a specific position in a linked list
Circular Linked List | Set 2 (Traversal)
Program to implement Singly Linked List in C++ using class
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 24567,
"s": 24539,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 24900,
"s": 24567,
"text": "Given a Linked List which represents a sentence S such that each node represents a letter, the task is to reverse the sentence without reversing individual words. For example, for a given sentence “I love Geeks for Geeks”, the Linked List representation is given as: I-> ->l->o->v->e-> ->G->e->e->k->s-> ->f->o->r-> ->G->e->e->k->s "
},
{
"code": null,
"e": 24911,
"s": 24900,
"text": "Examples: "
},
{
"code": null,
"e": 24972,
"s": 24911,
"text": "Input: I love Geeks for Geeks Output: Geeks for Geeks love I"
},
{
"code": null,
"e": 25046,
"s": 24972,
"text": "Input: practice makes a man perfect Output: perfect man a makes practice "
},
{
"code": null,
"e": 25362,
"s": 25046,
"text": "Approach: The idea is to navigate the linked list from the beginning. Every time space is encountered, swap the space to the beginning of that word. Repeat this step until the last node is reached. Finally set the first words last letter to point null which will become the last node and keep changing the pointers."
},
{
"code": null,
"e": 25409,
"s": 25362,
"text": "Below is the implementation of the approach: "
},
{
"code": null,
"e": 25414,
"s": 25409,
"text": "Java"
},
{
"code": null,
"e": 25417,
"s": 25414,
"text": "C#"
},
{
"code": "// Linked List Implementationpublic class Node { public Node(char data, Node next) { Data = data; Next = next; } public char Data; public Node Next;}class GFG { // Function to create a linked list // from the given String private static Node CreateLinkedList(String s) { Node header = null; Node temp = null; // Generates characters from the given string for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); Node node = new Node(c, null); if (header == null) { header = node; temp = header; } else { temp.Next = node; temp = temp.Next; } } return header; } // Function to reverse the words // Assume str = \"practice makes man perfect\" // to understand proper understanding of the code private static Node Reverse(Node header) { if (header == null) return header; Node wordStartPosition = null; Node endOfSentence = null; Node sentenceStartPosition = null; // Initialize wordStartPosition to header // ie. node 'p' first letter of the word 'practice' wordStartPosition = header; // Navigate the linked list until // a space(' ') is found or header is null //(this is for handing if there is // only one word in the given sentence) while (header != null && header.Data != ' ') { // Keep track the previous node. // This will become the // last node of the linked list endOfSentence = header; // Keep moving to the next node header = header.Next; } // After the above while loop, // endOfSentence points to // the last letter 'e'of word 'practice' // header points to the space(' ') // which is next to word 'practice' // If header is null then there is only // one word in the given sentence // so set header to the // first/wordStartPosition node and return. if (header == null) { header = wordStartPosition; return header; } do { // Swapping the space ie. // convert 'practice<space>' to //'<space>practice' // store the node which is next to space(' ') // 'm' which is the first letter of the word 'make' Node temp = header.Next; header.Next = wordStartPosition; wordStartPosition = header; header = temp; Node prev = null; // Setting sentenceStartPosition to node 'm' //(first letter of the word 'make') sentenceStartPosition = header; // Again Navigate the linked list until // a space(' ') is found or // header == null end of the linked list while (header != null && header.Data != ' ') { prev = header; header = header.Next; } // When the next space is found, // change the pointer to point the previous space // ie. the word is being converted to // \"m->a->k->e->s-> ->p->r->a->c->t->i->c->e\" prev.Next = wordStartPosition; // Newly found space will point to //'m' first letter of the word 'make' wordStartPosition = sentenceStartPosition; if (header == null) break; // Repeat the loop until // the end of the linked list is reached } while (header != null); header = sentenceStartPosition; // Set the last node's next to null // ie. ->m->a->k->e->s-> ->p->r->a->->c->t->i->c->e->null endOfSentence.Next = null; return header; } // Function to print the Linked List private static void PrintList(Node Header) { Node temp = Header; // Navigate till the end and print the data in each node while (temp != null) { System.out.print(temp.Data); temp = temp.Next; } } // Driver code public static void main(String[] args) { String s = \"practice makes a man perfect\"; // Convert given string to a linked list // with character as data in each node Node header = CreateLinkedList(s); System.out.println(\"Before:\"); PrintList(header); header = Reverse(header); System.out.println(\"\\nAfter:\"); PrintList(header); }}",
"e": 30011,
"s": 25417,
"text": null
},
{
"code": "using System; // Linked List Implementationpublic class Node{ public Node(char data, Node next) { Data = data; Next = next; } public char Data; public Node Next;} class GFG{ // Function to create a linked list // from the given String private static Node CreateList(String s) { Node header = null; Node temp = null; // Generates characters from the given string for (int i = 0; i < s.Length; i++) { char c = s[i]; Node node = new Node(c, null); if (header == null) { header = node; temp = header; } else { temp.Next = node; temp = temp.Next; } } return header; } // Function to reverse the words // Assume str = \"practice makes man perfect\" // to understand proper understanding of the code private static Node Reverse(Node header) { if (header == null) return header; Node wordStartPosition = null; Node endOfSentence = null; Node sentenceStartPosition = null; // Initialize wordStartPosition to header // ie. node 'p' first letter of the word 'practice' wordStartPosition = header; // Navigate the linked list until // a space(' ') is found or header is null //(this is for handing if there is // only one word in the given sentence) while (header != null && header.Data != ' ') { // Keep track the previous node. // This will become the // last node of the linked list endOfSentence = header; // Keep moving to the next node header = header.Next; } // After the above while loop, // endOfSentence points to // the last letter 'e'of word 'practice' // header points to the space(' ') // which is next to word 'practice' // If header is null then there is only // one word in the given sentance // so set header to the // first/wordStartPosition node and return. if (header == null) { header = wordStartPosition; return header; } do { // Swapping the space ie. // convert 'practice<space>' to //'<space>practice' // store the node which is next to space(' ') // 'm' which is the first letter of the word 'make' Node temp = header.Next; header.Next = wordStartPosition; wordStartPosition = header; header = temp; Node prev = null; // Setting sentenceStartPosition to node 'm' //(first letter of the word 'make') sentenceStartPosition = header; // Again Navigate the linked list until // a space(' ') is found or // header == null end of the linked list while (header != null && header.Data != ' ') { prev = header; header = header.Next; } // When the next space is found, // change the pointer to point the previous space // ie. the word is being converted to // \"m->a->k->e->s-> ->p->r->a->c->t->i->c->e\" prev.Next = wordStartPosition; // Newly found space will point to //'m' first letter of the word 'make' wordStartPosition = sentenceStartPosition; if (header == null) break; // Repeat the loop until // the end of the linked list is reached } while (header != null); header = sentenceStartPosition; // Set the last node's next to null // ie. ->m->a->k->e->s-> ->p->r->a->->c->t->i->c->e->null endOfSentence.Next = null; return header; } // Function to print the Linked List private static void PrintList(Node Header) { Node temp = Header; // Navigate till the end and print // the data in each node while (temp != null) { Console.Write(temp.Data); temp = temp.Next; } } // Driver code public static void Main(String[] args) { String s = \"practice makes a man perfect\"; // Convert given string to a linked list // with character as data in each node Node header = CreateList(s); Console.WriteLine(\"Before:\"); PrintList(header); header = Reverse(header); Console.WriteLine(\"\\nAfter:\"); PrintList(header); }} // This code is contributed by Rajput-Ji",
"e": 34757,
"s": 30011,
"text": null
},
{
"code": null,
"e": 34830,
"s": 34757,
"text": "Before:\npractice makes a man perfect\nAfter:\nperfect man a makes practice"
},
{
"code": null,
"e": 34842,
"s": 34832,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34850,
"s": 34842,
"text": "clintra"
},
{
"code": null,
"e": 34858,
"s": 34850,
"text": "Reverse"
},
{
"code": null,
"e": 34870,
"s": 34858,
"text": "Linked List"
},
{
"code": null,
"e": 34878,
"s": 34870,
"text": "Strings"
},
{
"code": null,
"e": 34890,
"s": 34878,
"text": "Linked List"
},
{
"code": null,
"e": 34898,
"s": 34890,
"text": "Strings"
},
{
"code": null,
"e": 34906,
"s": 34898,
"text": "Reverse"
},
{
"code": null,
"e": 35004,
"s": 34906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35013,
"s": 35004,
"text": "Comments"
},
{
"code": null,
"e": 35026,
"s": 35013,
"text": "Old Comments"
},
{
"code": null,
"e": 35064,
"s": 35026,
"text": "Delete a node in a Doubly Linked List"
},
{
"code": null,
"e": 35135,
"s": 35064,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 35189,
"s": 35135,
"text": "Insert a node at a specific position in a linked list"
},
{
"code": null,
"e": 35230,
"s": 35189,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 35289,
"s": 35230,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 35314,
"s": 35289,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35360,
"s": 35314,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35394,
"s": 35360,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 35454,
"s": 35394,
"text": "Write a program to print all permutations of a given string"
}
] |
Rotate a List in Java
|
To rotate a list in Java, let us first create a List and add elements −
List < Integer > list = new ArrayList < Integer > ();
list.add(5);
list.add(10);
list.add(15);
list.add(20);
list.add(25);
list.add(30);
list.add(35);
list.add(40);
list.add(45);
Now, rotate the list −
Collections.reverse(list);
Live Demo
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
public static void main(String args[]) {
List<Integer>list = new ArrayList<Integer>();
list.add(5);
list.add(10);
list.add(15);
list.add(20);
list.add(25);
list.add(30);
list.add(35);
list.add(40);
list.add(45);
System.out.println("Initial list = "+list);
Collections.reverse(list);
System.out.println("List after rotation = "+list);
}
}
Initial list = [5, 10, 15, 20, 25, 30, 35, 40, 45]
List after rotation = [45, 40, 35, 30, 25, 20, 15, 10, 5]
|
[
{
"code": null,
"e": 1134,
"s": 1062,
"text": "To rotate a list in Java, let us first create a List and add elements −"
},
{
"code": null,
"e": 1313,
"s": 1134,
"text": "List < Integer > list = new ArrayList < Integer > ();\nlist.add(5);\nlist.add(10);\nlist.add(15);\nlist.add(20);\nlist.add(25);\nlist.add(30);\nlist.add(35);\nlist.add(40);\nlist.add(45);"
},
{
"code": null,
"e": 1336,
"s": 1313,
"text": "Now, rotate the list −"
},
{
"code": null,
"e": 1363,
"s": 1336,
"text": "Collections.reverse(list);"
},
{
"code": null,
"e": 1374,
"s": 1363,
"text": " Live Demo"
},
{
"code": null,
"e": 1897,
"s": 1374,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\npublic class Demo {\n public static void main(String args[]) {\n List<Integer>list = new ArrayList<Integer>();\n list.add(5);\n list.add(10);\n list.add(15);\n list.add(20);\n list.add(25);\n list.add(30);\n list.add(35);\n list.add(40);\n list.add(45);\n System.out.println(\"Initial list = \"+list);\n Collections.reverse(list);\n System.out.println(\"List after rotation = \"+list);\n }\n}"
},
{
"code": null,
"e": 2006,
"s": 1897,
"text": "Initial list = [5, 10, 15, 20, 25, 30, 35, 40, 45]\nList after rotation = [45, 40, 35, 30, 25, 20, 15, 10, 5]"
}
] |
Program to convert the diagonal elements of the matrix to 0
|
13 Jun, 2022
Given an N*N matrix. The task is to convert the elements of diagonal of a matrix to 0.Examples:
Input: mat[][] =
{{ 2, 1, 7 },
{ 3, 7, 2 },
{ 5, 4, 9 }}
Output:
{ {0, 1, 0},
{3, 0, 2},
{0, 4, 0}}
Input: mat[][] =
{{1, 3, 5, 6, 7},
{3, 5, 3, 2, 1},
{1, 2, 3, 4, 5},
{7, 9, 2, 1, 6},
{9, 1, 5, 3, 2}}
Output:
{{0, 3, 5, 6, 0},
{3, 0, 3, 0, 1},
{1, 2, 0, 4, 5},
{7, 0, 2, 0, 6},
{0, 1, 5, 3, 0}}
Approach: Run two loops i.e. outer loop for no. of rows and inner loop for no. of columns. Check for the below condition:
if ((i == j ) || (i + j + 1) == n) mat[i][j] = 0
Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
C
// C++ program to change value of// diagonal elements of a matrix to 0.#include <iostream>using namespace std;const int MAX = 100; // to print the resultant matrixvoid print(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) cout << mat[i][j] << " "; cout << endl; }} // function to change the values// of diagonal elements to 0void makediagonalzero(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver codeint main(){ int n = 3, m = 3; int mat[][MAX] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makediagonalzero(mat, n, m); return 0;}
// Java program to change value of// diagonal elements of a matrix to 0.class GFG{ static final int MAX = 100; // to print the resultant matrixstatic void print(int mat[][], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(mat[i][j] + " "); } System.out.println(); }} // function to change the values// of diagonal elements to 0static void makediagonalzero(int mat[][], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) { mat[i][j] = 0; } } } // print resultant matrix print(mat, n, m);} // Driver codepublic static void main(String args[]){ int n = 3, m = 3; int mat[][] = {{2, 1, 7}, {3, 7, 2}, {5, 4, 9}}; makediagonalzero(mat, n, m);}} // This code is contributed// by PrinciRaj1992
# Python 3 program to change value of# diagonal elements of a matrix to 0.MAX = 100 # to print the resultant matrixdef print_1(mat, n, m): for i in range(n): for j in range(m): print( mat[i][j], end = " ") print() # function to change the values# of diagonal elements to 0def makediagonalzero(mat, n, m): for i in range(n): for j in range(m): # right and left diagonal condition if (i == j or (i + j + 1) == n): mat[i][j] = 0 # print resultant matrix print_1(mat, n, m) # Driver codeif __name__ == "__main__": n = 3 m = 3 mat = [[ 2, 1, 7 ], [ 3, 7, 2 ], [ 5, 4, 9 ]] makediagonalzero(mat, n, m) # This code is contributed by ChitraNayal
// C# program to change value of// diagonal elements of a matrix to 0.using System; class GFG{ static int MAX = 100; // to print the resultant matrixstatic void print(int[,] mat, int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Console.Write(mat[i, j] + " "); } Console.WriteLine(); }} // function to change the values// of diagonal elements to 0static void makediagonalzero(int[,] mat, int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) { mat[i, j] = 0; } } } // print resultant matrix print(mat, n, m);} // Driver codepublic static void Main(){ int n = 3, m = 3; int[,] mat = {{2, 1, 7}, {3, 7, 2}, {5, 4, 9}}; makediagonalzero(mat, n, m);}} // This code is contributed// by Akanksha Rai
<?php// PHP program to change value of// diagonal elements of a matrix to 0. // to print the resultant matrixfunction printsd(&$mat, $n, $m){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { echo ($mat[$i][$j]); echo (" "); } echo ("\n"); }} // function to change the values// of diagonal elements to 0function makediagonalzero(&$mat, $n, $m){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { // right and left diagonal condition if ($i == $j || ($i + $j + 1) == $n) $mat[$i][$j] = 0; } } // print resultant matrix printsd($mat, $n, $m);} // Driver code$n = 3; $m = 3;$mat = array(array(2, 1, 7), array(3, 7, 2), array(5, 4, 9)); makediagonalzero($mat, $n, $m); // This code is contributed by Shivi_Aggarwal?>
<script>// Javascript program to change value of// diagonal elements of a matrix to 0. const MAX = 100; // to print the resultant matrixfunction print(mat, n, m){ for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) document.write(mat[i][j] + " "); document.write("<br>"); }} // function to change the values// of diagonal elements to 0function makediagonalzero(mat, n, m){ for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver code let n = 3, m = 3; let mat = [ [ 2, 1, 7 ], [ 3, 7, 2 ], [ 5, 4, 9 ] ]; makediagonalzero(mat, n, m); // This code is contributed by souravmahato348.</script>
// C program to change value of// diagonal elements of a matrix to 0.#include <stdio.h> #define MAX 100 // to print the resultant matrixvoid print(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) printf("%d ",mat[i][j]); printf("\n"); }} // function to change the values// of diagonal elements to 0void makediagonalzero(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver codeint main(){ int n = 3, m = 3; int mat[][MAX] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makediagonalzero(mat, n, m); return 0;}
0 1 0
3 0 2
0 4 0
C++
C
Java
Python3
C#
Javascript
// C++ program to change value of// diagonal elements of a matrix to 0.#include <bits/stdc++.h>#define COL 100using namespace std; // Method to replace the diagonal matrix with zerosvoid diagonalMat( int m[][COL] ,int row, int col){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 int i = 0, l = 0, k = col - 1; // i used to iterate over rows of the matrix while (i < row) { int j = 0; // condition to check if it is // the centre of the matrix if (l == k) { m[l][k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else { m[i][l] = 0; l++; m[i][k] = 0; k--; } // print every element after replacing from the column while (j < col) { cout << " "<< m[i][j]; j++; } i++; cout << "\n"; } } // Driver codeint main(){ int m[][COL] ={{ 2, 1, 7}, { 3, 7, 2}, { 5, 4, 9}}; int row = 3, col = 3; diagonalMat( m, row, col); return 0;} // This code has been contributed by 29AjayKumar
// C program to change value of// diagonal elements of a matrix to 0.#include <stdio.h> #define COL 100 // Method to replace the diagonal matrix with zerosvoid diagonalMat( int m[][COL] ,int row, int col){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 int i = 0, l = 0, k = col - 1; // i used to iterate over rows of the matrix while (i < row) { int j = 0; // condition to check if it is // the centre of the matrix if (l == k) { m[l][k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else { m[i][l] = 0; l++; m[i][k] = 0; k--; } // print every element after replacing from the column while (j < col) { printf(" %d",m[i][j]); j++; } i++; printf("\n"); } } // Driver codeint main(){ int m[][COL] ={{ 2, 1, 7}, { 3, 7, 2}, { 5, 4, 9}}; int row = 3, col = 3; diagonalMat( m, row, col); return 0;} // This code has been contributed by kothavvsaakash
// Java program to change value of// diagonal elements of a matrix to 0.import java.io.*; class GFG { public static void main (String[] args) { int m[][] = {{ 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 }}; int row = 3, col = 3; GFG.diagonalMat(row,col,m); } // method to replace the diagonal matrix with zeros public static void diagonalMat(int row, int col, int m[][]){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 int i =0,l=0,k=col-1; // i used to iterate over rows of the matrix while(i<row){ int j=0; // condition to check if it is // the centre of the matrix if(l==k){ m[l][k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else{ m[i][l] = 0; l++; m[i][k]=0; k--; } // print every element after replacing from the column while(j<col){ System.out.print(" "+ m[i][j]); j++; } i++; System.out.println(); } } }
# Python3 program to change value of# diagonal elements of a matrix to 0. # method to replace the diagonal# matrix with zerosdef diagonalMat(row, col, m): # l is the left iterator which is # iterationg from 0 to col-1[4] here # k is the right iterator which is # iterating from col-1 to 0 i, l, k = 0, 0, col - 1; # i used to iterate over rows of the matrix while(i < row): j = 0; # condition to check if it is # the centre of the matrix if(l == k): m[l][k] = 0; l += 1; k -= 1; # otherwise the diagonal will be equivalent to l or k # increment l because l is traversing from left # to right and decrement k for vice-cersa else: m[i][l] = 0; l += 1; m[i][k] = 0; k -= 1; # print every element # after replacing from the column while(j < col): print(" ", m[i][j], end = ""); j += 1; i += 1; print(""); # Driver Codeif __name__ == '__main__': m = [[2, 1, 7 ], [ 3, 7, 2 ], [ 5, 4, 9 ]]; row, col = 3, 3; diagonalMat(row, col, m); # This code contributed by Rajput-Ji
// C# program to change value of// diagonal elements of a matrix to 0.using System; class GFG { public static void Main () { int[,] m = {{ 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 }}; int row = 3, col = 3; GFG.diagonalMat(row,col,m); } // method to replace the diagonal matrix with zeros public static void diagonalMat(int row, int col, int[,] m){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 int i =0,l=0,k=col-1; // i used to iterate over rows of the matrix while(i < row){ int j=0; // condition to check if it is // the centre of the matrix if(l==k){ m[l,k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else{ m[i,l] = 0; l++; m[i,k]=0; k--; } // print every element after replacing from the column while(j < col){ Console.Write(" " + m[i,j]); j++; } i++; Console.WriteLine(); } } } //This code is contributed by Mukul singh
<script>// Javascript program to change value of// diagonal elements of a matrix to 0. const COL = 100; // Method to replace the diagonal matrix with zerosfunction diagonalMat(m, row, col){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 let i = 0, l = 0, k = col - 1; // i used to iterate over rows of the matrix while (i < row) { let j = 0; // condition to check if it is // the centre of the matrix if (l == k) { m[l][k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else { m[i][l] = 0; l++; m[i][k] = 0; k--; } // print every element after replacing from the column while (j < col) { document.write(" " + m[i][j]); j++; } i++; document.write("<br>"); } } // Driver code let m =[[ 2, 1, 7], [ 3, 7, 2], [ 5, 4, 9]]; let row = 3, col = 3; diagonalMat( m, row, col); </script>
0 1 0
3 0 2
0 4 0
Time complexity : O(n*m)
GautamSarkar1
ukasp
princiraj1992
Akanksha_Rai
Code_Mech
Shivi_Aggarwal
VishalBachchas
Rajput-Ji
29AjayKumar
souravmahato348
subhammahato348
kothavvsaakash
rkbhola5
surinderdawra388
Technical Scripter 2018
C++ Programs
Matrix
Technical Scripter
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 150,
"s": 52,
"text": "Given an N*N matrix. The task is to convert the elements of diagonal of a matrix to 0.Examples: "
},
{
"code": null,
"e": 467,
"s": 150,
"text": "Input: mat[][] = \n{{ 2, 1, 7 },\n { 3, 7, 2 },\n { 5, 4, 9 }}\nOutput: \n{ {0, 1, 0},\n {3, 0, 2},\n {0, 4, 0}}\n\nInput: mat[][] = \n{{1, 3, 5, 6, 7},\n {3, 5, 3, 2, 1},\n {1, 2, 3, 4, 5},\n {7, 9, 2, 1, 6},\n {9, 1, 5, 3, 2}}\nOutput: \n{{0, 3, 5, 6, 0},\n {3, 0, 3, 0, 1},\n {1, 2, 0, 4, 5},\n {7, 0, 2, 0, 6},\n {0, 1, 5, 3, 0}}"
},
{
"code": null,
"e": 592,
"s": 469,
"text": "Approach: Run two loops i.e. outer loop for no. of rows and inner loop for no. of columns. Check for the below condition: "
},
{
"code": null,
"e": 643,
"s": 592,
"text": "if ((i == j ) || (i + j + 1) == n) mat[i][j] = 0 "
},
{
"code": null,
"e": 695,
"s": 643,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 699,
"s": 695,
"text": "C++"
},
{
"code": null,
"e": 704,
"s": 699,
"text": "Java"
},
{
"code": null,
"e": 713,
"s": 704,
"text": "Python 3"
},
{
"code": null,
"e": 716,
"s": 713,
"text": "C#"
},
{
"code": null,
"e": 720,
"s": 716,
"text": "PHP"
},
{
"code": null,
"e": 731,
"s": 720,
"text": "Javascript"
},
{
"code": null,
"e": 733,
"s": 731,
"text": "C"
},
{
"code": "// C++ program to change value of// diagonal elements of a matrix to 0.#include <iostream>using namespace std;const int MAX = 100; // to print the resultant matrixvoid print(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) cout << mat[i][j] << \" \"; cout << endl; }} // function to change the values// of diagonal elements to 0void makediagonalzero(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver codeint main(){ int n = 3, m = 3; int mat[][MAX] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makediagonalzero(mat, n, m); return 0;}",
"e": 1645,
"s": 733,
"text": null
},
{
"code": "// Java program to change value of// diagonal elements of a matrix to 0.class GFG{ static final int MAX = 100; // to print the resultant matrixstatic void print(int mat[][], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(mat[i][j] + \" \"); } System.out.println(); }} // function to change the values// of diagonal elements to 0static void makediagonalzero(int mat[][], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) { mat[i][j] = 0; } } } // print resultant matrix print(mat, n, m);} // Driver codepublic static void main(String args[]){ int n = 3, m = 3; int mat[][] = {{2, 1, 7}, {3, 7, 2}, {5, 4, 9}}; makediagonalzero(mat, n, m);}} // This code is contributed// by PrinciRaj1992",
"e": 2689,
"s": 1645,
"text": null
},
{
"code": "# Python 3 program to change value of# diagonal elements of a matrix to 0.MAX = 100 # to print the resultant matrixdef print_1(mat, n, m): for i in range(n): for j in range(m): print( mat[i][j], end = \" \") print() # function to change the values# of diagonal elements to 0def makediagonalzero(mat, n, m): for i in range(n): for j in range(m): # right and left diagonal condition if (i == j or (i + j + 1) == n): mat[i][j] = 0 # print resultant matrix print_1(mat, n, m) # Driver codeif __name__ == \"__main__\": n = 3 m = 3 mat = [[ 2, 1, 7 ], [ 3, 7, 2 ], [ 5, 4, 9 ]] makediagonalzero(mat, n, m) # This code is contributed by ChitraNayal",
"e": 3451,
"s": 2689,
"text": null
},
{
"code": "// C# program to change value of// diagonal elements of a matrix to 0.using System; class GFG{ static int MAX = 100; // to print the resultant matrixstatic void print(int[,] mat, int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Console.Write(mat[i, j] + \" \"); } Console.WriteLine(); }} // function to change the values// of diagonal elements to 0static void makediagonalzero(int[,] mat, int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) { mat[i, j] = 0; } } } // print resultant matrix print(mat, n, m);} // Driver codepublic static void Main(){ int n = 3, m = 3; int[,] mat = {{2, 1, 7}, {3, 7, 2}, {5, 4, 9}}; makediagonalzero(mat, n, m);}} // This code is contributed// by Akanksha Rai",
"e": 4477,
"s": 3451,
"text": null
},
{
"code": "<?php// PHP program to change value of// diagonal elements of a matrix to 0. // to print the resultant matrixfunction printsd(&$mat, $n, $m){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { echo ($mat[$i][$j]); echo (\" \"); } echo (\"\\n\"); }} // function to change the values// of diagonal elements to 0function makediagonalzero(&$mat, $n, $m){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $m; $j++) { // right and left diagonal condition if ($i == $j || ($i + $j + 1) == $n) $mat[$i][$j] = 0; } } // print resultant matrix printsd($mat, $n, $m);} // Driver code$n = 3; $m = 3;$mat = array(array(2, 1, 7), array(3, 7, 2), array(5, 4, 9)); makediagonalzero($mat, $n, $m); // This code is contributed by Shivi_Aggarwal?>",
"e": 5367,
"s": 4477,
"text": null
},
{
"code": "<script>// Javascript program to change value of// diagonal elements of a matrix to 0. const MAX = 100; // to print the resultant matrixfunction print(mat, n, m){ for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) document.write(mat[i][j] + \" \"); document.write(\"<br>\"); }} // function to change the values// of diagonal elements to 0function makediagonalzero(mat, n, m){ for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver code let n = 3, m = 3; let mat = [ [ 2, 1, 7 ], [ 3, 7, 2 ], [ 5, 4, 9 ] ]; makediagonalzero(mat, n, m); // This code is contributed by souravmahato348.</script>",
"e": 6284,
"s": 5367,
"text": null
},
{
"code": "// C program to change value of// diagonal elements of a matrix to 0.#include <stdio.h> #define MAX 100 // to print the resultant matrixvoid print(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) printf(\"%d \",mat[i][j]); printf(\"\\n\"); }} // function to change the values// of diagonal elements to 0void makediagonalzero(int mat[][MAX], int n, int m){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // right and left diagonal condition if (i == j || (i + j + 1) == n) mat[i][j] = 0; } } // print resultant matrix print(mat, n, m);} // Driver codeint main(){ int n = 3, m = 3; int mat[][MAX] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; makediagonalzero(mat, n, m); return 0;}",
"e": 7168,
"s": 6284,
"text": null
},
{
"code": null,
"e": 7188,
"s": 7168,
"text": "0 1 0 \n3 0 2 \n0 4 0"
},
{
"code": null,
"e": 7194,
"s": 7190,
"text": "C++"
},
{
"code": null,
"e": 7196,
"s": 7194,
"text": "C"
},
{
"code": null,
"e": 7201,
"s": 7196,
"text": "Java"
},
{
"code": null,
"e": 7209,
"s": 7201,
"text": "Python3"
},
{
"code": null,
"e": 7212,
"s": 7209,
"text": "C#"
},
{
"code": null,
"e": 7223,
"s": 7212,
"text": "Javascript"
},
{
"code": "// C++ program to change value of// diagonal elements of a matrix to 0.#include <bits/stdc++.h>#define COL 100using namespace std; // Method to replace the diagonal matrix with zerosvoid diagonalMat( int m[][COL] ,int row, int col){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 int i = 0, l = 0, k = col - 1; // i used to iterate over rows of the matrix while (i < row) { int j = 0; // condition to check if it is // the centre of the matrix if (l == k) { m[l][k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else { m[i][l] = 0; l++; m[i][k] = 0; k--; } // print every element after replacing from the column while (j < col) { cout << \" \"<< m[i][j]; j++; } i++; cout << \"\\n\"; } } // Driver codeint main(){ int m[][COL] ={{ 2, 1, 7}, { 3, 7, 2}, { 5, 4, 9}}; int row = 3, col = 3; diagonalMat( m, row, col); return 0;} // This code has been contributed by 29AjayKumar",
"e": 8629,
"s": 7223,
"text": null
},
{
"code": "// C program to change value of// diagonal elements of a matrix to 0.#include <stdio.h> #define COL 100 // Method to replace the diagonal matrix with zerosvoid diagonalMat( int m[][COL] ,int row, int col){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 int i = 0, l = 0, k = col - 1; // i used to iterate over rows of the matrix while (i < row) { int j = 0; // condition to check if it is // the centre of the matrix if (l == k) { m[l][k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else { m[i][l] = 0; l++; m[i][k] = 0; k--; } // print every element after replacing from the column while (j < col) { printf(\" %d\",m[i][j]); j++; } i++; printf(\"\\n\"); } } // Driver codeint main(){ int m[][COL] ={{ 2, 1, 7}, { 3, 7, 2}, { 5, 4, 9}}; int row = 3, col = 3; diagonalMat( m, row, col); return 0;} // This code has been contributed by kothavvsaakash",
"e": 10011,
"s": 8629,
"text": null
},
{
"code": "// Java program to change value of// diagonal elements of a matrix to 0.import java.io.*; class GFG { public static void main (String[] args) { int m[][] = {{ 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 }}; int row = 3, col = 3; GFG.diagonalMat(row,col,m); } // method to replace the diagonal matrix with zeros public static void diagonalMat(int row, int col, int m[][]){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 int i =0,l=0,k=col-1; // i used to iterate over rows of the matrix while(i<row){ int j=0; // condition to check if it is // the centre of the matrix if(l==k){ m[l][k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else{ m[i][l] = 0; l++; m[i][k]=0; k--; } // print every element after replacing from the column while(j<col){ System.out.print(\" \"+ m[i][j]); j++; } i++; System.out.println(); } } }",
"e": 11478,
"s": 10011,
"text": null
},
{
"code": "# Python3 program to change value of# diagonal elements of a matrix to 0. # method to replace the diagonal# matrix with zerosdef diagonalMat(row, col, m): # l is the left iterator which is # iterationg from 0 to col-1[4] here # k is the right iterator which is # iterating from col-1 to 0 i, l, k = 0, 0, col - 1; # i used to iterate over rows of the matrix while(i < row): j = 0; # condition to check if it is # the centre of the matrix if(l == k): m[l][k] = 0; l += 1; k -= 1; # otherwise the diagonal will be equivalent to l or k # increment l because l is traversing from left # to right and decrement k for vice-cersa else: m[i][l] = 0; l += 1; m[i][k] = 0; k -= 1; # print every element # after replacing from the column while(j < col): print(\" \", m[i][j], end = \"\"); j += 1; i += 1; print(\"\"); # Driver Codeif __name__ == '__main__': m = [[2, 1, 7 ], [ 3, 7, 2 ], [ 5, 4, 9 ]]; row, col = 3, 3; diagonalMat(row, col, m); # This code contributed by Rajput-Ji",
"e": 12718,
"s": 11478,
"text": null
},
{
"code": "// C# program to change value of// diagonal elements of a matrix to 0.using System; class GFG { public static void Main () { int[,] m = {{ 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 }}; int row = 3, col = 3; GFG.diagonalMat(row,col,m); } // method to replace the diagonal matrix with zeros public static void diagonalMat(int row, int col, int[,] m){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 int i =0,l=0,k=col-1; // i used to iterate over rows of the matrix while(i < row){ int j=0; // condition to check if it is // the centre of the matrix if(l==k){ m[l,k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else{ m[i,l] = 0; l++; m[i,k]=0; k--; } // print every element after replacing from the column while(j < col){ Console.Write(\" \" + m[i,j]); j++; } i++; Console.WriteLine(); } } } //This code is contributed by Mukul singh",
"e": 14209,
"s": 12718,
"text": null
},
{
"code": "<script>// Javascript program to change value of// diagonal elements of a matrix to 0. const COL = 100; // Method to replace the diagonal matrix with zerosfunction diagonalMat(m, row, col){ // l is the left iterator which is // iterationg from 0 to col-1[4] here //k is the right iterator which is // iterating from col-1 to 0 let i = 0, l = 0, k = col - 1; // i used to iterate over rows of the matrix while (i < row) { let j = 0; // condition to check if it is // the centre of the matrix if (l == k) { m[l][k] = 0; l++; k--; } //otherwise the diagonal will be equivalent to l or k //increment l because l is traversing from left //to right and decrement k for vice-cersa else { m[i][l] = 0; l++; m[i][k] = 0; k--; } // print every element after replacing from the column while (j < col) { document.write(\" \" + m[i][j]); j++; } i++; document.write(\"<br>\"); } } // Driver code let m =[[ 2, 1, 7], [ 3, 7, 2], [ 5, 4, 9]]; let row = 3, col = 3; diagonalMat( m, row, col); </script>",
"e": 15519,
"s": 14209,
"text": null
},
{
"code": null,
"e": 15540,
"s": 15519,
"text": " 0 1 0\n 3 0 2\n 0 4 0"
},
{
"code": null,
"e": 15568,
"s": 15542,
"text": "Time complexity : O(n*m) "
},
{
"code": null,
"e": 15582,
"s": 15568,
"text": "GautamSarkar1"
},
{
"code": null,
"e": 15588,
"s": 15582,
"text": "ukasp"
},
{
"code": null,
"e": 15602,
"s": 15588,
"text": "princiraj1992"
},
{
"code": null,
"e": 15615,
"s": 15602,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 15625,
"s": 15615,
"text": "Code_Mech"
},
{
"code": null,
"e": 15640,
"s": 15625,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 15655,
"s": 15640,
"text": "VishalBachchas"
},
{
"code": null,
"e": 15665,
"s": 15655,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 15677,
"s": 15665,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15693,
"s": 15677,
"text": "souravmahato348"
},
{
"code": null,
"e": 15709,
"s": 15693,
"text": "subhammahato348"
},
{
"code": null,
"e": 15724,
"s": 15709,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 15733,
"s": 15724,
"text": "rkbhola5"
},
{
"code": null,
"e": 15750,
"s": 15733,
"text": "surinderdawra388"
},
{
"code": null,
"e": 15774,
"s": 15750,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 15787,
"s": 15774,
"text": "C++ Programs"
},
{
"code": null,
"e": 15794,
"s": 15787,
"text": "Matrix"
},
{
"code": null,
"e": 15813,
"s": 15794,
"text": "Technical Scripter"
},
{
"code": null,
"e": 15820,
"s": 15813,
"text": "Matrix"
}
] |
Python – Matrix multiplication using Pytorch
|
22 Jan, 2021
The matrix multiplication is an integral part of scientific computing. It becomes complicated when the size of the matrix is huge. One of the ways to easily compute the product of two matrices is to use methods provided by PyTorch. This article covers how to perform matrix multiplication using PyTorch.
PyTorch and tensors:
It is a package that can be used for neural network-based deep learning projects. It is an open-source library developed by Facebook’s AI research team. It can replace NumPy with its power of GPU. One of the important classes provided by this library is Tensor. It is nothing but the n-dimensional arrays as provided by the NumPy package. There are so many methods in PyTorch that can be applied to Tensor, which makes computations faster and easy. The Tensor can hold only elements of the same data type.
Matrix multiplication with PyTorch:
The methods in PyTorch expect the inputs to be a Tensor and the ones available with PyTorch and Tensor for matrix multiplication are:
torch.mm().torch.matmul().torch.bmm()@ operator.
torch.mm().
torch.matmul().
torch.bmm()
@ operator.
This method computes matrix multiplication by taking an m×n Tensor and an n×p Tensor. It can deal with only two-dimensional matrices and not with single-dimensional ones. This function does not support broadcasting. Broadcasting is nothing but the way the Tensors are treated when their shapes are different. The smaller Tensor is broadcasted to suit the shape of the wider or larger Tensor for operations. The syntax of the function is given below.
torch.mm(Tensor_1, Tensor_2, out=None)
The parameters are two Tensors and the third one is an optional argument. Another Tensor to hold the output values can be given there.
Example-1: Matrices of the same dimension
Here both the inputs are of same dimensions. Thus, the output will also be of the same dimension.
Python3
import torch as t mat_1 = torch.tensor([[1, 2, 3], [4, 3, 8], [1, 7, 2]]) mat_2 = torch.tensor([[2, 4, 1], [1, 3, 6], [2, 6, 5]]) torch.mm(mat_1, mat_2, out=None)
Output:
tensor([[10, 28, 28],
[27, 73, 62],
[13, 37, 53]])
Example2: Matrices of a different dimension
Here tensor_1 is of 2×2 dimension, tensor_2 is of 2×3 dimension. So the output will be of 2×3.
Python3
import torch as t mat_1 = torch.tensor([[1, 2], [4, 3]]) mat_2 = torch.tensor([[2, 4, 1], [1, 3, 6]]) torch.mm(mat_1, mat_2, out=None)
Output:
tensor([[1.4013e-45, 0.0000e+00, 2.8026e-45],
[0.0000e+00, 5.6052e-45, 0.0000e+00]])
This method allows the computation of multiplication of two vector matrices (single-dimensional matrices), 2D matrices and mixed ones also. This method also supports broadcasting and batch operations. Depending upon the input matrices dimensions, the operation to be done is decided. The general syntax is given below.
torch.matmul(Tensor_1, Tensor_2, out=None)
The table below lists the various possible dimensions of the arguments and the operations based on it.
argument_1
argument_2
Action taken
Example1: Arguments of the same dimension
Python3
import torch as t # both arguments 1Dvec_1 = torch.tensor([3, 6, 2])vec_2 = torch.tensor([4, 1, 9]) print("Single dimensional tensors :", torch.matmul(vec_1, vec_2)) # both arguments 2Dmat_1 = torch.tensor([[1, 2, 3], [4, 3, 8], [1, 7, 2]]) mat_2 = torch.tensor([[2, 4, 1], [1, 3, 6], [2, 6, 5]]) out = torch.matmul(mat_1, mat_2) print("\n3x3 dimensional tensors :\n", out)
Output:
Single dimensional tensors : tensor(36)
3x3 dimensional tensors :
tensor([[10, 28, 28],
[27, 73, 62],
[13, 37, 53]])
Example2: Arguments of different dimensions
Python3
import torch # first argument 1D and second argument 2Dmat1_1 = torch.tensor([3, 6, 2]) mat1_2 = torch.tensor([[1, 2, 3], [4, 3, 8], [1, 7, 2]]) out_1 = torch.matmul(mat1_1, mat1_2)print("\n1D-2D multiplication :\n", out_1) # first argument 2D and second argument 1Dmat2_1 = torch.tensor([[2, 4, 1], [1, 3, 6], [2, 6, 5]]) mat2_2 = torch.tensor([4, 1, 9]) # assigning to output tensorout_2 = torch.matmul(mat2_1, mat2_2) print("\n2D-1D multiplication :\n", out_2)
Output:
1D-2D multiplication :
tensor([29, 38, 61])
2D-1D multiplication :
tensor([21, 61, 59])
Example3: N-dimensional argument (N>2)
Python3
import torch # creating Tensors using randn()mat_1 = torch.randn(2, 3, 3)mat_2 = torch.randn(3) # printing the matricesprint("matrix A :\n", mat_1)print("\nmatrix B :\n", mat_2) # outputprint("\nOutput :\n", torch.matmul(mat_1, mat_2))
Output:
matrix A :
tensor([[[ 0.5433, 0.0546, -0.5301],
[ 0.9275, -0.0420, -1.3966],
[-1.1851, -0.2918, -0.7161]],
[[-0.8659, 1.8350, 1.6068],
[-1.1046, 1.0045, -0.1193],
[ 0.9070, 0.7325, -0.4547]]])
matrix B :
tensor([ 1.8785, -0.4231, 0.1606])
Output :
tensor([[ 0.9124, 1.5358, -2.2177],
[-2.1448, -2.5191, 1.3208]])
This method provides batched matrix multiplication for the cases where both the matrices to be multiplied are of only 3-Dimensions (x×y×z) and the first dimension (x) of both the matrices must be same. This does not support broadcasting. The syntax is as given below.
torch.bmm( Tensor_1, Tensor_2, deterministic=false, out=None)
The “deterministic” parameter takes up boolean value. A ‘false‘ does a faster calculation which is non-deterministic. A ‘true‘ does a slower calculation however, it is deterministic.
Example:
In the example below, the matrix_1 is of dimension 2×3×3. The second matrix is of dimension 2×3×4.
Python3
import torch # 3D matricesmat_1 = torch.randn(2, 3, 3)mat_2 = torch.randn(2, 3, 4) print("matrix A :\n",mat_1)print("\nmatrix B :\n",mat_2) print("\nOutput :\n",torch.bmm(mat_1,mat_2))
Output:
matrix A :
tensor([[[-0.0135, -0.9197, -0.3395],
[-1.0369, -1.3242, 1.4799],
[-0.0182, -1.2917, 0.6575]],
[[-0.3585, -0.0478, 0.4674],
[-0.6688, -0.9217, -1.2612],
[ 1.6323, -0.0640, 0.4357]]])
matrix B :
tensor([[[ 0.2431, -0.1044, -0.1437, -1.4982],
[-1.4318, -0.2510, 1.6247, 0.5623],
[ 1.5265, -0.8568, -2.1125, -0.9463]],
[[ 0.0182, 0.5207, 1.2890, -1.3232],
[-0.2275, -0.8006, -0.6909, -1.0108],
[ 1.3881, -0.0327, -1.4890, -0.5550]]])
Output :
tensor([[[ 0.7954, 0.5231, -0.7752, -0.1756],
[ 3.9031, -0.8274, -5.1288, -0.5915],
[ 2.8488, -0.2372, -3.4850, -1.3212]],
[[ 0.6532, -0.1637, -1.1251, 0.2633],
[-1.5532, 0.4309, 1.6527, 2.5167],
[ 0.6492, 0.8870, 1.4994, -2.3371]]])
** Note: the matrices vary for each run as random values are filled dynamically.
The @ – Simon H operator, when applied on matrices performs multiplication element-wise on 1D matrices and normal matrix multiplication on 2D matrices. If both the matrices have the same dimension, then the matrix multiplication is carried out normally without any broadcasting/prepending. If any one of the matrices is of a different dimension, then appropriate broadcasting is carried out first and then the multiplication is carried out. This operator applies to N-Dimensional matrices also.
Example:
Python3
# single dimensional matricesoneD_1 = torch.tensor([3, 6, 2])oneD_2 = torch.tensor([4, 1, 9]) # two dimensional matricestwoD_1 = torch.tensor([[1, 2, 3], [4, 3, 8], [1, 7, 2]])twoD_2 = torch.tensor([[2, 4, 1], [1, 3, 6], [2, 6, 5]]) # N-dimensional matrices (N>2) # 2x3x3 dimensional matrixND_1 = torch.tensor([[[-0.0135, -0.9197, -0.3395], [-1.0369, -1.3242, 1.4799], [-0.0182, -1.2917, 0.6575]], [[-0.3585, -0.0478, 0.4674], [-0.6688, -0.9217, -1.2612], [1.6323, -0.0640, 0.4357]]]) # 2x3x4 dimensional matrixND_2 = torch.tensor([[[0.2431, -0.1044, -0.1437, -1.4982], [-1.4318, -0.2510, 1.6247, 0.5623], [1.5265, -0.8568, -2.1125, -0.9463]], [[0.0182, 0.5207, 1.2890, -1.3232], [-0.2275, -0.8006, -0.6909, -1.0108], [1.3881, -0.0327, -1.4890, -0.5550]]]) print("1D matrices output :\n", oneD_1 @ oneD_2)print("\n2D matrices output :\n", twoD_1 @ twoD_2)print("\nN-D matrices output :\n", ND_1 @ ND_2)print("\n Mixed matrices output :\n", oneD_1 @ twoD_1 @ twoD_2)
Output:
1D matrices output :
tensor(36)
2D matrices output :
tensor([[10, 28, 28],
[27, 73, 62],
[13, 37, 53]])
N-D matrices output :
tensor([[[ 0.7953, 0.5231, -0.7751, -0.1757],
[ 3.9030, -0.8274, -5.1287, -0.5915],
[ 2.8487, -0.2372, -3.4850, -1.3212]],
[[ 0.6531, -0.1637, -1.1250, 0.2633],
[-1.5532, 0.4309, 1.6526, 2.5166],
[ 0.6491, 0.8869, 1.4995, -2.3370]]])
Mixed matrices output:
tensor([218, 596, 562])
Picked
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "The matrix multiplication is an integral part of scientific computing. It becomes complicated when the size of the matrix is huge. One of the ways to easily compute the product of two matrices is to use methods provided by PyTorch. This article covers how to perform matrix multiplication using PyTorch."
},
{
"code": null,
"e": 354,
"s": 333,
"text": "PyTorch and tensors:"
},
{
"code": null,
"e": 860,
"s": 354,
"text": "It is a package that can be used for neural network-based deep learning projects. It is an open-source library developed by Facebook’s AI research team. It can replace NumPy with its power of GPU. One of the important classes provided by this library is Tensor. It is nothing but the n-dimensional arrays as provided by the NumPy package. There are so many methods in PyTorch that can be applied to Tensor, which makes computations faster and easy. The Tensor can hold only elements of the same data type."
},
{
"code": null,
"e": 896,
"s": 860,
"text": "Matrix multiplication with PyTorch:"
},
{
"code": null,
"e": 1030,
"s": 896,
"text": "The methods in PyTorch expect the inputs to be a Tensor and the ones available with PyTorch and Tensor for matrix multiplication are:"
},
{
"code": null,
"e": 1079,
"s": 1030,
"text": "torch.mm().torch.matmul().torch.bmm()@ operator."
},
{
"code": null,
"e": 1091,
"s": 1079,
"text": "torch.mm()."
},
{
"code": null,
"e": 1107,
"s": 1091,
"text": "torch.matmul()."
},
{
"code": null,
"e": 1119,
"s": 1107,
"text": "torch.bmm()"
},
{
"code": null,
"e": 1131,
"s": 1119,
"text": "@ operator."
},
{
"code": null,
"e": 1582,
"s": 1131,
"text": "This method computes matrix multiplication by taking an m×n Tensor and an n×p Tensor. It can deal with only two-dimensional matrices and not with single-dimensional ones. This function does not support broadcasting. Broadcasting is nothing but the way the Tensors are treated when their shapes are different. The smaller Tensor is broadcasted to suit the shape of the wider or larger Tensor for operations. The syntax of the function is given below. "
},
{
"code": null,
"e": 1621,
"s": 1582,
"text": "torch.mm(Tensor_1, Tensor_2, out=None)"
},
{
"code": null,
"e": 1756,
"s": 1621,
"text": "The parameters are two Tensors and the third one is an optional argument. Another Tensor to hold the output values can be given there."
},
{
"code": null,
"e": 1798,
"s": 1756,
"text": "Example-1: Matrices of the same dimension"
},
{
"code": null,
"e": 1896,
"s": 1798,
"text": "Here both the inputs are of same dimensions. Thus, the output will also be of the same dimension."
},
{
"code": null,
"e": 1904,
"s": 1896,
"text": "Python3"
},
{
"code": "import torch as t mat_1 = torch.tensor([[1, 2, 3], [4, 3, 8], [1, 7, 2]]) mat_2 = torch.tensor([[2, 4, 1], [1, 3, 6], [2, 6, 5]]) torch.mm(mat_1, mat_2, out=None)",
"e": 2154,
"s": 1904,
"text": null
},
{
"code": null,
"e": 2162,
"s": 2154,
"text": "Output:"
},
{
"code": null,
"e": 2229,
"s": 2162,
"text": "tensor([[10, 28, 28],\n [27, 73, 62],\n [13, 37, 53]])"
},
{
"code": null,
"e": 2273,
"s": 2229,
"text": "Example2: Matrices of a different dimension"
},
{
"code": null,
"e": 2368,
"s": 2273,
"text": "Here tensor_1 is of 2×2 dimension, tensor_2 is of 2×3 dimension. So the output will be of 2×3."
},
{
"code": null,
"e": 2376,
"s": 2368,
"text": "Python3"
},
{
"code": "import torch as t mat_1 = torch.tensor([[1, 2], [4, 3]]) mat_2 = torch.tensor([[2, 4, 1], [1, 3, 6]]) torch.mm(mat_1, mat_2, out=None)",
"e": 2556,
"s": 2376,
"text": null
},
{
"code": null,
"e": 2564,
"s": 2556,
"text": "Output:"
},
{
"code": null,
"e": 2657,
"s": 2564,
"text": "tensor([[1.4013e-45, 0.0000e+00, 2.8026e-45],\n [0.0000e+00, 5.6052e-45, 0.0000e+00]])"
},
{
"code": null,
"e": 2976,
"s": 2657,
"text": "This method allows the computation of multiplication of two vector matrices (single-dimensional matrices), 2D matrices and mixed ones also. This method also supports broadcasting and batch operations. Depending upon the input matrices dimensions, the operation to be done is decided. The general syntax is given below."
},
{
"code": null,
"e": 3019,
"s": 2976,
"text": "torch.matmul(Tensor_1, Tensor_2, out=None)"
},
{
"code": null,
"e": 3122,
"s": 3019,
"text": "The table below lists the various possible dimensions of the arguments and the operations based on it."
},
{
"code": null,
"e": 3161,
"s": 3122,
"text": " argument_1 "
},
{
"code": null,
"e": 3201,
"s": 3161,
"text": " argument_2 "
},
{
"code": null,
"e": 3290,
"s": 3201,
"text": " Action taken "
},
{
"code": null,
"e": 3332,
"s": 3290,
"text": "Example1: Arguments of the same dimension"
},
{
"code": null,
"e": 3340,
"s": 3332,
"text": "Python3"
},
{
"code": "import torch as t # both arguments 1Dvec_1 = torch.tensor([3, 6, 2])vec_2 = torch.tensor([4, 1, 9]) print(\"Single dimensional tensors :\", torch.matmul(vec_1, vec_2)) # both arguments 2Dmat_1 = torch.tensor([[1, 2, 3], [4, 3, 8], [1, 7, 2]]) mat_2 = torch.tensor([[2, 4, 1], [1, 3, 6], [2, 6, 5]]) out = torch.matmul(mat_1, mat_2) print(\"\\n3x3 dimensional tensors :\\n\", out)",
"e": 3804,
"s": 3340,
"text": null
},
{
"code": null,
"e": 3812,
"s": 3804,
"text": "Output:"
},
{
"code": null,
"e": 3947,
"s": 3812,
"text": "Single dimensional tensors : tensor(36)\n\n3x3 dimensional tensors :\n tensor([[10, 28, 28],\n [27, 73, 62],\n [13, 37, 53]])"
},
{
"code": null,
"e": 3991,
"s": 3947,
"text": "Example2: Arguments of different dimensions"
},
{
"code": null,
"e": 3999,
"s": 3991,
"text": "Python3"
},
{
"code": "import torch # first argument 1D and second argument 2Dmat1_1 = torch.tensor([3, 6, 2]) mat1_2 = torch.tensor([[1, 2, 3], [4, 3, 8], [1, 7, 2]]) out_1 = torch.matmul(mat1_1, mat1_2)print(\"\\n1D-2D multiplication :\\n\", out_1) # first argument 2D and second argument 1Dmat2_1 = torch.tensor([[2, 4, 1], [1, 3, 6], [2, 6, 5]]) mat2_2 = torch.tensor([4, 1, 9]) # assigning to output tensorout_2 = torch.matmul(mat2_1, mat2_2) print(\"\\n2D-1D multiplication :\\n\", out_2)",
"e": 4558,
"s": 3999,
"text": null
},
{
"code": null,
"e": 4566,
"s": 4558,
"text": "Output:"
},
{
"code": null,
"e": 4657,
"s": 4566,
"text": "1D-2D multiplication :\n tensor([29, 38, 61])\n\n2D-1D multiplication :\n tensor([21, 61, 59])"
},
{
"code": null,
"e": 4697,
"s": 4657,
"text": "Example3: N-dimensional argument (N>2)"
},
{
"code": null,
"e": 4705,
"s": 4697,
"text": "Python3"
},
{
"code": "import torch # creating Tensors using randn()mat_1 = torch.randn(2, 3, 3)mat_2 = torch.randn(3) # printing the matricesprint(\"matrix A :\\n\", mat_1)print(\"\\nmatrix B :\\n\", mat_2) # outputprint(\"\\nOutput :\\n\", torch.matmul(mat_1, mat_2))",
"e": 4944,
"s": 4705,
"text": null
},
{
"code": null,
"e": 4952,
"s": 4944,
"text": "Output:"
},
{
"code": null,
"e": 5331,
"s": 4952,
"text": "matrix A :\n tensor([[[ 0.5433, 0.0546, -0.5301],\n [ 0.9275, -0.0420, -1.3966],\n [-1.1851, -0.2918, -0.7161]],\n\n [[-0.8659, 1.8350, 1.6068],\n [-1.1046, 1.0045, -0.1193],\n [ 0.9070, 0.7325, -0.4547]]])\n\nmatrix B :\n tensor([ 1.8785, -0.4231, 0.1606])\n\nOutput :\n tensor([[ 0.9124, 1.5358, -2.2177],\n [-2.1448, -2.5191, 1.3208]])"
},
{
"code": null,
"e": 5599,
"s": 5331,
"text": "This method provides batched matrix multiplication for the cases where both the matrices to be multiplied are of only 3-Dimensions (x×y×z) and the first dimension (x) of both the matrices must be same. This does not support broadcasting. The syntax is as given below."
},
{
"code": null,
"e": 5661,
"s": 5599,
"text": "torch.bmm( Tensor_1, Tensor_2, deterministic=false, out=None)"
},
{
"code": null,
"e": 5844,
"s": 5661,
"text": "The “deterministic” parameter takes up boolean value. A ‘false‘ does a faster calculation which is non-deterministic. A ‘true‘ does a slower calculation however, it is deterministic."
},
{
"code": null,
"e": 5853,
"s": 5844,
"text": "Example:"
},
{
"code": null,
"e": 5952,
"s": 5853,
"text": "In the example below, the matrix_1 is of dimension 2×3×3. The second matrix is of dimension 2×3×4."
},
{
"code": null,
"e": 5960,
"s": 5952,
"text": "Python3"
},
{
"code": "import torch # 3D matricesmat_1 = torch.randn(2, 3, 3)mat_2 = torch.randn(2, 3, 4) print(\"matrix A :\\n\",mat_1)print(\"\\nmatrix B :\\n\",mat_2) print(\"\\nOutput :\\n\",torch.bmm(mat_1,mat_2))",
"e": 6148,
"s": 5960,
"text": null
},
{
"code": null,
"e": 6156,
"s": 6148,
"text": "Output:"
},
{
"code": null,
"e": 6996,
"s": 6156,
"text": "matrix A :\n tensor([[[-0.0135, -0.9197, -0.3395],\n [-1.0369, -1.3242, 1.4799],\n [-0.0182, -1.2917, 0.6575]],\n\n [[-0.3585, -0.0478, 0.4674],\n [-0.6688, -0.9217, -1.2612],\n [ 1.6323, -0.0640, 0.4357]]])\n\nmatrix B :\n tensor([[[ 0.2431, -0.1044, -0.1437, -1.4982],\n [-1.4318, -0.2510, 1.6247, 0.5623],\n [ 1.5265, -0.8568, -2.1125, -0.9463]],\n\n [[ 0.0182, 0.5207, 1.2890, -1.3232],\n [-0.2275, -0.8006, -0.6909, -1.0108],\n [ 1.3881, -0.0327, -1.4890, -0.5550]]])\n\nOutput :\n tensor([[[ 0.7954, 0.5231, -0.7752, -0.1756],\n [ 3.9031, -0.8274, -5.1288, -0.5915],\n [ 2.8488, -0.2372, -3.4850, -1.3212]],\n\n [[ 0.6532, -0.1637, -1.1251, 0.2633],\n [-1.5532, 0.4309, 1.6527, 2.5167],\n [ 0.6492, 0.8870, 1.4994, -2.3371]]])"
},
{
"code": null,
"e": 7077,
"s": 6996,
"text": "** Note: the matrices vary for each run as random values are filled dynamically."
},
{
"code": null,
"e": 7573,
"s": 7077,
"text": "The @ – Simon H operator, when applied on matrices performs multiplication element-wise on 1D matrices and normal matrix multiplication on 2D matrices. If both the matrices have the same dimension, then the matrix multiplication is carried out normally without any broadcasting/prepending. If any one of the matrices is of a different dimension, then appropriate broadcasting is carried out first and then the multiplication is carried out. This operator applies to N-Dimensional matrices also."
},
{
"code": null,
"e": 7582,
"s": 7573,
"text": "Example:"
},
{
"code": null,
"e": 7590,
"s": 7582,
"text": "Python3"
},
{
"code": "# single dimensional matricesoneD_1 = torch.tensor([3, 6, 2])oneD_2 = torch.tensor([4, 1, 9]) # two dimensional matricestwoD_1 = torch.tensor([[1, 2, 3], [4, 3, 8], [1, 7, 2]])twoD_2 = torch.tensor([[2, 4, 1], [1, 3, 6], [2, 6, 5]]) # N-dimensional matrices (N>2) # 2x3x3 dimensional matrixND_1 = torch.tensor([[[-0.0135, -0.9197, -0.3395], [-1.0369, -1.3242, 1.4799], [-0.0182, -1.2917, 0.6575]], [[-0.3585, -0.0478, 0.4674], [-0.6688, -0.9217, -1.2612], [1.6323, -0.0640, 0.4357]]]) # 2x3x4 dimensional matrixND_2 = torch.tensor([[[0.2431, -0.1044, -0.1437, -1.4982], [-1.4318, -0.2510, 1.6247, 0.5623], [1.5265, -0.8568, -2.1125, -0.9463]], [[0.0182, 0.5207, 1.2890, -1.3232], [-0.2275, -0.8006, -0.6909, -1.0108], [1.3881, -0.0327, -1.4890, -0.5550]]]) print(\"1D matrices output :\\n\", oneD_1 @ oneD_2)print(\"\\n2D matrices output :\\n\", twoD_1 @ twoD_2)print(\"\\nN-D matrices output :\\n\", ND_1 @ ND_2)print(\"\\n Mixed matrices output :\\n\", oneD_1 @ twoD_1 @ twoD_2)",
"e": 8871,
"s": 7590,
"text": null
},
{
"code": null,
"e": 8879,
"s": 8871,
"text": "Output:"
},
{
"code": null,
"e": 9362,
"s": 8879,
"text": "1D matrices output :\n tensor(36)\n\n2D matrices output :\n tensor([[10, 28, 28],\n [27, 73, 62],\n [13, 37, 53]])\n\nN-D matrices output :\n tensor([[[ 0.7953, 0.5231, -0.7751, -0.1757],\n [ 3.9030, -0.8274, -5.1287, -0.5915],\n [ 2.8487, -0.2372, -3.4850, -1.3212]],\n\n [[ 0.6531, -0.1637, -1.1250, 0.2633],\n [-1.5532, 0.4309, 1.6526, 2.5166],\n [ 0.6491, 0.8869, 1.4995, -2.3370]]])\n\n Mixed matrices output:\n tensor([218, 596, 562])"
},
{
"code": null,
"e": 9369,
"s": 9362,
"text": "Picked"
},
{
"code": null,
"e": 9384,
"s": 9369,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 9391,
"s": 9384,
"text": "Python"
}
] |
Operating Systems | Set 4
|
27 Mar, 2017
Following questions have been asked in GATE CS exam.
1. Using a larger block size in a fixed block size file system leads to (GATE CS 2003)a) better disk throughput but poorer disk space utilizationb) better disk throughput and better disk space utilizationc) poorer disk throughput but better disk space utilizationd) poorer disk throughput and poorer disk space utilization
Answer (a)If block size is large then seek time is less (fewer blocks to seek) and disk performance is improved, but remember larger block size also causes waste of disk space.
2. Consider the following statements with respect to user-level threads and kernel supported threadsi. context switch is faster with kernel-supported threadsii. for user-level threads, a system call can block the entire processiii. Kernel supported threads can be scheduled independentlyiv. User level threads are transparent to the kernel
Which of the above statements are true? (GATE CS 2004)a) (ii), (iii) and (iv) onlyb) (ii) and (iii) onlyc) (i) and (iii) onlyd) (i) and (ii) only
Answer(a)
http://en.wikipedia.org/wiki/Thread_%28computer_science%29
3. The minimum number of page frames that must be allocated to a running process in a virtual memory environment is determined by (GATE CS 2004)a) the instruction set architectureb) page sizec) physical memory sized) number of processes in memory
Answer (a)Each process needs minimum number of pages based on instruction set architecture. Example IBM 370: 6 pages to handle MVC (storage to storage move) instructionInstruction is 6 bytes, might span 2 pages.2 pages to handle from.2 pages to handle to.
4. In a system with 32 bit virtual addresses and 1 KB page size, use of one-level page tables for virtual to physical address translation is not practical because of (GATE CS 2003)a) the large amount of internal fragmentationb) the large amount of external fragmentationc) the large memory overhead in maintaining page tablesd) the large computation overhead in the translation process
Answer (c)Since page size is too small it will make size of page tables huge.
Size of page table =
(total number of page table entries) *(size of a page table entry)
Let us see how many entries are there in page table
Number of entries in page table =
(virtual address space size)/(page size)
= (2^32)/(2^10)
= 2^22
Now, let us see how big each entry is.
If size of physical memory is 512 MB then number of bits required to address a byte in 512 MB is 29. So, there will be (512MB)/(1KB) = (2^29)/(2^10) page frames in physical memory. To address a page frame 19 bits are required. Therefore, each entry in page table is required to have 19 bits.
Note that page table entry also holds auxiliary information about the page such
as a present bit, a dirty or modified bit, address space or process ID information,
amongst others. So size of page table
> (total number of page table entries) *(size of a page table entry)
> (2^22 *19) bytes
> 9.5 MB
And this much memory is required for each process because each process maintains its own page table. Also, size of page table will be more for physical memory more than 512MB. Therefore, it is advised to use multilevel page table for such scenarios.
References:http://barbara.stattenfield.org/ta/cs162/section-notes/sec8.txthttp://en.wikipedia.org/wiki/Page_table
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
GATE CS
MCQ
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Mar, 2017"
},
{
"code": null,
"e": 107,
"s": 54,
"text": "Following questions have been asked in GATE CS exam."
},
{
"code": null,
"e": 430,
"s": 107,
"text": "1. Using a larger block size in a fixed block size file system leads to (GATE CS 2003)a) better disk throughput but poorer disk space utilizationb) better disk throughput and better disk space utilizationc) poorer disk throughput but better disk space utilizationd) poorer disk throughput and poorer disk space utilization"
},
{
"code": null,
"e": 607,
"s": 430,
"text": "Answer (a)If block size is large then seek time is less (fewer blocks to seek) and disk performance is improved, but remember larger block size also causes waste of disk space."
},
{
"code": null,
"e": 947,
"s": 607,
"text": "2. Consider the following statements with respect to user-level threads and kernel supported threadsi. context switch is faster with kernel-supported threadsii. for user-level threads, a system call can block the entire processiii. Kernel supported threads can be scheduled independentlyiv. User level threads are transparent to the kernel"
},
{
"code": null,
"e": 1093,
"s": 947,
"text": "Which of the above statements are true? (GATE CS 2004)a) (ii), (iii) and (iv) onlyb) (ii) and (iii) onlyc) (i) and (iii) onlyd) (i) and (ii) only"
},
{
"code": null,
"e": 1103,
"s": 1093,
"text": "Answer(a)"
},
{
"code": null,
"e": 1162,
"s": 1103,
"text": "http://en.wikipedia.org/wiki/Thread_%28computer_science%29"
},
{
"code": null,
"e": 1409,
"s": 1162,
"text": "3. The minimum number of page frames that must be allocated to a running process in a virtual memory environment is determined by (GATE CS 2004)a) the instruction set architectureb) page sizec) physical memory sized) number of processes in memory"
},
{
"code": null,
"e": 1665,
"s": 1409,
"text": "Answer (a)Each process needs minimum number of pages based on instruction set architecture. Example IBM 370: 6 pages to handle MVC (storage to storage move) instructionInstruction is 6 bytes, might span 2 pages.2 pages to handle from.2 pages to handle to."
},
{
"code": null,
"e": 2051,
"s": 1665,
"text": "4. In a system with 32 bit virtual addresses and 1 KB page size, use of one-level page tables for virtual to physical address translation is not practical because of (GATE CS 2003)a) the large amount of internal fragmentationb) the large amount of external fragmentationc) the large memory overhead in maintaining page tablesd) the large computation overhead in the translation process"
},
{
"code": null,
"e": 2129,
"s": 2051,
"text": "Answer (c)Since page size is too small it will make size of page tables huge."
},
{
"code": null,
"e": 2220,
"s": 2129,
"text": "Size of page table =\n (total number of page table entries) *(size of a page table entry)\n"
},
{
"code": null,
"e": 2272,
"s": 2220,
"text": "Let us see how many entries are there in page table"
},
{
"code": null,
"e": 2432,
"s": 2272,
"text": "Number of entries in page table =\n (virtual address space size)/(page size)\n = (2^32)/(2^10) \n = 2^22\n"
},
{
"code": null,
"e": 2471,
"s": 2432,
"text": "Now, let us see how big each entry is."
},
{
"code": null,
"e": 2763,
"s": 2471,
"text": "If size of physical memory is 512 MB then number of bits required to address a byte in 512 MB is 29. So, there will be (512MB)/(1KB) = (2^29)/(2^10) page frames in physical memory. To address a page frame 19 bits are required. Therefore, each entry in page table is required to have 19 bits."
},
{
"code": null,
"e": 3078,
"s": 2763,
"text": "Note that page table entry also holds auxiliary information about the page such \nas a present bit, a dirty or modified bit, address space or process ID information, \namongst others. So size of page table \n > (total number of page table entries) *(size of a page table entry)\n > (2^22 *19) bytes\n > 9.5 MB\n"
},
{
"code": null,
"e": 3328,
"s": 3078,
"text": "And this much memory is required for each process because each process maintains its own page table. Also, size of page table will be more for physical memory more than 512MB. Therefore, it is advised to use multilevel page table for such scenarios."
},
{
"code": null,
"e": 3442,
"s": 3328,
"text": "References:http://barbara.stattenfield.org/ta/cs162/section-notes/sec8.txthttp://en.wikipedia.org/wiki/Page_table"
},
{
"code": null,
"e": 3556,
"s": 3442,
"text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc."
},
{
"code": null,
"e": 3705,
"s": 3556,
"text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above."
},
{
"code": null,
"e": 3713,
"s": 3705,
"text": "GATE CS"
},
{
"code": null,
"e": 3717,
"s": 3713,
"text": "MCQ"
},
{
"code": null,
"e": 3735,
"s": 3717,
"text": "Operating Systems"
},
{
"code": null,
"e": 3753,
"s": 3735,
"text": "Operating Systems"
}
] |
Perl | Extract IP Address from a String using Regex
|
26 Sep, 2019
Perl stands for Practical Extraction and Reporting Language and this not authorized acronym. One of the most powerful features of the Perl programming language is Regular Expression and in this article, you will learn how to extract an IP address from a string. A regular expression can be either simple or complex, depending on the pattern you want to match like our title – Extracting IP Address from a String using Regex. Extracting IP address from a string can be a simple or challenging task. Hence, people love and hate regular expressions. They are a great way to express a simple pattern and a horrific way to express complicated ones. Some of the examples of Quantifiers as well as Characters and their meaning is given below:
The easiest way is just to take any string of four decimal numbers separated by periods is
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ OR /^\d+\.\d+\.\d+\.\d+$/
In the following example we simply extracting an IP address from a given string.
#!/usr/bin/perl my $ip = "MY IP ADDRESS IS172.26.39.41THIS IS A VALID IP ADDRESS"; if($ip =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/){ $ip = $1; print "$ip\n";}
Output:
But, the above example also accepts the wrong IP address like 596.368.258.269. We know, a proper decimal dotted IP address has no value larger than 255 and writing a regex that matches the integers 0 to 255 is hard work as the regular expressions don’t understand arithmetic; they operate purely textually. Therefore, you have to describe the integers 0 through 255 in purely textual means.
Now, we will see an implementation of extracting an IP address which will check octet range also.
#!/usr/bin/perl my $ip = "MY IP ADDRESS IS 36.59.63 THIS IS A VALID IP ADDRESS"; if($ip =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/){ if($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255) { print("Each octet of an IP address ", "is within the range - $1\n"); print("\nIP address accepted!\n"); } else { print("Octet not in range - $1\n", "IP address not accepted\n"); }}else{ print("Valid IP address not found in a given string\n");}
Output:
If you change the string to
[my $ip = "MY IP ADDRESS IS 127.36.59.63 THIS IS A VALID IP ADDRESS";]
then the output is
In the following example, we are accepting a string from the user which contains an IP address and then we are extracting the IP address from it. We used the chomp() function to remove any newline character from the end of a string.
#!/usr/bin/perl print("Enter the IP Address you would like to validate - ");my $ip = <STDIN>; if($ip =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/){ $ip = $1;} chomp($ip); if($ip =~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/){ print("\nIP address found - $ip\n"); if($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255) { print("Each octet of an IP address is ", "within the range - $1.$2.$3.$4\n"); print("\n-> $ip IP address accepted!\n"); } else { print("Octet(s) out of range. ", "Valid number range between 0-255\n"); }}else{ print("IP Address $ip is not in a valid format\n");}
Output:
Perl-regex
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Sep, 2019"
},
{
"code": null,
"e": 764,
"s": 28,
"text": "Perl stands for Practical Extraction and Reporting Language and this not authorized acronym. One of the most powerful features of the Perl programming language is Regular Expression and in this article, you will learn how to extract an IP address from a string. A regular expression can be either simple or complex, depending on the pattern you want to match like our title – Extracting IP Address from a String using Regex. Extracting IP address from a string can be a simple or challenging task. Hence, people love and hate regular expressions. They are a great way to express a simple pattern and a horrific way to express complicated ones. Some of the examples of Quantifiers as well as Characters and their meaning is given below:"
},
{
"code": null,
"e": 855,
"s": 764,
"text": "The easiest way is just to take any string of four decimal numbers separated by periods is"
},
{
"code": null,
"e": 919,
"s": 855,
"text": "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})/ OR /^\\d+\\.\\d+\\.\\d+\\.\\d+$/\n"
},
{
"code": null,
"e": 1000,
"s": 919,
"text": "In the following example we simply extracting an IP address from a given string."
},
{
"code": "#!/usr/bin/perl my $ip = \"MY IP ADDRESS IS172.26.39.41THIS IS A VALID IP ADDRESS\"; if($ip =~ /(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})/){ $ip = $1; print \"$ip\\n\";}",
"e": 1168,
"s": 1000,
"text": null
},
{
"code": null,
"e": 1176,
"s": 1168,
"text": "Output:"
},
{
"code": null,
"e": 1567,
"s": 1176,
"text": "But, the above example also accepts the wrong IP address like 596.368.258.269. We know, a proper decimal dotted IP address has no value larger than 255 and writing a regex that matches the integers 0 to 255 is hard work as the regular expressions don’t understand arithmetic; they operate purely textually. Therefore, you have to describe the integers 0 through 255 in purely textual means."
},
{
"code": null,
"e": 1665,
"s": 1567,
"text": "Now, we will see an implementation of extracting an IP address which will check octet range also."
},
{
"code": "#!/usr/bin/perl my $ip = \"MY IP ADDRESS IS 36.59.63 THIS IS A VALID IP ADDRESS\"; if($ip =~ /(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})/){ if($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255) { print(\"Each octet of an IP address \", \"is within the range - $1\\n\"); print(\"\\nIP address accepted!\\n\"); } else { print(\"Octet not in range - $1\\n\", \"IP address not accepted\\n\"); }}else{ print(\"Valid IP address not found in a given string\\n\");}",
"e": 2166,
"s": 1665,
"text": null
},
{
"code": null,
"e": 2174,
"s": 2166,
"text": "Output:"
},
{
"code": null,
"e": 2202,
"s": 2174,
"text": "If you change the string to"
},
{
"code": null,
"e": 2274,
"s": 2202,
"text": "[my $ip = \"MY IP ADDRESS IS 127.36.59.63 THIS IS A VALID IP ADDRESS\";] "
},
{
"code": null,
"e": 2293,
"s": 2274,
"text": "then the output is"
},
{
"code": null,
"e": 2526,
"s": 2293,
"text": "In the following example, we are accepting a string from the user which contains an IP address and then we are extracting the IP address from it. We used the chomp() function to remove any newline character from the end of a string."
},
{
"code": "#!/usr/bin/perl print(\"Enter the IP Address you would like to validate - \");my $ip = <STDIN>; if($ip =~ /(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})/){ $ip = $1;} chomp($ip); if($ip =~ m/^(\\d\\d?\\d?)\\.(\\d\\d?\\d?)\\.(\\d\\d?\\d?)\\.(\\d\\d?\\d?)$/){ print(\"\\nIP address found - $ip\\n\"); if($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255) { print(\"Each octet of an IP address is \", \"within the range - $1.$2.$3.$4\\n\"); print(\"\\n-> $ip IP address accepted!\\n\"); } else { print(\"Octet(s) out of range. \", \"Valid number range between 0-255\\n\"); }}else{ print(\"IP Address $ip is not in a valid format\\n\");}",
"e": 3190,
"s": 2526,
"text": null
},
{
"code": null,
"e": 3198,
"s": 3190,
"text": "Output:"
},
{
"code": null,
"e": 3209,
"s": 3198,
"text": "Perl-regex"
},
{
"code": null,
"e": 3216,
"s": 3209,
"text": "Picked"
},
{
"code": null,
"e": 3221,
"s": 3216,
"text": "Perl"
},
{
"code": null,
"e": 3226,
"s": 3221,
"text": "Perl"
}
] |
How to Remove Unused CSS From Your Website ?
|
19 May, 2020
The CSS files of your website can sometimes become quite large. This will mostly happen when you will build new classes without deleting the old ones which you now have stopped using, making the CSS file very messy for other contributors to understand and modify.
This can also happen if you use a pre-built theme from WordPress. Here, we will be knowing how to reduce your CSS file size at a considerate ratio. There are some tools available to remove unused CSS. Here, we will be using PurifyCSS.
Prerequisites:
You will be required to install Node, it will be used to execute the code. Download and install Node, which will include the inbuilt package manager NPM.
You will also need any text editor, and if you don’t have one, try using Visual Studio Code.
Understanding how PurifyCSS works: PurifyCSS gets all HTML files through a range of CSS files. It means that we can’t just provide our index.html file, because we might have different HTML files present through a range of templates on our website. The list of HTML files will then check through the provided CSS files, like style.css and custom.css. In your case, it can be different, just think which of your files are using same CSS files. The similar pages will then be checked through CSS files. If not done, then we might end up losing the required CSS files.
Installing PurifyCSS: Install Node and get access to its package manager, NPM. PurifyCSS has an in built NPM Package for installation, install it by running the below command in the terminal at the root directory of the project folder:
npm i -D purify-css
Preparing our files: We will be needing some HTML files along with their CSS files. In our case, we suppose the main bulk of our CSS is in the style.css file.
In our root directory, we create a HTML file for each HTML layout that we want to process :
Homepage
Practice
Contests
Internships
Profile
jobs
After creating the template files that matches our website, just copy and paste them into the new files that we have created in our directory. Then we do the same with the CSS file.
The root directory for the purify tool will look like this:
node_modules/
practice.html
contests.html
index.html
internships.html
profile.html
jobs.html
style.css
Creating the JavaScript Purifier: Now, create a new .js file in the root directory, like purifyMyCSS.js. Add the following JavaScript code to the file.
const purify = require("purify-css") // Reference of all HTML files from root directorylet content = ['*.html']; // Reference of all CSS files from root directorylet css = ['*.css']; let files = { // Write purified CSS into a file output: 'purified.css', minified: true, // Minify boolean info: true // Output information}; purify(content, css, files, function (purifiedAndMinifiedResult) { console.log(purifiedAndMinifiedResult);});
This is enough for the working of PurifyCSS. Now just run the code using Node.
Purifying: After follow the above steps, unused CSS can be removed by running the following code in a terminal at the root directory level:
node purifyMyCss.js
And that is it, you will get an output similar to the following:
Now you’ll get a new CSS file named purified.css, just copy the contents of this file and paste them to your website’s CSS file.
Summary:PurifyCSS reduced around 70% of unused CSS from our files which is quite a lot if you have a large website like GeeksforGeeks. But, if you have a single-page website, then you don’t need to follow all these steps. There are various free online tools which you can use. One of them is UNCSS, which allows you to paste HTML contents in one input and CSS contents in the other. Hit the button, and your shortened CSS will be appended to the output box, copy it and paste it to your desired place.
CSS-Misc
HTML-Misc
JavaScript-Misc
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 May, 2020"
},
{
"code": null,
"e": 318,
"s": 53,
"text": "The CSS files of your website can sometimes become quite large. This will mostly happen when you will build new classes without deleting the old ones which you now have stopped using, making the CSS file very messy for other contributors to understand and modify. "
},
{
"code": null,
"e": 555,
"s": 318,
"text": "This can also happen if you use a pre-built theme from WordPress. Here, we will be knowing how to reduce your CSS file size at a considerate ratio. There are some tools available to remove unused CSS. Here, we will be using PurifyCSS. "
},
{
"code": null,
"e": 570,
"s": 555,
"text": "Prerequisites:"
},
{
"code": null,
"e": 726,
"s": 570,
"text": "You will be required to install Node, it will be used to execute the code. Download and install Node, which will include the inbuilt package manager NPM."
},
{
"code": null,
"e": 819,
"s": 726,
"text": "You will also need any text editor, and if you don’t have one, try using Visual Studio Code."
},
{
"code": null,
"e": 1384,
"s": 819,
"text": "Understanding how PurifyCSS works: PurifyCSS gets all HTML files through a range of CSS files. It means that we can’t just provide our index.html file, because we might have different HTML files present through a range of templates on our website. The list of HTML files will then check through the provided CSS files, like style.css and custom.css. In your case, it can be different, just think which of your files are using same CSS files. The similar pages will then be checked through CSS files. If not done, then we might end up losing the required CSS files."
},
{
"code": null,
"e": 1621,
"s": 1384,
"text": "Installing PurifyCSS: Install Node and get access to its package manager, NPM. PurifyCSS has an in built NPM Package for installation, install it by running the below command in the terminal at the root directory of the project folder: "
},
{
"code": null,
"e": 1642,
"s": 1621,
"text": "npm i -D purify-css\n"
},
{
"code": null,
"e": 1802,
"s": 1642,
"text": "Preparing our files: We will be needing some HTML files along with their CSS files. In our case, we suppose the main bulk of our CSS is in the style.css file. "
},
{
"code": null,
"e": 1894,
"s": 1802,
"text": "In our root directory, we create a HTML file for each HTML layout that we want to process :"
},
{
"code": null,
"e": 1903,
"s": 1894,
"text": "Homepage"
},
{
"code": null,
"e": 1912,
"s": 1903,
"text": "Practice"
},
{
"code": null,
"e": 1921,
"s": 1912,
"text": "Contests"
},
{
"code": null,
"e": 1933,
"s": 1921,
"text": "Internships"
},
{
"code": null,
"e": 1941,
"s": 1933,
"text": "Profile"
},
{
"code": null,
"e": 1946,
"s": 1941,
"text": "jobs"
},
{
"code": null,
"e": 2128,
"s": 1946,
"text": "After creating the template files that matches our website, just copy and paste them into the new files that we have created in our directory. Then we do the same with the CSS file."
},
{
"code": null,
"e": 2189,
"s": 2128,
"text": "The root directory for the purify tool will look like this: "
},
{
"code": null,
"e": 2203,
"s": 2189,
"text": "node_modules/"
},
{
"code": null,
"e": 2217,
"s": 2203,
"text": "practice.html"
},
{
"code": null,
"e": 2231,
"s": 2217,
"text": "contests.html"
},
{
"code": null,
"e": 2242,
"s": 2231,
"text": "index.html"
},
{
"code": null,
"e": 2259,
"s": 2242,
"text": "internships.html"
},
{
"code": null,
"e": 2272,
"s": 2259,
"text": "profile.html"
},
{
"code": null,
"e": 2282,
"s": 2272,
"text": "jobs.html"
},
{
"code": null,
"e": 2292,
"s": 2282,
"text": "style.css"
},
{
"code": null,
"e": 2445,
"s": 2292,
"text": "Creating the JavaScript Purifier: Now, create a new .js file in the root directory, like purifyMyCSS.js. Add the following JavaScript code to the file. "
},
{
"code": "const purify = require(\"purify-css\") // Reference of all HTML files from root directorylet content = ['*.html']; // Reference of all CSS files from root directorylet css = ['*.css']; let files = { // Write purified CSS into a file output: 'purified.css', minified: true, // Minify boolean info: true // Output information}; purify(content, css, files, function (purifiedAndMinifiedResult) { console.log(purifiedAndMinifiedResult);});",
"e": 2901,
"s": 2445,
"text": null
},
{
"code": null,
"e": 2981,
"s": 2901,
"text": "This is enough for the working of PurifyCSS. Now just run the code using Node. "
},
{
"code": null,
"e": 3121,
"s": 2981,
"text": "Purifying: After follow the above steps, unused CSS can be removed by running the following code in a terminal at the root directory level:"
},
{
"code": null,
"e": 3142,
"s": 3121,
"text": "node purifyMyCss.js\n"
},
{
"code": null,
"e": 3208,
"s": 3142,
"text": "And that is it, you will get an output similar to the following: "
},
{
"code": null,
"e": 3338,
"s": 3208,
"text": "Now you’ll get a new CSS file named purified.css, just copy the contents of this file and paste them to your website’s CSS file. "
},
{
"code": null,
"e": 3840,
"s": 3338,
"text": "Summary:PurifyCSS reduced around 70% of unused CSS from our files which is quite a lot if you have a large website like GeeksforGeeks. But, if you have a single-page website, then you don’t need to follow all these steps. There are various free online tools which you can use. One of them is UNCSS, which allows you to paste HTML contents in one input and CSS contents in the other. Hit the button, and your shortened CSS will be appended to the output box, copy it and paste it to your desired place."
},
{
"code": null,
"e": 3849,
"s": 3840,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3859,
"s": 3849,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3875,
"s": 3859,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3892,
"s": 3875,
"text": "Web Technologies"
},
{
"code": null,
"e": 3919,
"s": 3892,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3935,
"s": 3919,
"text": "Write From Home"
}
] |
How to Add Superscripts and Subscripts to Plots in R?
|
28 Nov, 2021
Plots can be used to create and display numerical values or data points. The x and y axes labels or titles are used to depict the labels to the plot data. These labels can create either subscript or superscript symbols within them. This can be done using various base R methods :
The superscripts can be added to the x or y axes labels or titles of the plot. These can be added using the ^ operator which is appended to the character string created in the plot() method. The superscript operator can be created using the expression method.
Syntax:
expression(str^val)
Parameters :
str – The character string to create
val – The value to raise the character string by
Example:
Here we are going to create a plot with numbers from 1 to 6 with power of 2 as an expression.The string “Numbers” is combined with a subscript ^2 formatted with ^ symbol.
R
# creating numbersnumb < - 1: 6 # creating the x axis labels# creating a plotplot(numb, xlab=expression("Numbers" ^ 2))
Output:
The subscripts can be added to the x or y axes labels or titles of the plot. These can be added using the [] operator which is appended to the character string created in the plot() method. The subscript operator can be created using the expression method.
Syntax:
expression(str[val])
Parameters :
str – The character string to create
val – The value to create the subscript the character string by
Example:
Here we are going to plot an expression [2] with the given numbers.The string “Numbers” is combined with a subscript [2] enclosed in braces.
R
# creating numbersnumb < - 1: 6 # creating the x axis labels# creating a plotplot(numb, xlab=expression("Numbers"[2]))
Output:
A combination of subscripts or superscripts can be appended to the plot strings using the ^ or [] operators. The * sign is appended each time the character string breaks into a part.
Example:
Here we are plot an expression log”[a]*”10′′^2 for the integers 1 to 6. The string “log” is combined with the subscript [a] and then combined with the string “10” along with the superscript 2 formatted with ^ symbol.
R
# creating numbersnumb < - 1: 6 # creating the x axis labels# creating a plotplot(numb, xlab=expression("log"[a]*"10" ^ 2))
Output:
Picked
R-Charts
R-Graphs
R-plots
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": "\n28 Nov, 2021"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "Plots can be used to create and display numerical values or data points. The x and y axes labels or titles are used to depict the labels to the plot data. These labels can create either subscript or superscript symbols within them. This can be done using various base R methods : "
},
{
"code": null,
"e": 570,
"s": 309,
"text": "The superscripts can be added to the x or y axes labels or titles of the plot. These can be added using the ^ operator which is appended to the character string created in the plot() method. The superscript operator can be created using the expression method. "
},
{
"code": null,
"e": 578,
"s": 570,
"text": "Syntax:"
},
{
"code": null,
"e": 598,
"s": 578,
"text": "expression(str^val)"
},
{
"code": null,
"e": 612,
"s": 598,
"text": "Parameters : "
},
{
"code": null,
"e": 649,
"s": 612,
"text": "str – The character string to create"
},
{
"code": null,
"e": 698,
"s": 649,
"text": "val – The value to raise the character string by"
},
{
"code": null,
"e": 707,
"s": 698,
"text": "Example:"
},
{
"code": null,
"e": 879,
"s": 707,
"text": "Here we are going to create a plot with numbers from 1 to 6 with power of 2 as an expression.The string “Numbers” is combined with a subscript ^2 formatted with ^ symbol. "
},
{
"code": null,
"e": 881,
"s": 879,
"text": "R"
},
{
"code": "# creating numbersnumb < - 1: 6 # creating the x axis labels# creating a plotplot(numb, xlab=expression(\"Numbers\" ^ 2))",
"e": 1002,
"s": 881,
"text": null
},
{
"code": null,
"e": 1010,
"s": 1002,
"text": "Output:"
},
{
"code": null,
"e": 1267,
"s": 1010,
"text": "The subscripts can be added to the x or y axes labels or titles of the plot. These can be added using the [] operator which is appended to the character string created in the plot() method. The subscript operator can be created using the expression method."
},
{
"code": null,
"e": 1275,
"s": 1267,
"text": "Syntax:"
},
{
"code": null,
"e": 1296,
"s": 1275,
"text": "expression(str[val])"
},
{
"code": null,
"e": 1309,
"s": 1296,
"text": "Parameters :"
},
{
"code": null,
"e": 1346,
"s": 1309,
"text": "str – The character string to create"
},
{
"code": null,
"e": 1410,
"s": 1346,
"text": "val – The value to create the subscript the character string by"
},
{
"code": null,
"e": 1419,
"s": 1410,
"text": "Example:"
},
{
"code": null,
"e": 1560,
"s": 1419,
"text": "Here we are going to plot an expression [2] with the given numbers.The string “Numbers” is combined with a subscript [2] enclosed in braces."
},
{
"code": null,
"e": 1562,
"s": 1560,
"text": "R"
},
{
"code": "# creating numbersnumb < - 1: 6 # creating the x axis labels# creating a plotplot(numb, xlab=expression(\"Numbers\"[2]))",
"e": 1682,
"s": 1562,
"text": null
},
{
"code": null,
"e": 1690,
"s": 1682,
"text": "Output:"
},
{
"code": null,
"e": 1874,
"s": 1690,
"text": "A combination of subscripts or superscripts can be appended to the plot strings using the ^ or [] operators. The * sign is appended each time the character string breaks into a part. "
},
{
"code": null,
"e": 1883,
"s": 1874,
"text": "Example:"
},
{
"code": null,
"e": 2101,
"s": 1883,
"text": "Here we are plot an expression log”[a]*”10′′^2 for the integers 1 to 6. The string “log” is combined with the subscript [a] and then combined with the string “10” along with the superscript 2 formatted with ^ symbol. "
},
{
"code": null,
"e": 2103,
"s": 2101,
"text": "R"
},
{
"code": "# creating numbersnumb < - 1: 6 # creating the x axis labels# creating a plotplot(numb, xlab=expression(\"log\"[a]*\"10\" ^ 2))",
"e": 2228,
"s": 2103,
"text": null
},
{
"code": null,
"e": 2236,
"s": 2228,
"text": "Output:"
},
{
"code": null,
"e": 2243,
"s": 2236,
"text": "Picked"
},
{
"code": null,
"e": 2252,
"s": 2243,
"text": "R-Charts"
},
{
"code": null,
"e": 2261,
"s": 2252,
"text": "R-Graphs"
},
{
"code": null,
"e": 2269,
"s": 2261,
"text": "R-plots"
},
{
"code": null,
"e": 2280,
"s": 2269,
"text": "R Language"
}
] |
SQL | USING Clause
|
21 Mar, 2018
If several columns have the same names but the datatypes do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an EQUIJOIN.
USING Clause is used to match only one column when more than one column matches.
NATURAL JOIN and USING Clause are mutually exclusive.
It should not have a qualifier(table name or Alias) in the referenced columns.
NATURAL JOIN uses all the columns with matching names and datatypes to join the tables. The USING Clause can be used to specify only those columns that should be used for an EQUIJOIN.
EXAMPLES:
We will apply the below mentioned commands on the following base tables:
Employee TableDepartment Table
Employee Table
Department Table
QUERY 1: Write SQL query to find the working location of the employees. Also give their respective employee_id and last_name?
Input : SELECT e.EMPLOYEE_ID, e.LAST_NAME, d.LOCATION_ID
FROM Employees e JOIN Departments d
USING(DEPARTMENT_ID);
Output :
QUERY 1: Write SQL query to find the working location of the employees. Also give their respective employee_id and last_name?
Input : SELECT e.EMPLOYEE_ID, e.LAST_NAME, d.LOCATION_ID
FROM Employees e JOIN Departments d
USING(DEPARTMENT_ID);
Output :
Explanation: The example shown joins the DEPARTMENT_ID column in the EMPLOYEES and DEPARTMENTStables, and thus shows the location where an employee works.
We will apply the below mentioned commands on the following base tables:
Country TableLocation TableQUERY 2: Write SQL query to find the location_id, street_address, postal_code and their respective country name?
Input : SELECT l.location_id, l.street_address, l.postal_code, c.country_name
FROM locations l JOIN countries c
USING(country_id);
Output :
Country Table
Location Table
QUERY 2: Write SQL query to find the location_id, street_address, postal_code and their respective country name?
Input : SELECT l.location_id, l.street_address, l.postal_code, c.country_name
FROM locations l JOIN countries c
USING(country_id);
Output :
Explanation: The example shown joins the COUNTRY_ID column in the LOCATIONS and COUNTRIEStables, and thus shows the required details.
NOTE: When we use the USING clause in a join statement, the join column is not qualified with table Alias. Do not Alias it even if the same column is used elsewhere in the SQL statement:
Example:
Input: SELECT l.location_id, l.street_address, l.postal_code, c.country_name
FROM locations l JOIN countries c
USING(country_id)
WHERE c.country_id'IT';
Output:
Input: SELECT l.location_id, l.street_address, l.postal_code, c.country_name
FROM locations l JOIN countries c
USING(country_id)
WHERE c.country_id'IT';
Output:
Explanation: Since the column in USING Clause is used again in WHERE Clause, thus it throws an error to the user.
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Sub queries in From Clause
Difference between DELETE, DROP and TRUNCATE
SQL Correlated Subqueries
MySQL | Group_CONCAT() Function
Window functions in SQL
Difference between DELETE and TRUNCATE
MySQL | Regular expressions (Regexp)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Mar, 2018"
},
{
"code": null,
"e": 247,
"s": 54,
"text": "If several columns have the same names but the datatypes do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an EQUIJOIN."
},
{
"code": null,
"e": 328,
"s": 247,
"text": "USING Clause is used to match only one column when more than one column matches."
},
{
"code": null,
"e": 382,
"s": 328,
"text": "NATURAL JOIN and USING Clause are mutually exclusive."
},
{
"code": null,
"e": 461,
"s": 382,
"text": "It should not have a qualifier(table name or Alias) in the referenced columns."
},
{
"code": null,
"e": 645,
"s": 461,
"text": "NATURAL JOIN uses all the columns with matching names and datatypes to join the tables. The USING Clause can be used to specify only those columns that should be used for an EQUIJOIN."
},
{
"code": null,
"e": 655,
"s": 645,
"text": "EXAMPLES:"
},
{
"code": null,
"e": 728,
"s": 655,
"text": "We will apply the below mentioned commands on the following base tables:"
},
{
"code": null,
"e": 759,
"s": 728,
"text": "Employee TableDepartment Table"
},
{
"code": null,
"e": 774,
"s": 759,
"text": "Employee Table"
},
{
"code": null,
"e": 791,
"s": 774,
"text": "Department Table"
},
{
"code": null,
"e": 1043,
"s": 791,
"text": "QUERY 1: Write SQL query to find the working location of the employees. Also give their respective employee_id and last_name?\nInput : SELECT e.EMPLOYEE_ID, e.LAST_NAME, d.LOCATION_ID\nFROM Employees e JOIN Departments d\nUSING(DEPARTMENT_ID);\nOutput :\n\n"
},
{
"code": null,
"e": 1169,
"s": 1043,
"text": "QUERY 1: Write SQL query to find the working location of the employees. Also give their respective employee_id and last_name?"
},
{
"code": null,
"e": 1296,
"s": 1169,
"text": "\nInput : SELECT e.EMPLOYEE_ID, e.LAST_NAME, d.LOCATION_ID\nFROM Employees e JOIN Departments d\nUSING(DEPARTMENT_ID);\nOutput :\n\n"
},
{
"code": null,
"e": 1451,
"s": 1296,
"text": "Explanation: The example shown joins the DEPARTMENT_ID column in the EMPLOYEES and DEPARTMENTStables, and thus shows the location where an employee works."
},
{
"code": null,
"e": 1524,
"s": 1451,
"text": "We will apply the below mentioned commands on the following base tables:"
},
{
"code": null,
"e": 1807,
"s": 1524,
"text": "Country TableLocation TableQUERY 2: Write SQL query to find the location_id, street_address, postal_code and their respective country name?\nInput : SELECT l.location_id, l.street_address, l.postal_code, c.country_name\nFROM locations l JOIN countries c\nUSING(country_id);\nOutput : \n\n"
},
{
"code": null,
"e": 1821,
"s": 1807,
"text": "Country Table"
},
{
"code": null,
"e": 1836,
"s": 1821,
"text": "Location Table"
},
{
"code": null,
"e": 1949,
"s": 1836,
"text": "QUERY 2: Write SQL query to find the location_id, street_address, postal_code and their respective country name?"
},
{
"code": null,
"e": 2093,
"s": 1949,
"text": "\nInput : SELECT l.location_id, l.street_address, l.postal_code, c.country_name\nFROM locations l JOIN countries c\nUSING(country_id);\nOutput : \n\n"
},
{
"code": null,
"e": 2227,
"s": 2093,
"text": "Explanation: The example shown joins the COUNTRY_ID column in the LOCATIONS and COUNTRIEStables, and thus shows the required details."
},
{
"code": null,
"e": 2414,
"s": 2227,
"text": "NOTE: When we use the USING clause in a join statement, the join column is not qualified with table Alias. Do not Alias it even if the same column is used elsewhere in the SQL statement:"
},
{
"code": null,
"e": 2423,
"s": 2414,
"text": "Example:"
},
{
"code": null,
"e": 2586,
"s": 2423,
"text": "Input: SELECT l.location_id, l.street_address, l.postal_code, c.country_name\nFROM locations l JOIN countries c\nUSING(country_id)\nWHERE c.country_id'IT';\nOutput: \n"
},
{
"code": null,
"e": 2749,
"s": 2586,
"text": "Input: SELECT l.location_id, l.street_address, l.postal_code, c.country_name\nFROM locations l JOIN countries c\nUSING(country_id)\nWHERE c.country_id'IT';\nOutput: \n"
},
{
"code": null,
"e": 2863,
"s": 2749,
"text": "Explanation: Since the column in USING Clause is used again in WHERE Clause, thus it throws an error to the user."
},
{
"code": null,
"e": 2885,
"s": 2863,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 2889,
"s": 2885,
"text": "SQL"
},
{
"code": null,
"e": 2893,
"s": 2889,
"text": "SQL"
},
{
"code": null,
"e": 2991,
"s": 2893,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3002,
"s": 2991,
"text": "CTE in SQL"
},
{
"code": null,
"e": 3068,
"s": 3002,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 3092,
"s": 3068,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 3125,
"s": 3092,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 3170,
"s": 3125,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 3196,
"s": 3170,
"text": "SQL Correlated Subqueries"
},
{
"code": null,
"e": 3228,
"s": 3196,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 3252,
"s": 3228,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 3291,
"s": 3252,
"text": "Difference between DELETE and TRUNCATE"
}
] |
Express.js | app.get() Request Function
|
07 Mar, 2022
The app.get() function routes the HTTP GET Requests to the path which is being specified with the specified callback functions. Basically it is intended for binding the middleware to your application.Syntax:
app.get( path, callback )
Parameters:
path: It is the path for which the middleware function is being called. callback: They can be a middleware function or series/array of middleware functions.
path: It is the path for which the middleware function is being called.
callback: They can be a middleware function or series/array of middleware functions.
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.
You can visit the link to Install express module. You can install this package by using this command.
npm install express
After installing express module, you can check your express version in command prompt using the command.
After installing express module, you can check your express version in command prompt using the command.
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
node index.js
Filename: index.js
javascript
var express = require('express');var app = express();var PORT = 3000; app.get('/', (req, res) => { res.send("GET Request Called")}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:
The project structure will look like this:
Make sure you have installed express module using following command:
Make sure you have installed express module using following command:
npm install express
Run index.js file using below command:
Run index.js file using below command:
node index.js
Output:
Output:
Server listening on PORT 3000
Now make GET request to http://localhost:3000/ and you will get the following output:
Now make GET request to http://localhost:3000/ and you will get the following output:
GET Request Called
simmytarika5
kapoorchiranjeev
Express.js
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": "\n07 Mar, 2022"
},
{
"code": null,
"e": 238,
"s": 28,
"text": "The app.get() function routes the HTTP GET Requests to the path which is being specified with the specified callback functions. Basically it is intended for binding the middleware to your application.Syntax: "
},
{
"code": null,
"e": 264,
"s": 238,
"text": "app.get( path, callback )"
},
{
"code": null,
"e": 278,
"s": 264,
"text": "Parameters: "
},
{
"code": null,
"e": 438,
"s": 278,
"text": "path: It is the path for which the middleware function is being called. callback: They can be a middleware function or series/array of middleware functions. "
},
{
"code": null,
"e": 512,
"s": 438,
"text": "path: It is the path for which the middleware function is being called. "
},
{
"code": null,
"e": 599,
"s": 512,
"text": "callback: They can be a middleware function or series/array of middleware functions. "
},
{
"code": null,
"e": 633,
"s": 599,
"text": "Installation of express module: "
},
{
"code": null,
"e": 737,
"s": 633,
"text": "You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 841,
"s": 737,
"text": "You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 861,
"s": 841,
"text": "npm install express"
},
{
"code": null,
"e": 968,
"s": 861,
"text": "After installing express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 1075,
"s": 968,
"text": "After installing express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 1095,
"s": 1075,
"text": "npm version express"
},
{
"code": null,
"e": 1232,
"s": 1095,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 1369,
"s": 1232,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 1383,
"s": 1369,
"text": "node index.js"
},
{
"code": null,
"e": 1404,
"s": 1383,
"text": "Filename: index.js "
},
{
"code": null,
"e": 1415,
"s": 1404,
"text": "javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; app.get('/', (req, res) => { res.send(\"GET Request Called\")}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);}); ",
"e": 1666,
"s": 1415,
"text": null
},
{
"code": null,
"e": 1694,
"s": 1666,
"text": "Steps to run the program: "
},
{
"code": null,
"e": 1739,
"s": 1694,
"text": "The project structure will look like this: "
},
{
"code": null,
"e": 1784,
"s": 1739,
"text": "The project structure will look like this: "
},
{
"code": null,
"e": 1855,
"s": 1784,
"text": "Make sure you have installed express module using following command: "
},
{
"code": null,
"e": 1926,
"s": 1855,
"text": "Make sure you have installed express module using following command: "
},
{
"code": null,
"e": 1946,
"s": 1926,
"text": "npm install express"
},
{
"code": null,
"e": 1987,
"s": 1946,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 2028,
"s": 1987,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 2042,
"s": 2028,
"text": "node index.js"
},
{
"code": null,
"e": 2052,
"s": 2042,
"text": "Output: "
},
{
"code": null,
"e": 2062,
"s": 2052,
"text": "Output: "
},
{
"code": null,
"e": 2092,
"s": 2062,
"text": "Server listening on PORT 3000"
},
{
"code": null,
"e": 2181,
"s": 2092,
"text": " Now make GET request to http://localhost:3000/ and you will get the following output: "
},
{
"code": null,
"e": 2271,
"s": 2183,
"text": "Now make GET request to http://localhost:3000/ and you will get the following output: "
},
{
"code": null,
"e": 2290,
"s": 2271,
"text": "GET Request Called"
},
{
"code": null,
"e": 2309,
"s": 2296,
"text": "simmytarika5"
},
{
"code": null,
"e": 2326,
"s": 2309,
"text": "kapoorchiranjeev"
},
{
"code": null,
"e": 2337,
"s": 2326,
"text": "Express.js"
},
{
"code": null,
"e": 2345,
"s": 2337,
"text": "Node.js"
},
{
"code": null,
"e": 2362,
"s": 2345,
"text": "Web Technologies"
}
] |
HTML | pattern Attribute
|
07 Dec, 2021
This attribute is used to specify the regular expression on which the input element value is checked. This attribute works with the following input types: text, password, date, search, email, etc. Use the Global title attribute to describe the pattern for helping the user.
Syntax:
<input pattern = "regular_exp">
Element: This attribute is associated with <input> element only.
Attribute: This attribute specifies the regular expression.
Example:
<!DOCTYPE html><html> <head> <title>pattern attribute</title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>pattern attribute</h2> <form action="#"> Password: <input type="text" name="Password" pattern="[A-Za-z]{3}" title="3 letter Password"> <input type="submit"> </form> </body></html>
Output:
Supported Browsers: The browser supported by pattern attribute are listed below:
Google Chrome 5.0 and above
Internet Explorer 10.0 and above
Firefox 4.0 and above
Opera 9.6 and above
hritikbhatnagar2182
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 327,
"s": 53,
"text": "This attribute is used to specify the regular expression on which the input element value is checked. This attribute works with the following input types: text, password, date, search, email, etc. Use the Global title attribute to describe the pattern for helping the user."
},
{
"code": null,
"e": 335,
"s": 327,
"text": "Syntax:"
},
{
"code": null,
"e": 367,
"s": 335,
"text": "<input pattern = \"regular_exp\">"
},
{
"code": null,
"e": 432,
"s": 367,
"text": "Element: This attribute is associated with <input> element only."
},
{
"code": null,
"e": 492,
"s": 432,
"text": "Attribute: This attribute specifies the regular expression."
},
{
"code": null,
"e": 501,
"s": 492,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>pattern attribute</title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>pattern attribute</h2> <form action=\"#\"> Password: <input type=\"text\" name=\"Password\" pattern=\"[A-Za-z]{3}\" title=\"3 letter Password\"> <input type=\"submit\"> </form> </body></html> ",
"e": 1034,
"s": 501,
"text": null
},
{
"code": null,
"e": 1042,
"s": 1034,
"text": "Output:"
},
{
"code": null,
"e": 1123,
"s": 1042,
"text": "Supported Browsers: The browser supported by pattern attribute are listed below:"
},
{
"code": null,
"e": 1151,
"s": 1123,
"text": "Google Chrome 5.0 and above"
},
{
"code": null,
"e": 1184,
"s": 1151,
"text": "Internet Explorer 10.0 and above"
},
{
"code": null,
"e": 1206,
"s": 1184,
"text": "Firefox 4.0 and above"
},
{
"code": null,
"e": 1226,
"s": 1206,
"text": "Opera 9.6 and above"
},
{
"code": null,
"e": 1246,
"s": 1226,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 1262,
"s": 1246,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1266,
"s": 1262,
"text": "CSS"
},
{
"code": null,
"e": 1271,
"s": 1266,
"text": "HTML"
},
{
"code": null,
"e": 1288,
"s": 1271,
"text": "Web Technologies"
},
{
"code": null,
"e": 1293,
"s": 1288,
"text": "HTML"
},
{
"code": null,
"e": 1391,
"s": 1293,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1439,
"s": 1391,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1501,
"s": 1439,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1551,
"s": 1501,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1609,
"s": 1551,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 1659,
"s": 1609,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 1707,
"s": 1659,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1769,
"s": 1707,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1819,
"s": 1769,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1843,
"s": 1819,
"text": "REST API (Introduction)"
}
] |
PyQtGraph – Clearing the Line in Line Graph
|
14 Jan, 2022
In this article, we will see how we can clear the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A line chart or line plot or line graph or curve chart is a type of chart that displays information as a series of data points called ‘markers’ connected by straight line segments. It is a basic type of chart common in many fields. Line graph is created with the help of plot class in PyQtGraph. Clearing of the line means that the data of the line will become None.
We can create a plot window and create lines on it with the help of the commands given below
# creating a pyqtgraph plot window
plt = pg.plot()
# plotting line in green color
# with dot symbol as x, not a mandatory field
line = plt.plot(x, y, pen='g', symbol='x', symbolPen='g', symbolBrush=0.2, name='green')
In order to do this we use clear method with the line objectSyntax : line.clear()Argument : It takes no argumentReturn : It returns None
Below is the implementation
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # setting scale self.setScale(0.2) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a new label label = QLabel("GeeksforGeeks Line Plot") # making it multiline label.setWordWrap(True) # y values to plot by line 1 y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2 y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16] x = range(0, 10) # create plot window object plt = pg.plot() # showing x and y grids plt.showGrid(x = True, y = True) # adding legend plt.addLegend() # set properties of the label for y axis plt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axis plt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal range plt.setXRange(0, 10) # setting vertical range plt.setYRange(0, 20) # plotting line in green color # with dot symbol as x, not a mandatory field line1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # plotting line2 with blue color # with dot symbol as o line2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # clearing the data of the line 1 line1.clear() # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding label to the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plt, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
simmytarika5
sagartomar9927
adnanirshad158
Python-gui
Python-PyQt
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 737,
"s": 28,
"text": "In this article, we will see how we can clear the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A line chart or line plot or line graph or curve chart is a type of chart that displays information as a series of data points called ‘markers’ connected by straight line segments. It is a basic type of chart common in many fields. Line graph is created with the help of plot class in PyQtGraph. Clearing of the line means that the data of the line will become None."
},
{
"code": null,
"e": 831,
"s": 737,
"text": "We can create a plot window and create lines on it with the help of the commands given below "
},
{
"code": null,
"e": 1049,
"s": 831,
"text": "# creating a pyqtgraph plot window\nplt = pg.plot()\n\n# plotting line in green color\n# with dot symbol as x, not a mandatory field\nline = plt.plot(x, y, pen='g', symbol='x', symbolPen='g', symbolBrush=0.2, name='green')"
},
{
"code": null,
"e": 1188,
"s": 1049,
"text": "In order to do this we use clear method with the line objectSyntax : line.clear()Argument : It takes no argumentReturn : It returns None "
},
{
"code": null,
"e": 1218,
"s": 1188,
"text": "Below is the implementation "
},
{
"code": null,
"e": 1226,
"s": 1218,
"text": "Python3"
},
{
"code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # setting scale self.setScale(0.2) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a new label label = QLabel(\"GeeksforGeeks Line Plot\") # making it multiline label.setWordWrap(True) # y values to plot by line 1 y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2 y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16] x = range(0, 10) # create plot window object plt = pg.plot() # showing x and y grids plt.showGrid(x = True, y = True) # adding legend plt.addLegend() # set properties of the label for y axis plt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axis plt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal range plt.setXRange(0, 10) # setting vertical range plt.setYRange(0, 20) # plotting line in green color # with dot symbol as x, not a mandatory field line1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # plotting line2 with blue color # with dot symbol as o line2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # clearing the data of the line 1 line1.clear() # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding label to the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plt, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 4107,
"s": 1226,
"text": null
},
{
"code": null,
"e": 4117,
"s": 4107,
"text": "Output : "
},
{
"code": null,
"e": 4132,
"s": 4119,
"text": "simmytarika5"
},
{
"code": null,
"e": 4147,
"s": 4132,
"text": "sagartomar9927"
},
{
"code": null,
"e": 4162,
"s": 4147,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4173,
"s": 4162,
"text": "Python-gui"
},
{
"code": null,
"e": 4185,
"s": 4173,
"text": "Python-PyQt"
},
{
"code": null,
"e": 4202,
"s": 4185,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 4209,
"s": 4202,
"text": "Python"
}
] |
How to Insert a Search Icon in Bootstrap ?
|
14 Sep, 2021
In this article, we will see how to insert a search icon in Bootstrap. While Bootstrap does not include an icon set by default, they do have their own comprehensive icon library called Bootstrap Icons. Feel free to use them or any other icon set in your project. There are various ways to add a search icon or other icons to your HTML page. All the icons in the icon libraries can be customized with CSS (size, align, rotate, shadow, color, etc.).
Method 1: Using bootstrap Glyphicons: Bootstrap gives us various predefined icons including search icons. You can add various types of icons from https://glyphicons.com/.
Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS.
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css”> <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script> <script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js”></script>
Step 2: Add <div> tag in the HTML body with class container.
Step 3: Now add any icon that you want using the below syntax, where the name is the name of glyphicon.
<span class="glyphicon glyphicon-name"></span>
Example: The following example shows different types of glyphicons and their usage.
HTML
<!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h2 style="color:green">Glyphicons Examples</h2> <p>Camera icon: <span class="glyphicon glyphicon-camera"></span> </p> <p>Search icon:<span class="glyphicon glyphicon-search"></span></p> <p>Search icon on a button: <button type="button" class="btn btn-default"> <span class="glyphicon glyphicon-search"></span> Search </button> </p> <p>Bell icon: <span class="glyphicon glyphicon-bell"></span> </p> </div></body> </html>
Output:
All glyphicons
Method 2 Using font awesome icons: Font Awesome is a web font containing all the icons from the Twitter Bootstrap framework. Font Awesome is a widely-used icon set that gives you scalable vector images that can be customized with CSS.
Step by step guide for the implementation:
Step 1: Copy your kit’s code into the <head> of each template or page in your project where you want to use Font Awesome via the kit. If you’ve got other versions or flavors of Font Awesome already in use, make sure to remove them.
<script src=”https://kit.fontawesome.com/6ec9c7cfba.js” crossorigin=”anonymous”></script>
Step 2: Add any free icons to a project with one line of code.
Syntax:
<i class="fas fa-camera"></i>
<i class="fas fa-camera"></i>
<span class="fas fa-camera"></span>
Example: The following example shows different types of font-awesome icons including search icon and their usage.
HTML
<!DOCTYPE><html> <head> <script src="https://kit.fontawesome.com/6ec9c7cfba.js" crossorigin="anonymous"> </script></head> <body> <h1 style="color:green"> GeeksforGeeks </h1> <i class="fas fa-chess" style="font-size:32px;"></i> <i class="fas fa-biking" style="font-size:42px;"></i> <i class="fas fa-bacteria" style="font-size:52px;"></i> <i class="fa fa-car" style="font-size:62px;"></i> <p style="color:green">Search icon <i class="fas fa-search" style="font-size:72px;"></i> </p></body> </html>
Output:
Search icon
Bootstrap-Questions
HTML-Questions
Picked
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to toggle password visibility in forms using Bootstrap-icons ?
How to set vertical alignment in Bootstrap ?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 476,
"s": 28,
"text": "In this article, we will see how to insert a search icon in Bootstrap. While Bootstrap does not include an icon set by default, they do have their own comprehensive icon library called Bootstrap Icons. Feel free to use them or any other icon set in your project. There are various ways to add a search icon or other icons to your HTML page. All the icons in the icon libraries can be customized with CSS (size, align, rotate, shadow, color, etc.)."
},
{
"code": null,
"e": 647,
"s": 476,
"text": "Method 1: Using bootstrap Glyphicons: Bootstrap gives us various predefined icons including search icons. You can add various types of icons from https://glyphicons.com/."
},
{
"code": null,
"e": 754,
"s": 647,
"text": "Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS."
},
{
"code": null,
"e": 1036,
"s": 754,
"text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css”> <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script> <script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js”></script>"
},
{
"code": null,
"e": 1099,
"s": 1038,
"text": "Step 2: Add <div> tag in the HTML body with class container."
},
{
"code": null,
"e": 1203,
"s": 1099,
"text": "Step 3: Now add any icon that you want using the below syntax, where the name is the name of glyphicon."
},
{
"code": null,
"e": 1250,
"s": 1203,
"text": "<span class=\"glyphicon glyphicon-name\"></span>"
},
{
"code": null,
"e": 1334,
"s": 1250,
"text": "Example: The following example shows different types of glyphicons and their usage."
},
{
"code": null,
"e": 1339,
"s": 1334,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h2 style=\"color:green\">Glyphicons Examples</h2> <p>Camera icon: <span class=\"glyphicon glyphicon-camera\"></span> </p> <p>Search icon:<span class=\"glyphicon glyphicon-search\"></span></p> <p>Search icon on a button: <button type=\"button\" class=\"btn btn-default\"> <span class=\"glyphicon glyphicon-search\"></span> Search </button> </p> <p>Bell icon: <span class=\"glyphicon glyphicon-bell\"></span> </p> </div></body> </html>",
"e": 2300,
"s": 1339,
"text": null
},
{
"code": null,
"e": 2308,
"s": 2300,
"text": "Output:"
},
{
"code": null,
"e": 2323,
"s": 2308,
"text": "All glyphicons"
},
{
"code": null,
"e": 2558,
"s": 2323,
"text": "Method 2 Using font awesome icons: Font Awesome is a web font containing all the icons from the Twitter Bootstrap framework. Font Awesome is a widely-used icon set that gives you scalable vector images that can be customized with CSS."
},
{
"code": null,
"e": 2601,
"s": 2558,
"text": "Step by step guide for the implementation:"
},
{
"code": null,
"e": 2833,
"s": 2601,
"text": "Step 1: Copy your kit’s code into the <head> of each template or page in your project where you want to use Font Awesome via the kit. If you’ve got other versions or flavors of Font Awesome already in use, make sure to remove them."
},
{
"code": null,
"e": 2923,
"s": 2833,
"text": "<script src=”https://kit.fontawesome.com/6ec9c7cfba.js” crossorigin=”anonymous”></script>"
},
{
"code": null,
"e": 2986,
"s": 2923,
"text": "Step 2: Add any free icons to a project with one line of code."
},
{
"code": null,
"e": 2994,
"s": 2986,
"text": "Syntax:"
},
{
"code": null,
"e": 3096,
"s": 2994,
"text": "<i class=\"fas fa-camera\"></i> \n<i class=\"fas fa-camera\"></i> \n<span class=\"fas fa-camera\"></span> "
},
{
"code": null,
"e": 3210,
"s": 3096,
"text": "Example: The following example shows different types of font-awesome icons including search icon and their usage."
},
{
"code": null,
"e": 3215,
"s": 3210,
"text": "HTML"
},
{
"code": "<!DOCTYPE><html> <head> <script src=\"https://kit.fontawesome.com/6ec9c7cfba.js\" crossorigin=\"anonymous\"> </script></head> <body> <h1 style=\"color:green\"> GeeksforGeeks </h1> <i class=\"fas fa-chess\" style=\"font-size:32px;\"></i> <i class=\"fas fa-biking\" style=\"font-size:42px;\"></i> <i class=\"fas fa-bacteria\" style=\"font-size:52px;\"></i> <i class=\"fa fa-car\" style=\"font-size:62px;\"></i> <p style=\"color:green\">Search icon <i class=\"fas fa-search\" style=\"font-size:72px;\"></i> </p></body> </html>",
"e": 3767,
"s": 3215,
"text": null
},
{
"code": null,
"e": 3775,
"s": 3767,
"text": "Output:"
},
{
"code": null,
"e": 3787,
"s": 3775,
"text": "Search icon"
},
{
"code": null,
"e": 3807,
"s": 3787,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 3822,
"s": 3807,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3829,
"s": 3822,
"text": "Picked"
},
{
"code": null,
"e": 3839,
"s": 3829,
"text": "Bootstrap"
},
{
"code": null,
"e": 3844,
"s": 3839,
"text": "HTML"
},
{
"code": null,
"e": 3861,
"s": 3844,
"text": "Web Technologies"
},
{
"code": null,
"e": 3866,
"s": 3861,
"text": "HTML"
},
{
"code": null,
"e": 3964,
"s": 3866,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4005,
"s": 3964,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 4038,
"s": 4005,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 4064,
"s": 4038,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 4131,
"s": 4064,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 4176,
"s": 4131,
"text": "How to set vertical alignment in Bootstrap ?"
},
{
"code": null,
"e": 4224,
"s": 4176,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4286,
"s": 4224,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4336,
"s": 4286,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4360,
"s": 4336,
"text": "REST API (Introduction)"
}
] |
Get current timestamp using Python
|
01 Aug, 2020
A timestamp is a sequence of characters or encoded information used to find when a particular event occurred, generally giving the date and time of the day, accurate to a small fraction of a second. In this article, we will learn how to Get current timestamp in Python.
There are different ways to get current timestamp in Python, We can use functions from modules time, datetime and calendar.
1. Using module time :The time module provides various time-related functions. The function time, return the time in seconds since the epoch as a floating point number. epoch is defined as the point where the time starts and is platform dependent.
Syntax: time.time()
Parameters: NA
Return: floating point number expressed in seconds.
# using time moduleimport time # ts stores the time in secondsts = time.time() # print the current timestampprint(ts)
Output:
1594819641.9622827
2. Using module datetime :The datetime module provides classes for manipulating dates and times.While date and time arithmetic is supported, the target of the implementation is on efficient attribute extraction for output formatting and manipulation. The function datetime.datetime.now which return number of seconds since the epoch.
Syntax: datetime.now()
Parameters: tz (time zone) which is optional.
Return: the current local date and time.
# using datetime moduleimport datetime; # ct stores current timect = datetime.datetime.now()print("current time:-", ct) # ts store timestamp of current timets = ct.timestamp()print("timestamp:-", ts)
Output:
current time:- 2020-07-15 14:30:26.159446
timestamp:- 1594823426.159446
3. Using module calendar :We can also get timestamp by combining multiple functions from multiple modules. In this we we’ll use function calendar.timegm to convert tuple representing current time.
Syntax: calendar.timegm(tuple)
Parameters: takes a time tuple such as returned by the gmtime() function in the time module.
Return: the corresponding Unix timestamp value.
# using calendar module# using time moduleimport calendar;import time; # gmt stores current gmtimegmt = time.gmtime()print("gmt:-", gmt) # ts stores timestampts = calendar.timegm(gmt)print("timestamp:-", ts)
Output:
gmt:- time.struct_time(tm_year=2020, tm_mon=7, tm_mday=15, tm_hour=19, tm_min=21, tm_sec=6, tm_wday=2, tm_yday=197, tm_isdst=0)timestamp:- 1594840866
Picked
Python Pandas-Timestamp
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 323,
"s": 53,
"text": "A timestamp is a sequence of characters or encoded information used to find when a particular event occurred, generally giving the date and time of the day, accurate to a small fraction of a second. In this article, we will learn how to Get current timestamp in Python."
},
{
"code": null,
"e": 447,
"s": 323,
"text": "There are different ways to get current timestamp in Python, We can use functions from modules time, datetime and calendar."
},
{
"code": null,
"e": 695,
"s": 447,
"text": "1. Using module time :The time module provides various time-related functions. The function time, return the time in seconds since the epoch as a floating point number. epoch is defined as the point where the time starts and is platform dependent."
},
{
"code": null,
"e": 782,
"s": 695,
"text": "Syntax: time.time()\nParameters: NA\nReturn: floating point number expressed in seconds."
},
{
"code": "# using time moduleimport time # ts stores the time in secondsts = time.time() # print the current timestampprint(ts)",
"e": 902,
"s": 782,
"text": null
},
{
"code": null,
"e": 910,
"s": 902,
"text": "Output:"
},
{
"code": null,
"e": 929,
"s": 910,
"text": "1594819641.9622827"
},
{
"code": null,
"e": 1264,
"s": 929,
"text": " 2. Using module datetime :The datetime module provides classes for manipulating dates and times.While date and time arithmetic is supported, the target of the implementation is on efficient attribute extraction for output formatting and manipulation. The function datetime.datetime.now which return number of seconds since the epoch."
},
{
"code": null,
"e": 1374,
"s": 1264,
"text": "Syntax: datetime.now()\nParameters: tz (time zone) which is optional.\nReturn: the current local date and time."
},
{
"code": "# using datetime moduleimport datetime; # ct stores current timect = datetime.datetime.now()print(\"current time:-\", ct) # ts store timestamp of current timets = ct.timestamp()print(\"timestamp:-\", ts)",
"e": 1576,
"s": 1374,
"text": null
},
{
"code": null,
"e": 1584,
"s": 1576,
"text": "Output:"
},
{
"code": null,
"e": 1656,
"s": 1584,
"text": "current time:- 2020-07-15 14:30:26.159446\ntimestamp:- 1594823426.159446"
},
{
"code": null,
"e": 1854,
"s": 1656,
"text": " 3. Using module calendar :We can also get timestamp by combining multiple functions from multiple modules. In this we we’ll use function calendar.timegm to convert tuple representing current time."
},
{
"code": null,
"e": 2026,
"s": 1854,
"text": "Syntax: calendar.timegm(tuple)\nParameters: takes a time tuple such as returned by the gmtime() function in the time module.\nReturn: the corresponding Unix timestamp value."
},
{
"code": "# using calendar module# using time moduleimport calendar;import time; # gmt stores current gmtimegmt = time.gmtime()print(\"gmt:-\", gmt) # ts stores timestampts = calendar.timegm(gmt)print(\"timestamp:-\", ts)",
"e": 2236,
"s": 2026,
"text": null
},
{
"code": null,
"e": 2244,
"s": 2236,
"text": "Output:"
},
{
"code": null,
"e": 2394,
"s": 2244,
"text": "gmt:- time.struct_time(tm_year=2020, tm_mon=7, tm_mday=15, tm_hour=19, tm_min=21, tm_sec=6, tm_wday=2, tm_yday=197, tm_isdst=0)timestamp:- 1594840866"
},
{
"code": null,
"e": 2401,
"s": 2394,
"text": "Picked"
},
{
"code": null,
"e": 2425,
"s": 2401,
"text": "Python Pandas-Timestamp"
},
{
"code": null,
"e": 2432,
"s": 2425,
"text": "Python"
}
] |
Python | NLP analysis of Restaurant reviews - GeeksforGeeks
|
02 Nov, 2021
Natural language processing (NLP) is an area of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to process and analyze large amounts of natural language data. It is the branch of machine learning which is about analyzing any text and handling predictive analysis.Scikit-learn is a free software machine learning library for the Python programming language. Scikit-learn is largely written in Python, with some core algorithms written in Cython to achieve performance. Cython is a superset of the Python programming language, designed to give C-like performance with code that is written mostly in Python.Let’s understand the various steps involved in text processing and the flow of NLP. This algorithm can be easily applied to any other kind of text like classify a book into Romance, Friction, but for now, let’s use a restaurant review dataset to review negative or positive feedback.
Step 1: Import dataset with setting delimiter as ‘\t’ as columns are separated as tab space. Reviews and their category(0 or 1) are not separated by any other symbol but with tab space as most of the other symbols are is the review (like $ for the price, ....!, etc) and the algorithm might use them as a delimiter, which will lead to strange behavior (like errors, weird output) in output.
Python3
# Importing Librariesimport numpy as np import pandas as pd # Import datasetdataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t')
To download the Restaurant_Reviews.tsv dataset used, click here.Step 2: Text Cleaning or Preprocessing
Remove Punctuations, Numbers: Punctuations, Numbers don’t help much in processing the given text, if included, they will just increase the size of a bag of words that we will create as the last step and decrease the efficiency of an algorithm.
Stemming: Take roots of the word
Convert each word into its lower case: For example, it is useless to have some words in different cases (eg ‘good’ and ‘GOOD’).
Python3
# library to clean dataimport re # Natural Language Tool Kitimport nltk nltk.download('stopwords') # to remove stopwordfrom nltk.corpus import stopwords # for Stemming proposefrom nltk.stem.porter import PorterStemmer # Initialize empty array# to append clean textcorpus = [] # 1000 (reviews) rows to cleanfor i in range(0, 1000): # column : "Review", row ith review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i]) # convert all cases to lower cases review = review.lower() # split to array(default delimiter is " ") review = review.split() # creating PorterStemmer object to # take main stem of each word ps = PorterStemmer() # loop for stemming each word # in string array at ith row review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))] # rejoin all string array elements # to create back into a string review = ' '.join(review) # append each string to create # array of clean text corpus.append(review)
Examples: Before and after applying above code (reviews = > before, corpus => after)
Step 3: Tokenization, involves splitting sentences and words from the body of the text.Step 4: Making the bag of words via sparse matrix
Take all the different words of reviews in the dataset without repeating of words.
One column for each word, therefore there is going to be many columns.
Rows are reviews
If a word is there in the row of a dataset of reviews, then the count of the word will be there in the row of a bag of words under the column of the word.
Examples: Let’s take a dataset of reviews of only two reviews
Input : "dam good steak", "good food good service"
Output :
For this purpose we need CountVectorizer class from sklearn.feature_extraction.text. We can also set a max number of features (max no. features which help the most via attribute “max_features”). Do the training on the corpus and then apply the same transformation to the corpus “.fit_transform(corpus)” and then convert it into an array. If the review is positive or negative that answer is in the second column of the dataset[:, 1]: all rows and 1st column (indexing from zero).
Python3
# Creating the Bag of Words modelfrom sklearn.feature_extraction.text import CountVectorizer # To extract max 1500 feature.# "max_features" is attribute to# experiment with to get better resultscv = CountVectorizer(max_features = 1500) # X contains corpus (dependent variable)X = cv.fit_transform(corpus).toarray() # y contains answers if review# is positive or negativey = dataset.iloc[:, 1].values
Description of the dataset to be used:
Columns separated by \t (tab space)
First column is about reviews of people
In second column, 0 is for negative review and 1 is for positive review
Step 5: Splitting Corpus into Training and Test set. For this, we need class train_test_split from sklearn.cross_validation. Split can be made 70/30 or 80/20 or 85/15 or 75/25, here I choose 75/25 via “test_size”. X is the bag of words, y is 0 or 1 (positive or negative).
Python3
# Splitting the dataset into# the Training set and Test setfrom sklearn.cross_validation import train_test_split # experiment with "test_size"# to get better resultsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
Step 6: Fitting a Predictive Model (here random forest)
Since Random forest is an ensemble model (made of many trees) from sklearn.ensemble, import RandomForestClassifier class
With 501 trees or “n_estimators” and criterion as ‘entropy’
Fit the model via .fit() method with attributes X_train and y_train
Python3
# Fitting Random Forest Classification# to the Training setfrom sklearn.ensemble import RandomForestClassifier # n_estimators can be said as number of# trees, experiment with n_estimators# to get better resultsmodel = RandomForestClassifier(n_estimators = 501, criterion = 'entropy') model.fit(X_train, y_train)
Step 7: Predicting Final Results via using .predict() method with attribute X_test
Python3
# Predicting the Test set resultsy_pred = model.predict(X_test) y_pred
Note: Accuracy with the random forest was 72%.(It may be different when performed an experiment with different test sizes, here = 0.25).Step 8: To know the accuracy, a confusion matrix is needed.Confusion Matrix is a 2X2 Matrix.
TRUE POSITIVE : measures the proportion of actual positives that are correctly identified. TRUE NEGATIVE : measures the proportion of actual positives that are not correctly identified. FALSE POSITIVE : measures the proportion of actual negatives that are correctly identified. FALSE NEGATIVE : measures the proportion of actual negatives that are not correctly identified.
Note: True or False refers to the assigned classification being Correct or Incorrect, while Positive or Negative refers to assignment to the Positive or the Negative Category
Python3
# Making the Confusion Matrixfrom sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) cm
shashank_v_ray
as5853535
sooda367
surinderdawra388
vaibhavsinghtanwar
clintra
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
System Design Tutorial
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
KDD Process in Data Mining
Clustering in Machine Learning
Agents in Artificial Intelligence
Search Algorithms in AI
Support Vector Machine Algorithm
Elbow Method for optimal value of k in KMeans
ML | Underfitting and Overfitting
|
[
{
"code": null,
"e": 24294,
"s": 24266,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 25300,
"s": 24294,
"text": "Natural language processing (NLP) is an area of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to process and analyze large amounts of natural language data. It is the branch of machine learning which is about analyzing any text and handling predictive analysis.Scikit-learn is a free software machine learning library for the Python programming language. Scikit-learn is largely written in Python, with some core algorithms written in Cython to achieve performance. Cython is a superset of the Python programming language, designed to give C-like performance with code that is written mostly in Python.Let’s understand the various steps involved in text processing and the flow of NLP. This algorithm can be easily applied to any other kind of text like classify a book into Romance, Friction, but for now, let’s use a restaurant review dataset to review negative or positive feedback. "
},
{
"code": null,
"e": 25693,
"s": 25300,
"text": "Step 1: Import dataset with setting delimiter as ‘\\t’ as columns are separated as tab space. Reviews and their category(0 or 1) are not separated by any other symbol but with tab space as most of the other symbols are is the review (like $ for the price, ....!, etc) and the algorithm might use them as a delimiter, which will lead to strange behavior (like errors, weird output) in output. "
},
{
"code": null,
"e": 25701,
"s": 25693,
"text": "Python3"
},
{
"code": "# Importing Librariesimport numpy as np import pandas as pd # Import datasetdataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\\t')",
"e": 25843,
"s": 25701,
"text": null
},
{
"code": null,
"e": 25948,
"s": 25843,
"text": "To download the Restaurant_Reviews.tsv dataset used, click here.Step 2: Text Cleaning or Preprocessing "
},
{
"code": null,
"e": 26192,
"s": 25948,
"text": "Remove Punctuations, Numbers: Punctuations, Numbers don’t help much in processing the given text, if included, they will just increase the size of a bag of words that we will create as the last step and decrease the efficiency of an algorithm."
},
{
"code": null,
"e": 26227,
"s": 26192,
"text": "Stemming: Take roots of the word "
},
{
"code": null,
"e": 26355,
"s": 26227,
"text": "Convert each word into its lower case: For example, it is useless to have some words in different cases (eg ‘good’ and ‘GOOD’)."
},
{
"code": null,
"e": 26365,
"s": 26357,
"text": "Python3"
},
{
"code": "# library to clean dataimport re # Natural Language Tool Kitimport nltk nltk.download('stopwords') # to remove stopwordfrom nltk.corpus import stopwords # for Stemming proposefrom nltk.stem.porter import PorterStemmer # Initialize empty array# to append clean textcorpus = [] # 1000 (reviews) rows to cleanfor i in range(0, 1000): # column : \"Review\", row ith review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i]) # convert all cases to lower cases review = review.lower() # split to array(default delimiter is \" \") review = review.split() # creating PorterStemmer object to # take main stem of each word ps = PorterStemmer() # loop for stemming each word # in string array at ith row review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))] # rejoin all string array elements # to create back into a string review = ' '.join(review) # append each string to create # array of clean text corpus.append(review)",
"e": 27430,
"s": 26365,
"text": null
},
{
"code": null,
"e": 27516,
"s": 27430,
"text": "Examples: Before and after applying above code (reviews = > before, corpus => after) "
},
{
"code": null,
"e": 27654,
"s": 27516,
"text": "Step 3: Tokenization, involves splitting sentences and words from the body of the text.Step 4: Making the bag of words via sparse matrix "
},
{
"code": null,
"e": 27737,
"s": 27654,
"text": "Take all the different words of reviews in the dataset without repeating of words."
},
{
"code": null,
"e": 27808,
"s": 27737,
"text": "One column for each word, therefore there is going to be many columns."
},
{
"code": null,
"e": 27825,
"s": 27808,
"text": "Rows are reviews"
},
{
"code": null,
"e": 27980,
"s": 27825,
"text": "If a word is there in the row of a dataset of reviews, then the count of the word will be there in the row of a bag of words under the column of the word."
},
{
"code": null,
"e": 28044,
"s": 27980,
"text": "Examples: Let’s take a dataset of reviews of only two reviews "
},
{
"code": null,
"e": 28106,
"s": 28044,
"text": "Input : \"dam good steak\", \"good food good service\"\nOutput :\n "
},
{
"code": null,
"e": 28589,
"s": 28108,
"text": "For this purpose we need CountVectorizer class from sklearn.feature_extraction.text. We can also set a max number of features (max no. features which help the most via attribute “max_features”). Do the training on the corpus and then apply the same transformation to the corpus “.fit_transform(corpus)” and then convert it into an array. If the review is positive or negative that answer is in the second column of the dataset[:, 1]: all rows and 1st column (indexing from zero). "
},
{
"code": null,
"e": 28597,
"s": 28589,
"text": "Python3"
},
{
"code": "# Creating the Bag of Words modelfrom sklearn.feature_extraction.text import CountVectorizer # To extract max 1500 feature.# \"max_features\" is attribute to# experiment with to get better resultscv = CountVectorizer(max_features = 1500) # X contains corpus (dependent variable)X = cv.fit_transform(corpus).toarray() # y contains answers if review# is positive or negativey = dataset.iloc[:, 1].values",
"e": 28997,
"s": 28597,
"text": null
},
{
"code": null,
"e": 29037,
"s": 28997,
"text": "Description of the dataset to be used: "
},
{
"code": null,
"e": 29073,
"s": 29037,
"text": "Columns separated by \\t (tab space)"
},
{
"code": null,
"e": 29113,
"s": 29073,
"text": "First column is about reviews of people"
},
{
"code": null,
"e": 29185,
"s": 29113,
"text": "In second column, 0 is for negative review and 1 is for positive review"
},
{
"code": null,
"e": 29459,
"s": 29185,
"text": "Step 5: Splitting Corpus into Training and Test set. For this, we need class train_test_split from sklearn.cross_validation. Split can be made 70/30 or 80/20 or 85/15 or 75/25, here I choose 75/25 via “test_size”. X is the bag of words, y is 0 or 1 (positive or negative). "
},
{
"code": null,
"e": 29467,
"s": 29459,
"text": "Python3"
},
{
"code": "# Splitting the dataset into# the Training set and Test setfrom sklearn.cross_validation import train_test_split # experiment with \"test_size\"# to get better resultsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)",
"e": 29708,
"s": 29467,
"text": null
},
{
"code": null,
"e": 29766,
"s": 29708,
"text": "Step 6: Fitting a Predictive Model (here random forest) "
},
{
"code": null,
"e": 29887,
"s": 29766,
"text": "Since Random forest is an ensemble model (made of many trees) from sklearn.ensemble, import RandomForestClassifier class"
},
{
"code": null,
"e": 29947,
"s": 29887,
"text": "With 501 trees or “n_estimators” and criterion as ‘entropy’"
},
{
"code": null,
"e": 30015,
"s": 29947,
"text": "Fit the model via .fit() method with attributes X_train and y_train"
},
{
"code": null,
"e": 30025,
"s": 30017,
"text": "Python3"
},
{
"code": "# Fitting Random Forest Classification# to the Training setfrom sklearn.ensemble import RandomForestClassifier # n_estimators can be said as number of# trees, experiment with n_estimators# to get better resultsmodel = RandomForestClassifier(n_estimators = 501, criterion = 'entropy') model.fit(X_train, y_train)",
"e": 30392,
"s": 30025,
"text": null
},
{
"code": null,
"e": 30477,
"s": 30392,
"text": "Step 7: Predicting Final Results via using .predict() method with attribute X_test "
},
{
"code": null,
"e": 30485,
"s": 30477,
"text": "Python3"
},
{
"code": "# Predicting the Test set resultsy_pred = model.predict(X_test) y_pred",
"e": 30556,
"s": 30485,
"text": null
},
{
"code": null,
"e": 30786,
"s": 30556,
"text": "Note: Accuracy with the random forest was 72%.(It may be different when performed an experiment with different test sizes, here = 0.25).Step 8: To know the accuracy, a confusion matrix is needed.Confusion Matrix is a 2X2 Matrix. "
},
{
"code": null,
"e": 31160,
"s": 30786,
"text": "TRUE POSITIVE : measures the proportion of actual positives that are correctly identified. TRUE NEGATIVE : measures the proportion of actual positives that are not correctly identified. FALSE POSITIVE : measures the proportion of actual negatives that are correctly identified. FALSE NEGATIVE : measures the proportion of actual negatives that are not correctly identified."
},
{
"code": null,
"e": 31337,
"s": 31160,
"text": "Note: True or False refers to the assigned classification being Correct or Incorrect, while Positive or Negative refers to assignment to the Positive or the Negative Category "
},
{
"code": null,
"e": 31347,
"s": 31339,
"text": "Python3"
},
{
"code": "# Making the Confusion Matrixfrom sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) cm",
"e": 31462,
"s": 31347,
"text": null
},
{
"code": null,
"e": 31477,
"s": 31462,
"text": "shashank_v_ray"
},
{
"code": null,
"e": 31487,
"s": 31477,
"text": "as5853535"
},
{
"code": null,
"e": 31496,
"s": 31487,
"text": "sooda367"
},
{
"code": null,
"e": 31513,
"s": 31496,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31532,
"s": 31513,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 31540,
"s": 31532,
"text": "clintra"
},
{
"code": null,
"e": 31566,
"s": 31540,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 31583,
"s": 31566,
"text": "Machine Learning"
},
{
"code": null,
"e": 31590,
"s": 31583,
"text": "Python"
},
{
"code": null,
"e": 31607,
"s": 31590,
"text": "Machine Learning"
},
{
"code": null,
"e": 31705,
"s": 31607,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31714,
"s": 31705,
"text": "Comments"
},
{
"code": null,
"e": 31727,
"s": 31714,
"text": "Old Comments"
},
{
"code": null,
"e": 31750,
"s": 31727,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 31794,
"s": 31750,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 31828,
"s": 31794,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 31855,
"s": 31828,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 31886,
"s": 31855,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 31920,
"s": 31886,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 31944,
"s": 31920,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 31977,
"s": 31944,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 32023,
"s": 31977,
"text": "Elbow Method for optimal value of k in KMeans"
}
] |
JavaScript: Balancing parentheses
|
Given a string that consists of only two types of characters: "(" and ")". We are required to write a function that takes in one such string and balances the parentheses by inserting either a "(" or a ")" as many times as necessary.
The function should then return the minimum number of insertions made in the string to balance it. For example −
If the string is −
const str = '()))';
Then the output should be 2, because by prepending '((', we can balance the string.
Following is the code −
const str = '()))';
const balanceParanthesis = str => {
let paren = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === "(") {
paren.push(str[i]);
} else if (str[i] === ")") {
if (paren[paren.length - 1] === "("){
paren.pop();
}else {
paren.push("#");
};
};
}
return paren.length;
}
console.log(balanceParanthesis(str));
This will produce the following output on console −
2
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "Given a string that consists of only two types of characters: \"(\" and \")\". We are required to write a function that takes in one such string and balances the parentheses by inserting either a \"(\" or a \")\" as many times as necessary."
},
{
"code": null,
"e": 1408,
"s": 1295,
"text": "The function should then return the minimum number of insertions made in the string to balance it. For example −"
},
{
"code": null,
"e": 1427,
"s": 1408,
"text": "If the string is −"
},
{
"code": null,
"e": 1447,
"s": 1427,
"text": "const str = '()))';"
},
{
"code": null,
"e": 1531,
"s": 1447,
"text": "Then the output should be 2, because by prepending '((', we can balance the string."
},
{
"code": null,
"e": 1555,
"s": 1531,
"text": "Following is the code −"
},
{
"code": null,
"e": 1972,
"s": 1555,
"text": "const str = '()))';\nconst balanceParanthesis = str => {\n let paren = [];\n for (let i = 0; i < str.length; i++) {\n if (str[i] === \"(\") {\n paren.push(str[i]);\n } else if (str[i] === \")\") {\n if (paren[paren.length - 1] === \"(\"){\n paren.pop();\n }else {\n paren.push(\"#\");\n };\n };\n }\n return paren.length;\n}\nconsole.log(balanceParanthesis(str));"
},
{
"code": null,
"e": 2024,
"s": 1972,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 2026,
"s": 2024,
"text": "2"
}
] |
Design HashSet in Python
|
Suppose we want to design a HashSet data structure without using any built-in hash table
libraries. There will be different functions like −
add(x) − Inserts a value x into the HashSet.
contains(x) − Checks whether the value x is present in the HashSet or not.
remove(x) − Removes x from the HashSet. In case the value does not exist in the HashSet, do nothing.
So, to test it Initialize the hash set, then call add(1), add(3), contains(1), contains(2), add(2), contains(2), remove(2), contains(2)., then the output will be true (1 is present), false (2 is not present), true (2 is present), false (2 is not present) respectively.
To solve this, we will follow these steps −
Define one data structure called Bucket, Initialize it like below
bucket := a new list
Define a function update(). This will take key
found := False
for each index i and key k in bucket, doif key is same as k, thenbucket[i]:= keyfound:= Truecome out from the loopif found false, theninsert key at the end of bucket
if key is same as k, thenbucket[i]:= keyfound:= Truecome out from the loop
bucket[i]:= key
found:= True
come out from the loop
if found false, theninsert key at the end of bucket
insert key at the end of bucket
Define a function get() . This will take keyfor each k in bucket, doif k is same as key, thenreturn Truereturn False
for each k in bucket, doif k is same as key, thenreturn Truereturn False
if k is same as key, thenreturn True
return True
return False
Define a function remove(). This will take keyfor each index i and key k in bucket, doif key is same as k, thendelete bucket[i]
for each index i and key k in bucket, doif key is same as k, thendelete bucket[i]
if key is same as k, thendelete bucket[i]
delete bucket[i]
Now create custom hashSet. There will be few methods as follows
Initialize this as follows −
key_space := 2096
hash_table:= a list of bucket type object of size key_space
Define a function add(). This will take keyhash_key:= key mod key_spacecall update(key) of hash_table[hash_key]
hash_key:= key mod key_space
call update(key) of hash_table[hash_key]
Define a function remove(). This will take keyhash_key:= keymodkey_spacedelete key from hash_table[hash_key]
hash_key:= keymodkey_space
delete key from hash_table[hash_key]
Define a function contains(). This will take keyhash_key:= keymodkey_spacereturn get(key) of hash_table[hash_key]
hash_key:= keymodkey_space
return get(key) of hash_table[hash_key]
Let us see the following implementation to get better understanding −
Live Demo
class Bucket:
def __init__(self):
self.bucket=[]
def update(self, key):
found=False
for i,k in enumerate(self.bucket):
if key==k:
self.bucket[i]=key
found=True
break
if not found:
self.bucket.append(key)
def get(self, key):
for k in self.bucket:
if k==key:
return True
return False
def remove(self, key):
for i,k in enumerate(self.bucket):
if key==k:
del self.bucket[i]
class MyHashSet:
def __init__(self):
self.key_space = 2096
self.hash_table=[Bucket() for i in range(self.key_space)]
def add(self, key):
hash_key=key%self.key_space
self.hash_table[hash_key].update(key)
def remove(self, key):
hash_key=key%self.key_space
self.hash_table[hash_key].remove(key)
def contains(self, key):
hash_key=key%self.key_space
return self.hash_table[hash_key].get(key)
ob = MyHashSet()
ob.add(1)
ob.add(3)
print(ob.contains(1))
print(ob.contains(2))
ob.add(2)
print(ob.contains(2))
ob.remove(2)
print(ob.contains(2))
ob = MyHashSet()
ob.add(1)
ob.add(3)
print(ob.contains(1))
print(ob.contains(2))
ob.add(2)
print(ob.contains(2))
ob.remove(2)
print(ob.contains(2))
True
False
True
False
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "Suppose we want to design a HashSet data structure without using any built-in hash table\nlibraries. There will be different functions like −"
},
{
"code": null,
"e": 1248,
"s": 1203,
"text": "add(x) − Inserts a value x into the HashSet."
},
{
"code": null,
"e": 1323,
"s": 1248,
"text": "contains(x) − Checks whether the value x is present in the HashSet or not."
},
{
"code": null,
"e": 1424,
"s": 1323,
"text": "remove(x) − Removes x from the HashSet. In case the value does not exist in the HashSet, do nothing."
},
{
"code": null,
"e": 1693,
"s": 1424,
"text": "So, to test it Initialize the hash set, then call add(1), add(3), contains(1), contains(2), add(2), contains(2), remove(2), contains(2)., then the output will be true (1 is present), false (2 is not present), true (2 is present), false (2 is not present) respectively."
},
{
"code": null,
"e": 1737,
"s": 1693,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1803,
"s": 1737,
"text": "Define one data structure called Bucket, Initialize it like below"
},
{
"code": null,
"e": 1824,
"s": 1803,
"text": "bucket := a new list"
},
{
"code": null,
"e": 1871,
"s": 1824,
"text": "Define a function update(). This will take key"
},
{
"code": null,
"e": 1886,
"s": 1871,
"text": "found := False"
},
{
"code": null,
"e": 2052,
"s": 1886,
"text": "for each index i and key k in bucket, doif key is same as k, thenbucket[i]:= keyfound:= Truecome out from the loopif found false, theninsert key at the end of bucket"
},
{
"code": null,
"e": 2127,
"s": 2052,
"text": "if key is same as k, thenbucket[i]:= keyfound:= Truecome out from the loop"
},
{
"code": null,
"e": 2143,
"s": 2127,
"text": "bucket[i]:= key"
},
{
"code": null,
"e": 2156,
"s": 2143,
"text": "found:= True"
},
{
"code": null,
"e": 2179,
"s": 2156,
"text": "come out from the loop"
},
{
"code": null,
"e": 2231,
"s": 2179,
"text": "if found false, theninsert key at the end of bucket"
},
{
"code": null,
"e": 2263,
"s": 2231,
"text": "insert key at the end of bucket"
},
{
"code": null,
"e": 2380,
"s": 2263,
"text": "Define a function get() . This will take keyfor each k in bucket, doif k is same as key, thenreturn Truereturn False"
},
{
"code": null,
"e": 2453,
"s": 2380,
"text": "for each k in bucket, doif k is same as key, thenreturn Truereturn False"
},
{
"code": null,
"e": 2490,
"s": 2453,
"text": "if k is same as key, thenreturn True"
},
{
"code": null,
"e": 2502,
"s": 2490,
"text": "return True"
},
{
"code": null,
"e": 2515,
"s": 2502,
"text": "return False"
},
{
"code": null,
"e": 2643,
"s": 2515,
"text": "Define a function remove(). This will take keyfor each index i and key k in bucket, doif key is same as k, thendelete bucket[i]"
},
{
"code": null,
"e": 2725,
"s": 2643,
"text": "for each index i and key k in bucket, doif key is same as k, thendelete bucket[i]"
},
{
"code": null,
"e": 2767,
"s": 2725,
"text": "if key is same as k, thendelete bucket[i]"
},
{
"code": null,
"e": 2784,
"s": 2767,
"text": "delete bucket[i]"
},
{
"code": null,
"e": 2848,
"s": 2784,
"text": "Now create custom hashSet. There will be few methods as follows"
},
{
"code": null,
"e": 2877,
"s": 2848,
"text": "Initialize this as follows −"
},
{
"code": null,
"e": 2895,
"s": 2877,
"text": "key_space := 2096"
},
{
"code": null,
"e": 2955,
"s": 2895,
"text": "hash_table:= a list of bucket type object of size key_space"
},
{
"code": null,
"e": 3067,
"s": 2955,
"text": "Define a function add(). This will take keyhash_key:= key mod key_spacecall update(key) of hash_table[hash_key]"
},
{
"code": null,
"e": 3096,
"s": 3067,
"text": "hash_key:= key mod key_space"
},
{
"code": null,
"e": 3137,
"s": 3096,
"text": "call update(key) of hash_table[hash_key]"
},
{
"code": null,
"e": 3246,
"s": 3137,
"text": "Define a function remove(). This will take keyhash_key:= keymodkey_spacedelete key from hash_table[hash_key]"
},
{
"code": null,
"e": 3273,
"s": 3246,
"text": "hash_key:= keymodkey_space"
},
{
"code": null,
"e": 3310,
"s": 3273,
"text": "delete key from hash_table[hash_key]"
},
{
"code": null,
"e": 3424,
"s": 3310,
"text": "Define a function contains(). This will take keyhash_key:= keymodkey_spacereturn get(key) of hash_table[hash_key]"
},
{
"code": null,
"e": 3451,
"s": 3424,
"text": "hash_key:= keymodkey_space"
},
{
"code": null,
"e": 3491,
"s": 3451,
"text": "return get(key) of hash_table[hash_key]"
},
{
"code": null,
"e": 3561,
"s": 3491,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3572,
"s": 3561,
"text": " Live Demo"
},
{
"code": null,
"e": 4687,
"s": 3572,
"text": "class Bucket:\n def __init__(self):\n self.bucket=[]\n def update(self, key):\n found=False\n for i,k in enumerate(self.bucket):\n if key==k:\n self.bucket[i]=key\n found=True\n break\n if not found:\n self.bucket.append(key)\n def get(self, key):\n for k in self.bucket:\n if k==key:\n return True\n return False\n def remove(self, key):\n for i,k in enumerate(self.bucket):\n if key==k:\n del self.bucket[i]\nclass MyHashSet:\n def __init__(self):\n self.key_space = 2096\n self.hash_table=[Bucket() for i in range(self.key_space)]\n def add(self, key):\n hash_key=key%self.key_space\n self.hash_table[hash_key].update(key)\n def remove(self, key):\n hash_key=key%self.key_space\n self.hash_table[hash_key].remove(key)\n def contains(self, key):\n hash_key=key%self.key_space\n return self.hash_table[hash_key].get(key)\nob = MyHashSet()\nob.add(1)\nob.add(3)\nprint(ob.contains(1))\nprint(ob.contains(2))\nob.add(2)\nprint(ob.contains(2))\nob.remove(2)\nprint(ob.contains(2))"
},
{
"code": null,
"e": 4835,
"s": 4687,
"text": "ob = MyHashSet()\nob.add(1)\nob.add(3)\nprint(ob.contains(1))\nprint(ob.contains(2))\nob.add(2)\nprint(ob.contains(2))\nob.remove(2)\nprint(ob.contains(2))"
},
{
"code": null,
"e": 4857,
"s": 4835,
"text": "True\nFalse\nTrue\nFalse"
}
] |
Django - Template System
|
Django makes it possible to separate python and HTML, the python goes in views and HTML goes in templates. To link the two, Django relies on the render function and the Django Template language.
This function takes three parameters −
Request − The initial request.
Request − The initial request.
The path to the template − This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables.
The path to the template − This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables.
Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view.
Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view.
Django’s template engine offers a mini-language to define the user-facing layer of the application.
A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view in the third parameter of the render function. Let's change our hello.html to display today’s date −
hello.html
<html>
<body>
Hello World!!!<p>Today is {{today}}</p>
</body>
</html>
Then our view will change to −
def hello(request):
today = datetime.datetime.now().date()
return render(request, "hello.html", {"today" : today})
We will now get the following output after accessing the URL/myapp/hello −
Hello World!!!
Today is Sept. 11, 2015
As you have probably noticed, if the variable is not a string, Django will use the __str__ method to display it; and with the same principle you can access an object attribute just like you do it in Python. For example: if we wanted to display the date year, my variable would be: {{today.year}}.
They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}.
Some examples −
{{string|truncatewords:80}} − This filter will truncate the string, so you will see only the first 80 words.
{{string|truncatewords:80}} − This filter will truncate the string, so you will see only the first 80 words.
{{string|lower}} − Converts the string to lowercase.
{{string|lower}} − Converts the string to lowercase.
{{string|escape|linebreaks}} − Escapes string contents, then converts line breaks to tags.
{{string|escape|linebreaks}} − Escapes string contents, then converts line breaks to tags.
You can also set the default for a variable.
Tags lets you perform the following operations: if condition, for loop, template inheritance and more.
Just like in Python you can use if, else and elif in your template −
<html>
<body>
Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}
the first day of month.
{% elif today.day == 30 %}
the last day of month.
{% else %}
I don't know.
{%endif%}
</body>
</html>
In this new template, depending on the date of the day, the template will render a certain value.
Just like 'if', we have the 'for' tag, that works exactly like in Python. Let's change our hello view to transmit a list to our template −
def hello(request):
today = datetime.datetime.now().date()
daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})
The template to display that list using {{ for }} −
<html>
<body>
Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}
the first day of month.
{% elif today.day == 30 %}
the last day of month.
{% else %}
I don't know.
{%endif%}
<p>
{% for day in days_of_week %}
{{day}}
</p>
{% endfor %}
</body>
</html>
And we should get something like −
Hello World!!!
Today is Sept. 11, 2015
We are I don't know.
Mon
Tue
Wed
Thu
Fri
Sat
Sun
A template system cannot be complete without template inheritance. Meaning when you are designing your templates, you should have a main template with holes that the child's template will fill according to his own need, like a page might need a special css for the selected tab.
Let’s change the hello.html template to inherit from a main_template.html.
main_template.html
<html>
<head>
<title>
{% block title %}Page Title{% endblock %}
</title>
</head>
<body>
{% block content %}
Body content
{% endblock %}
</body>
</html>
hello.html
{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% block content %}
Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}
the first day of month.
{% elif today.day == 30 %}
the last day of month.
{% else %}
I don't know.
{%endif%}
<p>
{% for day in days_of_week %}
{{day}}
</p>
{% endfor %}
{% endblock %}
In the above example, on calling /myapp/hello we will still get the same result as before but now we rely on extends and block to refactor our code −
In the main_template.html we define blocks using the tag block. The title block will contain the page title and the content block will have the page main content. In home.html we use extends to inherit from the main_template.html then we fill the block define above (content and title).
The comment tag helps to define comments into templates, not HTML comments, they won’t appear in HTML page. It can be useful for documentation or just commenting a line of code.
39 Lectures
3.5 hours
John Elder
36 Lectures
2.5 hours
John Elder
28 Lectures
2 hours
John Elder
20 Lectures
1 hours
John Elder
35 Lectures
3 hours
John Elder
79 Lectures
10 hours
Rathan Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2240,
"s": 2045,
"text": "Django makes it possible to separate python and HTML, the python goes in views and HTML goes in templates. To link the two, Django relies on the render function and the Django Template language."
},
{
"code": null,
"e": 2279,
"s": 2240,
"text": "This function takes three parameters −"
},
{
"code": null,
"e": 2310,
"s": 2279,
"text": "Request − The initial request."
},
{
"code": null,
"e": 2341,
"s": 2310,
"text": "Request − The initial request."
},
{
"code": null,
"e": 2460,
"s": 2341,
"text": "The path to the template − This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables."
},
{
"code": null,
"e": 2579,
"s": 2460,
"text": "The path to the template − This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables."
},
{
"code": null,
"e": 2773,
"s": 2579,
"text": "Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view."
},
{
"code": null,
"e": 2967,
"s": 2773,
"text": "Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view."
},
{
"code": null,
"e": 3067,
"s": 2967,
"text": "Django’s template engine offers a mini-language to define the user-facing layer of the application."
},
{
"code": null,
"e": 3278,
"s": 3067,
"text": "A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view in the third parameter of the render function. Let's change our hello.html to display today’s date −"
},
{
"code": null,
"e": 3289,
"s": 3278,
"text": "hello.html"
},
{
"code": null,
"e": 3379,
"s": 3289,
"text": "<html>\n \n <body>\n Hello World!!!<p>Today is {{today}}</p>\n </body>\n \n</html>"
},
{
"code": null,
"e": 3410,
"s": 3379,
"text": "Then our view will change to −"
},
{
"code": null,
"e": 3531,
"s": 3410,
"text": "def hello(request):\n today = datetime.datetime.now().date()\n return render(request, \"hello.html\", {\"today\" : today})"
},
{
"code": null,
"e": 3606,
"s": 3531,
"text": "We will now get the following output after accessing the URL/myapp/hello −"
},
{
"code": null,
"e": 3646,
"s": 3606,
"text": "Hello World!!!\nToday is Sept. 11, 2015\n"
},
{
"code": null,
"e": 3943,
"s": 3646,
"text": "As you have probably noticed, if the variable is not a string, Django will use the __str__ method to display it; and with the same principle you can access an object attribute just like you do it in Python. For example: if we wanted to display the date year, my variable would be: {{today.year}}."
},
{
"code": null,
"e": 4052,
"s": 3943,
"text": "They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}."
},
{
"code": null,
"e": 4068,
"s": 4052,
"text": "Some examples −"
},
{
"code": null,
"e": 4177,
"s": 4068,
"text": "{{string|truncatewords:80}} − This filter will truncate the string, so you will see only the first 80 words."
},
{
"code": null,
"e": 4286,
"s": 4177,
"text": "{{string|truncatewords:80}} − This filter will truncate the string, so you will see only the first 80 words."
},
{
"code": null,
"e": 4339,
"s": 4286,
"text": "{{string|lower}} − Converts the string to lowercase."
},
{
"code": null,
"e": 4392,
"s": 4339,
"text": "{{string|lower}} − Converts the string to lowercase."
},
{
"code": null,
"e": 4483,
"s": 4392,
"text": "{{string|escape|linebreaks}} − Escapes string contents, then converts line breaks to tags."
},
{
"code": null,
"e": 4574,
"s": 4483,
"text": "{{string|escape|linebreaks}} − Escapes string contents, then converts line breaks to tags."
},
{
"code": null,
"e": 4619,
"s": 4574,
"text": "You can also set the default for a variable."
},
{
"code": null,
"e": 4722,
"s": 4619,
"text": "Tags lets you perform the following operations: if condition, for loop, template inheritance and more."
},
{
"code": null,
"e": 4791,
"s": 4722,
"text": "Just like in Python you can use if, else and elif in your template −"
},
{
"code": null,
"e": 5093,
"s": 4791,
"text": "<html>\n <body>\n \n Hello World!!!<p>Today is {{today}}</p>\n We are\n {% if today.day == 1 %}\n \n the first day of month.\n {% elif today.day == 30 %}\n \n the last day of month.\n {% else %}\n \n I don't know.\n {%endif%}\n \n </body>\n</html>"
},
{
"code": null,
"e": 5191,
"s": 5093,
"text": "In this new template, depending on the date of the day, the template will render a certain value."
},
{
"code": null,
"e": 5330,
"s": 5191,
"text": "Just like 'if', we have the 'for' tag, that works exactly like in Python. Let's change our hello view to transmit a list to our template −"
},
{
"code": null,
"e": 5550,
"s": 5330,
"text": "def hello(request):\n today = datetime.datetime.now().date()\n \n daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n return render(request, \"hello.html\", {\"today\" : today, \"days_of_week\" : daysOfWeek})"
},
{
"code": null,
"e": 5602,
"s": 5550,
"text": "The template to display that list using {{ for }} −"
},
{
"code": null,
"e": 6013,
"s": 5602,
"text": "<html>\n <body>\n \n Hello World!!!<p>Today is {{today}}</p>\n We are\n {% if today.day == 1 %}\n \n the first day of month.\n {% elif today.day == 30 %}\n \n the last day of month.\n {% else %}\n \n I don't know.\n {%endif%}\n \n <p>\n {% for day in days_of_week %}\n {{day}}\n </p>\n\t\t\n {% endfor %}\n \n </body>\n</html>"
},
{
"code": null,
"e": 6048,
"s": 6013,
"text": "And we should get something like −"
},
{
"code": null,
"e": 6137,
"s": 6048,
"text": "Hello World!!!\nToday is Sept. 11, 2015\nWe are I don't know.\nMon\nTue\nWed\nThu\nFri\nSat\nSun\n"
},
{
"code": null,
"e": 6416,
"s": 6137,
"text": "A template system cannot be complete without template inheritance. Meaning when you are designing your templates, you should have a main template with holes that the child's template will fill according to his own need, like a page might need a special css for the selected tab."
},
{
"code": null,
"e": 6491,
"s": 6416,
"text": "Let’s change the hello.html template to inherit from a main_template.html."
},
{
"code": null,
"e": 6510,
"s": 6491,
"text": "main_template.html"
},
{
"code": null,
"e": 6743,
"s": 6510,
"text": "<html>\n <head>\n \n <title>\n {% block title %}Page Title{% endblock %}\n </title>\n \n </head>\n\t\n <body>\n \n {% block content %}\n Body content\n {% endblock %}\n \n </body>\n</html>"
},
{
"code": null,
"e": 6754,
"s": 6743,
"text": "hello.html"
},
{
"code": null,
"e": 7121,
"s": 6754,
"text": "{% extends \"main_template.html\" %}\n{% block title %}My Hello Page{% endblock %}\n{% block content %}\n\nHello World!!!<p>Today is {{today}}</p>\nWe are\n{% if today.day == 1 %}\n\nthe first day of month.\n{% elif today.day == 30 %}\n\nthe last day of month.\n{% else %}\n\nI don't know.\n{%endif%}\n\n<p>\n {% for day in days_of_week %}\n {{day}}\n</p>\n\n{% endfor %}\n{% endblock %}"
},
{
"code": null,
"e": 7271,
"s": 7121,
"text": "In the above example, on calling /myapp/hello we will still get the same result as before but now we rely on extends and block to refactor our code −"
},
{
"code": null,
"e": 7558,
"s": 7271,
"text": "In the main_template.html we define blocks using the tag block. The title block will contain the page title and the content block will have the page main content. In home.html we use extends to inherit from the main_template.html then we fill the block define above (content and title)."
},
{
"code": null,
"e": 7736,
"s": 7558,
"text": "The comment tag helps to define comments into templates, not HTML comments, they won’t appear in HTML page. It can be useful for documentation or just commenting a line of code."
},
{
"code": null,
"e": 7771,
"s": 7736,
"text": "\n 39 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7783,
"s": 7771,
"text": " John Elder"
},
{
"code": null,
"e": 7818,
"s": 7783,
"text": "\n 36 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7830,
"s": 7818,
"text": " John Elder"
},
{
"code": null,
"e": 7863,
"s": 7830,
"text": "\n 28 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7875,
"s": 7863,
"text": " John Elder"
},
{
"code": null,
"e": 7908,
"s": 7875,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7920,
"s": 7908,
"text": " John Elder"
},
{
"code": null,
"e": 7953,
"s": 7920,
"text": "\n 35 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7965,
"s": 7953,
"text": " John Elder"
},
{
"code": null,
"e": 7999,
"s": 7965,
"text": "\n 79 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 8013,
"s": 7999,
"text": " Rathan Kumar"
},
{
"code": null,
"e": 8020,
"s": 8013,
"text": " Print"
},
{
"code": null,
"e": 8031,
"s": 8020,
"text": " Add Notes"
}
] |
CSS Selectors
|
A CSS selector selects the HTML element(s) you
want to style.
CSS selectors are used to "find" (or select) the HTML elements you
want to style.
We can divide CSS selectors into five categories:
Simple selectors (select elements based on name, id, class)
Combinator selectors (select
elements based on a specific relationship between them)
Pseudo-class selectors (select elements based on a certain state)
Pseudo-elements selectors (select
and style a part of an element)
Attribute selectors (select elements based on
an attribute or attribute value)
This page will explain the most basic CSS selectors.
The element selector selects HTML elements based on the element name.
Here, all <p> elements on the page will be
center-aligned, with a red text color:
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is
used to
select one unique element!
To select an element with a specific id, write a hash (#) character, followed by
the id of the element.
The CSS rule below will be applied to the HTML element with id="para1":
Note: An id name cannot start with a number!
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the
class name.
In this example all HTML elements with class="center" will be red and center-aligned:
You can also specify that only specific HTML elements should be affected by a class.
In this example only <p> elements with class="center" will be
red and center-aligned:
HTML elements
can also refer to more than one class.
In this example the <p> element will be styled according to class="center"
and to class="large":
Note: A class name cannot start with a number!
The universal selector (*) selects all HTML
elements on the page.
The CSS rule below will affect every HTML element on the page:
The grouping selector selects all the HTML elements with the same style
definitions.
Look at the following CSS code (the h1, h2, and p elements have the same
style definitions):
It will be better to group the selectors, to minimize the code.
To group selectors, separate each selector with a comma.
In this example we have grouped the selectors from the code above:
Set the color of all <p> elements to red.
<style>
{
red;
}
</style>
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 63,
"s": 0,
"text": "A CSS selector selects the HTML element(s) you \nwant to style."
},
{
"code": null,
"e": 146,
"s": 63,
"text": "CSS selectors are used to \"find\" (or select) the HTML elements you \nwant to style."
},
{
"code": null,
"e": 196,
"s": 146,
"text": "We can divide CSS selectors into five categories:"
},
{
"code": null,
"e": 256,
"s": 196,
"text": "Simple selectors (select elements based on name, id, class)"
},
{
"code": null,
"e": 345,
"s": 256,
"text": "Combinator selectors (select \n elements based on a specific relationship between them)"
},
{
"code": null,
"e": 411,
"s": 345,
"text": "Pseudo-class selectors (select elements based on a certain state)"
},
{
"code": null,
"e": 480,
"s": 411,
"text": "Pseudo-elements selectors (select \n and style a part of an element)"
},
{
"code": null,
"e": 562,
"s": 480,
"text": "Attribute selectors (select elements based on \n an attribute or attribute value)"
},
{
"code": null,
"e": 615,
"s": 562,
"text": "This page will explain the most basic CSS selectors."
},
{
"code": null,
"e": 685,
"s": 615,
"text": "The element selector selects HTML elements based on the element name."
},
{
"code": null,
"e": 769,
"s": 685,
"text": "Here, all <p> elements on the page will be \ncenter-aligned, with a red text color: "
},
{
"code": null,
"e": 856,
"s": 769,
"text": "The id selector uses the id attribute of an HTML element to select a specific element."
},
{
"code": null,
"e": 961,
"s": 856,
"text": "The id of an element is unique within a page, so the id selector is \nused to \nselect one unique element!"
},
{
"code": null,
"e": 1066,
"s": 961,
"text": "To select an element with a specific id, write a hash (#) character, followed by \nthe id of the element."
},
{
"code": null,
"e": 1139,
"s": 1066,
"text": "The CSS rule below will be applied to the HTML element with id=\"para1\": "
},
{
"code": null,
"e": 1184,
"s": 1139,
"text": "Note: An id name cannot start with a number!"
},
{
"code": null,
"e": 1258,
"s": 1184,
"text": "The class selector selects HTML elements with a specific class attribute."
},
{
"code": null,
"e": 1359,
"s": 1258,
"text": "To select elements with a specific class, write a period (.) character, followed by the \nclass name."
},
{
"code": null,
"e": 1446,
"s": 1359,
"text": "In this example all HTML elements with class=\"center\" will be red and center-aligned: "
},
{
"code": null,
"e": 1531,
"s": 1446,
"text": "You can also specify that only specific HTML elements should be affected by a class."
},
{
"code": null,
"e": 1619,
"s": 1531,
"text": "In this example only <p> elements with class=\"center\" will be \nred and center-aligned: "
},
{
"code": null,
"e": 1673,
"s": 1619,
"text": "HTML elements \ncan also refer to more than one class."
},
{
"code": null,
"e": 1772,
"s": 1673,
"text": "In this example the <p> element will be styled according to class=\"center\" \nand to class=\"large\": "
},
{
"code": null,
"e": 1819,
"s": 1772,
"text": "Note: A class name cannot start with a number!"
},
{
"code": null,
"e": 1886,
"s": 1819,
"text": "The universal selector (*) selects all HTML \nelements on the page."
},
{
"code": null,
"e": 1950,
"s": 1886,
"text": "The CSS rule below will affect every HTML element on the page: "
},
{
"code": null,
"e": 2036,
"s": 1950,
"text": "The grouping selector selects all the HTML elements with the same style \ndefinitions."
},
{
"code": null,
"e": 2130,
"s": 2036,
"text": "Look at the following CSS code (the h1, h2, and p elements have the same \nstyle definitions):"
},
{
"code": null,
"e": 2194,
"s": 2130,
"text": "It will be better to group the selectors, to minimize the code."
},
{
"code": null,
"e": 2251,
"s": 2194,
"text": "To group selectors, separate each selector with a comma."
},
{
"code": null,
"e": 2319,
"s": 2251,
"text": "In this example we have grouped the selectors from the code above: "
},
{
"code": null,
"e": 2361,
"s": 2319,
"text": "Set the color of all <p> elements to red."
},
{
"code": null,
"e": 2392,
"s": 2361,
"text": "<style>\n {\n red;\n}\n</style>\n"
},
{
"code": null,
"e": 2411,
"s": 2392,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2444,
"s": 2411,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2486,
"s": 2444,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2593,
"s": 2486,
"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": 2612,
"s": 2593,
"text": "help@w3schools.com"
}
] |
Maximum number of overlapping Intervals - GeeksforGeeks
|
02 Feb, 2022
Given different intervals, the task is to print the maximum number of overlap among these intervals at any time.
Examples:
Input: v = {{1, 2}, {2, 4}, {3, 6}} Output: 2 The maximum overlapping is 2(between (1 2) and (2 4) or between (2 4) and (3 6))
Input: v = {{1, 8}, {2, 5}, {5, 6}, {3, 7}} Output: 4 The maximum overlapping is 4 (between (1, 8), (2, 5), (5, 6) and (3, 7))
Approach:
The idea is to store coordinates in a new vector of pair mapped with characters ‘x’ and ‘y’, to identify coordinates.
Sort the vector.
Traverse the vector, if an x coordinate is encountered it means a new range is added, so update count and if y coordinate is encountered that means a range is subtracted.
Update the value of count for every new coordinate and take maximum.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program that print maximum// number of overlap// among given ranges#include <bits/stdc++.h>using namespace std; // Function that print maximum// overlap among rangesvoid overlap(vector<pair<int, int> > v){ // variable to store the maximum // count int ans = 0; int count = 0; vector<pair<int, char> > data; // storing the x and y // coordinates in data vector for (int i = 0; i < v.size(); i++) { // pushing the x coordinate data.push_back({ v[i].first, 'x' }); // pushing the y coordinate data.push_back({ v[i].second, 'y' }); } // sorting of ranges sort(data.begin(), data.end()); // Traverse the data vector to // count number of overlaps for (int i = 0; i < data.size(); i++) { // if x occur it means a new range // is added so we increase count if (data[i].second == 'x') count++; // if y occur it means a range // is ended so we decrease count if (data[i].second == 'y') count--; // updating the value of ans // after every traversal ans = max(ans, count); } // printing the maximum value cout << ans << endl;} // Driver codeint main(){ vector<pair<int, int> > v = { { 1, 2 }, { 2, 4 }, { 3, 6 } }; overlap(v); return 0;}
// Java program that print maximum// number of overlap among given rangesimport java.util.*;import java.lang.*;import java.io.*;class GFG{ static class pair{ int first; char second; pair(int first, char second) { this.first = first; this.second = second; }} // Function that print maximum// overlap among rangesstatic void overlap(int[][] v){ // Variable to store the maximum // count int ans = 0; int count = 0; ArrayList<pair> data = new ArrayList<>(); // Storing the x and y // coordinates in data vector for(int i = 0; i < v.length; i++) { // Pushing the x coordinate data.add(new pair(v[i][0], 'x')); // pushing the y coordinate data.add(new pair(v[i][1], 'y')); } // Sorting of ranges Collections.sort(data, (a, b) -> a.first - b.first); // Traverse the data vector to // count number of overlaps for(int i = 0; i < data.size(); i++) { // If x occur it means a new range // is added so we increase count if (data.get(i).second == 'x') count++; // If y occur it means a range // is ended so we decrease count if (data.get(i).second == 'y') count--; // Updating the value of ans // after every traversal ans = Math.max(ans, count); } // Printing the maximum value System.out.println(ans);} // Driver codepublic static void main(String[] args){ int[][] v = { { 1, 2 }, { 2, 4 }, { 3, 6 } }; overlap(v);}} // This code is contributed by offbeat
# Python3 program that print maximum# number of overlap# among given ranges # Function that print maximum# overlap among rangesdef overlap(v): # variable to store the maximum # count ans = 0 count = 0 data = [] # storing the x and y # coordinates in data vector for i in range(len(v)): # pushing the x coordinate data.append([v[i][0], 'x']) # pushing the y coordinate data.append([v[i][1], 'y']) # sorting of ranges data = sorted(data) # Traverse the data vector to # count number of overlaps for i in range(len(data)): # if x occur it means a new range # is added so we increase count if (data[i][1] == 'x'): count += 1 # if y occur it means a range # is ended so we decrease count if (data[i][1] == 'y'): count -= 1 # updating the value of ans # after every traversal ans = max(ans, count) # printing the maximum value print(ans) # Driver codev = [ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ] ]overlap(v) # This code is contributed by mohit kumar 29
<script> // Javascript program that print maximum// number of overlap among given ranges // Function that print maximum// overlap among rangesfunction overlap(v){ // Variable to store the maximum // count var ans = 0; var count = 0; var data = []; // Storing the x and y // coordinates in data vector for(var i = 0; i < v.length; i++) { // Pushing the x coordinate data.push([v[i][0], 'x']); // Pushing the y coordinate data.push([v[i][1], 'y']); } // Sorting of ranges data.sort(); // Traverse the data vector to // count number of overlaps for(var i = 0; i < data.length; i++) { // If x occur it means a new range // is added so we increase count if (data[i][1] == 'x') count++; // If y occur it means a range // is ended so we decrease count if (data[i][1] == 'y') count--; // Updating the value of ans // after every traversal ans = Math.max(ans, count); } // Printing the maximum value document.write(ans + "<br>");} // Driver codevar v = [ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ] ];overlap(v); // This code is contributed by rutvik_56 </script>
2
mohit kumar 29
offbeat
rutvik_56
surinderdawra388
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Linear Search
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 24606,
"s": 24578,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 24719,
"s": 24606,
"text": "Given different intervals, the task is to print the maximum number of overlap among these intervals at any time."
},
{
"code": null,
"e": 24730,
"s": 24719,
"text": "Examples: "
},
{
"code": null,
"e": 24859,
"s": 24730,
"text": "Input: v = {{1, 2}, {2, 4}, {3, 6}} Output: 2 The maximum overlapping is 2(between (1 2) and (2 4) or between (2 4) and (3 6)) "
},
{
"code": null,
"e": 24987,
"s": 24859,
"text": "Input: v = {{1, 8}, {2, 5}, {5, 6}, {3, 7}} Output: 4 The maximum overlapping is 4 (between (1, 8), (2, 5), (5, 6) and (3, 7)) "
},
{
"code": null,
"e": 24998,
"s": 24987,
"text": "Approach: "
},
{
"code": null,
"e": 25116,
"s": 24998,
"text": "The idea is to store coordinates in a new vector of pair mapped with characters ‘x’ and ‘y’, to identify coordinates."
},
{
"code": null,
"e": 25133,
"s": 25116,
"text": "Sort the vector."
},
{
"code": null,
"e": 25304,
"s": 25133,
"text": "Traverse the vector, if an x coordinate is encountered it means a new range is added, so update count and if y coordinate is encountered that means a range is subtracted."
},
{
"code": null,
"e": 25373,
"s": 25304,
"text": "Update the value of count for every new coordinate and take maximum."
},
{
"code": null,
"e": 25425,
"s": 25373,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25429,
"s": 25425,
"text": "C++"
},
{
"code": null,
"e": 25434,
"s": 25429,
"text": "Java"
},
{
"code": null,
"e": 25442,
"s": 25434,
"text": "Python3"
},
{
"code": null,
"e": 25453,
"s": 25442,
"text": "Javascript"
},
{
"code": "// C++ program that print maximum// number of overlap// among given ranges#include <bits/stdc++.h>using namespace std; // Function that print maximum// overlap among rangesvoid overlap(vector<pair<int, int> > v){ // variable to store the maximum // count int ans = 0; int count = 0; vector<pair<int, char> > data; // storing the x and y // coordinates in data vector for (int i = 0; i < v.size(); i++) { // pushing the x coordinate data.push_back({ v[i].first, 'x' }); // pushing the y coordinate data.push_back({ v[i].second, 'y' }); } // sorting of ranges sort(data.begin(), data.end()); // Traverse the data vector to // count number of overlaps for (int i = 0; i < data.size(); i++) { // if x occur it means a new range // is added so we increase count if (data[i].second == 'x') count++; // if y occur it means a range // is ended so we decrease count if (data[i].second == 'y') count--; // updating the value of ans // after every traversal ans = max(ans, count); } // printing the maximum value cout << ans << endl;} // Driver codeint main(){ vector<pair<int, int> > v = { { 1, 2 }, { 2, 4 }, { 3, 6 } }; overlap(v); return 0;}",
"e": 26777,
"s": 25453,
"text": null
},
{
"code": "// Java program that print maximum// number of overlap among given rangesimport java.util.*;import java.lang.*;import java.io.*;class GFG{ static class pair{ int first; char second; pair(int first, char second) { this.first = first; this.second = second; }} // Function that print maximum// overlap among rangesstatic void overlap(int[][] v){ // Variable to store the maximum // count int ans = 0; int count = 0; ArrayList<pair> data = new ArrayList<>(); // Storing the x and y // coordinates in data vector for(int i = 0; i < v.length; i++) { // Pushing the x coordinate data.add(new pair(v[i][0], 'x')); // pushing the y coordinate data.add(new pair(v[i][1], 'y')); } // Sorting of ranges Collections.sort(data, (a, b) -> a.first - b.first); // Traverse the data vector to // count number of overlaps for(int i = 0; i < data.size(); i++) { // If x occur it means a new range // is added so we increase count if (data.get(i).second == 'x') count++; // If y occur it means a range // is ended so we decrease count if (data.get(i).second == 'y') count--; // Updating the value of ans // after every traversal ans = Math.max(ans, count); } // Printing the maximum value System.out.println(ans);} // Driver codepublic static void main(String[] args){ int[][] v = { { 1, 2 }, { 2, 4 }, { 3, 6 } }; overlap(v);}} // This code is contributed by offbeat",
"e": 28420,
"s": 26777,
"text": null
},
{
"code": "# Python3 program that print maximum# number of overlap# among given ranges # Function that print maximum# overlap among rangesdef overlap(v): # variable to store the maximum # count ans = 0 count = 0 data = [] # storing the x and y # coordinates in data vector for i in range(len(v)): # pushing the x coordinate data.append([v[i][0], 'x']) # pushing the y coordinate data.append([v[i][1], 'y']) # sorting of ranges data = sorted(data) # Traverse the data vector to # count number of overlaps for i in range(len(data)): # if x occur it means a new range # is added so we increase count if (data[i][1] == 'x'): count += 1 # if y occur it means a range # is ended so we decrease count if (data[i][1] == 'y'): count -= 1 # updating the value of ans # after every traversal ans = max(ans, count) # printing the maximum value print(ans) # Driver codev = [ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ] ]overlap(v) # This code is contributed by mohit kumar 29",
"e": 29525,
"s": 28420,
"text": null
},
{
"code": "<script> // Javascript program that print maximum// number of overlap among given ranges // Function that print maximum// overlap among rangesfunction overlap(v){ // Variable to store the maximum // count var ans = 0; var count = 0; var data = []; // Storing the x and y // coordinates in data vector for(var i = 0; i < v.length; i++) { // Pushing the x coordinate data.push([v[i][0], 'x']); // Pushing the y coordinate data.push([v[i][1], 'y']); } // Sorting of ranges data.sort(); // Traverse the data vector to // count number of overlaps for(var i = 0; i < data.length; i++) { // If x occur it means a new range // is added so we increase count if (data[i][1] == 'x') count++; // If y occur it means a range // is ended so we decrease count if (data[i][1] == 'y') count--; // Updating the value of ans // after every traversal ans = Math.max(ans, count); } // Printing the maximum value document.write(ans + \"<br>\");} // Driver codevar v = [ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ] ];overlap(v); // This code is contributed by rutvik_56 </script>",
"e": 30765,
"s": 29525,
"text": null
},
{
"code": null,
"e": 30767,
"s": 30765,
"text": "2"
},
{
"code": null,
"e": 30784,
"s": 30769,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30792,
"s": 30784,
"text": "offbeat"
},
{
"code": null,
"e": 30802,
"s": 30792,
"text": "rutvik_56"
},
{
"code": null,
"e": 30819,
"s": 30802,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30826,
"s": 30819,
"text": "Arrays"
},
{
"code": null,
"e": 30834,
"s": 30826,
"text": "Sorting"
},
{
"code": null,
"e": 30841,
"s": 30834,
"text": "Arrays"
},
{
"code": null,
"e": 30849,
"s": 30841,
"text": "Sorting"
},
{
"code": null,
"e": 30947,
"s": 30849,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30956,
"s": 30947,
"text": "Comments"
},
{
"code": null,
"e": 30969,
"s": 30956,
"text": "Old Comments"
},
{
"code": null,
"e": 31017,
"s": 30969,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 31061,
"s": 31017,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 31084,
"s": 31061,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 31098,
"s": 31084,
"text": "Linear Search"
}
] |
Validating email and password - JavaScript
|
Suppose, we have this dummy array that contains the login info of two of many users of a social networking platform −
const array = [{
email: 'usman@gmail.com',
password: '123'
},
{
email: 'ali@gmail.com',
password: '123'
}
];
We are required to write a JavaScript function that takes in an email string and a password string.
The function should return a boolean based on the fact whether or not the user exists in the database.
Following is the code −
const array = [{
email: 'usman@gmail.com',
password: '123'
}, {
email: 'ali@gmail.com',
password: '123'
}];
const matchCredentials = (email, password) => {
const match = array.find(el => {
return el.email === email && el.password === password;
});
return !!match;
};
console.log(matchCredentials('usman@gmail.com', '123'));
console.log(matchCredentials('usman@gmail.com', '1423'));
This will produce the following output on console −
true
false
|
[
{
"code": null,
"e": 1180,
"s": 1062,
"text": "Suppose, we have this dummy array that contains the login info of two of many users of a social networking platform −"
},
{
"code": null,
"e": 1304,
"s": 1180,
"text": "const array = [{\n email: 'usman@gmail.com',\n password: '123'\n },\n {\n email: 'ali@gmail.com',\n password: '123'\n }\n];"
},
{
"code": null,
"e": 1404,
"s": 1304,
"text": "We are required to write a JavaScript function that takes in an email string and a password string."
},
{
"code": null,
"e": 1507,
"s": 1404,
"text": "The function should return a boolean based on the fact whether or not the user exists in the database."
},
{
"code": null,
"e": 1531,
"s": 1507,
"text": "Following is the code −"
},
{
"code": null,
"e": 1940,
"s": 1531,
"text": "const array = [{\n email: 'usman@gmail.com',\n password: '123'\n}, {\n email: 'ali@gmail.com',\n password: '123'\n}];\nconst matchCredentials = (email, password) => {\n const match = array.find(el => {\n return el.email === email && el.password === password;\n });\n return !!match;\n};\nconsole.log(matchCredentials('usman@gmail.com', '123'));\nconsole.log(matchCredentials('usman@gmail.com', '1423'));"
},
{
"code": null,
"e": 1992,
"s": 1940,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 2003,
"s": 1992,
"text": "true\nfalse"
}
] |
Minimum number of swaps required to sort an array of first N number
|
16 Aug, 2021
😟😤🤓 Given an array arr[] of distinct integers from 1 to N. The task is to find the minimum number of swaps required to sort the array.
😟😤🤓 Example:
Input: arr[] = { 7, 1, 3, 2, 4, 5, 6 }
Output: 5
Explanation:
i arr swap (indices)
0 [7, 1, 3, 2, 4, 5, 6] swap (0, 3)
1 [2, 1, 3, 7, 4, 5, 6] swap (0, 1)
2 [1, 2, 3, 7, 4, 5, 6] swap (3, 4)
3 [1, 2, 3, 4, 7, 5, 6] swap (4, 5)
4 [1, 2, 3, 4, 5, 7, 6] swap (5, 6)
5 [1, 2, 3, 4, 5, 6, 7]
Therefore, total number of swaps = 5
Input: arr[] = { 2, 3, 4, 1, 5 }
Output: 3
😟😤🤓
😟😤🤓 Approach:
For each index in arr[].
Check if the current element is in it’s right position or not. Since the array contains distinct elements from 1 to N, we can simply compare the element with it’s index in array to check if it is at its right position.
If current element is not at it’s right position then swap the element with the element which has occupied its place.
Else check for next index.
😟😤🤓 Below is the implementation of the above approach:
😟😤🤓
😟😤🤓
😟😤🤓
#include <iostream>using namespace std; // Function to find minimum swapsint minimumSwaps(int arr[],int n){ // Initialise count variable int count = 0; int i = 0; while (i < n) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count;} // Driver codeint main(){ int arr[] = { 2, 3, 4, 1, 5 }; int n = sizeof(arr)/sizeof(arr[0]); // Function to find minimum swaps cout << minimumSwaps(arr,n) ;} // This code is contributed by AnkitRai01
😟😤🤓
😟😤🤓
😟😤🤓
// Java program to find the minimum// number of swaps required to sort// the given arrayimport java.io.*;import java.util.*; class GfG { // Function to find minimum swaps static int minimumSwaps(int[] arr) { // Initialise count variable int count = 0; int i = 0; while (i < arr.length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count; } // Driver code public static void main(String[] args) { int arr[] = { 2, 3, 4, 1, 5 }; // Function to find minimum swaps System.out.println(minimumSwaps(arr)); }}
😟😤🤓
😟😤🤓
😟😤🤓
# Python3 program to find the minimum# number of swaps required to sort# the given array # Function to find minimum swapsdef minimumSwaps(arr): # Initialise count variable count = 0; i = 0; while (i < len(arr)): # If current element is # not at the right position if (arr[i] != i + 1): while (arr[i] != i + 1): temp = 0; # Swap current element # with correct position # of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count += 1; # Increment for next index # when current element is at # correct position i += 1; return count; # Driver codeif __name__ == '__main__': arr = [ 2, 3, 4, 1, 5 ]; # Function to find minimum swaps print(minimumSwaps(arr)); # This code is contributed by 29AjayKumar
😟😤🤓
😟😤🤓
😟😤🤓
// C# program to find the minimum// number of swaps required to sort// the given arrayusing System; class GfG{ // Function to find minimum swaps static int minimumSwaps(int[] arr) { // Initialise count variable int count = 0; int i = 0; while (i < arr.Length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count; } // Driver code public static void Main(String[] args) { int []arr = { 2, 3, 4, 1, 5 }; // Function to find minimum swaps Console.WriteLine(minimumSwaps(arr)); }} // This code is contributed by 29AjayKumar
😟😤🤓
😟😤🤓
😟😤🤓
<script> // javascript program to find the minimum// number of swaps required to sort// the given array // Function to find minimum swapsfunction minimumSwaps(arr){ // Initialise count variable let count = 0; let i = 0; while (i < arr.length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { let temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count;} // Driver code let arr = [2, 3, 4, 1, 5 ]; // Function to find minimum swapsdocument.write(minimumSwaps(arr)); </script>
3
😟😤🤓
😟😤🤓 Time Complexity: O(N) where N is the size of array. Auxiliary Space: O(1)
29AjayKumar
ankthon
mohit kumar 29
anikakapoor
Natural Numbers
Arrays
Sorting
Arrays
Sorting
😟😤🤓 Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Linked List vs Array
Queue | Set 1 (Introduction and Array Implementation)
Find Second largest element in an array
Program to find largest element in an array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 191,
"s": 54,
"text": "😟😤🤓 Given an array arr[] of distinct integers from 1 to N. The task is to find the minimum number of swaps required to sort the array. "
},
{
"code": null,
"e": 206,
"s": 191,
"text": "😟😤🤓 Example: "
},
{
"code": null,
"e": 618,
"s": 206,
"text": "Input: arr[] = { 7, 1, 3, 2, 4, 5, 6 }\nOutput: 5\nExplanation:\ni arr swap (indices)\n0 [7, 1, 3, 2, 4, 5, 6] swap (0, 3)\n1 [2, 1, 3, 7, 4, 5, 6] swap (0, 1)\n2 [1, 2, 3, 7, 4, 5, 6] swap (3, 4)\n3 [1, 2, 3, 4, 7, 5, 6] swap (4, 5)\n4 [1, 2, 3, 4, 5, 7, 6] swap (5, 6)\n5 [1, 2, 3, 4, 5, 6, 7]\nTherefore, total number of swaps = 5\n\nInput: arr[] = { 2, 3, 4, 1, 5 }\nOutput: 3"
},
{
"code": null,
"e": 624,
"s": 618,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 640,
"s": 624,
"text": "😟😤🤓 Approach: "
},
{
"code": null,
"e": 665,
"s": 640,
"text": "For each index in arr[]."
},
{
"code": null,
"e": 884,
"s": 665,
"text": "Check if the current element is in it’s right position or not. Since the array contains distinct elements from 1 to N, we can simply compare the element with it’s index in array to check if it is at its right position."
},
{
"code": null,
"e": 1002,
"s": 884,
"text": "If current element is not at it’s right position then swap the element with the element which has occupied its place."
},
{
"code": null,
"e": 1029,
"s": 1002,
"text": "Else check for next index."
},
{
"code": null,
"e": 1086,
"s": 1029,
"text": "😟😤🤓 Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1091,
"s": 1086,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 1096,
"s": 1091,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 1101,
"s": 1096,
"text": "😟😤🤓 "
},
{
"code": "#include <iostream>using namespace std; // Function to find minimum swapsint minimumSwaps(int arr[],int n){ // Initialise count variable int count = 0; int i = 0; while (i < n) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count;} // Driver codeint main(){ int arr[] = { 2, 3, 4, 1, 5 }; int n = sizeof(arr)/sizeof(arr[0]); // Function to find minimum swaps cout << minimumSwaps(arr,n) ;} // This code is contributed by AnkitRai01",
"e": 2107,
"s": 1101,
"text": null
},
{
"code": null,
"e": 2112,
"s": 2107,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 2117,
"s": 2112,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 2122,
"s": 2117,
"text": "😟😤🤓 "
},
{
"code": "// Java program to find the minimum// number of swaps required to sort// the given arrayimport java.io.*;import java.util.*; class GfG { // Function to find minimum swaps static int minimumSwaps(int[] arr) { // Initialise count variable int count = 0; int i = 0; while (i < arr.length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count; } // Driver code public static void main(String[] args) { int arr[] = { 2, 3, 4, 1, 5 }; // Function to find minimum swaps System.out.println(minimumSwaps(arr)); }}",
"e": 3301,
"s": 2122,
"text": null
},
{
"code": null,
"e": 3306,
"s": 3301,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 3311,
"s": 3306,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 3316,
"s": 3311,
"text": "😟😤🤓 "
},
{
"code": "# Python3 program to find the minimum# number of swaps required to sort# the given array # Function to find minimum swapsdef minimumSwaps(arr): # Initialise count variable count = 0; i = 0; while (i < len(arr)): # If current element is # not at the right position if (arr[i] != i + 1): while (arr[i] != i + 1): temp = 0; # Swap current element # with correct position # of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count += 1; # Increment for next index # when current element is at # correct position i += 1; return count; # Driver codeif __name__ == '__main__': arr = [ 2, 3, 4, 1, 5 ]; # Function to find minimum swaps print(minimumSwaps(arr)); # This code is contributed by 29AjayKumar",
"e": 4277,
"s": 3316,
"text": null
},
{
"code": null,
"e": 4282,
"s": 4277,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 4287,
"s": 4282,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 4292,
"s": 4287,
"text": "😟😤🤓 "
},
{
"code": "// C# program to find the minimum// number of swaps required to sort// the given arrayusing System; class GfG{ // Function to find minimum swaps static int minimumSwaps(int[] arr) { // Initialise count variable int count = 0; int i = 0; while (i < arr.Length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count; } // Driver code public static void Main(String[] args) { int []arr = { 2, 3, 4, 1, 5 }; // Function to find minimum swaps Console.WriteLine(minimumSwaps(arr)); }} // This code is contributed by 29AjayKumar",
"e": 5520,
"s": 4292,
"text": null
},
{
"code": null,
"e": 5525,
"s": 5520,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 5530,
"s": 5525,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 5535,
"s": 5530,
"text": "😟😤🤓 "
},
{
"code": "<script> // javascript program to find the minimum// number of swaps required to sort// the given array // Function to find minimum swapsfunction minimumSwaps(arr){ // Initialise count variable let count = 0; let i = 0; while (i < arr.length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { let temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count;} // Driver code let arr = [2, 3, 4, 1, 5 ]; // Function to find minimum swapsdocument.write(minimumSwaps(arr)); </script>",
"e": 6506,
"s": 5535,
"text": null
},
{
"code": null,
"e": 6508,
"s": 6506,
"text": "3"
},
{
"code": null,
"e": 6514,
"s": 6508,
"text": "😟😤🤓 "
},
{
"code": null,
"e": 6592,
"s": 6514,
"text": "😟😤🤓 Time Complexity: O(N) where N is the size of array. Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6604,
"s": 6592,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6612,
"s": 6604,
"text": "ankthon"
},
{
"code": null,
"e": 6627,
"s": 6612,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 6639,
"s": 6627,
"text": "anikakapoor"
},
{
"code": null,
"e": 6655,
"s": 6639,
"text": "Natural Numbers"
},
{
"code": null,
"e": 6662,
"s": 6655,
"text": "Arrays"
},
{
"code": null,
"e": 6670,
"s": 6662,
"text": "Sorting"
},
{
"code": null,
"e": 6677,
"s": 6670,
"text": "Arrays"
},
{
"code": null,
"e": 6685,
"s": 6677,
"text": "Sorting"
},
{
"code": null,
"e": 6787,
"s": 6685,
"text": "😟😤🤓 Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6796,
"s": 6787,
"text": "Comments"
},
{
"code": null,
"e": 6809,
"s": 6796,
"text": "Old Comments"
},
{
"code": null,
"e": 6832,
"s": 6809,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 6853,
"s": 6832,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 6907,
"s": 6853,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 6947,
"s": 6907,
"text": "Find Second largest element in an array"
}
] |
Command Line Argument in Scala - GeeksforGeeks
|
26 May, 2021
The arguments which are passed by the user or programmer to the main() method are termed as Command-Line Arguments. main() method is the entry point of execution of a program. main() method accepts an array of strings. runtime. But it never accepts parameters from any other method in the program. Syntax:
def main(args: Array[String])
For accessing our Scala command-line arguments using the args array, which is made available to us implicitly when we extend App. Here is an example.Example 1: Print all given objects
Scala
// Scala Program on command line argumentobject CMDExample{ // Main method def main(args: Array[String]) { println("Scala Command Line Argument Example"); // You pass any thing at runtime // that will be print on the console for(arg<-args) { println(arg); } }}
To Compile and execute the above program on terminal follow below commands : First save program CMDExample.scala then open CMD/Terminal and go on that directory where you save your scala program.
Compile: scalac CMDExample.scala Execute: scala CMDExample Welcome To GeeksforGeeks!
Output:
Scala Command Line Argument Example
Welcome
To
GeeksforGeeks!
Example 2: Print some object which is given at runtime
Scala
// Scala Program on command line argumentobject CMDExample{ // Main method def main(args: Array[String]) { println("Scala Command Line Argument Example"); // You pass any thing at runtime // that will be print on the console println(args(0)); println(args(2)); }}
To Compile and execute the above program on terminal follow below commands :
Compile: scalac CMDExample.scala Execute: scala CMDExample 1 Welcome To GeeksforGeeks! 2
Output:
Scala Command Line Argument Example
1
To
Note:If given index not present in array then you find this error
sujayshashank
sweetyty
Picked
Scala
Scala-Basics
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Scala List filter() method with example
Scala Map
Type Casting in Scala
Scala Lists
Scala List contains() method with example
Scala String substring() method with example
Lambda Expression in Scala
Scala String replace() method with example
Scala | Arrays
|
[
{
"code": null,
"e": 23451,
"s": 23423,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 23759,
"s": 23451,
"text": "The arguments which are passed by the user or programmer to the main() method are termed as Command-Line Arguments. main() method is the entry point of execution of a program. main() method accepts an array of strings. runtime. But it never accepts parameters from any other method in the program. Syntax: "
},
{
"code": null,
"e": 23789,
"s": 23759,
"text": "def main(args: Array[String])"
},
{
"code": null,
"e": 23975,
"s": 23789,
"text": "For accessing our Scala command-line arguments using the args array, which is made available to us implicitly when we extend App. Here is an example.Example 1: Print all given objects "
},
{
"code": null,
"e": 23981,
"s": 23975,
"text": "Scala"
},
{
"code": "// Scala Program on command line argumentobject CMDExample{ // Main method def main(args: Array[String]) { println(\"Scala Command Line Argument Example\"); // You pass any thing at runtime // that will be print on the console for(arg<-args) { println(arg); } }}",
"e": 24316,
"s": 23981,
"text": null
},
{
"code": null,
"e": 24513,
"s": 24316,
"text": "To Compile and execute the above program on terminal follow below commands : First save program CMDExample.scala then open CMD/Terminal and go on that directory where you save your scala program. "
},
{
"code": null,
"e": 24600,
"s": 24513,
"text": "Compile: scalac CMDExample.scala Execute: scala CMDExample Welcome To GeeksforGeeks! "
},
{
"code": null,
"e": 24610,
"s": 24600,
"text": "Output: "
},
{
"code": null,
"e": 24672,
"s": 24610,
"text": "Scala Command Line Argument Example\nWelcome\nTo\nGeeksforGeeks!"
},
{
"code": null,
"e": 24731,
"s": 24674,
"text": "Example 2: Print some object which is given at runtime "
},
{
"code": null,
"e": 24737,
"s": 24731,
"text": "Scala"
},
{
"code": "// Scala Program on command line argumentobject CMDExample{ // Main method def main(args: Array[String]) { println(\"Scala Command Line Argument Example\"); // You pass any thing at runtime // that will be print on the console println(args(0)); println(args(2)); }}",
"e": 25057,
"s": 24737,
"text": null
},
{
"code": null,
"e": 25136,
"s": 25057,
"text": "To Compile and execute the above program on terminal follow below commands : "
},
{
"code": null,
"e": 25227,
"s": 25136,
"text": "Compile: scalac CMDExample.scala Execute: scala CMDExample 1 Welcome To GeeksforGeeks! 2 "
},
{
"code": null,
"e": 25237,
"s": 25227,
"text": "Output: "
},
{
"code": null,
"e": 25278,
"s": 25237,
"text": "Scala Command Line Argument Example\n1\nTo"
},
{
"code": null,
"e": 25348,
"s": 25280,
"text": "Note:If given index not present in array then you find this error "
},
{
"code": null,
"e": 25364,
"s": 25350,
"text": "sujayshashank"
},
{
"code": null,
"e": 25373,
"s": 25364,
"text": "sweetyty"
},
{
"code": null,
"e": 25380,
"s": 25373,
"text": "Picked"
},
{
"code": null,
"e": 25386,
"s": 25380,
"text": "Scala"
},
{
"code": null,
"e": 25399,
"s": 25386,
"text": "Scala-Basics"
},
{
"code": null,
"e": 25405,
"s": 25399,
"text": "Scala"
},
{
"code": null,
"e": 25503,
"s": 25405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25512,
"s": 25503,
"text": "Comments"
},
{
"code": null,
"e": 25525,
"s": 25512,
"text": "Old Comments"
},
{
"code": null,
"e": 25578,
"s": 25525,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 25618,
"s": 25578,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 25628,
"s": 25618,
"text": "Scala Map"
},
{
"code": null,
"e": 25650,
"s": 25628,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 25662,
"s": 25650,
"text": "Scala Lists"
},
{
"code": null,
"e": 25704,
"s": 25662,
"text": "Scala List contains() method with example"
},
{
"code": null,
"e": 25749,
"s": 25704,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 25776,
"s": 25749,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 25819,
"s": 25776,
"text": "Scala String replace() method with example"
}
] |
Print array elements in alternatively increasing and decreasing order - GeeksforGeeks
|
05 Nov, 2021
Given an array of N elements. The task is to print the array elements in such a way that first two elements are in increasing order, next 3 in decreasing order, next 4 in increasing order and so on.
Examples:
Input : arr = {2, 6, 2, 4, 0, 1, 4, 8, 2, 0, 0, 5,2,2} Output : 0 0 8 6 5 0 1 2 2 4 4 2 2 2
Input : arr = {1, 2, 3, 4, 5, 6} Output : 1 2 6 5 4 3
Source :Oracle Interview experience set 52The idea is to use 2 pointer technique. First sort the array in increasing order and maintain two pointers and where is to print the array in increasing order and to print the array in decreasing order. Keep a variable to specify the number of elements to be printed in an iteration and a variable flag to switch between printing in increasing order and decreasing order alternatively.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print array elements in// alternative increasing and decreasing// order #include <bits/stdc++.h>using namespace std; // Function to print array elements in// alternative increasing and decreasing// ordervoid printArray(int arr[], int n){ // First sort the array in increasing order sort(arr, arr + n); int l = 0, r = n - 1, flag = 0, i; // start with 2 elements in // increasing order int k = 2; // till all the elements are not printed while (l <= r) { // printing the elements in // increasing order if (flag == 0) { for (i = l; i < l + k && i <= r; i++) cout << arr[i] << " "; flag = 1; l = i; } else // printing the elements in // decreasing order { for (i = r; i > r - k && i >= l; i--) cout << arr[i] << " "; flag = 0; r = i; } // increasing the number of elements // to printed in next iteration k++; }} // Driver Codeint main(){ int n = 6; int arr[] = { 1, 2, 3, 4, 5, 6 }; printArray(arr, n); return 0;}
// Java program to print array elements in// alternative increasing and decreasing// orderimport java.util.*;class Solution{ // Function to print array elements in// alternative increasing and decreasing// orderstatic void printArray(int arr[], int n){ // First sort the array in increasing order Arrays.sort(arr); int l = 0, r = n - 1, flag = 0, i; // start with 2 elements in // increasing order int k = 2; // till all the elements are not printed while (l <= r) { // printing the elements in // increasing order if (flag == 0) { for (i = l; i < l + k && i <= r; i++) System.out.print(arr[i] + " "); flag = 1; l = i; } else // printing the elements in // decreasing order { for (i = r; i > r - k && i >= l; i--) System.out.print(arr[i] + " "); flag = 0; r = i; } // increasing the number of elements // to printed in next iteration k++; }} // Driver Codepublic static void main(String args[]){ int n = 6; int arr[] = { 1, 2, 3, 4, 5, 6 }; printArray(arr, n); } }//contributed by Arnab Kundu
# Python 3 program to print array elements# in alternative increasing and decreasing# order # Function to print array elements in# alternative increasing and decreasing# orderdef printArray(arr, n): # First sort the array in # increasing order arr.sort() l = 0 r = n - 1 flag = 0 # start with 2 elements in # increasing order k = 2 # till all the elements are not printed while (l <= r) : # printing the elements in # increasing order if (flag == 0): i = l while i < l + k and i <= r: print(arr[i], end = " ") i += 1 flag = 1 l = i else: # printing the elements in # decreasing order i = r while i > r - k and i >= l: print(arr[i], end = " ") i -= 1 flag = 0 r = i # increasing the number of elements # to printed in next iteration k += 1 # Driver Codeif __name__ == "__main__": n = 6 arr = [ 1, 2, 3, 4, 5, 6 ] printArray(arr, n) # This code is contributed by ita_c
// C# program to print array elements in// alternative increasing and decreasing// orderusing System; class GFG{ // Function to print array elements in// alternative increasing and decreasing// orderstatic void printArray(int []arr, int n){ // First sort the array // in increasing order Array.Sort(arr); int l = 0, r = n - 1, flag = 0, i; // start with 2 elements in // increasing order int k = 2; // till all the elements // are not printed while (l <= r) { // printing the elements in // increasing order if (flag == 0) { for (i = l; i < l + k && i <= r; i++) Console.Write(arr[i] + " "); flag = 1; l = i; } else // printing the elements in // decreasing order { for (i = r; i > r - k && i >= l; i--) Console.Write(arr[i] + " "); flag = 0; r = i; } // increasing the number of elements // to printed in next iteration k++; }} // Driver Codestatic public void Main (){ int n = 6; int []arr = { 1, 2, 3, 4, 5, 6 }; printArray(arr, n); }} // This code is contributed by Sach_Code
<?php// PHP program to print array elements in// alternative increasing and decreasing// order // Function to print array elements in// alternative increasing and decreasing// orderfunction printArray($arr, $n){ // First sort the array in // increasing order sort($arr); $l = 0; $r = $n - 1; $flag = 0; // start with 2 elements in // increasing order $k = 2; // till all the elements are // not printed while ($l <= $r) { // printing the elements in // increasing order if ($flag == 0) { for ($i = $l; $i < $l + $k && $i <= $r; $i++) echo $arr[$i] , " "; $flag = 1; $l = $i; } else // printing the elements in // decreasing order { for ($i = $r; $i > $r - $k && $i >= $l; $i--) echo $arr[$i] , " "; $flag = 0; $r = $i; } // increasing the number of elements // to printed in next iteration $k++; }} // Driver Code$n = 6;$arr = array( 1, 2, 3, 4, 5, 6 ); printArray($arr, $n); // This code is contributed by jit_t?>
<script> // Javascript program to print array elements in// alternative increasing and decreasing// order // Function to print array elements in// alternative increasing and decreasing// orderfunction printArray(arr, n){ // First sort the array // in increasing order arr.sort(); let l = 0, r = n - 1, flag = 0, i; // start with 2 elements in // increasing order let k = 2; // till all the elements // are not printed while (l <= r) { // printing the elements in // increasing order if (flag == 0) { for(i = l; i < l + k && i <= r; i++) document.write(arr[i] + " "); flag = 1; l = i; } else // Printing the elements in // decreasing order { for(i = r; i > r - k && i >= l; i--) document.write(arr[i] + " "); flag = 0; r = i; } // Increasing the number of elements // to printed in next iteration k++; }} // Driver codelet n = 6;let arr = [ 1, 2, 3, 4, 5, 6 ];printArray(arr, n); // This code is contributed by suresh07 </script>
1 2 6 5 4 3
Time Complexity : O(nlogn)Auxiliary Space: O(1)
andrew1234
Sach_Code
jit_t
ukasp
VishalBachchas
suresh07
pankajsharmagfg
ashutoshsinghgeeksforgeeks
Constructive Algorithms
Oracle
Technical Scripter 2018
Algorithms
Sorting
Oracle
Sorting
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Difference between Informed and Uninformed Search in AI
Quick Sort vs Merge Sort
|
[
{
"code": null,
"e": 24839,
"s": 24811,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 25038,
"s": 24839,
"text": "Given an array of N elements. The task is to print the array elements in such a way that first two elements are in increasing order, next 3 in decreasing order, next 4 in increasing order and so on."
},
{
"code": null,
"e": 25049,
"s": 25038,
"text": "Examples: "
},
{
"code": null,
"e": 25142,
"s": 25049,
"text": "Input : arr = {2, 6, 2, 4, 0, 1, 4, 8, 2, 0, 0, 5,2,2} Output : 0 0 8 6 5 0 1 2 2 4 4 2 2 2 "
},
{
"code": null,
"e": 25199,
"s": 25142,
"text": "Input : arr = {1, 2, 3, 4, 5, 6} Output : 1 2 6 5 4 3 "
},
{
"code": null,
"e": 25627,
"s": 25199,
"text": "Source :Oracle Interview experience set 52The idea is to use 2 pointer technique. First sort the array in increasing order and maintain two pointers and where is to print the array in increasing order and to print the array in decreasing order. Keep a variable to specify the number of elements to be printed in an iteration and a variable flag to switch between printing in increasing order and decreasing order alternatively."
},
{
"code": null,
"e": 25676,
"s": 25627,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 25680,
"s": 25676,
"text": "C++"
},
{
"code": null,
"e": 25685,
"s": 25680,
"text": "Java"
},
{
"code": null,
"e": 25693,
"s": 25685,
"text": "Python3"
},
{
"code": null,
"e": 25696,
"s": 25693,
"text": "C#"
},
{
"code": null,
"e": 25700,
"s": 25696,
"text": "PHP"
},
{
"code": null,
"e": 25711,
"s": 25700,
"text": "Javascript"
},
{
"code": "// C++ program to print array elements in// alternative increasing and decreasing// order #include <bits/stdc++.h>using namespace std; // Function to print array elements in// alternative increasing and decreasing// ordervoid printArray(int arr[], int n){ // First sort the array in increasing order sort(arr, arr + n); int l = 0, r = n - 1, flag = 0, i; // start with 2 elements in // increasing order int k = 2; // till all the elements are not printed while (l <= r) { // printing the elements in // increasing order if (flag == 0) { for (i = l; i < l + k && i <= r; i++) cout << arr[i] << \" \"; flag = 1; l = i; } else // printing the elements in // decreasing order { for (i = r; i > r - k && i >= l; i--) cout << arr[i] << \" \"; flag = 0; r = i; } // increasing the number of elements // to printed in next iteration k++; }} // Driver Codeint main(){ int n = 6; int arr[] = { 1, 2, 3, 4, 5, 6 }; printArray(arr, n); return 0;}",
"e": 26863,
"s": 25711,
"text": null
},
{
"code": "// Java program to print array elements in// alternative increasing and decreasing// orderimport java.util.*;class Solution{ // Function to print array elements in// alternative increasing and decreasing// orderstatic void printArray(int arr[], int n){ // First sort the array in increasing order Arrays.sort(arr); int l = 0, r = n - 1, flag = 0, i; // start with 2 elements in // increasing order int k = 2; // till all the elements are not printed while (l <= r) { // printing the elements in // increasing order if (flag == 0) { for (i = l; i < l + k && i <= r; i++) System.out.print(arr[i] + \" \"); flag = 1; l = i; } else // printing the elements in // decreasing order { for (i = r; i > r - k && i >= l; i--) System.out.print(arr[i] + \" \"); flag = 0; r = i; } // increasing the number of elements // to printed in next iteration k++; }} // Driver Codepublic static void main(String args[]){ int n = 6; int arr[] = { 1, 2, 3, 4, 5, 6 }; printArray(arr, n); } }//contributed by Arnab Kundu",
"e": 28085,
"s": 26863,
"text": null
},
{
"code": "# Python 3 program to print array elements# in alternative increasing and decreasing# order # Function to print array elements in# alternative increasing and decreasing# orderdef printArray(arr, n): # First sort the array in # increasing order arr.sort() l = 0 r = n - 1 flag = 0 # start with 2 elements in # increasing order k = 2 # till all the elements are not printed while (l <= r) : # printing the elements in # increasing order if (flag == 0): i = l while i < l + k and i <= r: print(arr[i], end = \" \") i += 1 flag = 1 l = i else: # printing the elements in # decreasing order i = r while i > r - k and i >= l: print(arr[i], end = \" \") i -= 1 flag = 0 r = i # increasing the number of elements # to printed in next iteration k += 1 # Driver Codeif __name__ == \"__main__\": n = 6 arr = [ 1, 2, 3, 4, 5, 6 ] printArray(arr, n) # This code is contributed by ita_c",
"e": 29245,
"s": 28085,
"text": null
},
{
"code": "// C# program to print array elements in// alternative increasing and decreasing// orderusing System; class GFG{ // Function to print array elements in// alternative increasing and decreasing// orderstatic void printArray(int []arr, int n){ // First sort the array // in increasing order Array.Sort(arr); int l = 0, r = n - 1, flag = 0, i; // start with 2 elements in // increasing order int k = 2; // till all the elements // are not printed while (l <= r) { // printing the elements in // increasing order if (flag == 0) { for (i = l; i < l + k && i <= r; i++) Console.Write(arr[i] + \" \"); flag = 1; l = i; } else // printing the elements in // decreasing order { for (i = r; i > r - k && i >= l; i--) Console.Write(arr[i] + \" \"); flag = 0; r = i; } // increasing the number of elements // to printed in next iteration k++; }} // Driver Codestatic public void Main (){ int n = 6; int []arr = { 1, 2, 3, 4, 5, 6 }; printArray(arr, n); }} // This code is contributed by Sach_Code",
"e": 30516,
"s": 29245,
"text": null
},
{
"code": "<?php// PHP program to print array elements in// alternative increasing and decreasing// order // Function to print array elements in// alternative increasing and decreasing// orderfunction printArray($arr, $n){ // First sort the array in // increasing order sort($arr); $l = 0; $r = $n - 1; $flag = 0; // start with 2 elements in // increasing order $k = 2; // till all the elements are // not printed while ($l <= $r) { // printing the elements in // increasing order if ($flag == 0) { for ($i = $l; $i < $l + $k && $i <= $r; $i++) echo $arr[$i] , \" \"; $flag = 1; $l = $i; } else // printing the elements in // decreasing order { for ($i = $r; $i > $r - $k && $i >= $l; $i--) echo $arr[$i] , \" \"; $flag = 0; $r = $i; } // increasing the number of elements // to printed in next iteration $k++; }} // Driver Code$n = 6;$arr = array( 1, 2, 3, 4, 5, 6 ); printArray($arr, $n); // This code is contributed by jit_t?>",
"e": 31728,
"s": 30516,
"text": null
},
{
"code": "<script> // Javascript program to print array elements in// alternative increasing and decreasing// order // Function to print array elements in// alternative increasing and decreasing// orderfunction printArray(arr, n){ // First sort the array // in increasing order arr.sort(); let l = 0, r = n - 1, flag = 0, i; // start with 2 elements in // increasing order let k = 2; // till all the elements // are not printed while (l <= r) { // printing the elements in // increasing order if (flag == 0) { for(i = l; i < l + k && i <= r; i++) document.write(arr[i] + \" \"); flag = 1; l = i; } else // Printing the elements in // decreasing order { for(i = r; i > r - k && i >= l; i--) document.write(arr[i] + \" \"); flag = 0; r = i; } // Increasing the number of elements // to printed in next iteration k++; }} // Driver codelet n = 6;let arr = [ 1, 2, 3, 4, 5, 6 ];printArray(arr, n); // This code is contributed by suresh07 </script>",
"e": 32901,
"s": 31728,
"text": null
},
{
"code": null,
"e": 32913,
"s": 32901,
"text": "1 2 6 5 4 3"
},
{
"code": null,
"e": 32964,
"s": 32915,
"text": "Time Complexity : O(nlogn)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 32975,
"s": 32964,
"text": "andrew1234"
},
{
"code": null,
"e": 32985,
"s": 32975,
"text": "Sach_Code"
},
{
"code": null,
"e": 32991,
"s": 32985,
"text": "jit_t"
},
{
"code": null,
"e": 32997,
"s": 32991,
"text": "ukasp"
},
{
"code": null,
"e": 33012,
"s": 32997,
"text": "VishalBachchas"
},
{
"code": null,
"e": 33021,
"s": 33012,
"text": "suresh07"
},
{
"code": null,
"e": 33037,
"s": 33021,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 33064,
"s": 33037,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 33088,
"s": 33064,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 33095,
"s": 33088,
"text": "Oracle"
},
{
"code": null,
"e": 33119,
"s": 33095,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 33130,
"s": 33119,
"text": "Algorithms"
},
{
"code": null,
"e": 33138,
"s": 33130,
"text": "Sorting"
},
{
"code": null,
"e": 33145,
"s": 33138,
"text": "Oracle"
},
{
"code": null,
"e": 33153,
"s": 33145,
"text": "Sorting"
},
{
"code": null,
"e": 33164,
"s": 33153,
"text": "Algorithms"
},
{
"code": null,
"e": 33262,
"s": 33164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33271,
"s": 33262,
"text": "Comments"
},
{
"code": null,
"e": 33284,
"s": 33271,
"text": "Old Comments"
},
{
"code": null,
"e": 33333,
"s": 33284,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 33358,
"s": 33333,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33385,
"s": 33358,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 33441,
"s": 33385,
"text": "Difference between Informed and Uninformed Search in AI"
}
] |
How to style text buttons with CSS?
|
Following is the code to style text buttons with CSS −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
button {
border: none;
color: white;
font-weight: bolder;
padding: 20px;
font-size: 18px;
cursor: pointer;
border-radius: 6px;
}
.Success {
color: #4caf50;
}
.Success:hover {
background: #e7e7e7;
}
.Info {
color: #2196f3;
}
.Info:hover {
background: #e7e7e7;
}
.Warning {
color: #ff9800;
}
.Warning:hover {
background: #e7e7e7;
}
.Danger {
color: #f44336;
}
.Danger:hover {
background: #e7e7e7;
}
.Default {
color: black;
}
.Default:hover {
background: #e7e7e7;
}
</style>
</head>
<body>
<h1>Text Buttons Example</h1>
<button class="Success">Success</button>
<button class="Info">Info</button>
<button class="Warning">Warning</button>
<button class="Danger">Danger</button>
<button class="Default">Default</button>
</body>
</html>
The above code will produce the following output −
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "Following is the code to style text buttons with CSS −"
},
{
"code": null,
"e": 1128,
"s": 1117,
"text": " Live Demo"
},
{
"code": null,
"e": 2019,
"s": 1128,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\nbutton {\n border: none;\n color: white;\n font-weight: bolder;\n padding: 20px;\n font-size: 18px;\n cursor: pointer;\n border-radius: 6px;\n}\n.Success {\n color: #4caf50;\n}\n.Success:hover {\n background: #e7e7e7;\n}\n.Info {\n color: #2196f3;\n}\n.Info:hover {\n background: #e7e7e7;\n}\n.Warning {\n color: #ff9800;\n}\n.Warning:hover {\n background: #e7e7e7;\n}\n.Danger {\n color: #f44336;\n}\n.Danger:hover {\n background: #e7e7e7;\n}\n.Default {\n color: black;\n}\n.Default:hover {\n background: #e7e7e7;\n}\n</style>\n</head>\n<body>\n<h1>Text Buttons Example</h1>\n<button class=\"Success\">Success</button>\n<button class=\"Info\">Info</button>\n<button class=\"Warning\">Warning</button>\n<button class=\"Danger\">Danger</button>\n<button class=\"Default\">Default</button>\n</body>\n</html>"
},
{
"code": null,
"e": 2070,
"s": 2019,
"text": "The above code will produce the following output −"
}
] |
Let’s Understand the Vector Space Model in Machine Learning by Modelling Cars | by GreekDataGuy | Towards Data Science
|
According to Wikipedia.
Vector space model or term vector model is an algebraic model for representing text documents (and any objects, in general) as vectors of identifiers, such as, for example, index terms.
Translation: We represent each example in our dataset as a list of features.
The model is used to represent documents in an n-dimensional space. But a “document” can mean any object you’re trying to model.
Whether you explicitly understand this or not, you’ve used it in your machine learning projects.
Just a feature of the objects we’re modelling. For example.
Houses could have dimensions: number_of_rooms, sale_price, construction_date, latitude and longitude.
People could have dimensions: age, weight, height, hair_color_is_blue and hair_color_is_other.
Sentences could have a dimension for each possible word/token.
Cars could have dimensions: max_speed, acceleration_time and price.
In the end, features/dimensions are whatever you decide on during the feature selection process.
Our dimensions will be:1. max_speed (maximum speed in kmph)2. acceleration_time (number seconds to reach 100 kmph)3. price (in USD)
I’ve picked 3 cars and collected their information (disclaimer: I know nothing about cars...).
2020 Porsche Cayennemax_speed: 304 kmphacceleration_time: 4.4sprice: $99,200
2018 Tesla Model Smax_speed: 250 kmphacceleration_time: 3.8sprice: $79,990
2020 BMW i3smax_speed: 160 kmphacceleration_time: 7sprice: $60,000
So what do the vectors look like?porsche = (304, 4.4, 99200)tesla = (250, 3.8, 79990)bmw = (160, 7, 60000)
Let’s plot these.
from matplotlib import pyplotfrom mpl_toolkits.mplot3d import Axes3Dfrom numpy.random import randfrom pylab import figure# featuresX = np.array([ [304, 4.4, 99200], [250, 3.8, 79990], [160, 7, 60000]])# labelsy = ['porsche', 'tesla', 'bmw']# setup our chartfig = figure()ax = Axes3D(fig)# iterate on the examples and plot themfor i in range(len(X)): ax.scatter( X[i,0], X[i,1], X[i,2], color='b') ax.text( X[i,0], X[i,1], X[i,2], '%s' % (str(y[i])), size=20, zorder=1, color='k')# label our chartax.set_xlabel('max_speed')ax.set_ylabel('acceleration_time')ax.set_zlabel('price')pyplot.show()
Cool.
It’s a little difficult to see the cars’ orientation to each other, but if we were more ambitious we’d use matplotlib’s “animation” module to view the chart from different angles.
I chose 3 continuous features because its easy to plot. In reality we could have thousands of features, In NLP where I work, this is typically the case.
But there are some mental tricks use can use to visualize more than 3 features. Like imagining each on its own bar scale. So if we had 5 features instead of 3...
It makes it easy to compute similarity between 2 objects, or relevance between a search query and an object.
How similar are our cars from above?
This similarity calculation is going to ignore some key factors (ie. the importance of each feature).
First we’ll scale our data, then calculate cosine similarity, one of the most popular similarity algorithms.
from sklearn.metrics.pairwise import cosine_similarityfrom sklearn.preprocessing import StandardScaler# scale unit variancescaler = StandardScaler()scaler.fit(X)X_scaled = scaler.transform(X)X_scaled# calculate cosine_similaritysimilarities = cosine_similarity(X_scaled,X_scaled)print(similarities)#=>[[ 1. 0.42538808 -0.9284599 ] [ 0.42538808 1. -0.73110643] [-0.9284599 -0.73110643 1. ]]
Alright! We can see that the Porsche and Tesla are more similar to each other than to the BMW.
That’s it folks.
This was a quick introduction to the vector space model and what it’s used for. While you’ll touch this with just about any machine learning project, it’s not something you need to consciously think about. And if nothing else, it’s an interesting mental model through which to view the world.
|
[
{
"code": null,
"e": 195,
"s": 171,
"text": "According to Wikipedia."
},
{
"code": null,
"e": 381,
"s": 195,
"text": "Vector space model or term vector model is an algebraic model for representing text documents (and any objects, in general) as vectors of identifiers, such as, for example, index terms."
},
{
"code": null,
"e": 458,
"s": 381,
"text": "Translation: We represent each example in our dataset as a list of features."
},
{
"code": null,
"e": 587,
"s": 458,
"text": "The model is used to represent documents in an n-dimensional space. But a “document” can mean any object you’re trying to model."
},
{
"code": null,
"e": 684,
"s": 587,
"text": "Whether you explicitly understand this or not, you’ve used it in your machine learning projects."
},
{
"code": null,
"e": 744,
"s": 684,
"text": "Just a feature of the objects we’re modelling. For example."
},
{
"code": null,
"e": 846,
"s": 744,
"text": "Houses could have dimensions: number_of_rooms, sale_price, construction_date, latitude and longitude."
},
{
"code": null,
"e": 941,
"s": 846,
"text": "People could have dimensions: age, weight, height, hair_color_is_blue and hair_color_is_other."
},
{
"code": null,
"e": 1004,
"s": 941,
"text": "Sentences could have a dimension for each possible word/token."
},
{
"code": null,
"e": 1072,
"s": 1004,
"text": "Cars could have dimensions: max_speed, acceleration_time and price."
},
{
"code": null,
"e": 1169,
"s": 1072,
"text": "In the end, features/dimensions are whatever you decide on during the feature selection process."
},
{
"code": null,
"e": 1301,
"s": 1169,
"text": "Our dimensions will be:1. max_speed (maximum speed in kmph)2. acceleration_time (number seconds to reach 100 kmph)3. price (in USD)"
},
{
"code": null,
"e": 1396,
"s": 1301,
"text": "I’ve picked 3 cars and collected their information (disclaimer: I know nothing about cars...)."
},
{
"code": null,
"e": 1473,
"s": 1396,
"text": "2020 Porsche Cayennemax_speed: 304 kmphacceleration_time: 4.4sprice: $99,200"
},
{
"code": null,
"e": 1548,
"s": 1473,
"text": "2018 Tesla Model Smax_speed: 250 kmphacceleration_time: 3.8sprice: $79,990"
},
{
"code": null,
"e": 1615,
"s": 1548,
"text": "2020 BMW i3smax_speed: 160 kmphacceleration_time: 7sprice: $60,000"
},
{
"code": null,
"e": 1722,
"s": 1615,
"text": "So what do the vectors look like?porsche = (304, 4.4, 99200)tesla = (250, 3.8, 79990)bmw = (160, 7, 60000)"
},
{
"code": null,
"e": 1740,
"s": 1722,
"text": "Let’s plot these."
},
{
"code": null,
"e": 2436,
"s": 1740,
"text": "from matplotlib import pyplotfrom mpl_toolkits.mplot3d import Axes3Dfrom numpy.random import randfrom pylab import figure# featuresX = np.array([ [304, 4.4, 99200], [250, 3.8, 79990], [160, 7, 60000]])# labelsy = ['porsche', 'tesla', 'bmw']# setup our chartfig = figure()ax = Axes3D(fig)# iterate on the examples and plot themfor i in range(len(X)): ax.scatter( X[i,0], X[i,1], X[i,2], color='b') ax.text( X[i,0], X[i,1], X[i,2], '%s' % (str(y[i])), size=20, zorder=1, color='k')# label our chartax.set_xlabel('max_speed')ax.set_ylabel('acceleration_time')ax.set_zlabel('price')pyplot.show()"
},
{
"code": null,
"e": 2442,
"s": 2436,
"text": "Cool."
},
{
"code": null,
"e": 2622,
"s": 2442,
"text": "It’s a little difficult to see the cars’ orientation to each other, but if we were more ambitious we’d use matplotlib’s “animation” module to view the chart from different angles."
},
{
"code": null,
"e": 2775,
"s": 2622,
"text": "I chose 3 continuous features because its easy to plot. In reality we could have thousands of features, In NLP where I work, this is typically the case."
},
{
"code": null,
"e": 2937,
"s": 2775,
"text": "But there are some mental tricks use can use to visualize more than 3 features. Like imagining each on its own bar scale. So if we had 5 features instead of 3..."
},
{
"code": null,
"e": 3046,
"s": 2937,
"text": "It makes it easy to compute similarity between 2 objects, or relevance between a search query and an object."
},
{
"code": null,
"e": 3083,
"s": 3046,
"text": "How similar are our cars from above?"
},
{
"code": null,
"e": 3185,
"s": 3083,
"text": "This similarity calculation is going to ignore some key factors (ie. the importance of each feature)."
},
{
"code": null,
"e": 3294,
"s": 3185,
"text": "First we’ll scale our data, then calculate cosine similarity, one of the most popular similarity algorithms."
},
{
"code": null,
"e": 3711,
"s": 3294,
"text": "from sklearn.metrics.pairwise import cosine_similarityfrom sklearn.preprocessing import StandardScaler# scale unit variancescaler = StandardScaler()scaler.fit(X)X_scaled = scaler.transform(X)X_scaled# calculate cosine_similaritysimilarities = cosine_similarity(X_scaled,X_scaled)print(similarities)#=>[[ 1. 0.42538808 -0.9284599 ] [ 0.42538808 1. -0.73110643] [-0.9284599 -0.73110643 1. ]]"
},
{
"code": null,
"e": 3806,
"s": 3711,
"text": "Alright! We can see that the Porsche and Tesla are more similar to each other than to the BMW."
},
{
"code": null,
"e": 3823,
"s": 3806,
"text": "That’s it folks."
}
] |
How I used Python to Collect Data from any Website | Towards Data Science
|
There are moments while working when you realize that you may need a large amount of data in a short amount of time. These could be instances when your boss or customer wants a specific set of information from a specific website. Maybe they want you to collect over a thousand pieces of information or data from said website. So what do you do?
One option could be to check out this website and manually type in every single piece of information requested. Or better yet, you could make Python do all the heavy lifting for you!
Utilizing one of Python’s most useful libraries, BeautifulSoup, we can collect most data displayed on any website by writing some relatively simple code. This action is called Web Scraping. In the next few parts, we will be learning and explaining the basics of BeautifulSoup and how it can be used to collect data from almost any website.
Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!
In order to learn how to use BeautifulSoup, we must first have a reason to use it. Let’s say that hypothetically, you have a customer that is looking for quotes from famous people. They want to have a new quote every week for the next year. They’ve tasked us with the job to present them with at least fifty-two quotes and their respective authors.
We can probably just go to any website to find these quotes but we will be using this website for the list of quotes. Now our customer wants these quotes formatted into a simple spreadsheet. So now we have the choice of either typing out fifty-two quotes and their respective authors in a spreadsheet or we can use Python and BeautifulSoup to do all of that for us. So for the sake of time and simplicity, we would rather go with Python and BeautifulSoup.
Let’s begin with opening up any IDE that you prefer but we will be using Jupyter Notebook. (The Github code for all of this will be available at the end of the article).
We will start by importing the libraries needed for BeautifulSoup:
from bs4 import BeautifulSoup as bsimport pandas as pdpd.set_option('display.max_colwidth', 500)import timeimport requestsimport random
Next, we’ll have to actually access the website for BeautifulSoup to parse by running the following code:
page = requests.get("http://quotes.toscrape.com/")page# <Response [200]>
This returns a response status code letting us know if the request has been successfully completed. Here we are looking for Response [200] meaning that we have successfully reached the website.
Here we will be parsing the website using BeautifulSoup.
soup = bs(page.content)soup
Running this code will return what looks like a printed text document in HTML code that looks like this:
We can navigate through the above, parsed document using BeautifulSoup.
Now we will need to find the exact thing we are looking for in the parsed HTML document. Let’s start by finding the quotes.
An easy way to find what we are looking for is by:
Going to the webpage and finding the desired piece of information (in our case, the quotes).
Highlight that piece of information (the quote)
Right click it and select Inspect
This will bring up a new window that look like this:
The highlighted section is where we will find the quote we are looking for. Just click the arrow on the left of the highlighted section to see the quote in the code.
Based on the HTML code we see highlighted we can use that information to navigate the soup. We will be using the .find_all() attribute in our own code to potentially find the quotes we are looking for. This attribute will be able to return to us the desired line (or lines) of code based on whatever arguments we give it. Since we can see that the HTML code for the quote contains class=“text”, we can use that in our BeautifulSoup code:
soup.find_all(class_='text')
Running this code will return the following results:
From this we can see that we are able to successfully locate and retrieve the code and text containing the quotes needed.
In order to only retrieve the text and exclude the unnecessary code, we will have to use the .text attribute in each result. To do so, we will have iterate through the list using a “for” loop:
quotes = [i.text for i in soup.find_all(class_='text')]quotes
This will give us the list of quotes without their respective HTML code:
Now we know how we can access the quotes within the website and retrieve them for our purposes. Repeat the steps mentioned before to retrieve the author names for each quote as well:
authors = [i.text for i in soup.find_all(class_='author')]
Now that we know how to retrieve data from a specific webpage, we can move on to the data from the next set of pages. As we can see from the website, all the quotes are not stored on a single page. We must be able to navigate to different pages in the website in order to get more quotes.
Notice that the url for each new page contains a changing value:
http://quotes.toscrape.com/page/2/
http://quotes.toscrape.com/page/3/
etc.
Knowing this we can create a simple list of URLs to iterate through in order to access different pages in the website:
urls=[f"http://quotes.toscrape.com/page/{i}/" for i in range(1,11)]urls
This returns a list of websites we can use:
From this list, we can create another “for” loop to collect the necessary number of quotes and their respective authors.
One important thing to note: some websites do not approve of web scraping. These sites will implement ways to detect if you are using a web scraping tool such as Beautiful Soup. For example, a website can detect if a large number requests were made in a short amount of time, which is what we are doing here. In order to potentially avoid detection, we can randomize our request rate to closely mimic human interaction. Here is how we do that:
Generate a list of values:
rate = [i/10 for i in range(10)]
Then at the end of every loop, input the following piece of code:
time.sleep(random.choice(rate))
Here we are randomly choosing a value from the list we created and waiting that selected amount of time before the loop begins again. This will slow down our code but will help us avoid detection.
Now that we have all the pieces, we can construct the final “for” loop that will gather at least 52 quotes and their respective authors:
Once we run the code above we will end up with a list of quotes and a list of authors. However, our customer wants the quotes in a spreadsheet. To accommodate that request, we will have to use the Python library: Pandas.
Inputting the lists into a Pandas DataFrame is very simple:
# Creating a DataFrame to store our newly scraped informationdf = pd.DataFrame()# Storing the quotes and authors in their respective columnsdf['Authors'] = authorsdf['Quotes'] = quotes
Since the quotes and the authors were scraped in order, they will be easy to input into the DataFrame.
Once we have finished and ran the code above, the final DF will look like so:
Excellent! The DF looks great and is in the exact format requested from the customer. We can then save the DF as an excel spreadsheet file which we can then send to our customer.
We hope you learned a little bit about web scraping from this step-by-step tutorial. Even though the example we used may be quite simple, the techniques used will still be applicable to many different websites all over the internet. More complex looking websites that require extensive user interaction will require another Python library called Selenium. However, most websites will only need BeautifulSoup to scrape data. The walkthrough we have done here should be enough to get you started. Happy scraping!
|
[
{
"code": null,
"e": 517,
"s": 172,
"text": "There are moments while working when you realize that you may need a large amount of data in a short amount of time. These could be instances when your boss or customer wants a specific set of information from a specific website. Maybe they want you to collect over a thousand pieces of information or data from said website. So what do you do?"
},
{
"code": null,
"e": 700,
"s": 517,
"text": "One option could be to check out this website and manually type in every single piece of information requested. Or better yet, you could make Python do all the heavy lifting for you!"
},
{
"code": null,
"e": 1040,
"s": 700,
"text": "Utilizing one of Python’s most useful libraries, BeautifulSoup, we can collect most data displayed on any website by writing some relatively simple code. This action is called Web Scraping. In the next few parts, we will be learning and explaining the basics of BeautifulSoup and how it can be used to collect data from almost any website."
},
{
"code": null,
"e": 1205,
"s": 1040,
"text": "Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!"
},
{
"code": null,
"e": 1554,
"s": 1205,
"text": "In order to learn how to use BeautifulSoup, we must first have a reason to use it. Let’s say that hypothetically, you have a customer that is looking for quotes from famous people. They want to have a new quote every week for the next year. They’ve tasked us with the job to present them with at least fifty-two quotes and their respective authors."
},
{
"code": null,
"e": 2010,
"s": 1554,
"text": "We can probably just go to any website to find these quotes but we will be using this website for the list of quotes. Now our customer wants these quotes formatted into a simple spreadsheet. So now we have the choice of either typing out fifty-two quotes and their respective authors in a spreadsheet or we can use Python and BeautifulSoup to do all of that for us. So for the sake of time and simplicity, we would rather go with Python and BeautifulSoup."
},
{
"code": null,
"e": 2180,
"s": 2010,
"text": "Let’s begin with opening up any IDE that you prefer but we will be using Jupyter Notebook. (The Github code for all of this will be available at the end of the article)."
},
{
"code": null,
"e": 2247,
"s": 2180,
"text": "We will start by importing the libraries needed for BeautifulSoup:"
},
{
"code": null,
"e": 2383,
"s": 2247,
"text": "from bs4 import BeautifulSoup as bsimport pandas as pdpd.set_option('display.max_colwidth', 500)import timeimport requestsimport random"
},
{
"code": null,
"e": 2489,
"s": 2383,
"text": "Next, we’ll have to actually access the website for BeautifulSoup to parse by running the following code:"
},
{
"code": null,
"e": 2562,
"s": 2489,
"text": "page = requests.get(\"http://quotes.toscrape.com/\")page# <Response [200]>"
},
{
"code": null,
"e": 2756,
"s": 2562,
"text": "This returns a response status code letting us know if the request has been successfully completed. Here we are looking for Response [200] meaning that we have successfully reached the website."
},
{
"code": null,
"e": 2813,
"s": 2756,
"text": "Here we will be parsing the website using BeautifulSoup."
},
{
"code": null,
"e": 2841,
"s": 2813,
"text": "soup = bs(page.content)soup"
},
{
"code": null,
"e": 2946,
"s": 2841,
"text": "Running this code will return what looks like a printed text document in HTML code that looks like this:"
},
{
"code": null,
"e": 3018,
"s": 2946,
"text": "We can navigate through the above, parsed document using BeautifulSoup."
},
{
"code": null,
"e": 3142,
"s": 3018,
"text": "Now we will need to find the exact thing we are looking for in the parsed HTML document. Let’s start by finding the quotes."
},
{
"code": null,
"e": 3193,
"s": 3142,
"text": "An easy way to find what we are looking for is by:"
},
{
"code": null,
"e": 3286,
"s": 3193,
"text": "Going to the webpage and finding the desired piece of information (in our case, the quotes)."
},
{
"code": null,
"e": 3334,
"s": 3286,
"text": "Highlight that piece of information (the quote)"
},
{
"code": null,
"e": 3368,
"s": 3334,
"text": "Right click it and select Inspect"
},
{
"code": null,
"e": 3421,
"s": 3368,
"text": "This will bring up a new window that look like this:"
},
{
"code": null,
"e": 3587,
"s": 3421,
"text": "The highlighted section is where we will find the quote we are looking for. Just click the arrow on the left of the highlighted section to see the quote in the code."
},
{
"code": null,
"e": 4025,
"s": 3587,
"text": "Based on the HTML code we see highlighted we can use that information to navigate the soup. We will be using the .find_all() attribute in our own code to potentially find the quotes we are looking for. This attribute will be able to return to us the desired line (or lines) of code based on whatever arguments we give it. Since we can see that the HTML code for the quote contains class=“text”, we can use that in our BeautifulSoup code:"
},
{
"code": null,
"e": 4054,
"s": 4025,
"text": "soup.find_all(class_='text')"
},
{
"code": null,
"e": 4107,
"s": 4054,
"text": "Running this code will return the following results:"
},
{
"code": null,
"e": 4229,
"s": 4107,
"text": "From this we can see that we are able to successfully locate and retrieve the code and text containing the quotes needed."
},
{
"code": null,
"e": 4422,
"s": 4229,
"text": "In order to only retrieve the text and exclude the unnecessary code, we will have to use the .text attribute in each result. To do so, we will have iterate through the list using a “for” loop:"
},
{
"code": null,
"e": 4484,
"s": 4422,
"text": "quotes = [i.text for i in soup.find_all(class_='text')]quotes"
},
{
"code": null,
"e": 4557,
"s": 4484,
"text": "This will give us the list of quotes without their respective HTML code:"
},
{
"code": null,
"e": 4740,
"s": 4557,
"text": "Now we know how we can access the quotes within the website and retrieve them for our purposes. Repeat the steps mentioned before to retrieve the author names for each quote as well:"
},
{
"code": null,
"e": 4799,
"s": 4740,
"text": "authors = [i.text for i in soup.find_all(class_='author')]"
},
{
"code": null,
"e": 5088,
"s": 4799,
"text": "Now that we know how to retrieve data from a specific webpage, we can move on to the data from the next set of pages. As we can see from the website, all the quotes are not stored on a single page. We must be able to navigate to different pages in the website in order to get more quotes."
},
{
"code": null,
"e": 5153,
"s": 5088,
"text": "Notice that the url for each new page contains a changing value:"
},
{
"code": null,
"e": 5188,
"s": 5153,
"text": "http://quotes.toscrape.com/page/2/"
},
{
"code": null,
"e": 5223,
"s": 5188,
"text": "http://quotes.toscrape.com/page/3/"
},
{
"code": null,
"e": 5228,
"s": 5223,
"text": "etc."
},
{
"code": null,
"e": 5347,
"s": 5228,
"text": "Knowing this we can create a simple list of URLs to iterate through in order to access different pages in the website:"
},
{
"code": null,
"e": 5419,
"s": 5347,
"text": "urls=[f\"http://quotes.toscrape.com/page/{i}/\" for i in range(1,11)]urls"
},
{
"code": null,
"e": 5463,
"s": 5419,
"text": "This returns a list of websites we can use:"
},
{
"code": null,
"e": 5584,
"s": 5463,
"text": "From this list, we can create another “for” loop to collect the necessary number of quotes and their respective authors."
},
{
"code": null,
"e": 6028,
"s": 5584,
"text": "One important thing to note: some websites do not approve of web scraping. These sites will implement ways to detect if you are using a web scraping tool such as Beautiful Soup. For example, a website can detect if a large number requests were made in a short amount of time, which is what we are doing here. In order to potentially avoid detection, we can randomize our request rate to closely mimic human interaction. Here is how we do that:"
},
{
"code": null,
"e": 6055,
"s": 6028,
"text": "Generate a list of values:"
},
{
"code": null,
"e": 6088,
"s": 6055,
"text": "rate = [i/10 for i in range(10)]"
},
{
"code": null,
"e": 6154,
"s": 6088,
"text": "Then at the end of every loop, input the following piece of code:"
},
{
"code": null,
"e": 6186,
"s": 6154,
"text": "time.sleep(random.choice(rate))"
},
{
"code": null,
"e": 6383,
"s": 6186,
"text": "Here we are randomly choosing a value from the list we created and waiting that selected amount of time before the loop begins again. This will slow down our code but will help us avoid detection."
},
{
"code": null,
"e": 6520,
"s": 6383,
"text": "Now that we have all the pieces, we can construct the final “for” loop that will gather at least 52 quotes and their respective authors:"
},
{
"code": null,
"e": 6741,
"s": 6520,
"text": "Once we run the code above we will end up with a list of quotes and a list of authors. However, our customer wants the quotes in a spreadsheet. To accommodate that request, we will have to use the Python library: Pandas."
},
{
"code": null,
"e": 6801,
"s": 6741,
"text": "Inputting the lists into a Pandas DataFrame is very simple:"
},
{
"code": null,
"e": 6986,
"s": 6801,
"text": "# Creating a DataFrame to store our newly scraped informationdf = pd.DataFrame()# Storing the quotes and authors in their respective columnsdf['Authors'] = authorsdf['Quotes'] = quotes"
},
{
"code": null,
"e": 7089,
"s": 6986,
"text": "Since the quotes and the authors were scraped in order, they will be easy to input into the DataFrame."
},
{
"code": null,
"e": 7167,
"s": 7089,
"text": "Once we have finished and ran the code above, the final DF will look like so:"
},
{
"code": null,
"e": 7346,
"s": 7167,
"text": "Excellent! The DF looks great and is in the exact format requested from the customer. We can then save the DF as an excel spreadsheet file which we can then send to our customer."
}
] |
Distributed DBMS - Quick Guide
|
For proper functioning of any organization, there’s a need for a well-maintained database. In the recent past, databases used to be centralized in nature. However, with the increase in globalization, organizations tend to be diversified across the globe. They may choose to distribute data over local servers instead of a central database. Thus, arrived the concept of Distributed Databases.
This chapter gives an overview of databases and Database Management Systems (DBMS). A database is an ordered collection of related data. A DBMS is a software package to work upon a database. A detailed study of DBMS is available in our tutorial named “Learn DBMS”. In this chapter, we revise the main concepts so that the study of DDBMS can be done with ease. The three topics covered are database schemas, types of databases and operations on databases.
A database is an ordered collection of related data that is built for a specific purpose. A database may be organized as a collection of multiple tables, where a table represents a real world element or entity. Each table has several different fields that represent the characteristic features of the entity.
For example, a company database may include tables for projects, employees, departments, products and financial records. The fields in the Employee table may be Name, Company_Id, Date_of_Joining, and so forth.
A database management system is a collection of programs that enables creation and maintenance of a database. DBMS is available as a software package that facilitates definition, construction, manipulation and sharing of data in a database. Definition of a database includes description of the structure of a database. Construction of a database involves actual storing of the data in any storage medium. Manipulation refers to the retrieving information from the database, updating the database and generating reports. Sharing of data facilitates data to be accessed by different users or programs.
Automatic Teller Machines
Train Reservation System
Employee Management System
Student Information System
MySQL
Oracle
SQL Server
dBASE
FoxPro
PostgreSQL, etc.
A database schema is a description of the database which is specified during database design and subject to infrequent alterations. It defines the organization of the data, the relationships among them, and the constraints associated with them.
Databases are often represented through the three-schema architecture or ANSISPARC architecture. The goal of this architecture is to separate the user application from the physical database. The three levels are −
Internal Level having Internal Schema − It describes the physical structure, details of internal storage and access paths for the database.
Internal Level having Internal Schema − It describes the physical structure, details of internal storage and access paths for the database.
Conceptual Level having Conceptual Schema − It describes the structure of the whole database while hiding the details of physical storage of data. This illustrates the entities, attributes with their data types and constraints, user operations and relationships.
Conceptual Level having Conceptual Schema − It describes the structure of the whole database while hiding the details of physical storage of data. This illustrates the entities, attributes with their data types and constraints, user operations and relationships.
External or View Level having External Schemas or Views − It describes the portion of a database relevant to a particular user or a group of users while hiding the rest of database.
External or View Level having External Schemas or Views − It describes the portion of a database relevant to a particular user or a group of users while hiding the rest of database.
There are four types of DBMS.
In hierarchical DBMS, the relationships among data in the database are established so that one data element exists as a subordinate of another. The data elements have parent-child relationships and are modelled using the “tree” data structure. These are very fast and simple.
Network DBMS in one where the relationships among data in the database are of type many-to-many in the form of a network. The structure is generally complicated due to the existence of numerous many-to-many relationships. Network DBMS is modelled using “graph” data structure.
In relational databases, the database is represented in the form of relations. Each relation models an entity and is represented as a table of values. In the relation or table, a row is called a tuple and denotes a single record. A column is called a field or an attribute and denotes a characteristic property of the entity. RDBMS is the most popular database management system.
For example − A Student Relation −
Object-oriented DBMS is derived from the model of the object-oriented programming paradigm. They are helpful in representing both consistent data as stored in databases, as well as transient data, as found in executing programs. They use small, reusable elements called objects. Each object contains a data part and a set of operations which works upon the data. The object and its attributes are accessed through pointers instead of being stored in relational table models.
For example − A simplified Bank Account object-oriented database −
A distributed database is a set of interconnected databases that is distributed over the computer network or internet. A Distributed Database Management System (DDBMS) manages the distributed database and provides mechanisms so as to make the databases transparent to the users. In these systems, data is intentionally distributed among multiple nodes so that all computing resources of the organization can be optimally used.
The four basic operations on a database are Create, Retrieve, Update and Delete.
CREATE database structure and populate it with data − Creation of a database relation involves specifying the data structures, data types and the constraints of the data to be stored.
Example − SQL command to create a student table −
CREATE database structure and populate it with data − Creation of a database relation involves specifying the data structures, data types and the constraints of the data to be stored.
Example − SQL command to create a student table −
CREATE TABLE STUDENT (
ROLL INTEGER PRIMARY KEY,
NAME VARCHAR2(25),
YEAR INTEGER,
STREAM VARCHAR2(10)
);
Once the data format is defined, the actual data is stored in accordance with the format in some storage medium.
Example SQL command to insert a single tuple into the student table −
Once the data format is defined, the actual data is stored in accordance with the format in some storage medium.
Example SQL command to insert a single tuple into the student table −
INSERT INTO STUDENT ( ROLL, NAME, YEAR, STREAM)
VALUES ( 1, 'ANKIT JHA', 1, 'COMPUTER SCIENCE');
RETRIEVE information from the database – Retrieving information generally involves selecting a subset of a table or displaying data from the table after some computations have been done. It is done by querying upon the table.
Example − To retrieve the names of all students of the Computer Science stream, the following SQL query needs to be executed −
RETRIEVE information from the database – Retrieving information generally involves selecting a subset of a table or displaying data from the table after some computations have been done. It is done by querying upon the table.
Example − To retrieve the names of all students of the Computer Science stream, the following SQL query needs to be executed −
SELECT NAME FROM STUDENT
WHERE STREAM = 'COMPUTER SCIENCE';
UPDATE information stored and modify database structure – Updating a table involves changing old values in the existing table’s rows with new values.
Example − SQL command to change stream from Electronics to Electronics and Communications −
UPDATE information stored and modify database structure – Updating a table involves changing old values in the existing table’s rows with new values.
Example − SQL command to change stream from Electronics to Electronics and Communications −
UPDATE STUDENT
SET STREAM = 'ELECTRONICS AND COMMUNICATIONS'
WHERE STREAM = 'ELECTRONICS';
Modifying database means to change the structure of the table. However, modification of the table is subject to a number of restrictions.
Example − To add a new field or column, say address to the Student table, we use the following SQL command −
Modifying database means to change the structure of the table. However, modification of the table is subject to a number of restrictions.
Example − To add a new field or column, say address to the Student table, we use the following SQL command −
ALTER TABLE STUDENT
ADD ( ADDRESS VARCHAR2(50) );
DELETE information stored or delete a table as a whole – Deletion of specific information involves removal of selected rows from the table that satisfies certain conditions.
Example − To delete all students who are in 4th year currently when they are passing out, we use the SQL command −
DELETE information stored or delete a table as a whole – Deletion of specific information involves removal of selected rows from the table that satisfies certain conditions.
Example − To delete all students who are in 4th year currently when they are passing out, we use the SQL command −
DELETE FROM STUDENT
WHERE YEAR = 4;
Alternatively, the whole table may be removed from the database.
Example − To remove the student table completely, the SQL command used is −
Alternatively, the whole table may be removed from the database.
Example − To remove the student table completely, the SQL command used is −
DROP TABLE STUDENT;
This chapter introduces the concept of DDBMS. In a distributed database, there are a number of databases that may be geographically distributed all over the world. A distributed DBMS manages the distributed database in a manner so that it appears as one single database to users. In the later part of the chapter, we go on to study the factors that lead to distributed databases, its advantages and disadvantages.
A distributed database is a collection of multiple interconnected databases, which are spread physically across various locations that communicate via a computer network.
Databases in the collection are logically interrelated with each other. Often they represent a single logical database.
Databases in the collection are logically interrelated with each other. Often they represent a single logical database.
Data is physically stored across multiple sites. Data in each site can be managed by a DBMS independent of the other sites.
Data is physically stored across multiple sites. Data in each site can be managed by a DBMS independent of the other sites.
The processors in the sites are connected via a network. They do not have any multiprocessor configuration.
The processors in the sites are connected via a network. They do not have any multiprocessor configuration.
A distributed database is not a loosely connected file system.
A distributed database is not a loosely connected file system.
A distributed database incorporates transaction processing, but it is not synonymous with a transaction processing system.
A distributed database incorporates transaction processing, but it is not synonymous with a transaction processing system.
A distributed database management system (DDBMS) is a centralized software system that manages a distributed database in a manner as if it were all stored in a single location.
It is used to create, retrieve, update and delete distributed databases.
It is used to create, retrieve, update and delete distributed databases.
It synchronizes the database periodically and provides access mechanisms by the virtue of which the distribution becomes transparent to the users.
It synchronizes the database periodically and provides access mechanisms by the virtue of which the distribution becomes transparent to the users.
It ensures that the data modified at any site is universally updated.
It ensures that the data modified at any site is universally updated.
It is used in application areas where large volumes of data are processed and accessed by numerous users simultaneously.
It is used in application areas where large volumes of data are processed and accessed by numerous users simultaneously.
It is designed for heterogeneous database platforms.
It is designed for heterogeneous database platforms.
It maintains confidentiality and data integrity of the databases.
It maintains confidentiality and data integrity of the databases.
The following factors encourage moving over to DDBMS −
Distributed Nature of Organizational Units − Most organizations in the current times are subdivided into multiple units that are physically distributed over the globe. Each unit requires its own set of local data. Thus, the overall database of the organization becomes distributed.
Distributed Nature of Organizational Units − Most organizations in the current times are subdivided into multiple units that are physically distributed over the globe. Each unit requires its own set of local data. Thus, the overall database of the organization becomes distributed.
Need for Sharing of Data − The multiple organizational units often need to communicate with each other and share their data and resources. This demands common databases or replicated databases that should be used in a synchronized manner.
Need for Sharing of Data − The multiple organizational units often need to communicate with each other and share their data and resources. This demands common databases or replicated databases that should be used in a synchronized manner.
Support for Both OLTP and OLAP − Online Transaction Processing (OLTP) and Online Analytical Processing (OLAP) work upon diversified systems which may have common data. Distributed database systems aid both these processing by providing synchronized data.
Support for Both OLTP and OLAP − Online Transaction Processing (OLTP) and Online Analytical Processing (OLAP) work upon diversified systems which may have common data. Distributed database systems aid both these processing by providing synchronized data.
Database Recovery − One of the common techniques used in DDBMS is replication of data across different sites. Replication of data automatically helps in data recovery if database in any site is damaged. Users can access data from other sites while the damaged site is being reconstructed. Thus, database failure may become almost inconspicuous to users.
Database Recovery − One of the common techniques used in DDBMS is replication of data across different sites. Replication of data automatically helps in data recovery if database in any site is damaged. Users can access data from other sites while the damaged site is being reconstructed. Thus, database failure may become almost inconspicuous to users.
Support for Multiple Application Software − Most organizations use a variety of application software each with its specific database support. DDBMS provides a uniform functionality for using the same data among different platforms.
Support for Multiple Application Software − Most organizations use a variety of application software each with its specific database support. DDBMS provides a uniform functionality for using the same data among different platforms.
Following are the advantages of distributed databases over centralized databases.
Modular Development − If the system needs to be expanded to new locations or new units, in centralized database systems, the action requires substantial efforts and disruption in the existing functioning. However, in distributed databases, the work simply requires adding new computers and local data to the new site and finally connecting them to the distributed system, with no interruption in current functions.
More Reliable − In case of database failures, the total system of centralized databases comes to a halt. However, in distributed systems, when a component fails, the functioning of the system continues may be at a reduced performance. Hence DDBMS is more reliable.
Better Response − If data is distributed in an efficient manner, then user requests can be met from local data itself, thus providing faster response. On the other hand, in centralized systems, all queries have to pass through the central computer for processing, which increases the response time.
Lower Communication Cost − In distributed database systems, if data is located locally where it is mostly used, then the communication costs for data manipulation can be minimized. This is not feasible in centralized systems.
Following are some of the adversities associated with distributed databases.
Need for complex and expensive software − DDBMS demands complex and often expensive software to provide data transparency and co-ordination across the several sites.
Need for complex and expensive software − DDBMS demands complex and often expensive software to provide data transparency and co-ordination across the several sites.
Processing overhead − Even simple operations may require a large number of communications and additional calculations to provide uniformity in data across the sites.
Processing overhead − Even simple operations may require a large number of communications and additional calculations to provide uniformity in data across the sites.
Data integrity − The need for updating data in multiple sites pose problems of data integrity.
Data integrity − The need for updating data in multiple sites pose problems of data integrity.
Overheads for improper data distribution − Responsiveness of queries is largely dependent upon proper data distribution. Improper data distribution often leads to very slow response to user requests.
Overheads for improper data distribution − Responsiveness of queries is largely dependent upon proper data distribution. Improper data distribution often leads to very slow response to user requests.
In this part of the tutorial, we will study the different aspects that aid in designing distributed database environments. This chapter starts with the types of distributed databases. Distributed databases can be classified into homogeneous and heterogeneous databases having further divisions. The next section of this chapter discusses the distributed architectures namely client – server, peer – to – peer and multi – DBMS. Finally, the different design alternatives like replication and fragmentation are introduced.
Distributed databases can be broadly classified into homogeneous and heterogeneous distributed database environments, each with further sub-divisions, as shown in the following illustration.
In a homogeneous distributed database, all the sites use identical DBMS and operating systems. Its properties are −
The sites use very similar software.
The sites use very similar software.
The sites use identical DBMS or DBMS from the same vendor.
The sites use identical DBMS or DBMS from the same vendor.
Each site is aware of all other sites and cooperates with other sites to process user requests.
Each site is aware of all other sites and cooperates with other sites to process user requests.
The database is accessed through a single interface as if it is a single database.
The database is accessed through a single interface as if it is a single database.
There are two types of homogeneous distributed database −
Autonomous − Each database is independent that functions on its own. They are integrated by a controlling application and use message passing to share data updates.
Autonomous − Each database is independent that functions on its own. They are integrated by a controlling application and use message passing to share data updates.
Non-autonomous − Data is distributed across the homogeneous nodes and a central or master DBMS co-ordinates data updates across the sites.
Non-autonomous − Data is distributed across the homogeneous nodes and a central or master DBMS co-ordinates data updates across the sites.
In a heterogeneous distributed database, different sites have different operating systems, DBMS products and data models. Its properties are −
Different sites use dissimilar schemas and software.
Different sites use dissimilar schemas and software.
The system may be composed of a variety of DBMSs like relational, network, hierarchical or object oriented.
The system may be composed of a variety of DBMSs like relational, network, hierarchical or object oriented.
Query processing is complex due to dissimilar schemas.
Query processing is complex due to dissimilar schemas.
Transaction processing is complex due to dissimilar software.
Transaction processing is complex due to dissimilar software.
A site may not be aware of other sites and so there is limited co-operation in processing user requests.
A site may not be aware of other sites and so there is limited co-operation in processing user requests.
Federated − The heterogeneous database systems are independent in nature and integrated together so that they function as a single database system.
Federated − The heterogeneous database systems are independent in nature and integrated together so that they function as a single database system.
Un-federated − The database systems employ a central coordinating module through which the databases are accessed.
Un-federated − The database systems employ a central coordinating module through which the databases are accessed.
DDBMS architectures are generally developed depending on three parameters −
Distribution − It states the physical distribution of data across the different sites.
Distribution − It states the physical distribution of data across the different sites.
Autonomy − It indicates the distribution of control of the database system and the degree to which each constituent DBMS can operate independently.
Autonomy − It indicates the distribution of control of the database system and the degree to which each constituent DBMS can operate independently.
Heterogeneity − It refers to the uniformity or dissimilarity of the data models, system components and databases.
Heterogeneity − It refers to the uniformity or dissimilarity of the data models, system components and databases.
Some of the common architectural models are −
Client - Server Architecture for DDBMS
Peer - to - Peer Architecture for DDBMS
Multi - DBMS Architecture
This is a two-level architecture where the functionality is divided into servers and clients. The server functions primarily encompass data management, query processing, optimization and transaction management. Client functions include mainly user interface. However, they have some functions like consistency checking and transaction management.
The two different client - server architecture are −
Single Server Multiple Client
Multiple Server Multiple Client (shown in the following diagram)
In these systems, each peer acts both as a client and a server for imparting database services. The peers share their resource with other peers and co-ordinate their activities.
This architecture generally has four levels of schemas −
Global Conceptual Schema − Depicts the global logical view of data.
Global Conceptual Schema − Depicts the global logical view of data.
Local Conceptual Schema − Depicts logical data organization at each site.
Local Conceptual Schema − Depicts logical data organization at each site.
Local Internal Schema − Depicts physical data organization at each site.
Local Internal Schema − Depicts physical data organization at each site.
External Schema − Depicts user view of data.
External Schema − Depicts user view of data.
This is an integrated database system formed by a collection of two or more autonomous database systems.
Multi-DBMS can be expressed through six levels of schemas −
Multi-database View Level − Depicts multiple user views comprising of subsets of the integrated distributed database.
Multi-database View Level − Depicts multiple user views comprising of subsets of the integrated distributed database.
Multi-database Conceptual Level − Depicts integrated multi-database that comprises of global logical multi-database structure definitions.
Multi-database Conceptual Level − Depicts integrated multi-database that comprises of global logical multi-database structure definitions.
Multi-database Internal Level − Depicts the data distribution across different sites and multi-database to local data mapping.
Multi-database Internal Level − Depicts the data distribution across different sites and multi-database to local data mapping.
Local database View Level − Depicts public view of local data.
Local database View Level − Depicts public view of local data.
Local database Conceptual Level − Depicts local data organization at each site.
Local database Conceptual Level − Depicts local data organization at each site.
Local database Internal Level − Depicts physical data organization at each site.
Local database Internal Level − Depicts physical data organization at each site.
There are two design alternatives for multi-DBMS −
Model with multi-database conceptual level.
Model without multi-database conceptual level.
The distribution design alternatives for the tables in a DDBMS are as follows −
Non-replicated and non-fragmented
Fully replicated
Partially replicated
Fragmented
Mixed
In this design alternative, different tables are placed at different sites. Data is placed so that it is at a close proximity to the site where it is used most. It is most suitable for database systems where the percentage of queries needed to join information in tables placed at different sites is low. If an appropriate distribution strategy is adopted, then this design alternative helps to reduce the communication cost during data processing.
In this design alternative, at each site, one copy of all the database tables is stored. Since, each site has its own copy of the entire database, queries are very fast requiring negligible communication cost. On the contrary, the massive redundancy in data requires huge cost during update operations. Hence, this is suitable for systems where a large number of queries is required to be handled whereas the number of database updates is low.
Copies of tables or portions of tables are stored at different sites. The distribution of the tables is done in accordance to the frequency of access. This takes into consideration the fact that the frequency of accessing the tables vary considerably from site to site. The number of copies of the tables (or portions) depends on how frequently the access queries execute and the site which generate the access queries.
In this design, a table is divided into two or more pieces referred to as fragments or partitions, and each fragment can be stored at different sites. This considers the fact that it seldom happens that all data stored in a table is required at a given site. Moreover, fragmentation increases parallelism and provides better disaster recovery. Here, there is only one copy of each fragment in the system, i.e. no redundant data.
The three fragmentation techniques are −
Vertical fragmentation
Horizontal fragmentation
Hybrid fragmentation
This is a combination of fragmentation and partial replications. Here, the tables are initially fragmented in any form (horizontal or vertical), and then these fragments are partially replicated across the different sites according to the frequency of accessing the fragments.
In the last chapter, we had introduced different design alternatives. In this chapter, we will study the strategies that aid in adopting the designs. The strategies can be broadly divided into replication and fragmentation. However, in most cases, a combination of the two is used.
Data replication is the process of storing separate copies of the database at two or more sites. It is a popular fault tolerance technique of distributed databases.
Reliability − In case of failure of any site, the database system continues to work since a copy is available at another site(s).
Reliability − In case of failure of any site, the database system continues to work since a copy is available at another site(s).
Reduction in Network Load − Since local copies of data are available, query processing can be done with reduced network usage, particularly during prime hours. Data updating can be done at non-prime hours.
Reduction in Network Load − Since local copies of data are available, query processing can be done with reduced network usage, particularly during prime hours. Data updating can be done at non-prime hours.
Quicker Response − Availability of local copies of data ensures quick query processing and consequently quick response time.
Quicker Response − Availability of local copies of data ensures quick query processing and consequently quick response time.
Simpler Transactions − Transactions require less number of joins of tables located at different sites and minimal coordination across the network. Thus, they become simpler in nature.
Simpler Transactions − Transactions require less number of joins of tables located at different sites and minimal coordination across the network. Thus, they become simpler in nature.
Increased Storage Requirements − Maintaining multiple copies of data is associated with increased storage costs. The storage space required is in multiples of the storage required for a centralized system.
Increased Storage Requirements − Maintaining multiple copies of data is associated with increased storage costs. The storage space required is in multiples of the storage required for a centralized system.
Increased Cost and Complexity of Data Updating − Each time a data item is updated, the update needs to be reflected in all the copies of the data at the different sites. This requires complex synchronization techniques and protocols.
Increased Cost and Complexity of Data Updating − Each time a data item is updated, the update needs to be reflected in all the copies of the data at the different sites. This requires complex synchronization techniques and protocols.
Undesirable Application – Database coupling − If complex update mechanisms are not used, removing data inconsistency requires complex co-ordination at application level. This results in undesirable application – database coupling.
Undesirable Application – Database coupling − If complex update mechanisms are not used, removing data inconsistency requires complex co-ordination at application level. This results in undesirable application – database coupling.
Some commonly used replication techniques are −
Snapshot replication
Near-real-time replication
Pull replication
Fragmentation is the task of dividing a table into a set of smaller tables. The subsets of the table are called fragments. Fragmentation can be of three types: horizontal, vertical, and hybrid (combination of horizontal and vertical). Horizontal fragmentation can further be classified into two techniques: primary horizontal fragmentation and derived horizontal fragmentation.
Fragmentation should be done in a way so that the original table can be reconstructed from the fragments. This is needed so that the original table can be reconstructed from the fragments whenever required. This requirement is called “reconstructiveness.”
Since data is stored close to the site of usage, efficiency of the database system is increased.
Since data is stored close to the site of usage, efficiency of the database system is increased.
Local query optimization techniques are sufficient for most queries since data is locally available.
Local query optimization techniques are sufficient for most queries since data is locally available.
Since irrelevant data is not available at the sites, security and privacy of the database system can be maintained.
Since irrelevant data is not available at the sites, security and privacy of the database system can be maintained.
When data from different fragments are required, the access speeds may be very low.
When data from different fragments are required, the access speeds may be very low.
In case of recursive fragmentations, the job of reconstruction will need expensive techniques.
In case of recursive fragmentations, the job of reconstruction will need expensive techniques.
Lack of back-up copies of data in different sites may render the database ineffective in case of failure of a site.
Lack of back-up copies of data in different sites may render the database ineffective in case of failure of a site.
In vertical fragmentation, the fields or columns of a table are grouped into fragments. In order to maintain reconstructiveness, each fragment should contain the primary key field(s) of the table. Vertical fragmentation can be used to enforce privacy of data.
For example, let us consider that a University database keeps records of all registered students in a Student table having the following schema.
STUDENT
Now, the fees details are maintained in the accounts section. In this case, the designer will fragment the database as follows −
CREATE TABLE STD_FEES AS
SELECT Regd_No, Fees
FROM STUDENT;
Horizontal fragmentation groups the tuples of a table in accordance to values of one or more fields. Horizontal fragmentation should also confirm to the rule of reconstructiveness. Each horizontal fragment must have all columns of the original base table.
For example, in the student schema, if the details of all students of Computer Science Course needs to be maintained at the School of Computer Science, then the designer will horizontally fragment the database as follows −
CREATE COMP_STD AS
SELECT * FROM STUDENT
WHERE COURSE = "Computer Science";
In hybrid fragmentation, a combination of horizontal and vertical fragmentation techniques are used. This is the most flexible fragmentation technique since it generates fragments with minimal extraneous information. However, reconstruction of the original table is often an expensive task.
Hybrid fragmentation can be done in two alternative ways −
At first, generate a set of horizontal fragments; then generate vertical fragments from one or more of the horizontal fragments.
At first, generate a set of horizontal fragments; then generate vertical fragments from one or more of the horizontal fragments.
At first, generate a set of vertical fragments; then generate horizontal fragments from one or more of the vertical fragments.
At first, generate a set of vertical fragments; then generate horizontal fragments from one or more of the vertical fragments.
Distribution transparency is the property of distributed databases by the virtue of which the internal details of the distribution are hidden from the users. The DDBMS designer may choose to fragment tables, replicate the fragments and store them at different sites. However, since users are oblivious of these details, they find the distributed database easy to use like any centralized database.
The three dimensions of distribution transparency are −
Location transparency
Fragmentation transparency
Replication transparency
Location transparency ensures that the user can query on any table(s) or fragment(s) of a table as if they were stored locally in the user’s site. The fact that the table or its fragments are stored at remote site in the distributed database system, should be completely oblivious to the end user. The address of the remote site(s) and the access mechanisms are completely hidden.
In order to incorporate location transparency, DDBMS should have access to updated and accurate data dictionary and DDBMS directory which contains the details of locations of data.
Fragmentation transparency enables users to query upon any table as if it were unfragmented. Thus, it hides the fact that the table the user is querying on is actually a fragment or union of some fragments. It also conceals the fact that the fragments are located at diverse sites.
This is somewhat similar to users of SQL views, where the user may not know that they are using a view of a table instead of the table itself.
Replication transparency ensures that replication of databases are hidden from the users. It enables users to query upon a table as if only a single copy of the table exists.
Replication transparency is associated with concurrency transparency and failure transparency. Whenever a user updates a data item, the update is reflected in all the copies of the table. However, this operation should not be known to the user. This is concurrency transparency. Also, in case of failure of a site, the user can still proceed with his queries using replicated copies without any knowledge of failure. This is failure transparency.
In any distributed database system, the designer should ensure that all the stated transparencies are maintained to a considerable extent. The designer may choose to fragment tables, replicate them and store them at different sites; all oblivious to the end user. However, complete distribution transparency is a tough task and requires considerable design efforts.
Database control refers to the task of enforcing regulations so as to provide correct data to authentic users and applications of a database. In order that correct data is available to users, all data should conform to the integrity constraints defined in the database. Besides, data should be screened away from unauthorized users so as to maintain security and privacy of the database. Database control is one of the primary tasks of the database administrator (DBA).
The three dimensions of database control are −
Authentication
Access rights
Integrity constraints
In a distributed database system, authentication is the process through which only legitimate users can gain access to the data resources.
Authentication can be enforced in two levels −
Controlling Access to Client Computer − At this level, user access is restricted while login to the client computer that provides user-interface to the database server. The most common method is a username/password combination. However, more sophisticated methods like biometric authentication may be used for high security data.
Controlling Access to Client Computer − At this level, user access is restricted while login to the client computer that provides user-interface to the database server. The most common method is a username/password combination. However, more sophisticated methods like biometric authentication may be used for high security data.
Controlling Access to the Database Software − At this level, the database software/administrator assigns some credentials to the user. The user gains access to the database using these credentials. One of the methods is to create a login account within the database server.
Controlling Access to the Database Software − At this level, the database software/administrator assigns some credentials to the user. The user gains access to the database using these credentials. One of the methods is to create a login account within the database server.
A user’s access rights refers to the privileges that the user is given regarding DBMS operations such as the rights to create a table, drop a table, add/delete/update tuples in a table or query upon the table.
In distributed environments, since there are large number of tables and yet larger number of users, it is not feasible to assign individual access rights to users. So, DDBMS defines certain roles. A role is a construct with certain privileges within a database system. Once the different roles are defined, the individual users are assigned one of these roles. Often a hierarchy of roles are defined according to the organization’s hierarchy of authority and responsibility.
For example, the following SQL statements create a role "Accountant" and then assigns this role to user "ABC".
CREATE ROLE ACCOUNTANT;
GRANT SELECT, INSERT, UPDATE ON EMP_SAL TO ACCOUNTANT;
GRANT INSERT, UPDATE, DELETE ON TENDER TO ACCOUNTANT;
GRANT INSERT, SELECT ON EXPENSE TO ACCOUNTANT;
COMMIT;
GRANT ACCOUNTANT TO ABC;
COMMIT;
Semantic integrity control defines and enforces the integrity constraints of the database system.
The integrity constraints are as follows −
Data type integrity constraint
Entity integrity constraint
Referential integrity constraint
A data type constraint restricts the range of values and the type of operations that can be applied to the field with the specified data type.
For example, let us consider that a table "HOSTEL" has three fields - the hostel number, hostel name and capacity. The hostel number should start with capital letter "H" and cannot be NULL, and the capacity should not be more than 150. The following SQL command can be used for data definition −
CREATE TABLE HOSTEL (
H_NO VARCHAR2(5) NOT NULL,
H_NAME VARCHAR2(15),
CAPACITY INTEGER,
CHECK ( H_NO LIKE 'H%'),
CHECK ( CAPACITY <= 150)
);
Entity integrity control enforces the rules so that each tuple can be uniquely identified from other tuples. For this a primary key is defined. A primary key is a set of minimal fields that can uniquely identify a tuple. Entity integrity constraint states that no two tuples in a table can have identical values for primary keys and that no field which is a part of the primary key can have NULL value.
For example, in the above hostel table, the hostel number can be assigned as the primary key through the following SQL statement (ignoring the checks) −
CREATE TABLE HOSTEL (
H_NO VARCHAR2(5) PRIMARY KEY,
H_NAME VARCHAR2(15),
CAPACITY INTEGER
);
Referential integrity constraint lays down the rules of foreign keys. A foreign key is a field in a data table that is the primary key of a related table. The referential integrity constraint lays down the rule that the value of the foreign key field should either be among the values of the primary key of the referenced table or be entirely NULL.
For example, let us consider a student table where a student may opt to live in a hostel. To include this, the primary key of hostel table should be included as a foreign key in the student table. The following SQL statement incorporates this −
CREATE TABLE STUDENT (
S_ROLL INTEGER PRIMARY KEY,
S_NAME VARCHAR2(25) NOT NULL,
S_COURSE VARCHAR2(10),
S_HOSTEL VARCHAR2(5) REFERENCES HOSTEL
);
When a query is placed, it is at first scanned, parsed and validated. An internal representation of the query is then created such as a query tree or a query graph. Then alternative execution strategies are devised for retrieving results from the database tables. The process of choosing the most appropriate execution strategy for query processing is called query optimization.
In DDBMS, query optimization is a crucial task. The complexity is high since number of alternative strategies may increase exponentially due to the following factors −
The presence of a number of fragments.
Distribution of the fragments or tables across various sites.
The speed of communication links.
Disparity in local processing capabilities.
Hence, in a distributed system, the target is often to find a good execution strategy for query processing rather than the best one. The time to execute a query is the sum of the following −
Time to communicate queries to databases.
Time to execute local query fragments.
Time to assemble data from different sites.
Time to display results to the application.
Query processing is a set of all activities starting from query placement to displaying the results of the query. The steps are as shown in the following diagram −
Relational algebra defines the basic set of operations of relational database model. A sequence of relational algebra operations forms a relational algebra expression. The result of this expression represents the result of a database query.
The basic operations are −
Projection
Selection
Union
Intersection
Minus
Join
Projection operation displays a subset of fields of a table. This gives a vertical partition of the table.
Syntax in Relational Algebra
π<AttributeList>(<TableName>)
For example, let us consider the following Student database −
If we want to display the names and courses of all students, we will use the following relational algebra expression −
πName,Course(STUDENT)
Selection operation displays a subset of tuples of a table that satisfies certain conditions. This gives a horizontal partition of the table.
Syntax in Relational Algebra
σ<Conditions>(<TableName>)
For example, in the Student table, if we want to display the details of all students who have opted for MCA course, we will use the following relational algebra expression −
σCourse="BCA"(STUDENT)
For most queries, we need a combination of projection and selection operations. There are two ways to write these expressions −
Using sequence of projection and selection operations.
Using rename operation to generate intermediate results.
For example, to display names of all female students of the BCA course −
Relational algebra expression using sequence of projection and selection operations
πName(σGender="Female"ANDCourse="BCA"(STUDENT))
Relational algebra expression using rename operation to generate intermediate results
FemaleBCAStudent←σGender="Female"ANDCourse="BCA"(STUDENT)
Result←πName(FemaleBCAStudent)
If P is a result of an operation and Q is a result of another operation, the union of P and Q (p∪Q) is the set of all tuples that is either in P or in Q or in both without duplicates.
For example, to display all students who are either in Semester 1 or are in BCA course −
Sem1Student←σSemester=1(STUDENT)
BCAStudent←σCourse="BCA"(STUDENT)
Result←Sem1Student∪BCAStudent
If P is a result of an operation and Q is a result of another operation, the intersection of P and Q ( p∩Q ) is the set of all tuples that are in P and Q both.
For example, given the following two schemas −
EMPLOYEE
PROJECT
To display the names of all cities where a project is located and also an employee resides −
CityEmp←πCity(EMPLOYEE)
CityProject←πCity(PROJECT)
Result←CityEmp∩CityProject
If P is a result of an operation and Q is a result of another operation, P - Q is the set of all tuples that are in P and not in Q.
For example, to list all the departments which do not have an ongoing project (projects with status = ongoing) −
AllDept←πDepartment(EMPLOYEE)
ProjectDept←πDepartment(σStatus="ongoing"(PROJECT))
Result←AllDept−ProjectDept
Join operation combines related tuples of two different tables (results of queries) into a single table.
For example, consider two schemas, Customer and Branch in a Bank database as follows −
CUSTOMER
BRANCH
To list the employee details along with branch details −
Result←CUSTOMER⋈Customer.BranchID=Branch.BranchIDBRANCH
SQL queries are translated into equivalent relational algebra expressions before optimization. A query is at first decomposed into smaller query blocks. These blocks are translated to equivalent relational algebra expressions. Optimization includes optimization of each block and then optimization of the query as a whole.
Let us consider the following schemas −
EMPLOYEE
PROJECT
WORKS
To display the details of all employees who earn a salary LESS than the average salary, we write the SQL query −
SELECT * FROM EMPLOYEE
WHERE SALARY < ( SELECT AVERAGE(SALARY) FROM EMPLOYEE ) ;
This query contains one nested sub-query. So, this can be broken down into two blocks.
The inner block is −
SELECT AVERAGE(SALARY)FROM EMPLOYEE ;
If the result of this query is AvgSal, then outer block is −
SELECT * FROM EMPLOYEE WHERE SALARY < AvgSal;
Relational algebra expression for inner block −
AvgSal←IAVERAGE(Salary)EMPLOYEE
Relational algebra expression for outer block −
σSalary<AvgSal>EMPLOYEE
To display the project ID and status of all projects of employee 'Arun Kumar', we write the SQL query −
SELECT PID, STATUS FROM PROJECT
WHERE PID = ( SELECT FROM WORKS WHERE EMPID = ( SELECT EMPID FROM EMPLOYEE
WHERE NAME = 'ARUN KUMAR'));
This query contains two nested sub-queries. Thus, can be broken down into three blocks, as follows −
SELECT EMPID FROM EMPLOYEE WHERE NAME = 'ARUN KUMAR';
SELECT PID FROM WORKS WHERE EMPID = ArunEmpID;
SELECT PID, STATUS FROM PROJECT WHERE PID = ArunPID;
(Here ArunEmpID and ArunPID are the results of inner queries)
Relational algebra expressions for the three blocks are −
ArunEmpID←πEmpID(σName="ArunKumar"(EMPLOYEE))
ArunPID←πPID(σEmpID="ArunEmpID"(WORKS))
Result←πPID,Status(σPID="ArunPID"(PROJECT))
The computation of relational algebra operators can be done in many different ways, and each alternative is called an access path.
The computation alternative depends upon three main factors −
Operator type
Available memory
Disk structures
The time to perform execution of a relational algebra operation is the sum of −
Time to process the tuples.
Time to fetch the tuples of the table from disk to memory.
Since the time to process a tuple is very much smaller than the time to fetch the tuple from the storage, particularly in a distributed system, disk access is very often considered as the metric for calculating cost of relational expression.
Computation of selection operation depends upon the complexity of the selection condition and the availability of indexes on the attributes of the table.
Following are the computation alternatives depending upon the indexes −
No Index − If the table is unsorted and has no indexes, then the selection process involves scanning all the disk blocks of the table. Each block is brought into the memory and each tuple in the block is examined to see whether it satisfies the selection condition. If the condition is satisfied, it is displayed as output. This is the costliest approach since each tuple is brought into memory and each tuple is processed.
No Index − If the table is unsorted and has no indexes, then the selection process involves scanning all the disk blocks of the table. Each block is brought into the memory and each tuple in the block is examined to see whether it satisfies the selection condition. If the condition is satisfied, it is displayed as output. This is the costliest approach since each tuple is brought into memory and each tuple is processed.
B+ Tree Index − Most database systems are built upon the B+ Tree index. If the selection condition is based upon the field, which is the key of this B+ Tree index, then this index is used for retrieving results. However, processing selection statements with complex conditions may involve a larger number of disk block accesses and in some cases complete scanning of the table.
B+ Tree Index − Most database systems are built upon the B+ Tree index. If the selection condition is based upon the field, which is the key of this B+ Tree index, then this index is used for retrieving results. However, processing selection statements with complex conditions may involve a larger number of disk block accesses and in some cases complete scanning of the table.
Hash Index − If hash indexes are used and its key field is used in the selection condition, then retrieving tuples using the hash index becomes a simple process. A hash index uses a hash function to find the address of a bucket where the key value corresponding to the hash value is stored. In order to find a key value in the index, the hash function is executed and the bucket address is found. The key values in the bucket are searched. If a match is found, the actual tuple is fetched from the disk block into the memory.
Hash Index − If hash indexes are used and its key field is used in the selection condition, then retrieving tuples using the hash index becomes a simple process. A hash index uses a hash function to find the address of a bucket where the key value corresponding to the hash value is stored. In order to find a key value in the index, the hash function is executed and the bucket address is found. The key values in the bucket are searched. If a match is found, the actual tuple is fetched from the disk block into the memory.
When we want to join two tables, say P and Q, each tuple in P has to be compared with each tuple in Q to test if the join condition is satisfied. If the condition is satisfied, the corresponding tuples are concatenated, eliminating duplicate fields and appended to the result relation. Consequently, this is the most expensive operation.
The common approaches for computing joins are −
This is the conventional join approach. It can be illustrated through the following pseudocode (Tables P and Q, with tuples tuple_p and tuple_q and joining attribute a) −
For each tuple_p in P
For each tuple_q in Q
If tuple_p.a = tuple_q.a Then
Concatenate tuple_p and tuple_q and append to Result
End If
Next tuple_q
Next tuple-p
In this approach, the two tables are individually sorted based upon the joining attribute and then the sorted tables are merged. External sorting techniques are adopted since the number of records is very high and cannot be accommodated in the memory. Once the individual tables are sorted, one page each of the sorted tables are brought to the memory, merged based upon the joining attribute and the joined tuples are written out.
This approach comprises of two phases: partitioning phase and probing phase. In partitioning phase, the tables P and Q are broken into two sets of disjoint partitions. A common hash function is decided upon. This hash function is used to assign tuples to partitions. In the probing phase, tuples in a partition of P are compared with the tuples of corresponding partition of Q. If they match, then they are written out.
Once the alternative access paths for computation of a relational algebra expression are derived, the optimal access path is determined. In this chapter, we will look into query optimization in centralized system while in the next chapter we will study query optimization in a distributed system.
In a centralized system, query processing is done with the following aim −
Minimization of response time of query (time taken to produce the results to user’s query).
Minimization of response time of query (time taken to produce the results to user’s query).
Maximize system throughput (the number of requests that are processed in a given amount of time).
Maximize system throughput (the number of requests that are processed in a given amount of time).
Reduce the amount of memory and storage required for processing.
Reduce the amount of memory and storage required for processing.
Increase parallelism.
Increase parallelism.
Initially, the SQL query is scanned. Then it is parsed to look for syntactical errors and correctness of data types. If the query passes this step, the query is decomposed into smaller query blocks. Each block is then translated to equivalent relational algebra expression.
Query optimization involves three steps, namely query tree generation, plan generation, and query plan code generation.
Step 1 − Query Tree Generation
A query tree is a tree data structure representing a relational algebra expression. The tables of the query are represented as leaf nodes. The relational algebra operations are represented as the internal nodes. The root represents the query as a whole.
During execution, an internal node is executed whenever its operand tables are available. The node is then replaced by the result table. This process continues for all internal nodes until the root node is executed and replaced by the result table.
For example, let us consider the following schemas −
EMPLOYEE
DEPARTMENT
Let us consider the query as the following.
πEmpID(σEName="ArunKumar"(EMPLOYEE))
The corresponding query tree will be −
Let us consider another query involving a join.
πEName,Salary(σDName="Marketing"(DEPARTMENT))⋈DNo=DeptNo(EMPLOYEE)
Following is the query tree for the above query.
Step 2 − Query Plan Generation
After the query tree is generated, a query plan is made. A query plan is an extended query tree that includes access paths for all operations in the query tree. Access paths specify how the relational operations in the tree should be performed. For example, a selection operation can have an access path that gives details about the use of B+ tree index for selection.
Besides, a query plan also states how the intermediate tables should be passed from one operator to the next, how temporary tables should be used and how operations should be pipelined/combined.
Step 3− Code Generation
Code generation is the final step in query optimization. It is the executable form of the query, whose form depends upon the type of the underlying operating system. Once the query code is generated, the Execution Manager runs it and produces the results.
Among the approaches for query optimization, exhaustive search and heuristics-based algorithms are mostly used.
In these techniques, for a query, all possible query plans are initially generated and then the best plan is selected. Though these techniques provide the best solution, it has an exponential time and space complexity owing to the large solution space. For example, dynamic programming technique.
Heuristic based optimization uses rule-based optimization approaches for query optimization. These algorithms have polynomial time and space complexity, which is lower than the exponential complexity of exhaustive search-based algorithms. However, these algorithms do not necessarily produce the best query plan.
Some of the common heuristic rules are −
Perform select and project operations before join operations. This is done by moving the select and project operations down the query tree. This reduces the number of tuples available for join.
Perform select and project operations before join operations. This is done by moving the select and project operations down the query tree. This reduces the number of tuples available for join.
Perform the most restrictive select/project operations at first before the other operations.
Perform the most restrictive select/project operations at first before the other operations.
Avoid cross-product operation since they result in very large-sized intermediate tables.
Avoid cross-product operation since they result in very large-sized intermediate tables.
This chapter discusses query optimization in distributed database system.
In a distributed database system, processing a query comprises of optimization at both the global and the local level. The query enters the database system at the client or controlling site. Here, the user is validated, the query is checked, translated, and optimized at a global level.
The architecture can be represented as −
The process of mapping global queries to local ones can be realized as follows −
The tables required in a global query have fragments distributed across multiple sites. The local databases have information only about local data. The controlling site uses the global data dictionary to gather information about the distribution and reconstructs the global view from the fragments.
The tables required in a global query have fragments distributed across multiple sites. The local databases have information only about local data. The controlling site uses the global data dictionary to gather information about the distribution and reconstructs the global view from the fragments.
If there is no replication, the global optimizer runs local queries at the sites where the fragments are stored. If there is replication, the global optimizer selects the site based upon communication cost, workload, and server speed.
If there is no replication, the global optimizer runs local queries at the sites where the fragments are stored. If there is replication, the global optimizer selects the site based upon communication cost, workload, and server speed.
The global optimizer generates a distributed execution plan so that least amount of data transfer occurs across the sites. The plan states the location of the fragments, order in which query steps needs to be executed and the processes involved in transferring intermediate results.
The global optimizer generates a distributed execution plan so that least amount of data transfer occurs across the sites. The plan states the location of the fragments, order in which query steps needs to be executed and the processes involved in transferring intermediate results.
The local queries are optimized by the local database servers. Finally, the local query results are merged together through union operation in case of horizontal fragments and join operation for vertical fragments.
The local queries are optimized by the local database servers. Finally, the local query results are merged together through union operation in case of horizontal fragments and join operation for vertical fragments.
For example, let us consider that the following Project schema is horizontally fragmented according to City, the cities being New Delhi, Kolkata and Hyderabad.
PROJECT
Suppose there is a query to retrieve details of all projects whose status is “Ongoing”.
The global query will be &inus;
σstatus="ongoing"(PROJECT)
Query in New Delhi’s server will be −
σstatus="ongoing"(NewD−PROJECT)
Query in Kolkata’s server will be −
σstatus="ongoing"(Kol−PROJECT)
Query in Hyderabad’s server will be −
σstatus="ongoing"(Hyd−PROJECT)
In order to get the overall result, we need to union the results of the three queries as follows −
σstatus="ongoing"(NewD−PROJECT)∪σstatus="ongoing"(kol−PROJECT)∪σstatus="ongoing"(Hyd−PROJECT)
Distributed query optimization requires evaluation of a large number of query trees each of which produce the required results of a query. This is primarily due to the presence of large amount of replicated and fragmented data. Hence, the target is to find an optimal solution instead of the best solution.
The main issues for distributed query optimization are −
Optimal utilization of resources in the distributed system.
Query trading.
Reduction of solution space of the query.
A distributed system has a number of database servers in the various sites to perform the operations pertaining to a query. Following are the approaches for optimal resource utilization −
Operation Shipping − In operation shipping, the operation is run at the site where the data is stored and not at the client site. The results are then transferred to the client site. This is appropriate for operations where the operands are available at the same site. Example: Select and Project operations.
Data Shipping − In data shipping, the data fragments are transferred to the database server, where the operations are executed. This is used in operations where the operands are distributed at different sites. This is also appropriate in systems where the communication costs are low, and local processors are much slower than the client server.
Hybrid Shipping − This is a combination of data and operation shipping. Here, data fragments are transferred to the high-speed processors, where the operation runs. The results are then sent to the client site.
In query trading algorithm for distributed database systems, the controlling/client site for a distributed query is called the buyer and the sites where the local queries execute are called sellers. The buyer formulates a number of alternatives for choosing sellers and for reconstructing the global results. The target of the buyer is to achieve the optimal cost.
The algorithm starts with the buyer assigning sub-queries to the seller sites. The optimal plan is created from local optimized query plans proposed by the sellers combined with the communication cost for reconstructing the final result. Once the global optimal plan is formulated, the query is executed.
Optimal solution generally involves reduction of solution space so that the cost of query and data transfer is reduced. This can be achieved through a set of heuristic rules, just as heuristics in centralized systems.
Following are some of the rules −
Perform selection and projection operations as early as possible. This reduces the data flow over communication network.
Perform selection and projection operations as early as possible. This reduces the data flow over communication network.
Simplify operations on horizontal fragments by eliminating selection conditions which are not relevant to a particular site.
Simplify operations on horizontal fragments by eliminating selection conditions which are not relevant to a particular site.
In case of join and union operations comprising of fragments located in multiple sites, transfer fragmented data to the site where most of the data is present and perform operation there.
In case of join and union operations comprising of fragments located in multiple sites, transfer fragmented data to the site where most of the data is present and perform operation there.
Use semi-join operation to qualify tuples that are to be joined. This reduces the amount of data transfer which in turn reduces communication cost.
Use semi-join operation to qualify tuples that are to be joined. This reduces the amount of data transfer which in turn reduces communication cost.
Merge the common leaves and sub-trees in a distributed query tree.
Merge the common leaves and sub-trees in a distributed query tree.
This chapter discusses the various aspects of transaction processing. We’ll also study the low level tasks included in a transaction, the transaction states and properties of a transaction. In the last portion, we will look over schedules and serializability of schedules.
A transaction is a program including a collection of database operations, executed as a logical unit of data processing. The operations performed in a transaction include one or more of database operations like insert, delete, update or retrieve data. It is an atomic process that is either performed into completion entirely or is not performed at all. A transaction involving only data retrieval without any data update is called read-only transaction.
Each high level operation can be divided into a number of low level tasks or operations. For example, a data update operation can be divided into three tasks −
read_item() − reads data item from storage to main memory.
read_item() − reads data item from storage to main memory.
modify_item() − change value of item in the main memory.
modify_item() − change value of item in the main memory.
write_item() − write the modified value from main memory to storage.
write_item() − write the modified value from main memory to storage.
Database access is restricted to read_item() and write_item() operations. Likewise, for all transactions, read and write forms the basic database operations.
The low level operations performed in a transaction are −
begin_transaction − A marker that specifies start of transaction execution.
begin_transaction − A marker that specifies start of transaction execution.
read_item or write_item − Database operations that may be interleaved with main memory operations as a part of transaction.
read_item or write_item − Database operations that may be interleaved with main memory operations as a part of transaction.
end_transaction − A marker that specifies end of transaction.
end_transaction − A marker that specifies end of transaction.
commit − A signal to specify that the transaction has been successfully completed in its entirety and will not be undone.
commit − A signal to specify that the transaction has been successfully completed in its entirety and will not be undone.
rollback − A signal to specify that the transaction has been unsuccessful and so all temporary changes in the database are undone. A committed transaction cannot be rolled back.
rollback − A signal to specify that the transaction has been unsuccessful and so all temporary changes in the database are undone. A committed transaction cannot be rolled back.
A transaction may go through a subset of five states, active, partially committed, committed, failed and aborted.
Active − The initial state where the transaction enters is the active state. The transaction remains in this state while it is executing read, write or other operations.
Active − The initial state where the transaction enters is the active state. The transaction remains in this state while it is executing read, write or other operations.
Partially Committed − The transaction enters this state after the last statement of the transaction has been executed.
Partially Committed − The transaction enters this state after the last statement of the transaction has been executed.
Committed − The transaction enters this state after successful completion of the transaction and system checks have issued commit signal.
Committed − The transaction enters this state after successful completion of the transaction and system checks have issued commit signal.
Failed − The transaction goes from partially committed state or active state to failed state when it is discovered that normal execution can no longer proceed or system checks fail.
Failed − The transaction goes from partially committed state or active state to failed state when it is discovered that normal execution can no longer proceed or system checks fail.
Aborted − This is the state after the transaction has been rolled back after failure and the database has been restored to its state that was before the transaction began.
Aborted − This is the state after the transaction has been rolled back after failure and the database has been restored to its state that was before the transaction began.
The following state transition diagram depicts the states in the transaction and the low level transaction operations that causes change in states.
Any transaction must maintain the ACID properties, viz. Atomicity, Consistency, Isolation, and Durability.
Atomicity − This property states that a transaction is an atomic unit of processing, that is, either it is performed in its entirety or not performed at all. No partial update should exist.
Atomicity − This property states that a transaction is an atomic unit of processing, that is, either it is performed in its entirety or not performed at all. No partial update should exist.
Consistency − A transaction should take the database from one consistent state to another consistent state. It should not adversely affect any data item in the database.
Consistency − A transaction should take the database from one consistent state to another consistent state. It should not adversely affect any data item in the database.
Isolation − A transaction should be executed as if it is the only one in the system. There should not be any interference from the other concurrent transactions that are simultaneously running.
Isolation − A transaction should be executed as if it is the only one in the system. There should not be any interference from the other concurrent transactions that are simultaneously running.
Durability − If a committed transaction brings about a change, that change should be durable in the database and not lost in case of any failure.
Durability − If a committed transaction brings about a change, that change should be durable in the database and not lost in case of any failure.
In a system with a number of simultaneous transactions, a schedule is the total order of execution of operations. Given a schedule S comprising of n transactions, say T1, T2, T3...........Tn; for any transaction Ti, the operations in Ti must execute as laid down in the schedule S.
There are two types of schedules −
Serial Schedules − In a serial schedule, at any point of time, only one transaction is active, i.e. there is no overlapping of transactions. This is depicted in the following graph −
Serial Schedules − In a serial schedule, at any point of time, only one transaction is active, i.e. there is no overlapping of transactions. This is depicted in the following graph −
Parallel Schedules − In parallel schedules, more than one transactions are active simultaneously, i.e. the transactions contain operations that overlap at time. This is depicted in the following graph −
Parallel Schedules − In parallel schedules, more than one transactions are active simultaneously, i.e. the transactions contain operations that overlap at time. This is depicted in the following graph −
In a schedule comprising of multiple transactions, a conflict occurs when two active transactions perform non-compatible operations. Two operations are said to be in conflict, when all of the following three conditions exists simultaneously −
The two operations are parts of different transactions.
The two operations are parts of different transactions.
Both the operations access the same data item.
Both the operations access the same data item.
At least one of the operations is a write_item() operation, i.e. it tries to modify the data item.
At least one of the operations is a write_item() operation, i.e. it tries to modify the data item.
A serializable schedule of ‘n’ transactions is a parallel schedule which is equivalent to a serial schedule comprising of the same ‘n’ transactions. A serializable schedule contains the correctness of serial schedule while ascertaining better CPU utilization of parallel schedule.
Equivalence of two schedules can be of the following types −
Result equivalence − Two schedules producing identical results are said to be result equivalent.
Result equivalence − Two schedules producing identical results are said to be result equivalent.
View equivalence − Two schedules that perform similar action in a similar manner are said to be view equivalent.
View equivalence − Two schedules that perform similar action in a similar manner are said to be view equivalent.
Conflict equivalence − Two schedules are said to be conflict equivalent if both contain the same set of transactions and has the same order of conflicting pairs of operations.
Conflict equivalence − Two schedules are said to be conflict equivalent if both contain the same set of transactions and has the same order of conflicting pairs of operations.
Concurrency controlling techniques ensure that multiple transactions are executed simultaneously while maintaining the ACID properties of the transactions and serializability in the schedules.
In this chapter, we will study the various approaches for concurrency control.
Locking-based concurrency control protocols use the concept of locking data items. A lock is a variable associated with a data item that determines whether read/write operations can be performed on that data item. Generally, a lock compatibility matrix is used which states whether a data item can be locked by two transactions at the same time.
Locking-based concurrency control systems can use either one-phase or two-phase locking protocols.
In this method, each transaction locks an item before use and releases the lock as soon as it has finished using it. This locking method provides for maximum concurrency but does not always enforce serializability.
In this method, all locking operations precede the first lock-release or unlock operation. The transaction comprise of two phases. In the first phase, a transaction only acquires all the locks it needs and do not release any lock. This is called the expanding or the growing phase. In the second phase, the transaction releases the locks and cannot request any new locks. This is called the shrinking phase.
Every transaction that follows two-phase locking protocol is guaranteed to be serializable. However, this approach provides low parallelism between two conflicting transactions.
Timestamp-based concurrency control algorithms use a transaction’s timestamp to coordinate concurrent access to a data item to ensure serializability. A timestamp is a unique identifier given by DBMS to a transaction that represents the transaction’s start time.
These algorithms ensure that transactions commit in the order dictated by their timestamps. An older transaction should commit before a younger transaction, since the older transaction enters the system before the younger one.
Timestamp-based concurrency control techniques generate serializable schedules such that the equivalent serial schedule is arranged in order of the age of the participating transactions.
Some of timestamp based concurrency control algorithms are −
Basic timestamp ordering algorithm.
Conservative timestamp ordering algorithm.
Multiversion algorithm based upon timestamp ordering.
Timestamp based ordering follow three rules to enforce serializability −
Access Rule − When two transactions try to access the same data item simultaneously, for conflicting operations, priority is given to the older transaction. This causes the younger transaction to wait for the older transaction to commit first.
Access Rule − When two transactions try to access the same data item simultaneously, for conflicting operations, priority is given to the older transaction. This causes the younger transaction to wait for the older transaction to commit first.
Late Transaction Rule − If a younger transaction has written a data item, then an older transaction is not allowed to read or write that data item. This rule prevents the older transaction from committing after the younger transaction has already committed.
Late Transaction Rule − If a younger transaction has written a data item, then an older transaction is not allowed to read or write that data item. This rule prevents the older transaction from committing after the younger transaction has already committed.
Younger Transaction Rule − A younger transaction can read or write a data item that has already been written by an older transaction.
Younger Transaction Rule − A younger transaction can read or write a data item that has already been written by an older transaction.
In systems with low conflict rates, the task of validating every transaction for serializability may lower performance. In these cases, the test for serializability is postponed to just before commit. Since the conflict rate is low, the probability of aborting transactions which are not serializable is also low. This approach is called optimistic concurrency control technique.
In this approach, a transaction’s life cycle is divided into the following three phases −
Execution Phase − A transaction fetches data items to memory and performs operations upon them.
Execution Phase − A transaction fetches data items to memory and performs operations upon them.
Validation Phase − A transaction performs checks to ensure that committing its changes to the database passes serializability test.
Validation Phase − A transaction performs checks to ensure that committing its changes to the database passes serializability test.
Commit Phase − A transaction writes back modified data item in memory to the disk.
Commit Phase − A transaction writes back modified data item in memory to the disk.
This algorithm uses three rules to enforce serializability in validation phase −
Rule 1 − Given two transactions Ti and Tj, if Ti is reading the data item which Tj is writing, then Ti’s execution phase cannot overlap with Tj’s commit phase. Tj can commit only after Ti has finished execution.
Rule 2 − Given two transactions Ti and Tj, if Ti is writing the data item that Tj is reading, then Ti’s commit phase cannot overlap with Tj’s execution phase. Tj can start executing only after Ti has already committed.
Rule 3 − Given two transactions Ti and Tj, if Ti is writing the data item which Tj is also writing, then Ti’s commit phase cannot overlap with Tj’s commit phase. Tj can start to commit only after Ti has already committed.
In this section, we will see how the above techniques are implemented in a distributed database system.
The basic principle of distributed two-phase locking is same as the basic two-phase locking protocol. However, in a distributed system there are sites designated as lock managers. A lock manager controls lock acquisition requests from transaction monitors. In order to enforce co-ordination between the lock managers in various sites, at least one site is given the authority to see all transactions and detect lock conflicts.
Depending upon the number of sites who can detect lock conflicts, distributed two-phase locking approaches can be of three types −
Centralized two-phase locking − In this approach, one site is designated as the central lock manager. All the sites in the environment know the location of the central lock manager and obtain lock from it during transactions.
Centralized two-phase locking − In this approach, one site is designated as the central lock manager. All the sites in the environment know the location of the central lock manager and obtain lock from it during transactions.
Primary copy two-phase locking − In this approach, a number of sites are designated as lock control centers. Each of these sites has the responsibility of managing a defined set of locks. All the sites know which lock control center is responsible for managing lock of which data table/fragment item.
Primary copy two-phase locking − In this approach, a number of sites are designated as lock control centers. Each of these sites has the responsibility of managing a defined set of locks. All the sites know which lock control center is responsible for managing lock of which data table/fragment item.
Distributed two-phase locking − In this approach, there are a number of lock managers, where each lock manager controls locks of data items stored at its local site. The location of the lock manager is based upon data distribution and replication.
Distributed two-phase locking − In this approach, there are a number of lock managers, where each lock manager controls locks of data items stored at its local site. The location of the lock manager is based upon data distribution and replication.
In a centralized system, timestamp of any transaction is determined by the physical clock reading. But, in a distributed system, any site’s local physical/logical clock readings cannot be used as global timestamps, since they are not globally unique. So, a timestamp comprises of a combination of site ID and that site’s clock reading.
For implementing timestamp ordering algorithms, each site has a scheduler that maintains a separate queue for each transaction manager. During transaction, a transaction manager sends a lock request to the site’s scheduler. The scheduler puts the request to the corresponding queue in increasing timestamp order. Requests are processed from the front of the queues in the order of their timestamps, i.e. the oldest first.
Another method is to create conflict graphs. For this transaction classes are defined. A transaction class contains two set of data items called read set and write set. A transaction belongs to a particular class if the transaction’s read set is a subset of the class’ read set and the transaction’s write set is a subset of the class’ write set. In the read phase, each transaction issues its read requests for the data items in its read set. In the write phase, each transaction issues its write requests.
A conflict graph is created for the classes to which active transactions belong. This contains a set of vertical, horizontal, and diagonal edges. A vertical edge connects two nodes within a class and denotes conflicts within the class. A horizontal edge connects two nodes across two classes and denotes a write-write conflict among different classes. A diagonal edge connects two nodes across two classes and denotes a write-read or a read-write conflict among two classes.
The conflict graphs are analyzed to ascertain whether two transactions within the same class or across two different classes can be run in parallel.
Distributed optimistic concurrency control algorithm extends optimistic concurrency control algorithm. For this extension, two rules are applied −
Rule 1 − According to this rule, a transaction must be validated locally at all sites when it executes. If a transaction is found to be invalid at any site, it is aborted. Local validation guarantees that the transaction maintains serializability at the sites where it has been executed. After a transaction passes local validation test, it is globally validated.
Rule 2 − According to this rule, after a transaction passes local validation test, it should be globally validated. Global validation ensures that if two conflicting transactions run together at more than one site, they should commit in the same relative order at all the sites they run together. This may require a transaction to wait for the other conflicting transaction, after validation before commit. This requirement makes the algorithm less optimistic since a transaction may not be able to commit as soon as it is validated at a site.
This chapter overviews deadlock handling mechanisms in database systems. We’ll study the deadlock handling mechanisms in both centralized and distributed database system.
Deadlock is a state of a database system having two or more transactions, when each transaction is waiting for a data item that is being locked by some other transaction. A deadlock can be indicated by a cycle in the wait-for-graph. This is a directed graph in which the vertices denote transactions and the edges denote waits for data items.
For example, in the following wait-for-graph, transaction T1 is waiting for data item X which is locked by T3. T3 is waiting for Y which is locked by T2 and T2 is waiting for Z which is locked by T1. Hence, a waiting cycle is formed, and none of the transactions can proceed executing.
There are three classical approaches for deadlock handling, namely −
Deadlock prevention.
Deadlock avoidance.
Deadlock detection and removal.
All of the three approaches can be incorporated in both a centralized and a distributed database system.
The deadlock prevention approach does not allow any transaction to acquire locks that will lead to deadlocks. The convention is that when more than one transactions request for locking the same data item, only one of them is granted the lock.
One of the most popular deadlock prevention methods is pre-acquisition of all the locks. In this method, a transaction acquires all the locks before starting to execute and retains the locks for the entire duration of transaction. If another transaction needs any of the already acquired locks, it has to wait until all the locks it needs are available. Using this approach, the system is prevented from being deadlocked since none of the waiting transactions are holding any lock.
The deadlock avoidance approach handles deadlocks before they occur. It analyzes the transactions and the locks to determine whether or not waiting leads to a deadlock.
The method can be briefly stated as follows. Transactions start executing and request data items that they need to lock. The lock manager checks whether the lock is available. If it is available, the lock manager allocates the data item and the transaction acquires the lock. However, if the item is locked by some other transaction in incompatible mode, the lock manager runs an algorithm to test whether keeping the transaction in waiting state will cause a deadlock or not. Accordingly, the algorithm decides whether the transaction can wait or one of the transactions should be aborted.
There are two algorithms for this purpose, namely wait-die and wound-wait. Let us assume that there are two transactions, T1 and T2, where T1 tries to lock a data item which is already locked by T2. The algorithms are as follows −
Wait-Die − If T1 is older than T2, T1 is allowed to wait. Otherwise, if T1 is younger than T2, T1 is aborted and later restarted.
Wait-Die − If T1 is older than T2, T1 is allowed to wait. Otherwise, if T1 is younger than T2, T1 is aborted and later restarted.
Wound-Wait − If T1 is older than T2, T2 is aborted and later restarted. Otherwise, if T1 is younger than T2, T1 is allowed to wait.
Wound-Wait − If T1 is older than T2, T2 is aborted and later restarted. Otherwise, if T1 is younger than T2, T1 is allowed to wait.
The deadlock detection and removal approach runs a deadlock detection algorithm periodically and removes deadlock in case there is one. It does not check for deadlock when a transaction places a request for a lock. When a transaction requests a lock, the lock manager checks whether it is available. If it is available, the transaction is allowed to lock the data item; otherwise the transaction is allowed to wait.
Since there are no precautions while granting lock requests, some of the transactions may be deadlocked. To detect deadlocks, the lock manager periodically checks if the wait-forgraph has cycles. If the system is deadlocked, the lock manager chooses a victim transaction from each cycle. The victim is aborted and rolled back; and then restarted later. Some of the methods used for victim selection are −
Choose the youngest transaction.
Choose the transaction with fewest data items.
Choose the transaction that has performed least number of updates.
Choose the transaction having least restart overhead.
Choose the transaction which is common to two or more cycles.
This approach is primarily suited for systems having transactions low and where fast response to lock requests is needed.
Transaction processing in a distributed database system is also distributed, i.e. the same transaction may be processing at more than one site. The two main deadlock handling concerns in a distributed database system that are not present in a centralized system are transaction location and transaction control. Once these concerns are addressed, deadlocks are handled through any of deadlock prevention, deadlock avoidance or deadlock detection and removal.
Transactions in a distributed database system are processed in multiple sites and use data items in multiple sites. The amount of data processing is not uniformly distributed among these sites. The time period of processing also varies. Thus the same transaction may be active at some sites and inactive at others. When two conflicting transactions are located in a site, it may happen that one of them is in inactive state. This condition does not arise in a centralized system. This concern is called transaction location issue.
This concern may be addressed by Daisy Chain model. In this model, a transaction carries certain details when it moves from one site to another. Some of the details are the list of tables required, the list of sites required, the list of visited tables and sites, the list of tables and sites that are yet to be visited and the list of acquired locks with types. After a transaction terminates by either commit or abort, the information should be sent to all the concerned sites.
Transaction control is concerned with designating and controlling the sites required for processing a transaction in a distributed database system. There are many options regarding the choice of where to process the transaction and how to designate the center of control, like −
One server may be selected as the center of control.
The center of control may travel from one server to another.
The responsibility of controlling may be shared by a number of servers.
Just like in centralized deadlock prevention, in distributed deadlock prevention approach, a transaction should acquire all the locks before starting to execute. This prevents deadlocks.
The site where the transaction enters is designated as the controlling site. The controlling site sends messages to the sites where the data items are located to lock the items. Then it waits for confirmation. When all the sites have confirmed that they have locked the data items, transaction starts. If any site or communication link fails, the transaction has to wait until they have been repaired.
Though the implementation is simple, this approach has some drawbacks −
Pre-acquisition of locks requires a long time for communication delays. This increases the time required for transaction.
Pre-acquisition of locks requires a long time for communication delays. This increases the time required for transaction.
In case of site or link failure, a transaction has to wait for a long time so that the sites recover. Meanwhile, in the running sites, the items are locked. This may prevent other transactions from executing.
In case of site or link failure, a transaction has to wait for a long time so that the sites recover. Meanwhile, in the running sites, the items are locked. This may prevent other transactions from executing.
If the controlling site fails, it cannot communicate with the other sites. These sites continue to keep the locked data items in their locked state, thus resulting in blocking.
If the controlling site fails, it cannot communicate with the other sites. These sites continue to keep the locked data items in their locked state, thus resulting in blocking.
As in centralized system, distributed deadlock avoidance handles deadlock prior to occurrence. Additionally, in distributed systems, transaction location and transaction control issues needs to be addressed. Due to the distributed nature of the transaction, the following conflicts may occur −
Conflict between two transactions in the same site.
Conflict between two transactions in different sites.
In case of conflict, one of the transactions may be aborted or allowed to wait as per distributed wait-die or distributed wound-wait algorithms.
Let us assume that there are two transactions, T1 and T2. T1 arrives at Site P and tries to lock a data item which is already locked by T2 at that site. Hence, there is a conflict at Site P. The algorithms are as follows −
Distributed Wound-Die
If T1 is older than T2, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has either committed or aborted successfully at all sites.
If T1 is younger than T2, T1 is aborted. The concurrency control at Site P sends a message to all sites where T1 has visited to abort T1. The controlling site notifies the user when T1 has been successfully aborted in all the sites.
Distributed Wound-Die
If T1 is older than T2, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has either committed or aborted successfully at all sites.
If T1 is older than T2, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has either committed or aborted successfully at all sites.
If T1 is younger than T2, T1 is aborted. The concurrency control at Site P sends a message to all sites where T1 has visited to abort T1. The controlling site notifies the user when T1 has been successfully aborted in all the sites.
If T1 is younger than T2, T1 is aborted. The concurrency control at Site P sends a message to all sites where T1 has visited to abort T1. The controlling site notifies the user when T1 has been successfully aborted in all the sites.
Distributed Wait-Wait
If T1 is older than T2, T2 needs to be aborted. If T2 is active at Site P, Site P aborts and rolls back T2 and then broadcasts this message to other relevant sites. If T2 has left Site P but is active at Site Q, Site P broadcasts that T2 has been aborted; Site L then aborts and rolls back T2 and sends this message to all sites.
If T1 is younger than T1, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has completed processing.
Distributed Wait-Wait
If T1 is older than T2, T2 needs to be aborted. If T2 is active at Site P, Site P aborts and rolls back T2 and then broadcasts this message to other relevant sites. If T2 has left Site P but is active at Site Q, Site P broadcasts that T2 has been aborted; Site L then aborts and rolls back T2 and sends this message to all sites.
If T1 is older than T2, T2 needs to be aborted. If T2 is active at Site P, Site P aborts and rolls back T2 and then broadcasts this message to other relevant sites. If T2 has left Site P but is active at Site Q, Site P broadcasts that T2 has been aborted; Site L then aborts and rolls back T2 and sends this message to all sites.
If T1 is younger than T1, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has completed processing.
If T1 is younger than T1, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has completed processing.
Just like centralized deadlock detection approach, deadlocks are allowed to occur and are removed if detected. The system does not perform any checks when a transaction places a lock request. For implementation, global wait-for-graphs are created. Existence of a cycle in the global wait-for-graph indicates deadlocks. However, it is difficult to spot deadlocks since transaction waits for resources across the network.
Alternatively, deadlock detection algorithms can use timers. Each transaction is associated with a timer which is set to a time period in which a transaction is expected to finish. If a transaction does not finish within this time period, the timer goes off, indicating a possible deadlock.
Another tool used for deadlock handling is a deadlock detector. In a centralized system, there is one deadlock detector. In a distributed system, there can be more than one deadlock detectors. A deadlock detector can find deadlocks for the sites under its control. There are three alternatives for deadlock detection in a distributed system, namely.
Centralized Deadlock Detector − One site is designated as the central deadlock detector.
Centralized Deadlock Detector − One site is designated as the central deadlock detector.
Hierarchical Deadlock Detector − A number of deadlock detectors are arranged in hierarchy.
Hierarchical Deadlock Detector − A number of deadlock detectors are arranged in hierarchy.
Distributed Deadlock Detector − All the sites participate in detecting deadlocks and removing them.
Distributed Deadlock Detector − All the sites participate in detecting deadlocks and removing them.
This chapter looks into replication control, which is required to maintain consistent data in all sites. We will study the replication control techniques and the algorithms required for replication control.
As discussed earlier, replication is a technique used in distributed databases to store multiple copies of a data table at different sites. The problem with having multiple copies in multiple sites is the overhead of maintaining data consistency, particularly during update operations.
In order to maintain mutually consistent data in all sites, replication control techniques need to be adopted. There are two approaches for replication control, namely −
Synchronous Replication Control
Asynchronous Replication Control
In synchronous replication approach, the database is synchronized so that all the replications always have the same value. A transaction requesting a data item will have access to the same value in all the sites. To ensure this uniformity, a transaction that updates a data item is expanded so that it makes the update in all the copies of the data item. Generally, two-phase commit protocol is used for the purpose.
For example, let us consider a data table PROJECT(PId, PName, PLocation). We need to run a transaction T1 that updates PLocation to ‘Mumbai’, if PLocation is ‘Bombay’. If no replications are there, the operations in transaction T1 will be −
Begin T1:
Update PROJECT Set PLocation = 'Mumbai'
Where PLocation = 'Bombay';
End T1;
If the data table has two replicas in Site A and Site B, T1 needs to spawn two children T1A and T1B corresponding to the two sites. The expanded transaction T1 will be −
Begin T1:
Begin T1A :
Update PROJECT Set PLocation = 'Mumbai'
Where PLocation = 'Bombay';
End T1A;
Begin T2A :
Update PROJECT Set PLocation = 'Mumbai'
Where PLocation = 'Bombay';
End T2A;
End T1;
In asynchronous replication approach, the replicas do not always maintain the same value. One or more replicas may store an outdated value, and a transaction can see the different values. The process of bringing all the replicas to the current value is called synchronization.
A popular method of synchronization is store and forward method. In this method, one site is designated as the primary site and the other sites are secondary sites. The primary site always contains updated values. All the transactions first enter the primary site. These transactions are then queued for application in the secondary sites. The secondary sites are updated using rollout method only when a transaction is scheduled to execute on it.
Some of the replication control algorithms are −
Master-slave replication control algorithm.
Distributed voting algorithm.
Majority consensus algorithm.
Circulating token algorithm.
There is one master site and ‘N’ slave sites. A master algorithm runs at the master site to detect conflicts. A copy of slave algorithm runs at each slave site. The overall algorithm executes in the following two phases −
Transaction acceptance/rejection phase − When a transaction enters the transaction monitor of a slave site, the slave site sends a request to the master site. The master site checks for conflicts. If there aren’t any conflicts, the master sends an “ACK+” message to the slave site which then starts the transaction application phase. Otherwise, the master sends an “ACK-” message to the slave which then rejects the transaction.
Transaction acceptance/rejection phase − When a transaction enters the transaction monitor of a slave site, the slave site sends a request to the master site. The master site checks for conflicts. If there aren’t any conflicts, the master sends an “ACK+” message to the slave site which then starts the transaction application phase. Otherwise, the master sends an “ACK-” message to the slave which then rejects the transaction.
Transaction application phase − Upon entering this phase, the slave site where transaction has entered broadcasts a request to all slaves for executing the transaction. On receiving the requests, the peer slaves execute the transaction and send an “ACK” to the requesting slave on completion. After the requesting slave has received “ACK” messages from all its peers, it sends a “DONE” message to the master site. The master understands that the transaction has been completed and removes it from the pending queue.
Transaction application phase − Upon entering this phase, the slave site where transaction has entered broadcasts a request to all slaves for executing the transaction. On receiving the requests, the peer slaves execute the transaction and send an “ACK” to the requesting slave on completion. After the requesting slave has received “ACK” messages from all its peers, it sends a “DONE” message to the master site. The master understands that the transaction has been completed and removes it from the pending queue.
This comprises of ‘N’ peer sites, all of whom must “OK” a transaction before it starts executing. Following are the two phases of this algorithm −
Distributed transaction acceptance phase − When a transaction enters the transaction manager of a site, it sends a transaction request to all other sites. On receiving a request, a peer site resolves conflicts using priority based voting rules. If all the peer sites are “OK” with the transaction, the requesting site starts application phase. If any of the peer sites does not “OK” a transaction, the requesting site rejects the transaction.
Distributed transaction acceptance phase − When a transaction enters the transaction manager of a site, it sends a transaction request to all other sites. On receiving a request, a peer site resolves conflicts using priority based voting rules. If all the peer sites are “OK” with the transaction, the requesting site starts application phase. If any of the peer sites does not “OK” a transaction, the requesting site rejects the transaction.
Distributed transaction application phase − Upon entering this phase, the site where the transaction has entered, broadcasts a request to all slaves for executing the transaction. On receiving the requests, the peer slaves execute the transaction and send an “ACK” message to the requesting slave on completion. After the requesting slave has received “ACK” messages from all its peers, it lets the transaction manager know that the transaction has been completed.
Distributed transaction application phase − Upon entering this phase, the site where the transaction has entered, broadcasts a request to all slaves for executing the transaction. On receiving the requests, the peer slaves execute the transaction and send an “ACK” message to the requesting slave on completion. After the requesting slave has received “ACK” messages from all its peers, it lets the transaction manager know that the transaction has been completed.
This is a variation from the distributed voting algorithm, where a transaction is allowed to execute when a majority of the peers “OK” a transaction. This is divided into three phases −
Voting phase − When a transaction enters the transaction manager of a site, it sends a transaction request to all other sites. On receiving a request, a peer site tests for conflicts using voting rules and keeps the conflicting transactions, if any, in pending queue. Then, it sends either an “OK” or a “NOT OK” message.
Voting phase − When a transaction enters the transaction manager of a site, it sends a transaction request to all other sites. On receiving a request, a peer site tests for conflicts using voting rules and keeps the conflicting transactions, if any, in pending queue. Then, it sends either an “OK” or a “NOT OK” message.
Transaction acceptance/rejection phase − If the requesting site receives a majority “OK” on the transaction, it accepts the transaction and broadcasts “ACCEPT” to all the sites. Otherwise, it broadcasts “REJECT” to all the sites and rejects the transaction.
Transaction acceptance/rejection phase − If the requesting site receives a majority “OK” on the transaction, it accepts the transaction and broadcasts “ACCEPT” to all the sites. Otherwise, it broadcasts “REJECT” to all the sites and rejects the transaction.
Transaction application phase − When a peer site receives a “REJECT” message, it removes this transaction from its pending list and reconsiders all deferred transactions. When a peer site receives an “ACCEPT” message, it applies the transaction and rejects all the deferred transactions in the pending queue which are in conflict with this transaction. It sends an “ACK” to the requesting slave on completion.
Transaction application phase − When a peer site receives a “REJECT” message, it removes this transaction from its pending list and reconsiders all deferred transactions. When a peer site receives an “ACCEPT” message, it applies the transaction and rejects all the deferred transactions in the pending queue which are in conflict with this transaction. It sends an “ACK” to the requesting slave on completion.
In this approach the transactions in the system are serialized using a circulating token and executed accordingly against every replica of the database. Thus, all the transactions are accepted, i.e. none is rejected. This has two phases −
Transaction serialization phase − In this phase, all transactions are scheduled to run in a serialization order. Each transaction in each site is assigned a unique ticket from a sequential series, indicating the order of transaction. Once a transaction has been assigned a ticket, it is broadcasted to all the sites.
Transaction serialization phase − In this phase, all transactions are scheduled to run in a serialization order. Each transaction in each site is assigned a unique ticket from a sequential series, indicating the order of transaction. Once a transaction has been assigned a ticket, it is broadcasted to all the sites.
Transaction application phase − When a site receives a transaction along with its ticket, it places the transaction for execution according to its ticket. After the transaction has finished execution, this site broadcasts an appropriate message. A transaction ends when it has completed execution in all the sites.
Transaction application phase − When a site receives a transaction along with its ticket, it places the transaction for execution according to its ticket. After the transaction has finished execution, this site broadcasts an appropriate message. A transaction ends when it has completed execution in all the sites.
A database management system is susceptible to a number of failures. In this chapter we will study the failure types and commit protocols. In a distributed database system, failures can be broadly categorized into soft failures, hard failures and network failures.
Soft failure is the type of failure that causes the loss in volatile memory of the computer and not in the persistent storage. Here, the information stored in the non-persistent storage like main memory, buffers, caches or registers, is lost. They are also known as system crash. The various types of soft failures are as follows −
Operating system failure.
Main memory crash.
Transaction failure or abortion.
System generated error like integer overflow or divide-by-zero error.
Failure of supporting software.
Power failure.
A hard failure is the type of failure that causes loss of data in the persistent or non-volatile storage like disk. Disk failure may cause corruption of data in some disk blocks or failure of the total disk. The causes of a hard failure are −
Power failure.
Faults in media.
Read-write malfunction.
Corruption of information on the disk.
Read/write head crash of disk.
Recovery from disk failures can be short, if there is a new, formatted, and ready-to-use disk on reserve. Otherwise, duration includes the time it takes to get a purchase order, buy the disk, and prepare it.
Network failures are prevalent in distributed or network databases. These comprises of the errors induced in the database system due to the distributed nature of the data and transferring data over the network. The causes of network failure are as follows −
Communication link failure.
Network congestion.
Information corruption during transfer.
Site failures.
Network partitioning.
Any database system should guarantee that the desirable properties of a transaction are maintained even after failures. If a failure occurs during the execution of a transaction, it may happen that all the changes brought about by the transaction are not committed. This makes the database inconsistent. Commit protocols prevent this scenario using either transaction undo (rollback) or transaction redo (roll forward).
The point of time at which the decision is made whether to commit or abort a transaction, is known as commit point. Following are the properties of a commit point.
It is a point of time when the database is consistent.
It is a point of time when the database is consistent.
At this point, the modifications brought about by the database can be seen by the other transactions. All transactions can have a consistent view of the database.
At this point, the modifications brought about by the database can be seen by the other transactions. All transactions can have a consistent view of the database.
At this point, all the operations of transaction have been successfully executed and their effects have been recorded in transaction log.
At this point, all the operations of transaction have been successfully executed and their effects have been recorded in transaction log.
At this point, a transaction can be safely undone, if required.
At this point, a transaction can be safely undone, if required.
At this point, a transaction releases all the locks held by it.
At this point, a transaction releases all the locks held by it.
The process of undoing all the changes made to a database by a transaction is called transaction undo or transaction rollback. This is mostly applied in case of soft failure.
The process of reapplying the changes made to a database by a transaction is called transaction redo or transaction roll forward. This is mostly applied for recovery from a hard failure.
A transaction log is a sequential file that keeps track of transaction operations on database items. As the log is sequential in nature, it is processed sequentially either from the beginning or from the end.
Purposes of a transaction log −
To support commit protocols to commit or support transactions.
To aid database recovery after failure.
A transaction log is usually kept on the disk, so that it is not affected by soft failures. Additionally, the log is periodically backed up to an archival storage like magnetic tape to protect it from disk failures as well.
The transaction log maintains five types of lists depending upon the status of the transaction. This list aids the recovery manager to ascertain the status of a transaction. The status and the corresponding lists are as follows −
A transaction that has a transaction start record and a transaction commit record, is a committed transaction – maintained in commit list.
A transaction that has a transaction start record and a transaction commit record, is a committed transaction – maintained in commit list.
A transaction that has a transaction start record and a transaction failed record but not a transaction abort record, is a failed transaction – maintained in failed list.
A transaction that has a transaction start record and a transaction failed record but not a transaction abort record, is a failed transaction – maintained in failed list.
A transaction that has a transaction start record and a transaction abort record is an aborted transaction – maintained in abort list.
A transaction that has a transaction start record and a transaction abort record is an aborted transaction – maintained in abort list.
A transaction that has a transaction start record and a transaction before-commit record is a before-commit transaction, i.e. a transaction where all the operations have been executed but not committed – maintained in before-commit list.
A transaction that has a transaction start record and a transaction before-commit record is a before-commit transaction, i.e. a transaction where all the operations have been executed but not committed – maintained in before-commit list.
A transaction that has a transaction start record but no records of before-commit, commit, abort or failed, is an active transaction – maintained in active list.
A transaction that has a transaction start record but no records of before-commit, commit, abort or failed, is an active transaction – maintained in active list.
Immediate Update and Deferred Update are two methods for maintaining transaction logs.
In immediate update mode, when a transaction executes, the updates made by the transaction are written directly onto the disk. The old values and the updates values are written onto the log before writing to the database in disk. On commit, the changes made to the disk are made permanent. On rollback, changes made by the transaction in the database are discarded and the old values are restored into the database from the old values stored in the log.
In deferred update mode, when a transaction executes, the updates made to the database by the transaction are recorded in the log file. On commit, the changes in the log are written onto the disk. On rollback, the changes in the log are discarded and no changes are applied to the database.
In order to recuperate from database failure, database management systems resort to a number of recovery management techniques. In this chapter, we will study the different approaches for database recovery.
The typical strategies for database recovery are −
In case of soft failures that result in inconsistency of database, recovery strategy includes transaction undo or rollback. However, sometimes, transaction redo may also be adopted to recover to a consistent state of the transaction.
In case of soft failures that result in inconsistency of database, recovery strategy includes transaction undo or rollback. However, sometimes, transaction redo may also be adopted to recover to a consistent state of the transaction.
In case of hard failures resulting in extensive damage to database, recovery strategies encompass restoring a past copy of the database from archival backup. A more current state of the database is obtained through redoing operations of committed transactions from transaction log.
In case of hard failures resulting in extensive damage to database, recovery strategies encompass restoring a past copy of the database from archival backup. A more current state of the database is obtained through redoing operations of committed transactions from transaction log.
Power failure causes loss of information in the non-persistent memory. When power is restored, the operating system and the database management system restart. Recovery manager initiates recovery from the transaction logs.
In case of immediate update mode, the recovery manager takes the following actions −
Transactions which are in active list and failed list are undone and written on the abort list.
Transactions which are in active list and failed list are undone and written on the abort list.
Transactions which are in before-commit list are redone.
Transactions which are in before-commit list are redone.
No action is taken for transactions in commit or abort lists.
No action is taken for transactions in commit or abort lists.
In case of deferred update mode, the recovery manager takes the following actions −
Transactions which are in the active list and failed list are written onto the abort list. No undo operations are required since the changes have not been written to the disk yet.
Transactions which are in the active list and failed list are written onto the abort list. No undo operations are required since the changes have not been written to the disk yet.
Transactions which are in before-commit list are redone.
Transactions which are in before-commit list are redone.
No action is taken for transactions in commit or abort lists.
No action is taken for transactions in commit or abort lists.
A disk failure or hard crash causes a total database loss. To recover from this hard crash, a new disk is prepared, then the operating system is restored, and finally the database is recovered using the database backup and transaction log. The recovery method is same for both immediate and deferred update modes.
The recovery manager takes the following actions −
The transactions in the commit list and before-commit list are redone and written onto the commit list in the transaction log.
The transactions in the commit list and before-commit list are redone and written onto the commit list in the transaction log.
The transactions in the active list and failed list are undone and written onto the abort list in the transaction log.
The transactions in the active list and failed list are undone and written onto the abort list in the transaction log.
Checkpoint is a point of time at which a record is written onto the database from the buffers. As a consequence, in case of a system crash, the recovery manager does not have to redo the transactions that have been committed before checkpoint. Periodical checkpointing shortens the recovery process.
The two types of checkpointing techniques are −
Consistent checkpointing
Fuzzy checkpointing
Consistent checkpointing creates a consistent image of the database at checkpoint. During recovery, only those transactions which are on the right side of the last checkpoint are undone or redone. The transactions to the left side of the last consistent checkpoint are already committed and needn’t be processed again. The actions taken for checkpointing are −
The active transactions are suspended temporarily.
All changes in main-memory buffers are written onto the disk.
A “checkpoint” record is written in the transaction log.
The transaction log is written to the disk.
The suspended transactions are resumed.
If in step 4, the transaction log is archived as well, then this checkpointing aids in recovery from disk failures and power failures, otherwise it aids recovery from only power failures.
In fuzzy checkpointing, at the time of checkpoint, all the active transactions are written in the log. In case of power failure, the recovery manager processes only those transactions that were active during checkpoint and later. The transactions that have been committed before checkpoint are written to the disk and hence need not be redone.
Let us consider that in system the time of checkpointing is tcheck and the time of system crash is tfail. Let there be four transactions Ta, Tb, Tc and Td such that −
Ta commits before checkpoint.
Ta commits before checkpoint.
Tb starts before checkpoint and commits before system crash.
Tb starts before checkpoint and commits before system crash.
Tc starts after checkpoint and commits before system crash.
Tc starts after checkpoint and commits before system crash.
Td starts after checkpoint and was active at the time of system crash.
Td starts after checkpoint and was active at the time of system crash.
The situation is depicted in the following diagram −
The actions that are taken by the recovery manager are −
Nothing is done with Ta.
Transaction redo is performed for Tb and Tc.
Transaction undo is performed for Td.
Transaction recovery is done to eliminate the adverse effects of faulty transactions rather than to recover from a failure. Faulty transactions include all transactions that have changed the database into undesired state and the transactions that have used values written by the faulty transactions.
Transaction recovery in these cases is a two-step process −
UNDO all faulty transactions and transactions that may be affected by the faulty transactions.
UNDO all faulty transactions and transactions that may be affected by the faulty transactions.
REDO all transactions that are not faulty but have been undone due to the faulty transactions.
REDO all transactions that are not faulty but have been undone due to the faulty transactions.
Steps for the UNDO operation are −
If the faulty transaction has done INSERT, the recovery manager deletes the data item(s) inserted.
If the faulty transaction has done INSERT, the recovery manager deletes the data item(s) inserted.
If the faulty transaction has done DELETE, the recovery manager inserts the deleted data item(s) from the log.
If the faulty transaction has done DELETE, the recovery manager inserts the deleted data item(s) from the log.
If the faulty transaction has done UPDATE, the recovery manager eliminates the value by writing the before-update value from the log.
If the faulty transaction has done UPDATE, the recovery manager eliminates the value by writing the before-update value from the log.
Steps for the REDO operation are −
If the transaction has done INSERT, the recovery manager generates an insert from the log.
If the transaction has done INSERT, the recovery manager generates an insert from the log.
If the transaction has done DELETE, the recovery manager generates a delete from the log.
If the transaction has done DELETE, the recovery manager generates a delete from the log.
If the transaction has done UPDATE, the recovery manager generates an update from the log.
If the transaction has done UPDATE, the recovery manager generates an update from the log.
In a local database system, for committing a transaction, the transaction manager has to only convey the decision to commit to the recovery manager. However, in a distributed system, the transaction manager should convey the decision to commit to all the servers in the various sites where the transaction is being executed and uniformly enforce the decision. When processing is complete at each site, it reaches the partially committed transaction state and waits for all other transactions to reach their partially committed states. When it receives the message that all the sites are ready to commit, it starts to commit. In a distributed system, either all sites commit or none of them does.
The different distributed commit protocols are −
One-phase commit
Two-phase commit
Three-phase commit
Distributed one-phase commit is the simplest commit protocol. Let us consider that there is a controlling site and a number of slave sites where the transaction is being executed. The steps in distributed commit are −
After each slave has locally completed its transaction, it sends a “DONE” message to the controlling site.
After each slave has locally completed its transaction, it sends a “DONE” message to the controlling site.
The slaves wait for “Commit” or “Abort” message from the controlling site. This waiting time is called window of vulnerability.
The slaves wait for “Commit” or “Abort” message from the controlling site. This waiting time is called window of vulnerability.
When the controlling site receives “DONE” message from each slave, it makes a decision to commit or abort. This is called the commit point. Then, it sends this message to all the slaves.
When the controlling site receives “DONE” message from each slave, it makes a decision to commit or abort. This is called the commit point. Then, it sends this message to all the slaves.
On receiving this message, a slave either commits or aborts and then sends an acknowledgement message to the controlling site.
On receiving this message, a slave either commits or aborts and then sends an acknowledgement message to the controlling site.
Distributed two-phase commit reduces the vulnerability of one-phase commit protocols. The steps performed in the two phases are as follows −
Phase 1: Prepare Phase
After each slave has locally completed its transaction, it sends a “DONE” message to the controlling site. When the controlling site has received “DONE” message from all slaves, it sends a “Prepare” message to the slaves.
After each slave has locally completed its transaction, it sends a “DONE” message to the controlling site. When the controlling site has received “DONE” message from all slaves, it sends a “Prepare” message to the slaves.
The slaves vote on whether they still want to commit or not. If a slave wants to commit, it sends a “Ready” message.
The slaves vote on whether they still want to commit or not. If a slave wants to commit, it sends a “Ready” message.
A slave that does not want to commit sends a “Not Ready” message. This may happen when the slave has conflicting concurrent transactions or there is a timeout.
A slave that does not want to commit sends a “Not Ready” message. This may happen when the slave has conflicting concurrent transactions or there is a timeout.
Phase 2: Commit/Abort Phase
After the controlling site has received “Ready” message from all the slaves −
The controlling site sends a “Global Commit” message to the slaves.
The slaves apply the transaction and send a “Commit ACK” message to the controlling site.
When the controlling site receives “Commit ACK” message from all the slaves, it considers the transaction as committed.
After the controlling site has received “Ready” message from all the slaves −
The controlling site sends a “Global Commit” message to the slaves.
The controlling site sends a “Global Commit” message to the slaves.
The slaves apply the transaction and send a “Commit ACK” message to the controlling site.
The slaves apply the transaction and send a “Commit ACK” message to the controlling site.
When the controlling site receives “Commit ACK” message from all the slaves, it considers the transaction as committed.
When the controlling site receives “Commit ACK” message from all the slaves, it considers the transaction as committed.
After the controlling site has received the first “Not Ready” message from any slave −
The controlling site sends a “Global Abort” message to the slaves.
The slaves abort the transaction and send a “Abort ACK” message to the controlling site.
When the controlling site receives “Abort ACK” message from all the slaves, it considers the transaction as aborted.
After the controlling site has received the first “Not Ready” message from any slave −
The controlling site sends a “Global Abort” message to the slaves.
The controlling site sends a “Global Abort” message to the slaves.
The slaves abort the transaction and send a “Abort ACK” message to the controlling site.
The slaves abort the transaction and send a “Abort ACK” message to the controlling site.
When the controlling site receives “Abort ACK” message from all the slaves, it considers the transaction as aborted.
When the controlling site receives “Abort ACK” message from all the slaves, it considers the transaction as aborted.
The steps in distributed three-phase commit are as follows −
Phase 1: Prepare Phase
The steps are same as in distributed two-phase commit.
Phase 2: Prepare to Commit Phase
The controlling site issues an “Enter Prepared State” broadcast message.
The slave sites vote “OK” in response.
Phase 3: Commit / Abort Phase
The steps are same as two-phase commit except that “Commit ACK”/”Abort ACK” message is not required.
In this chapter, we will look into the threats that a database system faces and the measures of control. We will also study cryptography as a security tool.
Data security is an imperative aspect of any database system. It is of particular importance in distributed systems because of large number of users, fragmented and replicated data, multiple sites and distributed control.
Availability loss − Availability loss refers to non-availability of database objects by legitimate users.
Availability loss − Availability loss refers to non-availability of database objects by legitimate users.
Integrity loss − Integrity loss occurs when unacceptable operations are performed upon the database either accidentally or maliciously. This may happen while creating, inserting, updating or deleting data. It results in corrupted data leading to incorrect decisions.
Integrity loss − Integrity loss occurs when unacceptable operations are performed upon the database either accidentally or maliciously. This may happen while creating, inserting, updating or deleting data. It results in corrupted data leading to incorrect decisions.
Confidentiality loss − Confidentiality loss occurs due to unauthorized or unintentional disclosure of confidential information. It may result in illegal actions, security threats and loss in public confidence.
Confidentiality loss − Confidentiality loss occurs due to unauthorized or unintentional disclosure of confidential information. It may result in illegal actions, security threats and loss in public confidence.
The measures of control can be broadly divided into the following categories −
Access Control − Access control includes security mechanisms in a database management system to protect against unauthorized access. A user can gain access to the database after clearing the login process through only valid user accounts. Each user account is password protected.
Access Control − Access control includes security mechanisms in a database management system to protect against unauthorized access. A user can gain access to the database after clearing the login process through only valid user accounts. Each user account is password protected.
Flow Control − Distributed systems encompass a lot of data flow from one site to another and also within a site. Flow control prevents data from being transferred in such a way that it can be accessed by unauthorized agents. A flow policy lists out the channels through which information can flow. It also defines security classes for data as well as transactions.
Flow Control − Distributed systems encompass a lot of data flow from one site to another and also within a site. Flow control prevents data from being transferred in such a way that it can be accessed by unauthorized agents. A flow policy lists out the channels through which information can flow. It also defines security classes for data as well as transactions.
Data Encryption − Data encryption refers to coding data when sensitive data is to be communicated over public channels. Even if an unauthorized agent gains access of the data, he cannot understand it since it is in an incomprehensible format.
Data Encryption − Data encryption refers to coding data when sensitive data is to be communicated over public channels. Even if an unauthorized agent gains access of the data, he cannot understand it since it is in an incomprehensible format.
Cryptography is the science of encoding information before sending via unreliable communication paths so that only an authorized receiver can decode and use it.
The coded message is called cipher text and the original message is called plain text. The process of converting plain text to cipher text by the sender is called encoding or encryption. The process of converting cipher text to plain text by the receiver is called decoding or decryption.
The entire procedure of communicating using cryptography can be illustrated through the following diagram −
In conventional cryptography, the encryption and decryption is done using the same secret key. Here, the sender encrypts the message with an encryption algorithm using a copy of the secret key. The encrypted message is then send over public communication channels. On receiving the encrypted message, the receiver decrypts it with a corresponding decryption algorithm using the same secret key.
Security in conventional cryptography depends on two factors −
A sound algorithm which is known to all.
A sound algorithm which is known to all.
A randomly generated, preferably long secret key known only by the sender and the receiver.
A randomly generated, preferably long secret key known only by the sender and the receiver.
The most famous conventional cryptography algorithm is Data Encryption Standard or DES.
The advantage of this method is its easy applicability. However, the greatest problem of conventional cryptography is sharing the secret key between the communicating parties. The ways to send the key are cumbersome and highly susceptible to eavesdropping.
In contrast to conventional cryptography, public key cryptography uses two different keys, referred to as public key and the private key. Each user generates the pair of public key and private key. The user then puts the public key in an accessible place. When a sender wants to sends a message, he encrypts it using the public key of the receiver. On receiving the encrypted message, the receiver decrypts it using his private key. Since the private key is not known to anyone but the receiver, no other person who receives the message can decrypt it.
The most popular public key cryptography algorithms are RSA algorithm and Diffie– Hellman algorithm. This method is very secure to send private messages. However, the problem is, it involves a lot of computations and so proves to be inefficient for long messages.
The solution is to use a combination of conventional and public key cryptography. The secret key is encrypted using public key cryptography before sharing between the communicating parties. Then, the message is send using conventional cryptography with the aid of the shared secret key.
A Digital Signature (DS) is an authentication technique based on public key cryptography used in e-commerce applications. It associates a unique mark to an individual within the body of his message. This helps others to authenticate valid senders of messages.
Typically, a user’s digital signature varies from message to message in order to provide security against counterfeiting. The method is as follows −
The sender takes a message, calculates the message digest of the message and signs it digest with a private key.
The sender takes a message, calculates the message digest of the message and signs it digest with a private key.
The sender then appends the signed digest along with the plaintext message.
The sender then appends the signed digest along with the plaintext message.
The message is sent over communication channel.
The message is sent over communication channel.
The receiver removes the appended signed digest and verifies the digest using the corresponding public key.
The receiver removes the appended signed digest and verifies the digest using the corresponding public key.
The receiver then takes the plaintext message and runs it through the same message digest algorithm.
The receiver then takes the plaintext message and runs it through the same message digest algorithm.
If the results of step 4 and step 5 match, then the receiver knows that the message has integrity and authentic.
If the results of step 4 and step 5 match, then the receiver knows that the message has integrity and authentic.
A distributed system needs additional security measures than centralized system, since there are many users, diversified data, multiple sites and distributed control. In this chapter, we will look into the various facets of distributed database security.
In distributed communication systems, there are two types of intruders −
Passive eavesdroppers − They monitor the messages and get hold of private information.
Passive eavesdroppers − They monitor the messages and get hold of private information.
Active attackers − They not only monitor the messages but also corrupt data by inserting new data or modifying existing data.
Active attackers − They not only monitor the messages but also corrupt data by inserting new data or modifying existing data.
Security measures encompass security in communications, security in data and data auditing.
In a distributed database, a lot of data communication takes place owing to the diversified location of data, users and transactions. So, it demands secure communication between users and databases and between the different database environments.
Security in communication encompasses the following −
Data should not be corrupt during transfer.
Data should not be corrupt during transfer.
The communication channel should be protected against both passive eavesdroppers and active attackers.
The communication channel should be protected against both passive eavesdroppers and active attackers.
In order to achieve the above stated requirements, well-defined security algorithms and protocols should be adopted.
In order to achieve the above stated requirements, well-defined security algorithms and protocols should be adopted.
Two popular, consistent technologies for achieving end-to-end secure communications are −
Secure Socket Layer Protocol or Transport Layer Security Protocol.
Virtual Private Networks (VPN).
In distributed systems, it is imperative to adopt measure to secure data apart from communications. The data security measures are −
Authentication and authorization − These are the access control measures adopted to ensure that only authentic users can use the database. To provide authentication digital certificates are used. Besides, login is restricted through username/password combination.
Authentication and authorization − These are the access control measures adopted to ensure that only authentic users can use the database. To provide authentication digital certificates are used. Besides, login is restricted through username/password combination.
Data encryption − The two approaches for data encryption in distributed systems are −
Internal to distributed database approach: The user applications encrypt the data and then store the encrypted data in the database. For using the stored data, the applications fetch the encrypted data from the database and then decrypt it.
External to distributed database: The distributed database system has its own encryption capabilities. The user applications store data and retrieve them without realizing that the data is stored in an encrypted form in the database.
Data encryption − The two approaches for data encryption in distributed systems are −
Internal to distributed database approach: The user applications encrypt the data and then store the encrypted data in the database. For using the stored data, the applications fetch the encrypted data from the database and then decrypt it.
Internal to distributed database approach: The user applications encrypt the data and then store the encrypted data in the database. For using the stored data, the applications fetch the encrypted data from the database and then decrypt it.
External to distributed database: The distributed database system has its own encryption capabilities. The user applications store data and retrieve them without realizing that the data is stored in an encrypted form in the database.
External to distributed database: The distributed database system has its own encryption capabilities. The user applications store data and retrieve them without realizing that the data is stored in an encrypted form in the database.
Validated input − In this security measure, the user application checks for each input before it can be used for updating the database. An un-validated input can cause a wide range of exploits like buffer overrun, command injection, cross-site scripting and corruption in data.
Validated input − In this security measure, the user application checks for each input before it can be used for updating the database. An un-validated input can cause a wide range of exploits like buffer overrun, command injection, cross-site scripting and corruption in data.
A database security system needs to detect and monitor security violations, in order to ascertain the security measures it should adopt. It is often very difficult to detect breach of security at the time of occurrences. One method to identify security violations is to examine audit logs. Audit logs contain information such as −
Date, time and site of failed access attempts.
Details of successful access attempts.
Vital modifications in the database system.
Access of huge amounts of data, particularly from databases in multiple sites.
All the above information gives an insight of the activities in the database. A periodical analysis of the log helps to identify any unnatural activity along with its site and time of occurrence. This log is ideally stored in a separate server so that it is inaccessible to attackers.
49 Lectures
11 hours
Hussein Rashad
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2615,
"s": 2223,
"text": "For proper functioning of any organization, there’s a need for a well-maintained database. In the recent past, databases used to be centralized in nature. However, with the increase in globalization, organizations tend to be diversified across the globe. They may choose to distribute data over local servers instead of a central database. Thus, arrived the concept of Distributed Databases."
},
{
"code": null,
"e": 3070,
"s": 2615,
"text": "This chapter gives an overview of databases and Database Management Systems (DBMS). A database is an ordered collection of related data. A DBMS is a software package to work upon a database. A detailed study of DBMS is available in our tutorial named “Learn DBMS”. In this chapter, we revise the main concepts so that the study of DDBMS can be done with ease. The three topics covered are database schemas, types of databases and operations on databases."
},
{
"code": null,
"e": 3379,
"s": 3070,
"text": "A database is an ordered collection of related data that is built for a specific purpose. A database may be organized as a collection of multiple tables, where a table represents a real world element or entity. Each table has several different fields that represent the characteristic features of the entity."
},
{
"code": null,
"e": 3589,
"s": 3379,
"text": "For example, a company database may include tables for projects, employees, departments, products and financial records. The fields in the Employee table may be Name, Company_Id, Date_of_Joining, and so forth."
},
{
"code": null,
"e": 4189,
"s": 3589,
"text": "A database management system is a collection of programs that enables creation and maintenance of a database. DBMS is available as a software package that facilitates definition, construction, manipulation and sharing of data in a database. Definition of a database includes description of the structure of a database. Construction of a database involves actual storing of the data in any storage medium. Manipulation refers to the retrieving information from the database, updating the database and generating reports. Sharing of data facilitates data to be accessed by different users or programs."
},
{
"code": null,
"e": 4215,
"s": 4189,
"text": "Automatic Teller Machines"
},
{
"code": null,
"e": 4240,
"s": 4215,
"text": "Train Reservation System"
},
{
"code": null,
"e": 4267,
"s": 4240,
"text": "Employee Management System"
},
{
"code": null,
"e": 4294,
"s": 4267,
"text": "Student Information System"
},
{
"code": null,
"e": 4300,
"s": 4294,
"text": "MySQL"
},
{
"code": null,
"e": 4307,
"s": 4300,
"text": "Oracle"
},
{
"code": null,
"e": 4318,
"s": 4307,
"text": "SQL Server"
},
{
"code": null,
"e": 4324,
"s": 4318,
"text": "dBASE"
},
{
"code": null,
"e": 4331,
"s": 4324,
"text": "FoxPro"
},
{
"code": null,
"e": 4348,
"s": 4331,
"text": "PostgreSQL, etc."
},
{
"code": null,
"e": 4593,
"s": 4348,
"text": "A database schema is a description of the database which is specified during database design and subject to infrequent alterations. It defines the organization of the data, the relationships among them, and the constraints associated with them."
},
{
"code": null,
"e": 4807,
"s": 4593,
"text": "Databases are often represented through the three-schema architecture or ANSISPARC architecture. The goal of this architecture is to separate the user application from the physical database. The three levels are −"
},
{
"code": null,
"e": 4947,
"s": 4807,
"text": "Internal Level having Internal Schema − It describes the physical structure, details of internal storage and access paths for the database."
},
{
"code": null,
"e": 5087,
"s": 4947,
"text": "Internal Level having Internal Schema − It describes the physical structure, details of internal storage and access paths for the database."
},
{
"code": null,
"e": 5350,
"s": 5087,
"text": "Conceptual Level having Conceptual Schema − It describes the structure of the whole database while hiding the details of physical storage of data. This illustrates the entities, attributes with their data types and constraints, user operations and relationships."
},
{
"code": null,
"e": 5613,
"s": 5350,
"text": "Conceptual Level having Conceptual Schema − It describes the structure of the whole database while hiding the details of physical storage of data. This illustrates the entities, attributes with their data types and constraints, user operations and relationships."
},
{
"code": null,
"e": 5795,
"s": 5613,
"text": "External or View Level having External Schemas or Views − It describes the portion of a database relevant to a particular user or a group of users while hiding the rest of database."
},
{
"code": null,
"e": 5977,
"s": 5795,
"text": "External or View Level having External Schemas or Views − It describes the portion of a database relevant to a particular user or a group of users while hiding the rest of database."
},
{
"code": null,
"e": 6007,
"s": 5977,
"text": "There are four types of DBMS."
},
{
"code": null,
"e": 6283,
"s": 6007,
"text": "In hierarchical DBMS, the relationships among data in the database are established so that one data element exists as a subordinate of another. The data elements have parent-child relationships and are modelled using the “tree” data structure. These are very fast and simple."
},
{
"code": null,
"e": 6560,
"s": 6283,
"text": "Network DBMS in one where the relationships among data in the database are of type many-to-many in the form of a network. The structure is generally complicated due to the existence of numerous many-to-many relationships. Network DBMS is modelled using “graph” data structure."
},
{
"code": null,
"e": 6940,
"s": 6560,
"text": "In relational databases, the database is represented in the form of relations. Each relation models an entity and is represented as a table of values. In the relation or table, a row is called a tuple and denotes a single record. A column is called a field or an attribute and denotes a characteristic property of the entity. RDBMS is the most popular database management system."
},
{
"code": null,
"e": 6975,
"s": 6940,
"text": "For example − A Student Relation −"
},
{
"code": null,
"e": 7450,
"s": 6975,
"text": "Object-oriented DBMS is derived from the model of the object-oriented programming paradigm. They are helpful in representing both consistent data as stored in databases, as well as transient data, as found in executing programs. They use small, reusable elements called objects. Each object contains a data part and a set of operations which works upon the data. The object and its attributes are accessed through pointers instead of being stored in relational table models."
},
{
"code": null,
"e": 7517,
"s": 7450,
"text": "For example − A simplified Bank Account object-oriented database −"
},
{
"code": null,
"e": 7944,
"s": 7517,
"text": "A distributed database is a set of interconnected databases that is distributed over the computer network or internet. A Distributed Database Management System (DDBMS) manages the distributed database and provides mechanisms so as to make the databases transparent to the users. In these systems, data is intentionally distributed among multiple nodes so that all computing resources of the organization can be optimally used."
},
{
"code": null,
"e": 8025,
"s": 7944,
"text": "The four basic operations on a database are Create, Retrieve, Update and Delete."
},
{
"code": null,
"e": 8259,
"s": 8025,
"text": "CREATE database structure and populate it with data − Creation of a database relation involves specifying the data structures, data types and the constraints of the data to be stored.\nExample − SQL command to create a student table −"
},
{
"code": null,
"e": 8443,
"s": 8259,
"text": "CREATE database structure and populate it with data − Creation of a database relation involves specifying the data structures, data types and the constraints of the data to be stored."
},
{
"code": null,
"e": 8493,
"s": 8443,
"text": "Example − SQL command to create a student table −"
},
{
"code": null,
"e": 8615,
"s": 8493,
"text": "CREATE TABLE STUDENT ( \n ROLL INTEGER PRIMARY KEY, \n NAME VARCHAR2(25), \n YEAR INTEGER, \n STREAM VARCHAR2(10) \n);"
},
{
"code": null,
"e": 8798,
"s": 8615,
"text": "Once the data format is defined, the actual data is stored in accordance with the format in some storage medium.\nExample SQL command to insert a single tuple into the student table −"
},
{
"code": null,
"e": 8911,
"s": 8798,
"text": "Once the data format is defined, the actual data is stored in accordance with the format in some storage medium."
},
{
"code": null,
"e": 8981,
"s": 8911,
"text": "Example SQL command to insert a single tuple into the student table −"
},
{
"code": null,
"e": 9079,
"s": 8981,
"text": "INSERT INTO STUDENT ( ROLL, NAME, YEAR, STREAM) \nVALUES ( 1, 'ANKIT JHA', 1, 'COMPUTER SCIENCE');"
},
{
"code": null,
"e": 9432,
"s": 9079,
"text": "RETRIEVE information from the database – Retrieving information generally involves selecting a subset of a table or displaying data from the table after some computations have been done. It is done by querying upon the table.\nExample − To retrieve the names of all students of the Computer Science stream, the following SQL query needs to be executed −"
},
{
"code": null,
"e": 9658,
"s": 9432,
"text": "RETRIEVE information from the database – Retrieving information generally involves selecting a subset of a table or displaying data from the table after some computations have been done. It is done by querying upon the table."
},
{
"code": null,
"e": 9785,
"s": 9658,
"text": "Example − To retrieve the names of all students of the Computer Science stream, the following SQL query needs to be executed −"
},
{
"code": null,
"e": 9846,
"s": 9785,
"text": "SELECT NAME FROM STUDENT \nWHERE STREAM = 'COMPUTER SCIENCE';"
},
{
"code": null,
"e": 10088,
"s": 9846,
"text": "UPDATE information stored and modify database structure – Updating a table involves changing old values in the existing table’s rows with new values.\nExample − SQL command to change stream from Electronics to Electronics and Communications −"
},
{
"code": null,
"e": 10238,
"s": 10088,
"text": "UPDATE information stored and modify database structure – Updating a table involves changing old values in the existing table’s rows with new values."
},
{
"code": null,
"e": 10330,
"s": 10238,
"text": "Example − SQL command to change stream from Electronics to Electronics and Communications −"
},
{
"code": null,
"e": 10423,
"s": 10330,
"text": "UPDATE STUDENT \nSET STREAM = 'ELECTRONICS AND COMMUNICATIONS' \nWHERE STREAM = 'ELECTRONICS';"
},
{
"code": null,
"e": 10670,
"s": 10423,
"text": "Modifying database means to change the structure of the table. However, modification of the table is subject to a number of restrictions.\nExample − To add a new field or column, say address to the Student table, we use the following SQL command −"
},
{
"code": null,
"e": 10808,
"s": 10670,
"text": "Modifying database means to change the structure of the table. However, modification of the table is subject to a number of restrictions."
},
{
"code": null,
"e": 10917,
"s": 10808,
"text": "Example − To add a new field or column, say address to the Student table, we use the following SQL command −"
},
{
"code": null,
"e": 10969,
"s": 10917,
"text": "ALTER TABLE STUDENT \nADD ( ADDRESS VARCHAR2(50) ); "
},
{
"code": null,
"e": 11258,
"s": 10969,
"text": "DELETE information stored or delete a table as a whole – Deletion of specific information involves removal of selected rows from the table that satisfies certain conditions.\nExample − To delete all students who are in 4th year currently when they are passing out, we use the SQL command −"
},
{
"code": null,
"e": 11432,
"s": 11258,
"text": "DELETE information stored or delete a table as a whole – Deletion of specific information involves removal of selected rows from the table that satisfies certain conditions."
},
{
"code": null,
"e": 11547,
"s": 11432,
"text": "Example − To delete all students who are in 4th year currently when they are passing out, we use the SQL command −"
},
{
"code": null,
"e": 11584,
"s": 11547,
"text": "DELETE FROM STUDENT \nWHERE YEAR = 4;"
},
{
"code": null,
"e": 11725,
"s": 11584,
"text": "Alternatively, the whole table may be removed from the database.\nExample − To remove the student table completely, the SQL command used is −"
},
{
"code": null,
"e": 11790,
"s": 11725,
"text": "Alternatively, the whole table may be removed from the database."
},
{
"code": null,
"e": 11866,
"s": 11790,
"text": "Example − To remove the student table completely, the SQL command used is −"
},
{
"code": null,
"e": 11886,
"s": 11866,
"text": "DROP TABLE STUDENT;"
},
{
"code": null,
"e": 12300,
"s": 11886,
"text": "This chapter introduces the concept of DDBMS. In a distributed database, there are a number of databases that may be geographically distributed all over the world. A distributed DBMS manages the distributed database in a manner so that it appears as one single database to users. In the later part of the chapter, we go on to study the factors that lead to distributed databases, its advantages and disadvantages."
},
{
"code": null,
"e": 12471,
"s": 12300,
"text": "A distributed database is a collection of multiple interconnected databases, which are spread physically across various locations that communicate via a computer network."
},
{
"code": null,
"e": 12591,
"s": 12471,
"text": "Databases in the collection are logically interrelated with each other. Often they represent a single logical database."
},
{
"code": null,
"e": 12711,
"s": 12591,
"text": "Databases in the collection are logically interrelated with each other. Often they represent a single logical database."
},
{
"code": null,
"e": 12835,
"s": 12711,
"text": "Data is physically stored across multiple sites. Data in each site can be managed by a DBMS independent of the other sites."
},
{
"code": null,
"e": 12959,
"s": 12835,
"text": "Data is physically stored across multiple sites. Data in each site can be managed by a DBMS independent of the other sites."
},
{
"code": null,
"e": 13067,
"s": 12959,
"text": "The processors in the sites are connected via a network. They do not have any multiprocessor configuration."
},
{
"code": null,
"e": 13175,
"s": 13067,
"text": "The processors in the sites are connected via a network. They do not have any multiprocessor configuration."
},
{
"code": null,
"e": 13238,
"s": 13175,
"text": "A distributed database is not a loosely connected file system."
},
{
"code": null,
"e": 13301,
"s": 13238,
"text": "A distributed database is not a loosely connected file system."
},
{
"code": null,
"e": 13424,
"s": 13301,
"text": "A distributed database incorporates transaction processing, but it is not synonymous with a transaction processing system."
},
{
"code": null,
"e": 13547,
"s": 13424,
"text": "A distributed database incorporates transaction processing, but it is not synonymous with a transaction processing system."
},
{
"code": null,
"e": 13724,
"s": 13547,
"text": "A distributed database management system (DDBMS) is a centralized software system that manages a distributed database in a manner as if it were all stored in a single location."
},
{
"code": null,
"e": 13797,
"s": 13724,
"text": "It is used to create, retrieve, update and delete distributed databases."
},
{
"code": null,
"e": 13870,
"s": 13797,
"text": "It is used to create, retrieve, update and delete distributed databases."
},
{
"code": null,
"e": 14017,
"s": 13870,
"text": "It synchronizes the database periodically and provides access mechanisms by the virtue of which the distribution becomes transparent to the users."
},
{
"code": null,
"e": 14164,
"s": 14017,
"text": "It synchronizes the database periodically and provides access mechanisms by the virtue of which the distribution becomes transparent to the users."
},
{
"code": null,
"e": 14234,
"s": 14164,
"text": "It ensures that the data modified at any site is universally updated."
},
{
"code": null,
"e": 14304,
"s": 14234,
"text": "It ensures that the data modified at any site is universally updated."
},
{
"code": null,
"e": 14425,
"s": 14304,
"text": "It is used in application areas where large volumes of data are processed and accessed by numerous users simultaneously."
},
{
"code": null,
"e": 14546,
"s": 14425,
"text": "It is used in application areas where large volumes of data are processed and accessed by numerous users simultaneously."
},
{
"code": null,
"e": 14599,
"s": 14546,
"text": "It is designed for heterogeneous database platforms."
},
{
"code": null,
"e": 14652,
"s": 14599,
"text": "It is designed for heterogeneous database platforms."
},
{
"code": null,
"e": 14718,
"s": 14652,
"text": "It maintains confidentiality and data integrity of the databases."
},
{
"code": null,
"e": 14784,
"s": 14718,
"text": "It maintains confidentiality and data integrity of the databases."
},
{
"code": null,
"e": 14839,
"s": 14784,
"text": "The following factors encourage moving over to DDBMS −"
},
{
"code": null,
"e": 15121,
"s": 14839,
"text": "Distributed Nature of Organizational Units − Most organizations in the current times are subdivided into multiple units that are physically distributed over the globe. Each unit requires its own set of local data. Thus, the overall database of the organization becomes distributed."
},
{
"code": null,
"e": 15403,
"s": 15121,
"text": "Distributed Nature of Organizational Units − Most organizations in the current times are subdivided into multiple units that are physically distributed over the globe. Each unit requires its own set of local data. Thus, the overall database of the organization becomes distributed."
},
{
"code": null,
"e": 15642,
"s": 15403,
"text": "Need for Sharing of Data − The multiple organizational units often need to communicate with each other and share their data and resources. This demands common databases or replicated databases that should be used in a synchronized manner."
},
{
"code": null,
"e": 15881,
"s": 15642,
"text": "Need for Sharing of Data − The multiple organizational units often need to communicate with each other and share their data and resources. This demands common databases or replicated databases that should be used in a synchronized manner."
},
{
"code": null,
"e": 16136,
"s": 15881,
"text": "Support for Both OLTP and OLAP − Online Transaction Processing (OLTP) and Online Analytical Processing (OLAP) work upon diversified systems which may have common data. Distributed database systems aid both these processing by providing synchronized data."
},
{
"code": null,
"e": 16391,
"s": 16136,
"text": "Support for Both OLTP and OLAP − Online Transaction Processing (OLTP) and Online Analytical Processing (OLAP) work upon diversified systems which may have common data. Distributed database systems aid both these processing by providing synchronized data."
},
{
"code": null,
"e": 16745,
"s": 16391,
"text": "Database Recovery − One of the common techniques used in DDBMS is replication of data across different sites. Replication of data automatically helps in data recovery if database in any site is damaged. Users can access data from other sites while the damaged site is being reconstructed. Thus, database failure may become almost inconspicuous to users."
},
{
"code": null,
"e": 17099,
"s": 16745,
"text": "Database Recovery − One of the common techniques used in DDBMS is replication of data across different sites. Replication of data automatically helps in data recovery if database in any site is damaged. Users can access data from other sites while the damaged site is being reconstructed. Thus, database failure may become almost inconspicuous to users."
},
{
"code": null,
"e": 17331,
"s": 17099,
"text": "Support for Multiple Application Software − Most organizations use a variety of application software each with its specific database support. DDBMS provides a uniform functionality for using the same data among different platforms."
},
{
"code": null,
"e": 17563,
"s": 17331,
"text": "Support for Multiple Application Software − Most organizations use a variety of application software each with its specific database support. DDBMS provides a uniform functionality for using the same data among different platforms."
},
{
"code": null,
"e": 17645,
"s": 17563,
"text": "Following are the advantages of distributed databases over centralized databases."
},
{
"code": null,
"e": 18060,
"s": 17645,
"text": "Modular Development − If the system needs to be expanded to new locations or new units, in centralized database systems, the action requires substantial efforts and disruption in the existing functioning. However, in distributed databases, the work simply requires adding new computers and local data to the new site and finally connecting them to the distributed system, with no interruption in current functions."
},
{
"code": null,
"e": 18325,
"s": 18060,
"text": "More Reliable − In case of database failures, the total system of centralized databases comes to a halt. However, in distributed systems, when a component fails, the functioning of the system continues may be at a reduced performance. Hence DDBMS is more reliable."
},
{
"code": null,
"e": 18624,
"s": 18325,
"text": "Better Response − If data is distributed in an efficient manner, then user requests can be met from local data itself, thus providing faster response. On the other hand, in centralized systems, all queries have to pass through the central computer for processing, which increases the response time."
},
{
"code": null,
"e": 18850,
"s": 18624,
"text": "Lower Communication Cost − In distributed database systems, if data is located locally where it is mostly used, then the communication costs for data manipulation can be minimized. This is not feasible in centralized systems."
},
{
"code": null,
"e": 18927,
"s": 18850,
"text": "Following are some of the adversities associated with distributed databases."
},
{
"code": null,
"e": 19093,
"s": 18927,
"text": "Need for complex and expensive software − DDBMS demands complex and often expensive software to provide data transparency and co-ordination across the several sites."
},
{
"code": null,
"e": 19259,
"s": 19093,
"text": "Need for complex and expensive software − DDBMS demands complex and often expensive software to provide data transparency and co-ordination across the several sites."
},
{
"code": null,
"e": 19425,
"s": 19259,
"text": "Processing overhead − Even simple operations may require a large number of communications and additional calculations to provide uniformity in data across the sites."
},
{
"code": null,
"e": 19591,
"s": 19425,
"text": "Processing overhead − Even simple operations may require a large number of communications and additional calculations to provide uniformity in data across the sites."
},
{
"code": null,
"e": 19686,
"s": 19591,
"text": "Data integrity − The need for updating data in multiple sites pose problems of data integrity."
},
{
"code": null,
"e": 19781,
"s": 19686,
"text": "Data integrity − The need for updating data in multiple sites pose problems of data integrity."
},
{
"code": null,
"e": 19981,
"s": 19781,
"text": "Overheads for improper data distribution − Responsiveness of queries is largely dependent upon proper data distribution. Improper data distribution often leads to very slow response to user requests."
},
{
"code": null,
"e": 20181,
"s": 19981,
"text": "Overheads for improper data distribution − Responsiveness of queries is largely dependent upon proper data distribution. Improper data distribution often leads to very slow response to user requests."
},
{
"code": null,
"e": 20702,
"s": 20181,
"text": "In this part of the tutorial, we will study the different aspects that aid in designing distributed database environments. This chapter starts with the types of distributed databases. Distributed databases can be classified into homogeneous and heterogeneous databases having further divisions. The next section of this chapter discusses the distributed architectures namely client – server, peer – to – peer and multi – DBMS. Finally, the different design alternatives like replication and fragmentation are introduced."
},
{
"code": null,
"e": 20893,
"s": 20702,
"text": "Distributed databases can be broadly classified into homogeneous and heterogeneous distributed database environments, each with further sub-divisions, as shown in the following illustration."
},
{
"code": null,
"e": 21009,
"s": 20893,
"text": "In a homogeneous distributed database, all the sites use identical DBMS and operating systems. Its properties are −"
},
{
"code": null,
"e": 21046,
"s": 21009,
"text": "The sites use very similar software."
},
{
"code": null,
"e": 21083,
"s": 21046,
"text": "The sites use very similar software."
},
{
"code": null,
"e": 21142,
"s": 21083,
"text": "The sites use identical DBMS or DBMS from the same vendor."
},
{
"code": null,
"e": 21201,
"s": 21142,
"text": "The sites use identical DBMS or DBMS from the same vendor."
},
{
"code": null,
"e": 21297,
"s": 21201,
"text": "Each site is aware of all other sites and cooperates with other sites to process user requests."
},
{
"code": null,
"e": 21393,
"s": 21297,
"text": "Each site is aware of all other sites and cooperates with other sites to process user requests."
},
{
"code": null,
"e": 21476,
"s": 21393,
"text": "The database is accessed through a single interface as if it is a single database."
},
{
"code": null,
"e": 21559,
"s": 21476,
"text": "The database is accessed through a single interface as if it is a single database."
},
{
"code": null,
"e": 21617,
"s": 21559,
"text": "There are two types of homogeneous distributed database −"
},
{
"code": null,
"e": 21782,
"s": 21617,
"text": "Autonomous − Each database is independent that functions on its own. They are integrated by a controlling application and use message passing to share data updates."
},
{
"code": null,
"e": 21947,
"s": 21782,
"text": "Autonomous − Each database is independent that functions on its own. They are integrated by a controlling application and use message passing to share data updates."
},
{
"code": null,
"e": 22086,
"s": 21947,
"text": "Non-autonomous − Data is distributed across the homogeneous nodes and a central or master DBMS co-ordinates data updates across the sites."
},
{
"code": null,
"e": 22225,
"s": 22086,
"text": "Non-autonomous − Data is distributed across the homogeneous nodes and a central or master DBMS co-ordinates data updates across the sites."
},
{
"code": null,
"e": 22368,
"s": 22225,
"text": "In a heterogeneous distributed database, different sites have different operating systems, DBMS products and data models. Its properties are −"
},
{
"code": null,
"e": 22421,
"s": 22368,
"text": "Different sites use dissimilar schemas and software."
},
{
"code": null,
"e": 22474,
"s": 22421,
"text": "Different sites use dissimilar schemas and software."
},
{
"code": null,
"e": 22582,
"s": 22474,
"text": "The system may be composed of a variety of DBMSs like relational, network, hierarchical or object oriented."
},
{
"code": null,
"e": 22690,
"s": 22582,
"text": "The system may be composed of a variety of DBMSs like relational, network, hierarchical or object oriented."
},
{
"code": null,
"e": 22745,
"s": 22690,
"text": "Query processing is complex due to dissimilar schemas."
},
{
"code": null,
"e": 22800,
"s": 22745,
"text": "Query processing is complex due to dissimilar schemas."
},
{
"code": null,
"e": 22862,
"s": 22800,
"text": "Transaction processing is complex due to dissimilar software."
},
{
"code": null,
"e": 22924,
"s": 22862,
"text": "Transaction processing is complex due to dissimilar software."
},
{
"code": null,
"e": 23029,
"s": 22924,
"text": "A site may not be aware of other sites and so there is limited co-operation in processing user requests."
},
{
"code": null,
"e": 23134,
"s": 23029,
"text": "A site may not be aware of other sites and so there is limited co-operation in processing user requests."
},
{
"code": null,
"e": 23282,
"s": 23134,
"text": "Federated − The heterogeneous database systems are independent in nature and integrated together so that they function as a single database system."
},
{
"code": null,
"e": 23430,
"s": 23282,
"text": "Federated − The heterogeneous database systems are independent in nature and integrated together so that they function as a single database system."
},
{
"code": null,
"e": 23545,
"s": 23430,
"text": "Un-federated − The database systems employ a central coordinating module through which the databases are accessed."
},
{
"code": null,
"e": 23660,
"s": 23545,
"text": "Un-federated − The database systems employ a central coordinating module through which the databases are accessed."
},
{
"code": null,
"e": 23736,
"s": 23660,
"text": "DDBMS architectures are generally developed depending on three parameters −"
},
{
"code": null,
"e": 23823,
"s": 23736,
"text": "Distribution − It states the physical distribution of data across the different sites."
},
{
"code": null,
"e": 23910,
"s": 23823,
"text": "Distribution − It states the physical distribution of data across the different sites."
},
{
"code": null,
"e": 24058,
"s": 23910,
"text": "Autonomy − It indicates the distribution of control of the database system and the degree to which each constituent DBMS can operate independently."
},
{
"code": null,
"e": 24206,
"s": 24058,
"text": "Autonomy − It indicates the distribution of control of the database system and the degree to which each constituent DBMS can operate independently."
},
{
"code": null,
"e": 24320,
"s": 24206,
"text": "Heterogeneity − It refers to the uniformity or dissimilarity of the data models, system components and databases."
},
{
"code": null,
"e": 24434,
"s": 24320,
"text": "Heterogeneity − It refers to the uniformity or dissimilarity of the data models, system components and databases."
},
{
"code": null,
"e": 24480,
"s": 24434,
"text": "Some of the common architectural models are −"
},
{
"code": null,
"e": 24519,
"s": 24480,
"text": "Client - Server Architecture for DDBMS"
},
{
"code": null,
"e": 24559,
"s": 24519,
"text": "Peer - to - Peer Architecture for DDBMS"
},
{
"code": null,
"e": 24585,
"s": 24559,
"text": "Multi - DBMS Architecture"
},
{
"code": null,
"e": 24932,
"s": 24585,
"text": "This is a two-level architecture where the functionality is divided into servers and clients. The server functions primarily encompass data management, query processing, optimization and transaction management. Client functions include mainly user interface. However, they have some functions like consistency checking and transaction management."
},
{
"code": null,
"e": 24985,
"s": 24932,
"text": "The two different client - server architecture are −"
},
{
"code": null,
"e": 25015,
"s": 24985,
"text": "Single Server Multiple Client"
},
{
"code": null,
"e": 25080,
"s": 25015,
"text": "Multiple Server Multiple Client (shown in the following diagram)"
},
{
"code": null,
"e": 25258,
"s": 25080,
"text": "In these systems, each peer acts both as a client and a server for imparting database services. The peers share their resource with other peers and co-ordinate their activities."
},
{
"code": null,
"e": 25315,
"s": 25258,
"text": "This architecture generally has four levels of schemas −"
},
{
"code": null,
"e": 25383,
"s": 25315,
"text": "Global Conceptual Schema − Depicts the global logical view of data."
},
{
"code": null,
"e": 25451,
"s": 25383,
"text": "Global Conceptual Schema − Depicts the global logical view of data."
},
{
"code": null,
"e": 25525,
"s": 25451,
"text": "Local Conceptual Schema − Depicts logical data organization at each site."
},
{
"code": null,
"e": 25599,
"s": 25525,
"text": "Local Conceptual Schema − Depicts logical data organization at each site."
},
{
"code": null,
"e": 25672,
"s": 25599,
"text": "Local Internal Schema − Depicts physical data organization at each site."
},
{
"code": null,
"e": 25745,
"s": 25672,
"text": "Local Internal Schema − Depicts physical data organization at each site."
},
{
"code": null,
"e": 25790,
"s": 25745,
"text": "External Schema − Depicts user view of data."
},
{
"code": null,
"e": 25835,
"s": 25790,
"text": "External Schema − Depicts user view of data."
},
{
"code": null,
"e": 25940,
"s": 25835,
"text": "This is an integrated database system formed by a collection of two or more autonomous database systems."
},
{
"code": null,
"e": 26000,
"s": 25940,
"text": "Multi-DBMS can be expressed through six levels of schemas −"
},
{
"code": null,
"e": 26118,
"s": 26000,
"text": "Multi-database View Level − Depicts multiple user views comprising of subsets of the integrated distributed database."
},
{
"code": null,
"e": 26236,
"s": 26118,
"text": "Multi-database View Level − Depicts multiple user views comprising of subsets of the integrated distributed database."
},
{
"code": null,
"e": 26375,
"s": 26236,
"text": "Multi-database Conceptual Level − Depicts integrated multi-database that comprises of global logical multi-database structure definitions."
},
{
"code": null,
"e": 26514,
"s": 26375,
"text": "Multi-database Conceptual Level − Depicts integrated multi-database that comprises of global logical multi-database structure definitions."
},
{
"code": null,
"e": 26641,
"s": 26514,
"text": "Multi-database Internal Level − Depicts the data distribution across different sites and multi-database to local data mapping."
},
{
"code": null,
"e": 26768,
"s": 26641,
"text": "Multi-database Internal Level − Depicts the data distribution across different sites and multi-database to local data mapping."
},
{
"code": null,
"e": 26831,
"s": 26768,
"text": "Local database View Level − Depicts public view of local data."
},
{
"code": null,
"e": 26894,
"s": 26831,
"text": "Local database View Level − Depicts public view of local data."
},
{
"code": null,
"e": 26974,
"s": 26894,
"text": "Local database Conceptual Level − Depicts local data organization at each site."
},
{
"code": null,
"e": 27054,
"s": 26974,
"text": "Local database Conceptual Level − Depicts local data organization at each site."
},
{
"code": null,
"e": 27135,
"s": 27054,
"text": "Local database Internal Level − Depicts physical data organization at each site."
},
{
"code": null,
"e": 27216,
"s": 27135,
"text": "Local database Internal Level − Depicts physical data organization at each site."
},
{
"code": null,
"e": 27267,
"s": 27216,
"text": "There are two design alternatives for multi-DBMS −"
},
{
"code": null,
"e": 27311,
"s": 27267,
"text": "Model with multi-database conceptual level."
},
{
"code": null,
"e": 27358,
"s": 27311,
"text": "Model without multi-database conceptual level."
},
{
"code": null,
"e": 27438,
"s": 27358,
"text": "The distribution design alternatives for the tables in a DDBMS are as follows −"
},
{
"code": null,
"e": 27472,
"s": 27438,
"text": "Non-replicated and non-fragmented"
},
{
"code": null,
"e": 27489,
"s": 27472,
"text": "Fully replicated"
},
{
"code": null,
"e": 27510,
"s": 27489,
"text": "Partially replicated"
},
{
"code": null,
"e": 27521,
"s": 27510,
"text": "Fragmented"
},
{
"code": null,
"e": 27527,
"s": 27521,
"text": "Mixed"
},
{
"code": null,
"e": 27976,
"s": 27527,
"text": "In this design alternative, different tables are placed at different sites. Data is placed so that it is at a close proximity to the site where it is used most. It is most suitable for database systems where the percentage of queries needed to join information in tables placed at different sites is low. If an appropriate distribution strategy is adopted, then this design alternative helps to reduce the communication cost during data processing."
},
{
"code": null,
"e": 28420,
"s": 27976,
"text": "In this design alternative, at each site, one copy of all the database tables is stored. Since, each site has its own copy of the entire database, queries are very fast requiring negligible communication cost. On the contrary, the massive redundancy in data requires huge cost during update operations. Hence, this is suitable for systems where a large number of queries is required to be handled whereas the number of database updates is low."
},
{
"code": null,
"e": 28840,
"s": 28420,
"text": "Copies of tables or portions of tables are stored at different sites. The distribution of the tables is done in accordance to the frequency of access. This takes into consideration the fact that the frequency of accessing the tables vary considerably from site to site. The number of copies of the tables (or portions) depends on how frequently the access queries execute and the site which generate the access queries."
},
{
"code": null,
"e": 29269,
"s": 28840,
"text": "In this design, a table is divided into two or more pieces referred to as fragments or partitions, and each fragment can be stored at different sites. This considers the fact that it seldom happens that all data stored in a table is required at a given site. Moreover, fragmentation increases parallelism and provides better disaster recovery. Here, there is only one copy of each fragment in the system, i.e. no redundant data."
},
{
"code": null,
"e": 29310,
"s": 29269,
"text": "The three fragmentation techniques are −"
},
{
"code": null,
"e": 29333,
"s": 29310,
"text": "Vertical fragmentation"
},
{
"code": null,
"e": 29358,
"s": 29333,
"text": "Horizontal fragmentation"
},
{
"code": null,
"e": 29379,
"s": 29358,
"text": "Hybrid fragmentation"
},
{
"code": null,
"e": 29656,
"s": 29379,
"text": "This is a combination of fragmentation and partial replications. Here, the tables are initially fragmented in any form (horizontal or vertical), and then these fragments are partially replicated across the different sites according to the frequency of accessing the fragments."
},
{
"code": null,
"e": 29938,
"s": 29656,
"text": "In the last chapter, we had introduced different design alternatives. In this chapter, we will study the strategies that aid in adopting the designs. The strategies can be broadly divided into replication and fragmentation. However, in most cases, a combination of the two is used."
},
{
"code": null,
"e": 30103,
"s": 29938,
"text": "Data replication is the process of storing separate copies of the database at two or more sites. It is a popular fault tolerance technique of distributed databases."
},
{
"code": null,
"e": 30233,
"s": 30103,
"text": "Reliability − In case of failure of any site, the database system continues to work since a copy is available at another site(s)."
},
{
"code": null,
"e": 30363,
"s": 30233,
"text": "Reliability − In case of failure of any site, the database system continues to work since a copy is available at another site(s)."
},
{
"code": null,
"e": 30569,
"s": 30363,
"text": "Reduction in Network Load − Since local copies of data are available, query processing can be done with reduced network usage, particularly during prime hours. Data updating can be done at non-prime hours."
},
{
"code": null,
"e": 30775,
"s": 30569,
"text": "Reduction in Network Load − Since local copies of data are available, query processing can be done with reduced network usage, particularly during prime hours. Data updating can be done at non-prime hours."
},
{
"code": null,
"e": 30900,
"s": 30775,
"text": "Quicker Response − Availability of local copies of data ensures quick query processing and consequently quick response time."
},
{
"code": null,
"e": 31025,
"s": 30900,
"text": "Quicker Response − Availability of local copies of data ensures quick query processing and consequently quick response time."
},
{
"code": null,
"e": 31209,
"s": 31025,
"text": "Simpler Transactions − Transactions require less number of joins of tables located at different sites and minimal coordination across the network. Thus, they become simpler in nature."
},
{
"code": null,
"e": 31393,
"s": 31209,
"text": "Simpler Transactions − Transactions require less number of joins of tables located at different sites and minimal coordination across the network. Thus, they become simpler in nature."
},
{
"code": null,
"e": 31599,
"s": 31393,
"text": "Increased Storage Requirements − Maintaining multiple copies of data is associated with increased storage costs. The storage space required is in multiples of the storage required for a centralized system."
},
{
"code": null,
"e": 31805,
"s": 31599,
"text": "Increased Storage Requirements − Maintaining multiple copies of data is associated with increased storage costs. The storage space required is in multiples of the storage required for a centralized system."
},
{
"code": null,
"e": 32039,
"s": 31805,
"text": "Increased Cost and Complexity of Data Updating − Each time a data item is updated, the update needs to be reflected in all the copies of the data at the different sites. This requires complex synchronization techniques and protocols."
},
{
"code": null,
"e": 32273,
"s": 32039,
"text": "Increased Cost and Complexity of Data Updating − Each time a data item is updated, the update needs to be reflected in all the copies of the data at the different sites. This requires complex synchronization techniques and protocols."
},
{
"code": null,
"e": 32505,
"s": 32273,
"text": "Undesirable Application – Database coupling − If complex update mechanisms are not used, removing data inconsistency requires complex co-ordination at application level. This results in undesirable application – database coupling."
},
{
"code": null,
"e": 32737,
"s": 32505,
"text": "Undesirable Application – Database coupling − If complex update mechanisms are not used, removing data inconsistency requires complex co-ordination at application level. This results in undesirable application – database coupling."
},
{
"code": null,
"e": 32785,
"s": 32737,
"text": "Some commonly used replication techniques are −"
},
{
"code": null,
"e": 32806,
"s": 32785,
"text": "Snapshot replication"
},
{
"code": null,
"e": 32833,
"s": 32806,
"text": "Near-real-time replication"
},
{
"code": null,
"e": 32850,
"s": 32833,
"text": "Pull replication"
},
{
"code": null,
"e": 33228,
"s": 32850,
"text": "Fragmentation is the task of dividing a table into a set of smaller tables. The subsets of the table are called fragments. Fragmentation can be of three types: horizontal, vertical, and hybrid (combination of horizontal and vertical). Horizontal fragmentation can further be classified into two techniques: primary horizontal fragmentation and derived horizontal fragmentation."
},
{
"code": null,
"e": 33484,
"s": 33228,
"text": "Fragmentation should be done in a way so that the original table can be reconstructed from the fragments. This is needed so that the original table can be reconstructed from the fragments whenever required. This requirement is called “reconstructiveness.”"
},
{
"code": null,
"e": 33581,
"s": 33484,
"text": "Since data is stored close to the site of usage, efficiency of the database system is increased."
},
{
"code": null,
"e": 33678,
"s": 33581,
"text": "Since data is stored close to the site of usage, efficiency of the database system is increased."
},
{
"code": null,
"e": 33779,
"s": 33678,
"text": "Local query optimization techniques are sufficient for most queries since data is locally available."
},
{
"code": null,
"e": 33880,
"s": 33779,
"text": "Local query optimization techniques are sufficient for most queries since data is locally available."
},
{
"code": null,
"e": 33996,
"s": 33880,
"text": "Since irrelevant data is not available at the sites, security and privacy of the database system can be maintained."
},
{
"code": null,
"e": 34112,
"s": 33996,
"text": "Since irrelevant data is not available at the sites, security and privacy of the database system can be maintained."
},
{
"code": null,
"e": 34196,
"s": 34112,
"text": "When data from different fragments are required, the access speeds may be very low."
},
{
"code": null,
"e": 34280,
"s": 34196,
"text": "When data from different fragments are required, the access speeds may be very low."
},
{
"code": null,
"e": 34375,
"s": 34280,
"text": "In case of recursive fragmentations, the job of reconstruction will need expensive techniques."
},
{
"code": null,
"e": 34470,
"s": 34375,
"text": "In case of recursive fragmentations, the job of reconstruction will need expensive techniques."
},
{
"code": null,
"e": 34586,
"s": 34470,
"text": "Lack of back-up copies of data in different sites may render the database ineffective in case of failure of a site."
},
{
"code": null,
"e": 34702,
"s": 34586,
"text": "Lack of back-up copies of data in different sites may render the database ineffective in case of failure of a site."
},
{
"code": null,
"e": 34962,
"s": 34702,
"text": "In vertical fragmentation, the fields or columns of a table are grouped into fragments. In order to maintain reconstructiveness, each fragment should contain the primary key field(s) of the table. Vertical fragmentation can be used to enforce privacy of data."
},
{
"code": null,
"e": 35107,
"s": 34962,
"text": "For example, let us consider that a University database keeps records of all registered students in a Student table having the following schema."
},
{
"code": null,
"e": 35115,
"s": 35107,
"text": "STUDENT"
},
{
"code": null,
"e": 35244,
"s": 35115,
"text": "Now, the fees details are maintained in the accounts section. In this case, the designer will fragment the database as follows −"
},
{
"code": null,
"e": 35312,
"s": 35244,
"text": "CREATE TABLE STD_FEES AS \n SELECT Regd_No, Fees \n FROM STUDENT;"
},
{
"code": null,
"e": 35568,
"s": 35312,
"text": "Horizontal fragmentation groups the tuples of a table in accordance to values of one or more fields. Horizontal fragmentation should also confirm to the rule of reconstructiveness. Each horizontal fragment must have all columns of the original base table."
},
{
"code": null,
"e": 35791,
"s": 35568,
"text": "For example, in the student schema, if the details of all students of Computer Science Course needs to be maintained at the School of Computer Science, then the designer will horizontally fragment the database as follows −"
},
{
"code": null,
"e": 35876,
"s": 35791,
"text": "CREATE COMP_STD AS \n SELECT * FROM STUDENT \n WHERE COURSE = \"Computer Science\";"
},
{
"code": null,
"e": 36167,
"s": 35876,
"text": "In hybrid fragmentation, a combination of horizontal and vertical fragmentation techniques are used. This is the most flexible fragmentation technique since it generates fragments with minimal extraneous information. However, reconstruction of the original table is often an expensive task."
},
{
"code": null,
"e": 36226,
"s": 36167,
"text": "Hybrid fragmentation can be done in two alternative ways −"
},
{
"code": null,
"e": 36355,
"s": 36226,
"text": "At first, generate a set of horizontal fragments; then generate vertical fragments from one or more of the horizontal fragments."
},
{
"code": null,
"e": 36484,
"s": 36355,
"text": "At first, generate a set of horizontal fragments; then generate vertical fragments from one or more of the horizontal fragments."
},
{
"code": null,
"e": 36611,
"s": 36484,
"text": "At first, generate a set of vertical fragments; then generate horizontal fragments from one or more of the vertical fragments."
},
{
"code": null,
"e": 36738,
"s": 36611,
"text": "At first, generate a set of vertical fragments; then generate horizontal fragments from one or more of the vertical fragments."
},
{
"code": null,
"e": 37136,
"s": 36738,
"text": "Distribution transparency is the property of distributed databases by the virtue of which the internal details of the distribution are hidden from the users. The DDBMS designer may choose to fragment tables, replicate the fragments and store them at different sites. However, since users are oblivious of these details, they find the distributed database easy to use like any centralized database."
},
{
"code": null,
"e": 37192,
"s": 37136,
"text": "The three dimensions of distribution transparency are −"
},
{
"code": null,
"e": 37214,
"s": 37192,
"text": "Location transparency"
},
{
"code": null,
"e": 37241,
"s": 37214,
"text": "Fragmentation transparency"
},
{
"code": null,
"e": 37266,
"s": 37241,
"text": "Replication transparency"
},
{
"code": null,
"e": 37647,
"s": 37266,
"text": "Location transparency ensures that the user can query on any table(s) or fragment(s) of a table as if they were stored locally in the user’s site. The fact that the table or its fragments are stored at remote site in the distributed database system, should be completely oblivious to the end user. The address of the remote site(s) and the access mechanisms are completely hidden."
},
{
"code": null,
"e": 37828,
"s": 37647,
"text": "In order to incorporate location transparency, DDBMS should have access to updated and accurate data dictionary and DDBMS directory which contains the details of locations of data."
},
{
"code": null,
"e": 38110,
"s": 37828,
"text": "Fragmentation transparency enables users to query upon any table as if it were unfragmented. Thus, it hides the fact that the table the user is querying on is actually a fragment or union of some fragments. It also conceals the fact that the fragments are located at diverse sites."
},
{
"code": null,
"e": 38253,
"s": 38110,
"text": "This is somewhat similar to users of SQL views, where the user may not know that they are using a view of a table instead of the table itself."
},
{
"code": null,
"e": 38428,
"s": 38253,
"text": "Replication transparency ensures that replication of databases are hidden from the users. It enables users to query upon a table as if only a single copy of the table exists."
},
{
"code": null,
"e": 38875,
"s": 38428,
"text": "Replication transparency is associated with concurrency transparency and failure transparency. Whenever a user updates a data item, the update is reflected in all the copies of the table. However, this operation should not be known to the user. This is concurrency transparency. Also, in case of failure of a site, the user can still proceed with his queries using replicated copies without any knowledge of failure. This is failure transparency."
},
{
"code": null,
"e": 39241,
"s": 38875,
"text": "In any distributed database system, the designer should ensure that all the stated transparencies are maintained to a considerable extent. The designer may choose to fragment tables, replicate them and store them at different sites; all oblivious to the end user. However, complete distribution transparency is a tough task and requires considerable design efforts."
},
{
"code": null,
"e": 39711,
"s": 39241,
"text": "Database control refers to the task of enforcing regulations so as to provide correct data to authentic users and applications of a database. In order that correct data is available to users, all data should conform to the integrity constraints defined in the database. Besides, data should be screened away from unauthorized users so as to maintain security and privacy of the database. Database control is one of the primary tasks of the database administrator (DBA)."
},
{
"code": null,
"e": 39758,
"s": 39711,
"text": "The three dimensions of database control are −"
},
{
"code": null,
"e": 39773,
"s": 39758,
"text": "Authentication"
},
{
"code": null,
"e": 39787,
"s": 39773,
"text": "Access rights"
},
{
"code": null,
"e": 39809,
"s": 39787,
"text": "Integrity constraints"
},
{
"code": null,
"e": 39948,
"s": 39809,
"text": "In a distributed database system, authentication is the process through which only legitimate users can gain access to the data resources."
},
{
"code": null,
"e": 39995,
"s": 39948,
"text": "Authentication can be enforced in two levels −"
},
{
"code": null,
"e": 40325,
"s": 39995,
"text": "Controlling Access to Client Computer − At this level, user access is restricted while login to the client computer that provides user-interface to the database server. The most common method is a username/password combination. However, more sophisticated methods like biometric authentication may be used for high security data."
},
{
"code": null,
"e": 40655,
"s": 40325,
"text": "Controlling Access to Client Computer − At this level, user access is restricted while login to the client computer that provides user-interface to the database server. The most common method is a username/password combination. However, more sophisticated methods like biometric authentication may be used for high security data."
},
{
"code": null,
"e": 40929,
"s": 40655,
"text": "Controlling Access to the Database Software − At this level, the database software/administrator assigns some credentials to the user. The user gains access to the database using these credentials. One of the methods is to create a login account within the database server."
},
{
"code": null,
"e": 41203,
"s": 40929,
"text": "Controlling Access to the Database Software − At this level, the database software/administrator assigns some credentials to the user. The user gains access to the database using these credentials. One of the methods is to create a login account within the database server."
},
{
"code": null,
"e": 41413,
"s": 41203,
"text": "A user’s access rights refers to the privileges that the user is given regarding DBMS operations such as the rights to create a table, drop a table, add/delete/update tuples in a table or query upon the table."
},
{
"code": null,
"e": 41888,
"s": 41413,
"text": "In distributed environments, since there are large number of tables and yet larger number of users, it is not feasible to assign individual access rights to users. So, DDBMS defines certain roles. A role is a construct with certain privileges within a database system. Once the different roles are defined, the individual users are assigned one of these roles. Often a hierarchy of roles are defined according to the organization’s hierarchy of authority and responsibility."
},
{
"code": null,
"e": 41999,
"s": 41888,
"text": "For example, the following SQL statements create a role \"Accountant\" and then assigns this role to user \"ABC\"."
},
{
"code": null,
"e": 42226,
"s": 41999,
"text": "CREATE ROLE ACCOUNTANT; \nGRANT SELECT, INSERT, UPDATE ON EMP_SAL TO ACCOUNTANT; \nGRANT INSERT, UPDATE, DELETE ON TENDER TO ACCOUNTANT; \nGRANT INSERT, SELECT ON EXPENSE TO ACCOUNTANT; \nCOMMIT; \nGRANT ACCOUNTANT TO ABC; \nCOMMIT;"
},
{
"code": null,
"e": 42324,
"s": 42226,
"text": "Semantic integrity control defines and enforces the integrity constraints of the database system."
},
{
"code": null,
"e": 42367,
"s": 42324,
"text": "The integrity constraints are as follows −"
},
{
"code": null,
"e": 42398,
"s": 42367,
"text": "Data type integrity constraint"
},
{
"code": null,
"e": 42426,
"s": 42398,
"text": "Entity integrity constraint"
},
{
"code": null,
"e": 42459,
"s": 42426,
"text": "Referential integrity constraint"
},
{
"code": null,
"e": 42602,
"s": 42459,
"text": "A data type constraint restricts the range of values and the type of operations that can be applied to the field with the specified data type."
},
{
"code": null,
"e": 42898,
"s": 42602,
"text": "For example, let us consider that a table \"HOSTEL\" has three fields - the hostel number, hostel name and capacity. The hostel number should start with capital letter \"H\" and cannot be NULL, and the capacity should not be more than 150. The following SQL command can be used for data definition −"
},
{
"code": null,
"e": 43061,
"s": 42898,
"text": "CREATE TABLE HOSTEL ( \n H_NO VARCHAR2(5) NOT NULL, \n H_NAME VARCHAR2(15), \n CAPACITY INTEGER, \n CHECK ( H_NO LIKE 'H%'), \n CHECK ( CAPACITY <= 150) \n); "
},
{
"code": null,
"e": 43464,
"s": 43061,
"text": "Entity integrity control enforces the rules so that each tuple can be uniquely identified from other tuples. For this a primary key is defined. A primary key is a set of minimal fields that can uniquely identify a tuple. Entity integrity constraint states that no two tuples in a table can have identical values for primary keys and that no field which is a part of the primary key can have NULL value."
},
{
"code": null,
"e": 43617,
"s": 43464,
"text": "For example, in the above hostel table, the hostel number can be assigned as the primary key through the following SQL statement (ignoring the checks) −"
},
{
"code": null,
"e": 43724,
"s": 43617,
"text": "CREATE TABLE HOSTEL ( \n H_NO VARCHAR2(5) PRIMARY KEY, \n H_NAME VARCHAR2(15), \n CAPACITY INTEGER \n); "
},
{
"code": null,
"e": 44073,
"s": 43724,
"text": "Referential integrity constraint lays down the rules of foreign keys. A foreign key is a field in a data table that is the primary key of a related table. The referential integrity constraint lays down the rule that the value of the foreign key field should either be among the values of the primary key of the referenced table or be entirely NULL."
},
{
"code": null,
"e": 44318,
"s": 44073,
"text": "For example, let us consider a student table where a student may opt to live in a hostel. To include this, the primary key of hostel table should be included as a foreign key in the student table. The following SQL statement incorporates this −"
},
{
"code": null,
"e": 44483,
"s": 44318,
"text": "CREATE TABLE STUDENT ( \n S_ROLL INTEGER PRIMARY KEY, \n S_NAME VARCHAR2(25) NOT NULL, \n S_COURSE VARCHAR2(10), \n S_HOSTEL VARCHAR2(5) REFERENCES HOSTEL \n); "
},
{
"code": null,
"e": 44862,
"s": 44483,
"text": "When a query is placed, it is at first scanned, parsed and validated. An internal representation of the query is then created such as a query tree or a query graph. Then alternative execution strategies are devised for retrieving results from the database tables. The process of choosing the most appropriate execution strategy for query processing is called query optimization."
},
{
"code": null,
"e": 45030,
"s": 44862,
"text": "In DDBMS, query optimization is a crucial task. The complexity is high since number of alternative strategies may increase exponentially due to the following factors −"
},
{
"code": null,
"e": 45069,
"s": 45030,
"text": "The presence of a number of fragments."
},
{
"code": null,
"e": 45131,
"s": 45069,
"text": "Distribution of the fragments or tables across various sites."
},
{
"code": null,
"e": 45165,
"s": 45131,
"text": "The speed of communication links."
},
{
"code": null,
"e": 45209,
"s": 45165,
"text": "Disparity in local processing capabilities."
},
{
"code": null,
"e": 45400,
"s": 45209,
"text": "Hence, in a distributed system, the target is often to find a good execution strategy for query processing rather than the best one. The time to execute a query is the sum of the following −"
},
{
"code": null,
"e": 45442,
"s": 45400,
"text": "Time to communicate queries to databases."
},
{
"code": null,
"e": 45481,
"s": 45442,
"text": "Time to execute local query fragments."
},
{
"code": null,
"e": 45525,
"s": 45481,
"text": "Time to assemble data from different sites."
},
{
"code": null,
"e": 45569,
"s": 45525,
"text": "Time to display results to the application."
},
{
"code": null,
"e": 45733,
"s": 45569,
"text": "Query processing is a set of all activities starting from query placement to displaying the results of the query. The steps are as shown in the following diagram −"
},
{
"code": null,
"e": 45974,
"s": 45733,
"text": "Relational algebra defines the basic set of operations of relational database model. A sequence of relational algebra operations forms a relational algebra expression. The result of this expression represents the result of a database query."
},
{
"code": null,
"e": 46001,
"s": 45974,
"text": "The basic operations are −"
},
{
"code": null,
"e": 46012,
"s": 46001,
"text": "Projection"
},
{
"code": null,
"e": 46022,
"s": 46012,
"text": "Selection"
},
{
"code": null,
"e": 46028,
"s": 46022,
"text": "Union"
},
{
"code": null,
"e": 46041,
"s": 46028,
"text": "Intersection"
},
{
"code": null,
"e": 46047,
"s": 46041,
"text": "Minus"
},
{
"code": null,
"e": 46053,
"s": 46047,
"text": "Join "
},
{
"code": null,
"e": 46160,
"s": 46053,
"text": "Projection operation displays a subset of fields of a table. This gives a vertical partition of the table."
},
{
"code": null,
"e": 46189,
"s": 46160,
"text": "Syntax in Relational Algebra"
},
{
"code": null,
"e": 46219,
"s": 46189,
"text": "π<AttributeList>(<TableName>)"
},
{
"code": null,
"e": 46281,
"s": 46219,
"text": "For example, let us consider the following Student database −"
},
{
"code": null,
"e": 46400,
"s": 46281,
"text": "If we want to display the names and courses of all students, we will use the following relational algebra expression −"
},
{
"code": null,
"e": 46422,
"s": 46400,
"text": "πName,Course(STUDENT)"
},
{
"code": null,
"e": 46564,
"s": 46422,
"text": "Selection operation displays a subset of tuples of a table that satisfies certain conditions. This gives a horizontal partition of the table."
},
{
"code": null,
"e": 46593,
"s": 46564,
"text": "Syntax in Relational Algebra"
},
{
"code": null,
"e": 46620,
"s": 46593,
"text": "σ<Conditions>(<TableName>)"
},
{
"code": null,
"e": 46794,
"s": 46620,
"text": "For example, in the Student table, if we want to display the details of all students who have opted for MCA course, we will use the following relational algebra expression −"
},
{
"code": null,
"e": 46817,
"s": 46794,
"text": "σCourse=\"BCA\"(STUDENT)"
},
{
"code": null,
"e": 46945,
"s": 46817,
"text": "For most queries, we need a combination of projection and selection operations. There are two ways to write these expressions −"
},
{
"code": null,
"e": 47000,
"s": 46945,
"text": "Using sequence of projection and selection operations."
},
{
"code": null,
"e": 47057,
"s": 47000,
"text": "Using rename operation to generate intermediate results."
},
{
"code": null,
"e": 47130,
"s": 47057,
"text": "For example, to display names of all female students of the BCA course −"
},
{
"code": null,
"e": 47214,
"s": 47130,
"text": "Relational algebra expression using sequence of projection and selection operations"
},
{
"code": null,
"e": 47262,
"s": 47214,
"text": "πName(σGender=\"Female\"ANDCourse=\"BCA\"(STUDENT))"
},
{
"code": null,
"e": 47348,
"s": 47262,
"text": "Relational algebra expression using rename operation to generate intermediate results"
},
{
"code": null,
"e": 47406,
"s": 47348,
"text": "FemaleBCAStudent←σGender=\"Female\"ANDCourse=\"BCA\"(STUDENT)"
},
{
"code": null,
"e": 47437,
"s": 47406,
"text": "Result←πName(FemaleBCAStudent)"
},
{
"code": null,
"e": 47621,
"s": 47437,
"text": "If P is a result of an operation and Q is a result of another operation, the union of P and Q (p∪Q) is the set of all tuples that is either in P or in Q or in both without duplicates."
},
{
"code": null,
"e": 47710,
"s": 47621,
"text": "For example, to display all students who are either in Semester 1 or are in BCA course −"
},
{
"code": null,
"e": 47743,
"s": 47710,
"text": "Sem1Student←σSemester=1(STUDENT)"
},
{
"code": null,
"e": 47777,
"s": 47743,
"text": "BCAStudent←σCourse=\"BCA\"(STUDENT)"
},
{
"code": null,
"e": 47807,
"s": 47777,
"text": "Result←Sem1Student∪BCAStudent"
},
{
"code": null,
"e": 47967,
"s": 47807,
"text": "If P is a result of an operation and Q is a result of another operation, the intersection of P and Q ( p∩Q ) is the set of all tuples that are in P and Q both."
},
{
"code": null,
"e": 48014,
"s": 47967,
"text": "For example, given the following two schemas −"
},
{
"code": null,
"e": 48023,
"s": 48014,
"text": "EMPLOYEE"
},
{
"code": null,
"e": 48031,
"s": 48023,
"text": "PROJECT"
},
{
"code": null,
"e": 48124,
"s": 48031,
"text": "To display the names of all cities where a project is located and also an employee resides −"
},
{
"code": null,
"e": 48148,
"s": 48124,
"text": "CityEmp←πCity(EMPLOYEE)"
},
{
"code": null,
"e": 48175,
"s": 48148,
"text": "CityProject←πCity(PROJECT)"
},
{
"code": null,
"e": 48202,
"s": 48175,
"text": "Result←CityEmp∩CityProject"
},
{
"code": null,
"e": 48335,
"s": 48202,
"text": "If P is a result of an operation and Q is a result of another operation, P - Q is the set of all tuples that are in P and not in Q."
},
{
"code": null,
"e": 48448,
"s": 48335,
"text": "For example, to list all the departments which do not have an ongoing project (projects with status = ongoing) −"
},
{
"code": null,
"e": 48478,
"s": 48448,
"text": "AllDept←πDepartment(EMPLOYEE)"
},
{
"code": null,
"e": 48530,
"s": 48478,
"text": "ProjectDept←πDepartment(σStatus=\"ongoing\"(PROJECT))"
},
{
"code": null,
"e": 48557,
"s": 48530,
"text": "Result←AllDept−ProjectDept"
},
{
"code": null,
"e": 48662,
"s": 48557,
"text": "Join operation combines related tuples of two different tables (results of queries) into a single table."
},
{
"code": null,
"e": 48749,
"s": 48662,
"text": "For example, consider two schemas, Customer and Branch in a Bank database as follows −"
},
{
"code": null,
"e": 48758,
"s": 48749,
"text": "CUSTOMER"
},
{
"code": null,
"e": 48765,
"s": 48758,
"text": "BRANCH"
},
{
"code": null,
"e": 48822,
"s": 48765,
"text": "To list the employee details along with branch details −"
},
{
"code": null,
"e": 48878,
"s": 48822,
"text": "Result←CUSTOMER⋈Customer.BranchID=Branch.BranchIDBRANCH"
},
{
"code": null,
"e": 49201,
"s": 48878,
"text": "SQL queries are translated into equivalent relational algebra expressions before optimization. A query is at first decomposed into smaller query blocks. These blocks are translated to equivalent relational algebra expressions. Optimization includes optimization of each block and then optimization of the query as a whole."
},
{
"code": null,
"e": 49241,
"s": 49201,
"text": "Let us consider the following schemas −"
},
{
"code": null,
"e": 49250,
"s": 49241,
"text": "EMPLOYEE"
},
{
"code": null,
"e": 49258,
"s": 49250,
"text": "PROJECT"
},
{
"code": null,
"e": 49264,
"s": 49258,
"text": "WORKS"
},
{
"code": null,
"e": 49377,
"s": 49264,
"text": "To display the details of all employees who earn a salary LESS than the average salary, we write the SQL query −"
},
{
"code": null,
"e": 49459,
"s": 49377,
"text": "SELECT * FROM EMPLOYEE \nWHERE SALARY < ( SELECT AVERAGE(SALARY) FROM EMPLOYEE ) ;"
},
{
"code": null,
"e": 49546,
"s": 49459,
"text": "This query contains one nested sub-query. So, this can be broken down into two blocks."
},
{
"code": null,
"e": 49567,
"s": 49546,
"text": "The inner block is −"
},
{
"code": null,
"e": 49605,
"s": 49567,
"text": "SELECT AVERAGE(SALARY)FROM EMPLOYEE ;"
},
{
"code": null,
"e": 49666,
"s": 49605,
"text": "If the result of this query is AvgSal, then outer block is −"
},
{
"code": null,
"e": 49712,
"s": 49666,
"text": "SELECT * FROM EMPLOYEE WHERE SALARY < AvgSal;"
},
{
"code": null,
"e": 49760,
"s": 49712,
"text": "Relational algebra expression for inner block −"
},
{
"code": null,
"e": 49792,
"s": 49760,
"text": "AvgSal←IAVERAGE(Salary)EMPLOYEE"
},
{
"code": null,
"e": 49840,
"s": 49792,
"text": "Relational algebra expression for outer block −"
},
{
"code": null,
"e": 49864,
"s": 49840,
"text": "σSalary<AvgSal>EMPLOYEE"
},
{
"code": null,
"e": 49968,
"s": 49864,
"text": "To display the project ID and status of all projects of employee 'Arun Kumar', we write the SQL query −"
},
{
"code": null,
"e": 50119,
"s": 49968,
"text": "SELECT PID, STATUS FROM PROJECT \nWHERE PID = ( SELECT FROM WORKS WHERE EMPID = ( SELECT EMPID FROM EMPLOYEE \n WHERE NAME = 'ARUN KUMAR'));"
},
{
"code": null,
"e": 50220,
"s": 50119,
"text": "This query contains two nested sub-queries. Thus, can be broken down into three blocks, as follows −"
},
{
"code": null,
"e": 50376,
"s": 50220,
"text": "SELECT EMPID FROM EMPLOYEE WHERE NAME = 'ARUN KUMAR'; \nSELECT PID FROM WORKS WHERE EMPID = ArunEmpID; \nSELECT PID, STATUS FROM PROJECT WHERE PID = ArunPID;"
},
{
"code": null,
"e": 50438,
"s": 50376,
"text": "(Here ArunEmpID and ArunPID are the results of inner queries)"
},
{
"code": null,
"e": 50496,
"s": 50438,
"text": "Relational algebra expressions for the three blocks are −"
},
{
"code": null,
"e": 50542,
"s": 50496,
"text": "ArunEmpID←πEmpID(σName=\"ArunKumar\"(EMPLOYEE))"
},
{
"code": null,
"e": 50582,
"s": 50542,
"text": "ArunPID←πPID(σEmpID=\"ArunEmpID\"(WORKS))"
},
{
"code": null,
"e": 50626,
"s": 50582,
"text": "Result←πPID,Status(σPID=\"ArunPID\"(PROJECT))"
},
{
"code": null,
"e": 50757,
"s": 50626,
"text": "The computation of relational algebra operators can be done in many different ways, and each alternative is called an access path."
},
{
"code": null,
"e": 50819,
"s": 50757,
"text": "The computation alternative depends upon three main factors −"
},
{
"code": null,
"e": 50833,
"s": 50819,
"text": "Operator type"
},
{
"code": null,
"e": 50850,
"s": 50833,
"text": "Available memory"
},
{
"code": null,
"e": 50866,
"s": 50850,
"text": "Disk structures"
},
{
"code": null,
"e": 50946,
"s": 50866,
"text": "The time to perform execution of a relational algebra operation is the sum of −"
},
{
"code": null,
"e": 50974,
"s": 50946,
"text": "Time to process the tuples."
},
{
"code": null,
"e": 51033,
"s": 50974,
"text": "Time to fetch the tuples of the table from disk to memory."
},
{
"code": null,
"e": 51275,
"s": 51033,
"text": "Since the time to process a tuple is very much smaller than the time to fetch the tuple from the storage, particularly in a distributed system, disk access is very often considered as the metric for calculating cost of relational expression."
},
{
"code": null,
"e": 51429,
"s": 51275,
"text": "Computation of selection operation depends upon the complexity of the selection condition and the availability of indexes on the attributes of the table."
},
{
"code": null,
"e": 51501,
"s": 51429,
"text": "Following are the computation alternatives depending upon the indexes −"
},
{
"code": null,
"e": 51925,
"s": 51501,
"text": "No Index − If the table is unsorted and has no indexes, then the selection process involves scanning all the disk blocks of the table. Each block is brought into the memory and each tuple in the block is examined to see whether it satisfies the selection condition. If the condition is satisfied, it is displayed as output. This is the costliest approach since each tuple is brought into memory and each tuple is processed."
},
{
"code": null,
"e": 52349,
"s": 51925,
"text": "No Index − If the table is unsorted and has no indexes, then the selection process involves scanning all the disk blocks of the table. Each block is brought into the memory and each tuple in the block is examined to see whether it satisfies the selection condition. If the condition is satisfied, it is displayed as output. This is the costliest approach since each tuple is brought into memory and each tuple is processed."
},
{
"code": null,
"e": 52727,
"s": 52349,
"text": "B+ Tree Index − Most database systems are built upon the B+ Tree index. If the selection condition is based upon the field, which is the key of this B+ Tree index, then this index is used for retrieving results. However, processing selection statements with complex conditions may involve a larger number of disk block accesses and in some cases complete scanning of the table."
},
{
"code": null,
"e": 53105,
"s": 52727,
"text": "B+ Tree Index − Most database systems are built upon the B+ Tree index. If the selection condition is based upon the field, which is the key of this B+ Tree index, then this index is used for retrieving results. However, processing selection statements with complex conditions may involve a larger number of disk block accesses and in some cases complete scanning of the table."
},
{
"code": null,
"e": 53631,
"s": 53105,
"text": "Hash Index − If hash indexes are used and its key field is used in the selection condition, then retrieving tuples using the hash index becomes a simple process. A hash index uses a hash function to find the address of a bucket where the key value corresponding to the hash value is stored. In order to find a key value in the index, the hash function is executed and the bucket address is found. The key values in the bucket are searched. If a match is found, the actual tuple is fetched from the disk block into the memory."
},
{
"code": null,
"e": 54157,
"s": 53631,
"text": "Hash Index − If hash indexes are used and its key field is used in the selection condition, then retrieving tuples using the hash index becomes a simple process. A hash index uses a hash function to find the address of a bucket where the key value corresponding to the hash value is stored. In order to find a key value in the index, the hash function is executed and the bucket address is found. The key values in the bucket are searched. If a match is found, the actual tuple is fetched from the disk block into the memory."
},
{
"code": null,
"e": 54495,
"s": 54157,
"text": "When we want to join two tables, say P and Q, each tuple in P has to be compared with each tuple in Q to test if the join condition is satisfied. If the condition is satisfied, the corresponding tuples are concatenated, eliminating duplicate fields and appended to the result relation. Consequently, this is the most expensive operation."
},
{
"code": null,
"e": 54543,
"s": 54495,
"text": "The common approaches for computing joins are −"
},
{
"code": null,
"e": 54714,
"s": 54543,
"text": "This is the conventional join approach. It can be illustrated through the following pseudocode (Tables P and Q, with tuples tuple_p and tuple_q and joining attribute a) −"
},
{
"code": null,
"e": 54883,
"s": 54714,
"text": "For each tuple_p in P \nFor each tuple_q in Q\nIf tuple_p.a = tuple_q.a Then \n Concatenate tuple_p and tuple_q and append to Result \nEnd If \nNext tuple_q \nNext tuple-p "
},
{
"code": null,
"e": 55315,
"s": 54883,
"text": "In this approach, the two tables are individually sorted based upon the joining attribute and then the sorted tables are merged. External sorting techniques are adopted since the number of records is very high and cannot be accommodated in the memory. Once the individual tables are sorted, one page each of the sorted tables are brought to the memory, merged based upon the joining attribute and the joined tuples are written out."
},
{
"code": null,
"e": 55735,
"s": 55315,
"text": "This approach comprises of two phases: partitioning phase and probing phase. In partitioning phase, the tables P and Q are broken into two sets of disjoint partitions. A common hash function is decided upon. This hash function is used to assign tuples to partitions. In the probing phase, tuples in a partition of P are compared with the tuples of corresponding partition of Q. If they match, then they are written out."
},
{
"code": null,
"e": 56032,
"s": 55735,
"text": "Once the alternative access paths for computation of a relational algebra expression are derived, the optimal access path is determined. In this chapter, we will look into query optimization in centralized system while in the next chapter we will study query optimization in a distributed system."
},
{
"code": null,
"e": 56107,
"s": 56032,
"text": "In a centralized system, query processing is done with the following aim −"
},
{
"code": null,
"e": 56199,
"s": 56107,
"text": "Minimization of response time of query (time taken to produce the results to user’s query)."
},
{
"code": null,
"e": 56291,
"s": 56199,
"text": "Minimization of response time of query (time taken to produce the results to user’s query)."
},
{
"code": null,
"e": 56389,
"s": 56291,
"text": "Maximize system throughput (the number of requests that are processed in a given amount of time)."
},
{
"code": null,
"e": 56487,
"s": 56389,
"text": "Maximize system throughput (the number of requests that are processed in a given amount of time)."
},
{
"code": null,
"e": 56552,
"s": 56487,
"text": "Reduce the amount of memory and storage required for processing."
},
{
"code": null,
"e": 56617,
"s": 56552,
"text": "Reduce the amount of memory and storage required for processing."
},
{
"code": null,
"e": 56639,
"s": 56617,
"text": "Increase parallelism."
},
{
"code": null,
"e": 56661,
"s": 56639,
"text": "Increase parallelism."
},
{
"code": null,
"e": 56935,
"s": 56661,
"text": "Initially, the SQL query is scanned. Then it is parsed to look for syntactical errors and correctness of data types. If the query passes this step, the query is decomposed into smaller query blocks. Each block is then translated to equivalent relational algebra expression."
},
{
"code": null,
"e": 57055,
"s": 56935,
"text": "Query optimization involves three steps, namely query tree generation, plan generation, and query plan code generation."
},
{
"code": null,
"e": 57086,
"s": 57055,
"text": "Step 1 − Query Tree Generation"
},
{
"code": null,
"e": 57340,
"s": 57086,
"text": "A query tree is a tree data structure representing a relational algebra expression. The tables of the query are represented as leaf nodes. The relational algebra operations are represented as the internal nodes. The root represents the query as a whole."
},
{
"code": null,
"e": 57589,
"s": 57340,
"text": "During execution, an internal node is executed whenever its operand tables are available. The node is then replaced by the result table. This process continues for all internal nodes until the root node is executed and replaced by the result table."
},
{
"code": null,
"e": 57642,
"s": 57589,
"text": "For example, let us consider the following schemas −"
},
{
"code": null,
"e": 57651,
"s": 57642,
"text": "EMPLOYEE"
},
{
"code": null,
"e": 57662,
"s": 57651,
"text": "DEPARTMENT"
},
{
"code": null,
"e": 57706,
"s": 57662,
"text": "Let us consider the query as the following."
},
{
"code": null,
"e": 57743,
"s": 57706,
"text": "πEmpID(σEName=\"ArunKumar\"(EMPLOYEE))"
},
{
"code": null,
"e": 57782,
"s": 57743,
"text": "The corresponding query tree will be −"
},
{
"code": null,
"e": 57830,
"s": 57782,
"text": "Let us consider another query involving a join."
},
{
"code": null,
"e": 57897,
"s": 57830,
"text": "πEName,Salary(σDName=\"Marketing\"(DEPARTMENT))⋈DNo=DeptNo(EMPLOYEE)"
},
{
"code": null,
"e": 57946,
"s": 57897,
"text": "Following is the query tree for the above query."
},
{
"code": null,
"e": 57977,
"s": 57946,
"text": "Step 2 − Query Plan Generation"
},
{
"code": null,
"e": 58346,
"s": 57977,
"text": "After the query tree is generated, a query plan is made. A query plan is an extended query tree that includes access paths for all operations in the query tree. Access paths specify how the relational operations in the tree should be performed. For example, a selection operation can have an access path that gives details about the use of B+ tree index for selection."
},
{
"code": null,
"e": 58541,
"s": 58346,
"text": "Besides, a query plan also states how the intermediate tables should be passed from one operator to the next, how temporary tables should be used and how operations should be pipelined/combined."
},
{
"code": null,
"e": 58565,
"s": 58541,
"text": "Step 3− Code Generation"
},
{
"code": null,
"e": 58821,
"s": 58565,
"text": "Code generation is the final step in query optimization. It is the executable form of the query, whose form depends upon the type of the underlying operating system. Once the query code is generated, the Execution Manager runs it and produces the results."
},
{
"code": null,
"e": 58933,
"s": 58821,
"text": "Among the approaches for query optimization, exhaustive search and heuristics-based algorithms are mostly used."
},
{
"code": null,
"e": 59230,
"s": 58933,
"text": "In these techniques, for a query, all possible query plans are initially generated and then the best plan is selected. Though these techniques provide the best solution, it has an exponential time and space complexity owing to the large solution space. For example, dynamic programming technique."
},
{
"code": null,
"e": 59543,
"s": 59230,
"text": "Heuristic based optimization uses rule-based optimization approaches for query optimization. These algorithms have polynomial time and space complexity, which is lower than the exponential complexity of exhaustive search-based algorithms. However, these algorithms do not necessarily produce the best query plan."
},
{
"code": null,
"e": 59584,
"s": 59543,
"text": "Some of the common heuristic rules are −"
},
{
"code": null,
"e": 59778,
"s": 59584,
"text": "Perform select and project operations before join operations. This is done by moving the select and project operations down the query tree. This reduces the number of tuples available for join."
},
{
"code": null,
"e": 59972,
"s": 59778,
"text": "Perform select and project operations before join operations. This is done by moving the select and project operations down the query tree. This reduces the number of tuples available for join."
},
{
"code": null,
"e": 60065,
"s": 59972,
"text": "Perform the most restrictive select/project operations at first before the other operations."
},
{
"code": null,
"e": 60158,
"s": 60065,
"text": "Perform the most restrictive select/project operations at first before the other operations."
},
{
"code": null,
"e": 60247,
"s": 60158,
"text": "Avoid cross-product operation since they result in very large-sized intermediate tables."
},
{
"code": null,
"e": 60336,
"s": 60247,
"text": "Avoid cross-product operation since they result in very large-sized intermediate tables."
},
{
"code": null,
"e": 60410,
"s": 60336,
"text": "This chapter discusses query optimization in distributed database system."
},
{
"code": null,
"e": 60697,
"s": 60410,
"text": "In a distributed database system, processing a query comprises of optimization at both the global and the local level. The query enters the database system at the client or controlling site. Here, the user is validated, the query is checked, translated, and optimized at a global level."
},
{
"code": null,
"e": 60738,
"s": 60697,
"text": "The architecture can be represented as −"
},
{
"code": null,
"e": 60819,
"s": 60738,
"text": "The process of mapping global queries to local ones can be realized as follows −"
},
{
"code": null,
"e": 61118,
"s": 60819,
"text": "The tables required in a global query have fragments distributed across multiple sites. The local databases have information only about local data. The controlling site uses the global data dictionary to gather information about the distribution and reconstructs the global view from the fragments."
},
{
"code": null,
"e": 61417,
"s": 61118,
"text": "The tables required in a global query have fragments distributed across multiple sites. The local databases have information only about local data. The controlling site uses the global data dictionary to gather information about the distribution and reconstructs the global view from the fragments."
},
{
"code": null,
"e": 61652,
"s": 61417,
"text": "If there is no replication, the global optimizer runs local queries at the sites where the fragments are stored. If there is replication, the global optimizer selects the site based upon communication cost, workload, and server speed."
},
{
"code": null,
"e": 61887,
"s": 61652,
"text": "If there is no replication, the global optimizer runs local queries at the sites where the fragments are stored. If there is replication, the global optimizer selects the site based upon communication cost, workload, and server speed."
},
{
"code": null,
"e": 62170,
"s": 61887,
"text": "The global optimizer generates a distributed execution plan so that least amount of data transfer occurs across the sites. The plan states the location of the fragments, order in which query steps needs to be executed and the processes involved in transferring intermediate results."
},
{
"code": null,
"e": 62453,
"s": 62170,
"text": "The global optimizer generates a distributed execution plan so that least amount of data transfer occurs across the sites. The plan states the location of the fragments, order in which query steps needs to be executed and the processes involved in transferring intermediate results."
},
{
"code": null,
"e": 62668,
"s": 62453,
"text": "The local queries are optimized by the local database servers. Finally, the local query results are merged together through union operation in case of horizontal fragments and join operation for vertical fragments."
},
{
"code": null,
"e": 62883,
"s": 62668,
"text": "The local queries are optimized by the local database servers. Finally, the local query results are merged together through union operation in case of horizontal fragments and join operation for vertical fragments."
},
{
"code": null,
"e": 63043,
"s": 62883,
"text": "For example, let us consider that the following Project schema is horizontally fragmented according to City, the cities being New Delhi, Kolkata and Hyderabad."
},
{
"code": null,
"e": 63051,
"s": 63043,
"text": "PROJECT"
},
{
"code": null,
"e": 63139,
"s": 63051,
"text": "Suppose there is a query to retrieve details of all projects whose status is “Ongoing”."
},
{
"code": null,
"e": 63171,
"s": 63139,
"text": "The global query will be &inus;"
},
{
"code": null,
"e": 63198,
"s": 63171,
"text": "σstatus=\"ongoing\"(PROJECT)"
},
{
"code": null,
"e": 63236,
"s": 63198,
"text": "Query in New Delhi’s server will be −"
},
{
"code": null,
"e": 63268,
"s": 63236,
"text": "σstatus=\"ongoing\"(NewD−PROJECT)"
},
{
"code": null,
"e": 63304,
"s": 63268,
"text": "Query in Kolkata’s server will be −"
},
{
"code": null,
"e": 63335,
"s": 63304,
"text": "σstatus=\"ongoing\"(Kol−PROJECT)"
},
{
"code": null,
"e": 63373,
"s": 63335,
"text": "Query in Hyderabad’s server will be −"
},
{
"code": null,
"e": 63404,
"s": 63373,
"text": "σstatus=\"ongoing\"(Hyd−PROJECT)"
},
{
"code": null,
"e": 63503,
"s": 63404,
"text": "In order to get the overall result, we need to union the results of the three queries as follows −"
},
{
"code": null,
"e": 63597,
"s": 63503,
"text": "σstatus=\"ongoing\"(NewD−PROJECT)∪σstatus=\"ongoing\"(kol−PROJECT)∪σstatus=\"ongoing\"(Hyd−PROJECT)"
},
{
"code": null,
"e": 63904,
"s": 63597,
"text": "Distributed query optimization requires evaluation of a large number of query trees each of which produce the required results of a query. This is primarily due to the presence of large amount of replicated and fragmented data. Hence, the target is to find an optimal solution instead of the best solution."
},
{
"code": null,
"e": 63961,
"s": 63904,
"text": "The main issues for distributed query optimization are −"
},
{
"code": null,
"e": 64021,
"s": 63961,
"text": "Optimal utilization of resources in the distributed system."
},
{
"code": null,
"e": 64036,
"s": 64021,
"text": "Query trading."
},
{
"code": null,
"e": 64078,
"s": 64036,
"text": "Reduction of solution space of the query."
},
{
"code": null,
"e": 64266,
"s": 64078,
"text": "A distributed system has a number of database servers in the various sites to perform the operations pertaining to a query. Following are the approaches for optimal resource utilization −"
},
{
"code": null,
"e": 64575,
"s": 64266,
"text": "Operation Shipping − In operation shipping, the operation is run at the site where the data is stored and not at the client site. The results are then transferred to the client site. This is appropriate for operations where the operands are available at the same site. Example: Select and Project operations."
},
{
"code": null,
"e": 64921,
"s": 64575,
"text": "Data Shipping − In data shipping, the data fragments are transferred to the database server, where the operations are executed. This is used in operations where the operands are distributed at different sites. This is also appropriate in systems where the communication costs are low, and local processors are much slower than the client server."
},
{
"code": null,
"e": 65132,
"s": 64921,
"text": "Hybrid Shipping − This is a combination of data and operation shipping. Here, data fragments are transferred to the high-speed processors, where the operation runs. The results are then sent to the client site."
},
{
"code": null,
"e": 65497,
"s": 65132,
"text": "In query trading algorithm for distributed database systems, the controlling/client site for a distributed query is called the buyer and the sites where the local queries execute are called sellers. The buyer formulates a number of alternatives for choosing sellers and for reconstructing the global results. The target of the buyer is to achieve the optimal cost."
},
{
"code": null,
"e": 65802,
"s": 65497,
"text": "The algorithm starts with the buyer assigning sub-queries to the seller sites. The optimal plan is created from local optimized query plans proposed by the sellers combined with the communication cost for reconstructing the final result. Once the global optimal plan is formulated, the query is executed."
},
{
"code": null,
"e": 66020,
"s": 65802,
"text": "Optimal solution generally involves reduction of solution space so that the cost of query and data transfer is reduced. This can be achieved through a set of heuristic rules, just as heuristics in centralized systems."
},
{
"code": null,
"e": 66054,
"s": 66020,
"text": "Following are some of the rules −"
},
{
"code": null,
"e": 66175,
"s": 66054,
"text": "Perform selection and projection operations as early as possible. This reduces the data flow over communication network."
},
{
"code": null,
"e": 66296,
"s": 66175,
"text": "Perform selection and projection operations as early as possible. This reduces the data flow over communication network."
},
{
"code": null,
"e": 66421,
"s": 66296,
"text": "Simplify operations on horizontal fragments by eliminating selection conditions which are not relevant to a particular site."
},
{
"code": null,
"e": 66546,
"s": 66421,
"text": "Simplify operations on horizontal fragments by eliminating selection conditions which are not relevant to a particular site."
},
{
"code": null,
"e": 66734,
"s": 66546,
"text": "In case of join and union operations comprising of fragments located in multiple sites, transfer fragmented data to the site where most of the data is present and perform operation there."
},
{
"code": null,
"e": 66922,
"s": 66734,
"text": "In case of join and union operations comprising of fragments located in multiple sites, transfer fragmented data to the site where most of the data is present and perform operation there."
},
{
"code": null,
"e": 67070,
"s": 66922,
"text": "Use semi-join operation to qualify tuples that are to be joined. This reduces the amount of data transfer which in turn reduces communication cost."
},
{
"code": null,
"e": 67218,
"s": 67070,
"text": "Use semi-join operation to qualify tuples that are to be joined. This reduces the amount of data transfer which in turn reduces communication cost."
},
{
"code": null,
"e": 67285,
"s": 67218,
"text": "Merge the common leaves and sub-trees in a distributed query tree."
},
{
"code": null,
"e": 67352,
"s": 67285,
"text": "Merge the common leaves and sub-trees in a distributed query tree."
},
{
"code": null,
"e": 67625,
"s": 67352,
"text": "This chapter discusses the various aspects of transaction processing. We’ll also study the low level tasks included in a transaction, the transaction states and properties of a transaction. In the last portion, we will look over schedules and serializability of schedules."
},
{
"code": null,
"e": 68080,
"s": 67625,
"text": "A transaction is a program including a collection of database operations, executed as a logical unit of data processing. The operations performed in a transaction include one or more of database operations like insert, delete, update or retrieve data. It is an atomic process that is either performed into completion entirely or is not performed at all. A transaction involving only data retrieval without any data update is called read-only transaction."
},
{
"code": null,
"e": 68240,
"s": 68080,
"text": "Each high level operation can be divided into a number of low level tasks or operations. For example, a data update operation can be divided into three tasks −"
},
{
"code": null,
"e": 68299,
"s": 68240,
"text": "read_item() − reads data item from storage to main memory."
},
{
"code": null,
"e": 68358,
"s": 68299,
"text": "read_item() − reads data item from storage to main memory."
},
{
"code": null,
"e": 68415,
"s": 68358,
"text": "modify_item() − change value of item in the main memory."
},
{
"code": null,
"e": 68472,
"s": 68415,
"text": "modify_item() − change value of item in the main memory."
},
{
"code": null,
"e": 68541,
"s": 68472,
"text": "write_item() − write the modified value from main memory to storage."
},
{
"code": null,
"e": 68610,
"s": 68541,
"text": "write_item() − write the modified value from main memory to storage."
},
{
"code": null,
"e": 68768,
"s": 68610,
"text": "Database access is restricted to read_item() and write_item() operations. Likewise, for all transactions, read and write forms the basic database operations."
},
{
"code": null,
"e": 68826,
"s": 68768,
"text": "The low level operations performed in a transaction are −"
},
{
"code": null,
"e": 68902,
"s": 68826,
"text": "begin_transaction − A marker that specifies start of transaction execution."
},
{
"code": null,
"e": 68978,
"s": 68902,
"text": "begin_transaction − A marker that specifies start of transaction execution."
},
{
"code": null,
"e": 69102,
"s": 68978,
"text": "read_item or write_item − Database operations that may be interleaved with main memory operations as a part of transaction."
},
{
"code": null,
"e": 69226,
"s": 69102,
"text": "read_item or write_item − Database operations that may be interleaved with main memory operations as a part of transaction."
},
{
"code": null,
"e": 69288,
"s": 69226,
"text": "end_transaction − A marker that specifies end of transaction."
},
{
"code": null,
"e": 69350,
"s": 69288,
"text": "end_transaction − A marker that specifies end of transaction."
},
{
"code": null,
"e": 69472,
"s": 69350,
"text": "commit − A signal to specify that the transaction has been successfully completed in its entirety and will not be undone."
},
{
"code": null,
"e": 69594,
"s": 69472,
"text": "commit − A signal to specify that the transaction has been successfully completed in its entirety and will not be undone."
},
{
"code": null,
"e": 69772,
"s": 69594,
"text": "rollback − A signal to specify that the transaction has been unsuccessful and so all temporary changes in the database are undone. A committed transaction cannot be rolled back."
},
{
"code": null,
"e": 69950,
"s": 69772,
"text": "rollback − A signal to specify that the transaction has been unsuccessful and so all temporary changes in the database are undone. A committed transaction cannot be rolled back."
},
{
"code": null,
"e": 70064,
"s": 69950,
"text": "A transaction may go through a subset of five states, active, partially committed, committed, failed and aborted."
},
{
"code": null,
"e": 70234,
"s": 70064,
"text": "Active − The initial state where the transaction enters is the active state. The transaction remains in this state while it is executing read, write or other operations."
},
{
"code": null,
"e": 70404,
"s": 70234,
"text": "Active − The initial state where the transaction enters is the active state. The transaction remains in this state while it is executing read, write or other operations."
},
{
"code": null,
"e": 70523,
"s": 70404,
"text": "Partially Committed − The transaction enters this state after the last statement of the transaction has been executed."
},
{
"code": null,
"e": 70642,
"s": 70523,
"text": "Partially Committed − The transaction enters this state after the last statement of the transaction has been executed."
},
{
"code": null,
"e": 70780,
"s": 70642,
"text": "Committed − The transaction enters this state after successful completion of the transaction and system checks have issued commit signal."
},
{
"code": null,
"e": 70918,
"s": 70780,
"text": "Committed − The transaction enters this state after successful completion of the transaction and system checks have issued commit signal."
},
{
"code": null,
"e": 71100,
"s": 70918,
"text": "Failed − The transaction goes from partially committed state or active state to failed state when it is discovered that normal execution can no longer proceed or system checks fail."
},
{
"code": null,
"e": 71282,
"s": 71100,
"text": "Failed − The transaction goes from partially committed state or active state to failed state when it is discovered that normal execution can no longer proceed or system checks fail."
},
{
"code": null,
"e": 71454,
"s": 71282,
"text": "Aborted − This is the state after the transaction has been rolled back after failure and the database has been restored to its state that was before the transaction began."
},
{
"code": null,
"e": 71626,
"s": 71454,
"text": "Aborted − This is the state after the transaction has been rolled back after failure and the database has been restored to its state that was before the transaction began."
},
{
"code": null,
"e": 71774,
"s": 71626,
"text": "The following state transition diagram depicts the states in the transaction and the low level transaction operations that causes change in states."
},
{
"code": null,
"e": 71881,
"s": 71774,
"text": "Any transaction must maintain the ACID properties, viz. Atomicity, Consistency, Isolation, and Durability."
},
{
"code": null,
"e": 72071,
"s": 71881,
"text": "Atomicity − This property states that a transaction is an atomic unit of processing, that is, either it is performed in its entirety or not performed at all. No partial update should exist."
},
{
"code": null,
"e": 72261,
"s": 72071,
"text": "Atomicity − This property states that a transaction is an atomic unit of processing, that is, either it is performed in its entirety or not performed at all. No partial update should exist."
},
{
"code": null,
"e": 72431,
"s": 72261,
"text": "Consistency − A transaction should take the database from one consistent state to another consistent state. It should not adversely affect any data item in the database."
},
{
"code": null,
"e": 72601,
"s": 72431,
"text": "Consistency − A transaction should take the database from one consistent state to another consistent state. It should not adversely affect any data item in the database."
},
{
"code": null,
"e": 72795,
"s": 72601,
"text": "Isolation − A transaction should be executed as if it is the only one in the system. There should not be any interference from the other concurrent transactions that are simultaneously running."
},
{
"code": null,
"e": 72989,
"s": 72795,
"text": "Isolation − A transaction should be executed as if it is the only one in the system. There should not be any interference from the other concurrent transactions that are simultaneously running."
},
{
"code": null,
"e": 73135,
"s": 72989,
"text": "Durability − If a committed transaction brings about a change, that change should be durable in the database and not lost in case of any failure."
},
{
"code": null,
"e": 73281,
"s": 73135,
"text": "Durability − If a committed transaction brings about a change, that change should be durable in the database and not lost in case of any failure."
},
{
"code": null,
"e": 73563,
"s": 73281,
"text": "In a system with a number of simultaneous transactions, a schedule is the total order of execution of operations. Given a schedule S comprising of n transactions, say T1, T2, T3...........Tn; for any transaction Ti, the operations in Ti must execute as laid down in the schedule S."
},
{
"code": null,
"e": 73598,
"s": 73563,
"text": "There are two types of schedules −"
},
{
"code": null,
"e": 73781,
"s": 73598,
"text": "Serial Schedules − In a serial schedule, at any point of time, only one transaction is active, i.e. there is no overlapping of transactions. This is depicted in the following graph −"
},
{
"code": null,
"e": 73964,
"s": 73781,
"text": "Serial Schedules − In a serial schedule, at any point of time, only one transaction is active, i.e. there is no overlapping of transactions. This is depicted in the following graph −"
},
{
"code": null,
"e": 74167,
"s": 73964,
"text": "Parallel Schedules − In parallel schedules, more than one transactions are active simultaneously, i.e. the transactions contain operations that overlap at time. This is depicted in the following graph −"
},
{
"code": null,
"e": 74370,
"s": 74167,
"text": "Parallel Schedules − In parallel schedules, more than one transactions are active simultaneously, i.e. the transactions contain operations that overlap at time. This is depicted in the following graph −"
},
{
"code": null,
"e": 74613,
"s": 74370,
"text": "In a schedule comprising of multiple transactions, a conflict occurs when two active transactions perform non-compatible operations. Two operations are said to be in conflict, when all of the following three conditions exists simultaneously −"
},
{
"code": null,
"e": 74669,
"s": 74613,
"text": "The two operations are parts of different transactions."
},
{
"code": null,
"e": 74725,
"s": 74669,
"text": "The two operations are parts of different transactions."
},
{
"code": null,
"e": 74772,
"s": 74725,
"text": "Both the operations access the same data item."
},
{
"code": null,
"e": 74819,
"s": 74772,
"text": "Both the operations access the same data item."
},
{
"code": null,
"e": 74918,
"s": 74819,
"text": "At least one of the operations is a write_item() operation, i.e. it tries to modify the data item."
},
{
"code": null,
"e": 75017,
"s": 74918,
"text": "At least one of the operations is a write_item() operation, i.e. it tries to modify the data item."
},
{
"code": null,
"e": 75298,
"s": 75017,
"text": "A serializable schedule of ‘n’ transactions is a parallel schedule which is equivalent to a serial schedule comprising of the same ‘n’ transactions. A serializable schedule contains the correctness of serial schedule while ascertaining better CPU utilization of parallel schedule."
},
{
"code": null,
"e": 75359,
"s": 75298,
"text": "Equivalence of two schedules can be of the following types −"
},
{
"code": null,
"e": 75456,
"s": 75359,
"text": "Result equivalence − Two schedules producing identical results are said to be result equivalent."
},
{
"code": null,
"e": 75553,
"s": 75456,
"text": "Result equivalence − Two schedules producing identical results are said to be result equivalent."
},
{
"code": null,
"e": 75666,
"s": 75553,
"text": "View equivalence − Two schedules that perform similar action in a similar manner are said to be view equivalent."
},
{
"code": null,
"e": 75779,
"s": 75666,
"text": "View equivalence − Two schedules that perform similar action in a similar manner are said to be view equivalent."
},
{
"code": null,
"e": 75955,
"s": 75779,
"text": "Conflict equivalence − Two schedules are said to be conflict equivalent if both contain the same set of transactions and has the same order of conflicting pairs of operations."
},
{
"code": null,
"e": 76131,
"s": 75955,
"text": "Conflict equivalence − Two schedules are said to be conflict equivalent if both contain the same set of transactions and has the same order of conflicting pairs of operations."
},
{
"code": null,
"e": 76324,
"s": 76131,
"text": "Concurrency controlling techniques ensure that multiple transactions are executed simultaneously while maintaining the ACID properties of the transactions and serializability in the schedules."
},
{
"code": null,
"e": 76403,
"s": 76324,
"text": "In this chapter, we will study the various approaches for concurrency control."
},
{
"code": null,
"e": 76749,
"s": 76403,
"text": "Locking-based concurrency control protocols use the concept of locking data items. A lock is a variable associated with a data item that determines whether read/write operations can be performed on that data item. Generally, a lock compatibility matrix is used which states whether a data item can be locked by two transactions at the same time."
},
{
"code": null,
"e": 76848,
"s": 76749,
"text": "Locking-based concurrency control systems can use either one-phase or two-phase locking protocols."
},
{
"code": null,
"e": 77063,
"s": 76848,
"text": "In this method, each transaction locks an item before use and releases the lock as soon as it has finished using it. This locking method provides for maximum concurrency but does not always enforce serializability."
},
{
"code": null,
"e": 77471,
"s": 77063,
"text": "In this method, all locking operations precede the first lock-release or unlock operation. The transaction comprise of two phases. In the first phase, a transaction only acquires all the locks it needs and do not release any lock. This is called the expanding or the growing phase. In the second phase, the transaction releases the locks and cannot request any new locks. This is called the shrinking phase."
},
{
"code": null,
"e": 77649,
"s": 77471,
"text": "Every transaction that follows two-phase locking protocol is guaranteed to be serializable. However, this approach provides low parallelism between two conflicting transactions."
},
{
"code": null,
"e": 77912,
"s": 77649,
"text": "Timestamp-based concurrency control algorithms use a transaction’s timestamp to coordinate concurrent access to a data item to ensure serializability. A timestamp is a unique identifier given by DBMS to a transaction that represents the transaction’s start time."
},
{
"code": null,
"e": 78139,
"s": 77912,
"text": "These algorithms ensure that transactions commit in the order dictated by their timestamps. An older transaction should commit before a younger transaction, since the older transaction enters the system before the younger one."
},
{
"code": null,
"e": 78326,
"s": 78139,
"text": "Timestamp-based concurrency control techniques generate serializable schedules such that the equivalent serial schedule is arranged in order of the age of the participating transactions."
},
{
"code": null,
"e": 78387,
"s": 78326,
"text": "Some of timestamp based concurrency control algorithms are −"
},
{
"code": null,
"e": 78423,
"s": 78387,
"text": "Basic timestamp ordering algorithm."
},
{
"code": null,
"e": 78466,
"s": 78423,
"text": "Conservative timestamp ordering algorithm."
},
{
"code": null,
"e": 78520,
"s": 78466,
"text": "Multiversion algorithm based upon timestamp ordering."
},
{
"code": null,
"e": 78593,
"s": 78520,
"text": "Timestamp based ordering follow three rules to enforce serializability −"
},
{
"code": null,
"e": 78837,
"s": 78593,
"text": "Access Rule − When two transactions try to access the same data item simultaneously, for conflicting operations, priority is given to the older transaction. This causes the younger transaction to wait for the older transaction to commit first."
},
{
"code": null,
"e": 79081,
"s": 78837,
"text": "Access Rule − When two transactions try to access the same data item simultaneously, for conflicting operations, priority is given to the older transaction. This causes the younger transaction to wait for the older transaction to commit first."
},
{
"code": null,
"e": 79339,
"s": 79081,
"text": "Late Transaction Rule − If a younger transaction has written a data item, then an older transaction is not allowed to read or write that data item. This rule prevents the older transaction from committing after the younger transaction has already committed."
},
{
"code": null,
"e": 79597,
"s": 79339,
"text": "Late Transaction Rule − If a younger transaction has written a data item, then an older transaction is not allowed to read or write that data item. This rule prevents the older transaction from committing after the younger transaction has already committed."
},
{
"code": null,
"e": 79731,
"s": 79597,
"text": "Younger Transaction Rule − A younger transaction can read or write a data item that has already been written by an older transaction."
},
{
"code": null,
"e": 79865,
"s": 79731,
"text": "Younger Transaction Rule − A younger transaction can read or write a data item that has already been written by an older transaction."
},
{
"code": null,
"e": 80245,
"s": 79865,
"text": "In systems with low conflict rates, the task of validating every transaction for serializability may lower performance. In these cases, the test for serializability is postponed to just before commit. Since the conflict rate is low, the probability of aborting transactions which are not serializable is also low. This approach is called optimistic concurrency control technique."
},
{
"code": null,
"e": 80335,
"s": 80245,
"text": "In this approach, a transaction’s life cycle is divided into the following three phases −"
},
{
"code": null,
"e": 80431,
"s": 80335,
"text": "Execution Phase − A transaction fetches data items to memory and performs operations upon them."
},
{
"code": null,
"e": 80527,
"s": 80431,
"text": "Execution Phase − A transaction fetches data items to memory and performs operations upon them."
},
{
"code": null,
"e": 80659,
"s": 80527,
"text": "Validation Phase − A transaction performs checks to ensure that committing its changes to the database passes serializability test."
},
{
"code": null,
"e": 80791,
"s": 80659,
"text": "Validation Phase − A transaction performs checks to ensure that committing its changes to the database passes serializability test."
},
{
"code": null,
"e": 80874,
"s": 80791,
"text": "Commit Phase − A transaction writes back modified data item in memory to the disk."
},
{
"code": null,
"e": 80957,
"s": 80874,
"text": "Commit Phase − A transaction writes back modified data item in memory to the disk."
},
{
"code": null,
"e": 81038,
"s": 80957,
"text": "This algorithm uses three rules to enforce serializability in validation phase −"
},
{
"code": null,
"e": 81250,
"s": 81038,
"text": "Rule 1 − Given two transactions Ti and Tj, if Ti is reading the data item which Tj is writing, then Ti’s execution phase cannot overlap with Tj’s commit phase. Tj can commit only after Ti has finished execution."
},
{
"code": null,
"e": 81469,
"s": 81250,
"text": "Rule 2 − Given two transactions Ti and Tj, if Ti is writing the data item that Tj is reading, then Ti’s commit phase cannot overlap with Tj’s execution phase. Tj can start executing only after Ti has already committed."
},
{
"code": null,
"e": 81691,
"s": 81469,
"text": "Rule 3 − Given two transactions Ti and Tj, if Ti is writing the data item which Tj is also writing, then Ti’s commit phase cannot overlap with Tj’s commit phase. Tj can start to commit only after Ti has already committed."
},
{
"code": null,
"e": 81795,
"s": 81691,
"text": "In this section, we will see how the above techniques are implemented in a distributed database system."
},
{
"code": null,
"e": 82222,
"s": 81795,
"text": "The basic principle of distributed two-phase locking is same as the basic two-phase locking protocol. However, in a distributed system there are sites designated as lock managers. A lock manager controls lock acquisition requests from transaction monitors. In order to enforce co-ordination between the lock managers in various sites, at least one site is given the authority to see all transactions and detect lock conflicts."
},
{
"code": null,
"e": 82353,
"s": 82222,
"text": "Depending upon the number of sites who can detect lock conflicts, distributed two-phase locking approaches can be of three types −"
},
{
"code": null,
"e": 82579,
"s": 82353,
"text": "Centralized two-phase locking − In this approach, one site is designated as the central lock manager. All the sites in the environment know the location of the central lock manager and obtain lock from it during transactions."
},
{
"code": null,
"e": 82805,
"s": 82579,
"text": "Centralized two-phase locking − In this approach, one site is designated as the central lock manager. All the sites in the environment know the location of the central lock manager and obtain lock from it during transactions."
},
{
"code": null,
"e": 83106,
"s": 82805,
"text": "Primary copy two-phase locking − In this approach, a number of sites are designated as lock control centers. Each of these sites has the responsibility of managing a defined set of locks. All the sites know which lock control center is responsible for managing lock of which data table/fragment item."
},
{
"code": null,
"e": 83407,
"s": 83106,
"text": "Primary copy two-phase locking − In this approach, a number of sites are designated as lock control centers. Each of these sites has the responsibility of managing a defined set of locks. All the sites know which lock control center is responsible for managing lock of which data table/fragment item."
},
{
"code": null,
"e": 83655,
"s": 83407,
"text": "Distributed two-phase locking − In this approach, there are a number of lock managers, where each lock manager controls locks of data items stored at its local site. The location of the lock manager is based upon data distribution and replication."
},
{
"code": null,
"e": 83903,
"s": 83655,
"text": "Distributed two-phase locking − In this approach, there are a number of lock managers, where each lock manager controls locks of data items stored at its local site. The location of the lock manager is based upon data distribution and replication."
},
{
"code": null,
"e": 84239,
"s": 83903,
"text": "In a centralized system, timestamp of any transaction is determined by the physical clock reading. But, in a distributed system, any site’s local physical/logical clock readings cannot be used as global timestamps, since they are not globally unique. So, a timestamp comprises of a combination of site ID and that site’s clock reading."
},
{
"code": null,
"e": 84661,
"s": 84239,
"text": "For implementing timestamp ordering algorithms, each site has a scheduler that maintains a separate queue for each transaction manager. During transaction, a transaction manager sends a lock request to the site’s scheduler. The scheduler puts the request to the corresponding queue in increasing timestamp order. Requests are processed from the front of the queues in the order of their timestamps, i.e. the oldest first."
},
{
"code": null,
"e": 85169,
"s": 84661,
"text": "Another method is to create conflict graphs. For this transaction classes are defined. A transaction class contains two set of data items called read set and write set. A transaction belongs to a particular class if the transaction’s read set is a subset of the class’ read set and the transaction’s write set is a subset of the class’ write set. In the read phase, each transaction issues its read requests for the data items in its read set. In the write phase, each transaction issues its write requests."
},
{
"code": null,
"e": 85644,
"s": 85169,
"text": "A conflict graph is created for the classes to which active transactions belong. This contains a set of vertical, horizontal, and diagonal edges. A vertical edge connects two nodes within a class and denotes conflicts within the class. A horizontal edge connects two nodes across two classes and denotes a write-write conflict among different classes. A diagonal edge connects two nodes across two classes and denotes a write-read or a read-write conflict among two classes."
},
{
"code": null,
"e": 85793,
"s": 85644,
"text": "The conflict graphs are analyzed to ascertain whether two transactions within the same class or across two different classes can be run in parallel."
},
{
"code": null,
"e": 85940,
"s": 85793,
"text": "Distributed optimistic concurrency control algorithm extends optimistic concurrency control algorithm. For this extension, two rules are applied −"
},
{
"code": null,
"e": 86304,
"s": 85940,
"text": "Rule 1 − According to this rule, a transaction must be validated locally at all sites when it executes. If a transaction is found to be invalid at any site, it is aborted. Local validation guarantees that the transaction maintains serializability at the sites where it has been executed. After a transaction passes local validation test, it is globally validated."
},
{
"code": null,
"e": 86848,
"s": 86304,
"text": "Rule 2 − According to this rule, after a transaction passes local validation test, it should be globally validated. Global validation ensures that if two conflicting transactions run together at more than one site, they should commit in the same relative order at all the sites they run together. This may require a transaction to wait for the other conflicting transaction, after validation before commit. This requirement makes the algorithm less optimistic since a transaction may not be able to commit as soon as it is validated at a site."
},
{
"code": null,
"e": 87019,
"s": 86848,
"text": "This chapter overviews deadlock handling mechanisms in database systems. We’ll study the deadlock handling mechanisms in both centralized and distributed database system."
},
{
"code": null,
"e": 87362,
"s": 87019,
"text": "Deadlock is a state of a database system having two or more transactions, when each transaction is waiting for a data item that is being locked by some other transaction. A deadlock can be indicated by a cycle in the wait-for-graph. This is a directed graph in which the vertices denote transactions and the edges denote waits for data items."
},
{
"code": null,
"e": 87648,
"s": 87362,
"text": "For example, in the following wait-for-graph, transaction T1 is waiting for data item X which is locked by T3. T3 is waiting for Y which is locked by T2 and T2 is waiting for Z which is locked by T1. Hence, a waiting cycle is formed, and none of the transactions can proceed executing."
},
{
"code": null,
"e": 87717,
"s": 87648,
"text": "There are three classical approaches for deadlock handling, namely −"
},
{
"code": null,
"e": 87738,
"s": 87717,
"text": "Deadlock prevention."
},
{
"code": null,
"e": 87758,
"s": 87738,
"text": "Deadlock avoidance."
},
{
"code": null,
"e": 87790,
"s": 87758,
"text": "Deadlock detection and removal."
},
{
"code": null,
"e": 87895,
"s": 87790,
"text": "All of the three approaches can be incorporated in both a centralized and a distributed database system."
},
{
"code": null,
"e": 88138,
"s": 87895,
"text": "The deadlock prevention approach does not allow any transaction to acquire locks that will lead to deadlocks. The convention is that when more than one transactions request for locking the same data item, only one of them is granted the lock."
},
{
"code": null,
"e": 88620,
"s": 88138,
"text": "One of the most popular deadlock prevention methods is pre-acquisition of all the locks. In this method, a transaction acquires all the locks before starting to execute and retains the locks for the entire duration of transaction. If another transaction needs any of the already acquired locks, it has to wait until all the locks it needs are available. Using this approach, the system is prevented from being deadlocked since none of the waiting transactions are holding any lock."
},
{
"code": null,
"e": 88789,
"s": 88620,
"text": "The deadlock avoidance approach handles deadlocks before they occur. It analyzes the transactions and the locks to determine whether or not waiting leads to a deadlock."
},
{
"code": null,
"e": 89380,
"s": 88789,
"text": "The method can be briefly stated as follows. Transactions start executing and request data items that they need to lock. The lock manager checks whether the lock is available. If it is available, the lock manager allocates the data item and the transaction acquires the lock. However, if the item is locked by some other transaction in incompatible mode, the lock manager runs an algorithm to test whether keeping the transaction in waiting state will cause a deadlock or not. Accordingly, the algorithm decides whether the transaction can wait or one of the transactions should be aborted."
},
{
"code": null,
"e": 89611,
"s": 89380,
"text": "There are two algorithms for this purpose, namely wait-die and wound-wait. Let us assume that there are two transactions, T1 and T2, where T1 tries to lock a data item which is already locked by T2. The algorithms are as follows −"
},
{
"code": null,
"e": 89741,
"s": 89611,
"text": "Wait-Die − If T1 is older than T2, T1 is allowed to wait. Otherwise, if T1 is younger than T2, T1 is aborted and later restarted."
},
{
"code": null,
"e": 89871,
"s": 89741,
"text": "Wait-Die − If T1 is older than T2, T1 is allowed to wait. Otherwise, if T1 is younger than T2, T1 is aborted and later restarted."
},
{
"code": null,
"e": 90003,
"s": 89871,
"text": "Wound-Wait − If T1 is older than T2, T2 is aborted and later restarted. Otherwise, if T1 is younger than T2, T1 is allowed to wait."
},
{
"code": null,
"e": 90135,
"s": 90003,
"text": "Wound-Wait − If T1 is older than T2, T2 is aborted and later restarted. Otherwise, if T1 is younger than T2, T1 is allowed to wait."
},
{
"code": null,
"e": 90551,
"s": 90135,
"text": "The deadlock detection and removal approach runs a deadlock detection algorithm periodically and removes deadlock in case there is one. It does not check for deadlock when a transaction places a request for a lock. When a transaction requests a lock, the lock manager checks whether it is available. If it is available, the transaction is allowed to lock the data item; otherwise the transaction is allowed to wait."
},
{
"code": null,
"e": 90956,
"s": 90551,
"text": "Since there are no precautions while granting lock requests, some of the transactions may be deadlocked. To detect deadlocks, the lock manager periodically checks if the wait-forgraph has cycles. If the system is deadlocked, the lock manager chooses a victim transaction from each cycle. The victim is aborted and rolled back; and then restarted later. Some of the methods used for victim selection are −"
},
{
"code": null,
"e": 90989,
"s": 90956,
"text": "Choose the youngest transaction."
},
{
"code": null,
"e": 91036,
"s": 90989,
"text": "Choose the transaction with fewest data items."
},
{
"code": null,
"e": 91103,
"s": 91036,
"text": "Choose the transaction that has performed least number of updates."
},
{
"code": null,
"e": 91157,
"s": 91103,
"text": "Choose the transaction having least restart overhead."
},
{
"code": null,
"e": 91219,
"s": 91157,
"text": "Choose the transaction which is common to two or more cycles."
},
{
"code": null,
"e": 91341,
"s": 91219,
"text": "This approach is primarily suited for systems having transactions low and where fast response to lock requests is needed."
},
{
"code": null,
"e": 91800,
"s": 91341,
"text": "Transaction processing in a distributed database system is also distributed, i.e. the same transaction may be processing at more than one site. The two main deadlock handling concerns in a distributed database system that are not present in a centralized system are transaction location and transaction control. Once these concerns are addressed, deadlocks are handled through any of deadlock prevention, deadlock avoidance or deadlock detection and removal."
},
{
"code": null,
"e": 92331,
"s": 91800,
"text": "Transactions in a distributed database system are processed in multiple sites and use data items in multiple sites. The amount of data processing is not uniformly distributed among these sites. The time period of processing also varies. Thus the same transaction may be active at some sites and inactive at others. When two conflicting transactions are located in a site, it may happen that one of them is in inactive state. This condition does not arise in a centralized system. This concern is called transaction location issue."
},
{
"code": null,
"e": 92811,
"s": 92331,
"text": "This concern may be addressed by Daisy Chain model. In this model, a transaction carries certain details when it moves from one site to another. Some of the details are the list of tables required, the list of sites required, the list of visited tables and sites, the list of tables and sites that are yet to be visited and the list of acquired locks with types. After a transaction terminates by either commit or abort, the information should be sent to all the concerned sites."
},
{
"code": null,
"e": 93090,
"s": 92811,
"text": "Transaction control is concerned with designating and controlling the sites required for processing a transaction in a distributed database system. There are many options regarding the choice of where to process the transaction and how to designate the center of control, like −"
},
{
"code": null,
"e": 93143,
"s": 93090,
"text": "One server may be selected as the center of control."
},
{
"code": null,
"e": 93204,
"s": 93143,
"text": "The center of control may travel from one server to another."
},
{
"code": null,
"e": 93276,
"s": 93204,
"text": "The responsibility of controlling may be shared by a number of servers."
},
{
"code": null,
"e": 93463,
"s": 93276,
"text": "Just like in centralized deadlock prevention, in distributed deadlock prevention approach, a transaction should acquire all the locks before starting to execute. This prevents deadlocks."
},
{
"code": null,
"e": 93865,
"s": 93463,
"text": "The site where the transaction enters is designated as the controlling site. The controlling site sends messages to the sites where the data items are located to lock the items. Then it waits for confirmation. When all the sites have confirmed that they have locked the data items, transaction starts. If any site or communication link fails, the transaction has to wait until they have been repaired."
},
{
"code": null,
"e": 93937,
"s": 93865,
"text": "Though the implementation is simple, this approach has some drawbacks −"
},
{
"code": null,
"e": 94059,
"s": 93937,
"text": "Pre-acquisition of locks requires a long time for communication delays. This increases the time required for transaction."
},
{
"code": null,
"e": 94181,
"s": 94059,
"text": "Pre-acquisition of locks requires a long time for communication delays. This increases the time required for transaction."
},
{
"code": null,
"e": 94390,
"s": 94181,
"text": "In case of site or link failure, a transaction has to wait for a long time so that the sites recover. Meanwhile, in the running sites, the items are locked. This may prevent other transactions from executing."
},
{
"code": null,
"e": 94599,
"s": 94390,
"text": "In case of site or link failure, a transaction has to wait for a long time so that the sites recover. Meanwhile, in the running sites, the items are locked. This may prevent other transactions from executing."
},
{
"code": null,
"e": 94776,
"s": 94599,
"text": "If the controlling site fails, it cannot communicate with the other sites. These sites continue to keep the locked data items in their locked state, thus resulting in blocking."
},
{
"code": null,
"e": 94953,
"s": 94776,
"text": "If the controlling site fails, it cannot communicate with the other sites. These sites continue to keep the locked data items in their locked state, thus resulting in blocking."
},
{
"code": null,
"e": 95247,
"s": 94953,
"text": "As in centralized system, distributed deadlock avoidance handles deadlock prior to occurrence. Additionally, in distributed systems, transaction location and transaction control issues needs to be addressed. Due to the distributed nature of the transaction, the following conflicts may occur −"
},
{
"code": null,
"e": 95299,
"s": 95247,
"text": "Conflict between two transactions in the same site."
},
{
"code": null,
"e": 95353,
"s": 95299,
"text": "Conflict between two transactions in different sites."
},
{
"code": null,
"e": 95498,
"s": 95353,
"text": "In case of conflict, one of the transactions may be aborted or allowed to wait as per distributed wait-die or distributed wound-wait algorithms."
},
{
"code": null,
"e": 95721,
"s": 95498,
"text": "Let us assume that there are two transactions, T1 and T2. T1 arrives at Site P and tries to lock a data item which is already locked by T2 at that site. Hence, there is a conflict at Site P. The algorithms are as follows −"
},
{
"code": null,
"e": 96149,
"s": 95721,
"text": "Distributed Wound-Die\n\nIf T1 is older than T2, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has either committed or aborted successfully at all sites.\nIf T1 is younger than T2, T1 is aborted. The concurrency control at Site P sends a message to all sites where T1 has visited to abort T1. The controlling site notifies the user when T1 has been successfully aborted in all the sites.\n\n"
},
{
"code": null,
"e": 96171,
"s": 96149,
"text": "Distributed Wound-Die"
},
{
"code": null,
"e": 96341,
"s": 96171,
"text": "If T1 is older than T2, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has either committed or aborted successfully at all sites."
},
{
"code": null,
"e": 96511,
"s": 96341,
"text": "If T1 is older than T2, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has either committed or aborted successfully at all sites."
},
{
"code": null,
"e": 96744,
"s": 96511,
"text": "If T1 is younger than T2, T1 is aborted. The concurrency control at Site P sends a message to all sites where T1 has visited to abort T1. The controlling site notifies the user when T1 has been successfully aborted in all the sites."
},
{
"code": null,
"e": 96977,
"s": 96744,
"text": "If T1 is younger than T2, T1 is aborted. The concurrency control at Site P sends a message to all sites where T1 has visited to abort T1. The controlling site notifies the user when T1 has been successfully aborted in all the sites."
},
{
"code": null,
"e": 97471,
"s": 96977,
"text": "Distributed Wait-Wait\n\nIf T1 is older than T2, T2 needs to be aborted. If T2 is active at Site P, Site P aborts and rolls back T2 and then broadcasts this message to other relevant sites. If T2 has left Site P but is active at Site Q, Site P broadcasts that T2 has been aborted; Site L then aborts and rolls back T2 and sends this message to all sites.\nIf T1 is younger than T1, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has completed processing.\n\n"
},
{
"code": null,
"e": 97493,
"s": 97471,
"text": "Distributed Wait-Wait"
},
{
"code": null,
"e": 97823,
"s": 97493,
"text": "If T1 is older than T2, T2 needs to be aborted. If T2 is active at Site P, Site P aborts and rolls back T2 and then broadcasts this message to other relevant sites. If T2 has left Site P but is active at Site Q, Site P broadcasts that T2 has been aborted; Site L then aborts and rolls back T2 and sends this message to all sites."
},
{
"code": null,
"e": 98153,
"s": 97823,
"text": "If T1 is older than T2, T2 needs to be aborted. If T2 is active at Site P, Site P aborts and rolls back T2 and then broadcasts this message to other relevant sites. If T2 has left Site P but is active at Site Q, Site P broadcasts that T2 has been aborted; Site L then aborts and rolls back T2 and sends this message to all sites."
},
{
"code": null,
"e": 98292,
"s": 98153,
"text": "If T1 is younger than T1, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has completed processing."
},
{
"code": null,
"e": 98431,
"s": 98292,
"text": "If T1 is younger than T1, T1 is allowed to wait. T1 can resume execution after Site P receives a message that T2 has completed processing."
},
{
"code": null,
"e": 98851,
"s": 98431,
"text": "Just like centralized deadlock detection approach, deadlocks are allowed to occur and are removed if detected. The system does not perform any checks when a transaction places a lock request. For implementation, global wait-for-graphs are created. Existence of a cycle in the global wait-for-graph indicates deadlocks. However, it is difficult to spot deadlocks since transaction waits for resources across the network."
},
{
"code": null,
"e": 99142,
"s": 98851,
"text": "Alternatively, deadlock detection algorithms can use timers. Each transaction is associated with a timer which is set to a time period in which a transaction is expected to finish. If a transaction does not finish within this time period, the timer goes off, indicating a possible deadlock."
},
{
"code": null,
"e": 99492,
"s": 99142,
"text": "Another tool used for deadlock handling is a deadlock detector. In a centralized system, there is one deadlock detector. In a distributed system, there can be more than one deadlock detectors. A deadlock detector can find deadlocks for the sites under its control. There are three alternatives for deadlock detection in a distributed system, namely."
},
{
"code": null,
"e": 99581,
"s": 99492,
"text": "Centralized Deadlock Detector − One site is designated as the central deadlock detector."
},
{
"code": null,
"e": 99670,
"s": 99581,
"text": "Centralized Deadlock Detector − One site is designated as the central deadlock detector."
},
{
"code": null,
"e": 99761,
"s": 99670,
"text": "Hierarchical Deadlock Detector − A number of deadlock detectors are arranged in hierarchy."
},
{
"code": null,
"e": 99852,
"s": 99761,
"text": "Hierarchical Deadlock Detector − A number of deadlock detectors are arranged in hierarchy."
},
{
"code": null,
"e": 99952,
"s": 99852,
"text": "Distributed Deadlock Detector − All the sites participate in detecting deadlocks and removing them."
},
{
"code": null,
"e": 100052,
"s": 99952,
"text": "Distributed Deadlock Detector − All the sites participate in detecting deadlocks and removing them."
},
{
"code": null,
"e": 100259,
"s": 100052,
"text": "This chapter looks into replication control, which is required to maintain consistent data in all sites. We will study the replication control techniques and the algorithms required for replication control."
},
{
"code": null,
"e": 100545,
"s": 100259,
"text": "As discussed earlier, replication is a technique used in distributed databases to store multiple copies of a data table at different sites. The problem with having multiple copies in multiple sites is the overhead of maintaining data consistency, particularly during update operations."
},
{
"code": null,
"e": 100715,
"s": 100545,
"text": "In order to maintain mutually consistent data in all sites, replication control techniques need to be adopted. There are two approaches for replication control, namely −"
},
{
"code": null,
"e": 100747,
"s": 100715,
"text": "Synchronous Replication Control"
},
{
"code": null,
"e": 100780,
"s": 100747,
"text": "Asynchronous Replication Control"
},
{
"code": null,
"e": 101197,
"s": 100780,
"text": "In synchronous replication approach, the database is synchronized so that all the replications always have the same value. A transaction requesting a data item will have access to the same value in all the sites. To ensure this uniformity, a transaction that updates a data item is expanded so that it makes the update in all the copies of the data item. Generally, two-phase commit protocol is used for the purpose."
},
{
"code": null,
"e": 101438,
"s": 101197,
"text": "For example, let us consider a data table PROJECT(PId, PName, PLocation). We need to run a transaction T1 that updates PLocation to ‘Mumbai’, if PLocation is ‘Bombay’. If no replications are there, the operations in transaction T1 will be −"
},
{
"code": null,
"e": 101533,
"s": 101438,
"text": "Begin T1: \n Update PROJECT Set PLocation = 'Mumbai' \n Where PLocation = 'Bombay'; \nEnd T1;"
},
{
"code": null,
"e": 101703,
"s": 101533,
"text": "If the data table has two replicas in Site A and Site B, T1 needs to spawn two children T1A and T1B corresponding to the two sites. The expanded transaction T1 will be −"
},
{
"code": null,
"e": 101948,
"s": 101703,
"text": "Begin T1: \n Begin T1A : \n Update PROJECT Set PLocation = 'Mumbai' \n Where PLocation = 'Bombay'; \n End T1A; \n\t\n Begin T2A : \n Update PROJECT Set PLocation = 'Mumbai'\n Where PLocation = 'Bombay'; \n End T2A; \n\t\nEnd T1;"
},
{
"code": null,
"e": 102225,
"s": 101948,
"text": "In asynchronous replication approach, the replicas do not always maintain the same value. One or more replicas may store an outdated value, and a transaction can see the different values. The process of bringing all the replicas to the current value is called synchronization."
},
{
"code": null,
"e": 102673,
"s": 102225,
"text": "A popular method of synchronization is store and forward method. In this method, one site is designated as the primary site and the other sites are secondary sites. The primary site always contains updated values. All the transactions first enter the primary site. These transactions are then queued for application in the secondary sites. The secondary sites are updated using rollout method only when a transaction is scheduled to execute on it."
},
{
"code": null,
"e": 102722,
"s": 102673,
"text": "Some of the replication control algorithms are −"
},
{
"code": null,
"e": 102766,
"s": 102722,
"text": "Master-slave replication control algorithm."
},
{
"code": null,
"e": 102796,
"s": 102766,
"text": "Distributed voting algorithm."
},
{
"code": null,
"e": 102826,
"s": 102796,
"text": "Majority consensus algorithm."
},
{
"code": null,
"e": 102855,
"s": 102826,
"text": "Circulating token algorithm."
},
{
"code": null,
"e": 103077,
"s": 102855,
"text": "There is one master site and ‘N’ slave sites. A master algorithm runs at the master site to detect conflicts. A copy of slave algorithm runs at each slave site. The overall algorithm executes in the following two phases −"
},
{
"code": null,
"e": 103506,
"s": 103077,
"text": "Transaction acceptance/rejection phase − When a transaction enters the transaction monitor of a slave site, the slave site sends a request to the master site. The master site checks for conflicts. If there aren’t any conflicts, the master sends an “ACK+” message to the slave site which then starts the transaction application phase. Otherwise, the master sends an “ACK-” message to the slave which then rejects the transaction."
},
{
"code": null,
"e": 103935,
"s": 103506,
"text": "Transaction acceptance/rejection phase − When a transaction enters the transaction monitor of a slave site, the slave site sends a request to the master site. The master site checks for conflicts. If there aren’t any conflicts, the master sends an “ACK+” message to the slave site which then starts the transaction application phase. Otherwise, the master sends an “ACK-” message to the slave which then rejects the transaction."
},
{
"code": null,
"e": 104451,
"s": 103935,
"text": "Transaction application phase − Upon entering this phase, the slave site where transaction has entered broadcasts a request to all slaves for executing the transaction. On receiving the requests, the peer slaves execute the transaction and send an “ACK” to the requesting slave on completion. After the requesting slave has received “ACK” messages from all its peers, it sends a “DONE” message to the master site. The master understands that the transaction has been completed and removes it from the pending queue."
},
{
"code": null,
"e": 104967,
"s": 104451,
"text": "Transaction application phase − Upon entering this phase, the slave site where transaction has entered broadcasts a request to all slaves for executing the transaction. On receiving the requests, the peer slaves execute the transaction and send an “ACK” to the requesting slave on completion. After the requesting slave has received “ACK” messages from all its peers, it sends a “DONE” message to the master site. The master understands that the transaction has been completed and removes it from the pending queue."
},
{
"code": null,
"e": 105114,
"s": 104967,
"text": "This comprises of ‘N’ peer sites, all of whom must “OK” a transaction before it starts executing. Following are the two phases of this algorithm −"
},
{
"code": null,
"e": 105557,
"s": 105114,
"text": "Distributed transaction acceptance phase − When a transaction enters the transaction manager of a site, it sends a transaction request to all other sites. On receiving a request, a peer site resolves conflicts using priority based voting rules. If all the peer sites are “OK” with the transaction, the requesting site starts application phase. If any of the peer sites does not “OK” a transaction, the requesting site rejects the transaction."
},
{
"code": null,
"e": 106000,
"s": 105557,
"text": "Distributed transaction acceptance phase − When a transaction enters the transaction manager of a site, it sends a transaction request to all other sites. On receiving a request, a peer site resolves conflicts using priority based voting rules. If all the peer sites are “OK” with the transaction, the requesting site starts application phase. If any of the peer sites does not “OK” a transaction, the requesting site rejects the transaction."
},
{
"code": null,
"e": 106465,
"s": 106000,
"text": "Distributed transaction application phase − Upon entering this phase, the site where the transaction has entered, broadcasts a request to all slaves for executing the transaction. On receiving the requests, the peer slaves execute the transaction and send an “ACK” message to the requesting slave on completion. After the requesting slave has received “ACK” messages from all its peers, it lets the transaction manager know that the transaction has been completed."
},
{
"code": null,
"e": 106930,
"s": 106465,
"text": "Distributed transaction application phase − Upon entering this phase, the site where the transaction has entered, broadcasts a request to all slaves for executing the transaction. On receiving the requests, the peer slaves execute the transaction and send an “ACK” message to the requesting slave on completion. After the requesting slave has received “ACK” messages from all its peers, it lets the transaction manager know that the transaction has been completed."
},
{
"code": null,
"e": 107116,
"s": 106930,
"text": "This is a variation from the distributed voting algorithm, where a transaction is allowed to execute when a majority of the peers “OK” a transaction. This is divided into three phases −"
},
{
"code": null,
"e": 107437,
"s": 107116,
"text": "Voting phase − When a transaction enters the transaction manager of a site, it sends a transaction request to all other sites. On receiving a request, a peer site tests for conflicts using voting rules and keeps the conflicting transactions, if any, in pending queue. Then, it sends either an “OK” or a “NOT OK” message."
},
{
"code": null,
"e": 107758,
"s": 107437,
"text": "Voting phase − When a transaction enters the transaction manager of a site, it sends a transaction request to all other sites. On receiving a request, a peer site tests for conflicts using voting rules and keeps the conflicting transactions, if any, in pending queue. Then, it sends either an “OK” or a “NOT OK” message."
},
{
"code": null,
"e": 108016,
"s": 107758,
"text": "Transaction acceptance/rejection phase − If the requesting site receives a majority “OK” on the transaction, it accepts the transaction and broadcasts “ACCEPT” to all the sites. Otherwise, it broadcasts “REJECT” to all the sites and rejects the transaction."
},
{
"code": null,
"e": 108274,
"s": 108016,
"text": "Transaction acceptance/rejection phase − If the requesting site receives a majority “OK” on the transaction, it accepts the transaction and broadcasts “ACCEPT” to all the sites. Otherwise, it broadcasts “REJECT” to all the sites and rejects the transaction."
},
{
"code": null,
"e": 108684,
"s": 108274,
"text": "Transaction application phase − When a peer site receives a “REJECT” message, it removes this transaction from its pending list and reconsiders all deferred transactions. When a peer site receives an “ACCEPT” message, it applies the transaction and rejects all the deferred transactions in the pending queue which are in conflict with this transaction. It sends an “ACK” to the requesting slave on completion."
},
{
"code": null,
"e": 109094,
"s": 108684,
"text": "Transaction application phase − When a peer site receives a “REJECT” message, it removes this transaction from its pending list and reconsiders all deferred transactions. When a peer site receives an “ACCEPT” message, it applies the transaction and rejects all the deferred transactions in the pending queue which are in conflict with this transaction. It sends an “ACK” to the requesting slave on completion."
},
{
"code": null,
"e": 109333,
"s": 109094,
"text": "In this approach the transactions in the system are serialized using a circulating token and executed accordingly against every replica of the database. Thus, all the transactions are accepted, i.e. none is rejected. This has two phases −"
},
{
"code": null,
"e": 109650,
"s": 109333,
"text": "Transaction serialization phase − In this phase, all transactions are scheduled to run in a serialization order. Each transaction in each site is assigned a unique ticket from a sequential series, indicating the order of transaction. Once a transaction has been assigned a ticket, it is broadcasted to all the sites."
},
{
"code": null,
"e": 109967,
"s": 109650,
"text": "Transaction serialization phase − In this phase, all transactions are scheduled to run in a serialization order. Each transaction in each site is assigned a unique ticket from a sequential series, indicating the order of transaction. Once a transaction has been assigned a ticket, it is broadcasted to all the sites."
},
{
"code": null,
"e": 110282,
"s": 109967,
"text": "Transaction application phase − When a site receives a transaction along with its ticket, it places the transaction for execution according to its ticket. After the transaction has finished execution, this site broadcasts an appropriate message. A transaction ends when it has completed execution in all the sites."
},
{
"code": null,
"e": 110597,
"s": 110282,
"text": "Transaction application phase − When a site receives a transaction along with its ticket, it places the transaction for execution according to its ticket. After the transaction has finished execution, this site broadcasts an appropriate message. A transaction ends when it has completed execution in all the sites."
},
{
"code": null,
"e": 110862,
"s": 110597,
"text": "A database management system is susceptible to a number of failures. In this chapter we will study the failure types and commit protocols. In a distributed database system, failures can be broadly categorized into soft failures, hard failures and network failures."
},
{
"code": null,
"e": 111194,
"s": 110862,
"text": "Soft failure is the type of failure that causes the loss in volatile memory of the computer and not in the persistent storage. Here, the information stored in the non-persistent storage like main memory, buffers, caches or registers, is lost. They are also known as system crash. The various types of soft failures are as follows −"
},
{
"code": null,
"e": 111220,
"s": 111194,
"text": "Operating system failure."
},
{
"code": null,
"e": 111239,
"s": 111220,
"text": "Main memory crash."
},
{
"code": null,
"e": 111272,
"s": 111239,
"text": "Transaction failure or abortion."
},
{
"code": null,
"e": 111342,
"s": 111272,
"text": "System generated error like integer overflow or divide-by-zero error."
},
{
"code": null,
"e": 111374,
"s": 111342,
"text": "Failure of supporting software."
},
{
"code": null,
"e": 111389,
"s": 111374,
"text": "Power failure."
},
{
"code": null,
"e": 111632,
"s": 111389,
"text": "A hard failure is the type of failure that causes loss of data in the persistent or non-volatile storage like disk. Disk failure may cause corruption of data in some disk blocks or failure of the total disk. The causes of a hard failure are −"
},
{
"code": null,
"e": 111647,
"s": 111632,
"text": "Power failure."
},
{
"code": null,
"e": 111664,
"s": 111647,
"text": "Faults in media."
},
{
"code": null,
"e": 111688,
"s": 111664,
"text": "Read-write malfunction."
},
{
"code": null,
"e": 111727,
"s": 111688,
"text": "Corruption of information on the disk."
},
{
"code": null,
"e": 111758,
"s": 111727,
"text": "Read/write head crash of disk."
},
{
"code": null,
"e": 111966,
"s": 111758,
"text": "Recovery from disk failures can be short, if there is a new, formatted, and ready-to-use disk on reserve. Otherwise, duration includes the time it takes to get a purchase order, buy the disk, and prepare it."
},
{
"code": null,
"e": 112224,
"s": 111966,
"text": "Network failures are prevalent in distributed or network databases. These comprises of the errors induced in the database system due to the distributed nature of the data and transferring data over the network. The causes of network failure are as follows −"
},
{
"code": null,
"e": 112252,
"s": 112224,
"text": "Communication link failure."
},
{
"code": null,
"e": 112272,
"s": 112252,
"text": "Network congestion."
},
{
"code": null,
"e": 112312,
"s": 112272,
"text": "Information corruption during transfer."
},
{
"code": null,
"e": 112327,
"s": 112312,
"text": "Site failures."
},
{
"code": null,
"e": 112349,
"s": 112327,
"text": "Network partitioning."
},
{
"code": null,
"e": 112769,
"s": 112349,
"text": "Any database system should guarantee that the desirable properties of a transaction are maintained even after failures. If a failure occurs during the execution of a transaction, it may happen that all the changes brought about by the transaction are not committed. This makes the database inconsistent. Commit protocols prevent this scenario using either transaction undo (rollback) or transaction redo (roll forward)."
},
{
"code": null,
"e": 112933,
"s": 112769,
"text": "The point of time at which the decision is made whether to commit or abort a transaction, is known as commit point. Following are the properties of a commit point."
},
{
"code": null,
"e": 112988,
"s": 112933,
"text": "It is a point of time when the database is consistent."
},
{
"code": null,
"e": 113043,
"s": 112988,
"text": "It is a point of time when the database is consistent."
},
{
"code": null,
"e": 113206,
"s": 113043,
"text": "At this point, the modifications brought about by the database can be seen by the other transactions. All transactions can have a consistent view of the database."
},
{
"code": null,
"e": 113369,
"s": 113206,
"text": "At this point, the modifications brought about by the database can be seen by the other transactions. All transactions can have a consistent view of the database."
},
{
"code": null,
"e": 113507,
"s": 113369,
"text": "At this point, all the operations of transaction have been successfully executed and their effects have been recorded in transaction log."
},
{
"code": null,
"e": 113645,
"s": 113507,
"text": "At this point, all the operations of transaction have been successfully executed and their effects have been recorded in transaction log."
},
{
"code": null,
"e": 113709,
"s": 113645,
"text": "At this point, a transaction can be safely undone, if required."
},
{
"code": null,
"e": 113773,
"s": 113709,
"text": "At this point, a transaction can be safely undone, if required."
},
{
"code": null,
"e": 113837,
"s": 113773,
"text": "At this point, a transaction releases all the locks held by it."
},
{
"code": null,
"e": 113901,
"s": 113837,
"text": "At this point, a transaction releases all the locks held by it."
},
{
"code": null,
"e": 114076,
"s": 113901,
"text": "The process of undoing all the changes made to a database by a transaction is called transaction undo or transaction rollback. This is mostly applied in case of soft failure."
},
{
"code": null,
"e": 114263,
"s": 114076,
"text": "The process of reapplying the changes made to a database by a transaction is called transaction redo or transaction roll forward. This is mostly applied for recovery from a hard failure."
},
{
"code": null,
"e": 114472,
"s": 114263,
"text": "A transaction log is a sequential file that keeps track of transaction operations on database items. As the log is sequential in nature, it is processed sequentially either from the beginning or from the end."
},
{
"code": null,
"e": 114504,
"s": 114472,
"text": "Purposes of a transaction log −"
},
{
"code": null,
"e": 114567,
"s": 114504,
"text": "To support commit protocols to commit or support transactions."
},
{
"code": null,
"e": 114607,
"s": 114567,
"text": "To aid database recovery after failure."
},
{
"code": null,
"e": 114831,
"s": 114607,
"text": "A transaction log is usually kept on the disk, so that it is not affected by soft failures. Additionally, the log is periodically backed up to an archival storage like magnetic tape to protect it from disk failures as well."
},
{
"code": null,
"e": 115061,
"s": 114831,
"text": "The transaction log maintains five types of lists depending upon the status of the transaction. This list aids the recovery manager to ascertain the status of a transaction. The status and the corresponding lists are as follows −"
},
{
"code": null,
"e": 115200,
"s": 115061,
"text": "A transaction that has a transaction start record and a transaction commit record, is a committed transaction – maintained in commit list."
},
{
"code": null,
"e": 115339,
"s": 115200,
"text": "A transaction that has a transaction start record and a transaction commit record, is a committed transaction – maintained in commit list."
},
{
"code": null,
"e": 115510,
"s": 115339,
"text": "A transaction that has a transaction start record and a transaction failed record but not a transaction abort record, is a failed transaction – maintained in failed list."
},
{
"code": null,
"e": 115681,
"s": 115510,
"text": "A transaction that has a transaction start record and a transaction failed record but not a transaction abort record, is a failed transaction – maintained in failed list."
},
{
"code": null,
"e": 115816,
"s": 115681,
"text": "A transaction that has a transaction start record and a transaction abort record is an aborted transaction – maintained in abort list."
},
{
"code": null,
"e": 115951,
"s": 115816,
"text": "A transaction that has a transaction start record and a transaction abort record is an aborted transaction – maintained in abort list."
},
{
"code": null,
"e": 116189,
"s": 115951,
"text": "A transaction that has a transaction start record and a transaction before-commit record is a before-commit transaction, i.e. a transaction where all the operations have been executed but not committed – maintained in before-commit list."
},
{
"code": null,
"e": 116427,
"s": 116189,
"text": "A transaction that has a transaction start record and a transaction before-commit record is a before-commit transaction, i.e. a transaction where all the operations have been executed but not committed – maintained in before-commit list."
},
{
"code": null,
"e": 116589,
"s": 116427,
"text": "A transaction that has a transaction start record but no records of before-commit, commit, abort or failed, is an active transaction – maintained in active list."
},
{
"code": null,
"e": 116751,
"s": 116589,
"text": "A transaction that has a transaction start record but no records of before-commit, commit, abort or failed, is an active transaction – maintained in active list."
},
{
"code": null,
"e": 116838,
"s": 116751,
"text": "Immediate Update and Deferred Update are two methods for maintaining transaction logs."
},
{
"code": null,
"e": 117292,
"s": 116838,
"text": "In immediate update mode, when a transaction executes, the updates made by the transaction are written directly onto the disk. The old values and the updates values are written onto the log before writing to the database in disk. On commit, the changes made to the disk are made permanent. On rollback, changes made by the transaction in the database are discarded and the old values are restored into the database from the old values stored in the log."
},
{
"code": null,
"e": 117583,
"s": 117292,
"text": "In deferred update mode, when a transaction executes, the updates made to the database by the transaction are recorded in the log file. On commit, the changes in the log are written onto the disk. On rollback, the changes in the log are discarded and no changes are applied to the database."
},
{
"code": null,
"e": 117790,
"s": 117583,
"text": "In order to recuperate from database failure, database management systems resort to a number of recovery management techniques. In this chapter, we will study the different approaches for database recovery."
},
{
"code": null,
"e": 117841,
"s": 117790,
"text": "The typical strategies for database recovery are −"
},
{
"code": null,
"e": 118075,
"s": 117841,
"text": "In case of soft failures that result in inconsistency of database, recovery strategy includes transaction undo or rollback. However, sometimes, transaction redo may also be adopted to recover to a consistent state of the transaction."
},
{
"code": null,
"e": 118309,
"s": 118075,
"text": "In case of soft failures that result in inconsistency of database, recovery strategy includes transaction undo or rollback. However, sometimes, transaction redo may also be adopted to recover to a consistent state of the transaction."
},
{
"code": null,
"e": 118591,
"s": 118309,
"text": "In case of hard failures resulting in extensive damage to database, recovery strategies encompass restoring a past copy of the database from archival backup. A more current state of the database is obtained through redoing operations of committed transactions from transaction log."
},
{
"code": null,
"e": 118873,
"s": 118591,
"text": "In case of hard failures resulting in extensive damage to database, recovery strategies encompass restoring a past copy of the database from archival backup. A more current state of the database is obtained through redoing operations of committed transactions from transaction log."
},
{
"code": null,
"e": 119096,
"s": 118873,
"text": "Power failure causes loss of information in the non-persistent memory. When power is restored, the operating system and the database management system restart. Recovery manager initiates recovery from the transaction logs."
},
{
"code": null,
"e": 119181,
"s": 119096,
"text": "In case of immediate update mode, the recovery manager takes the following actions −"
},
{
"code": null,
"e": 119277,
"s": 119181,
"text": "Transactions which are in active list and failed list are undone and written on the abort list."
},
{
"code": null,
"e": 119373,
"s": 119277,
"text": "Transactions which are in active list and failed list are undone and written on the abort list."
},
{
"code": null,
"e": 119430,
"s": 119373,
"text": "Transactions which are in before-commit list are redone."
},
{
"code": null,
"e": 119487,
"s": 119430,
"text": "Transactions which are in before-commit list are redone."
},
{
"code": null,
"e": 119549,
"s": 119487,
"text": "No action is taken for transactions in commit or abort lists."
},
{
"code": null,
"e": 119611,
"s": 119549,
"text": "No action is taken for transactions in commit or abort lists."
},
{
"code": null,
"e": 119695,
"s": 119611,
"text": "In case of deferred update mode, the recovery manager takes the following actions −"
},
{
"code": null,
"e": 119875,
"s": 119695,
"text": "Transactions which are in the active list and failed list are written onto the abort list. No undo operations are required since the changes have not been written to the disk yet."
},
{
"code": null,
"e": 120055,
"s": 119875,
"text": "Transactions which are in the active list and failed list are written onto the abort list. No undo operations are required since the changes have not been written to the disk yet."
},
{
"code": null,
"e": 120112,
"s": 120055,
"text": "Transactions which are in before-commit list are redone."
},
{
"code": null,
"e": 120169,
"s": 120112,
"text": "Transactions which are in before-commit list are redone."
},
{
"code": null,
"e": 120231,
"s": 120169,
"text": "No action is taken for transactions in commit or abort lists."
},
{
"code": null,
"e": 120293,
"s": 120231,
"text": "No action is taken for transactions in commit or abort lists."
},
{
"code": null,
"e": 120607,
"s": 120293,
"text": "A disk failure or hard crash causes a total database loss. To recover from this hard crash, a new disk is prepared, then the operating system is restored, and finally the database is recovered using the database backup and transaction log. The recovery method is same for both immediate and deferred update modes."
},
{
"code": null,
"e": 120658,
"s": 120607,
"text": "The recovery manager takes the following actions −"
},
{
"code": null,
"e": 120785,
"s": 120658,
"text": "The transactions in the commit list and before-commit list are redone and written onto the commit list in the transaction log."
},
{
"code": null,
"e": 120912,
"s": 120785,
"text": "The transactions in the commit list and before-commit list are redone and written onto the commit list in the transaction log."
},
{
"code": null,
"e": 121031,
"s": 120912,
"text": "The transactions in the active list and failed list are undone and written onto the abort list in the transaction log."
},
{
"code": null,
"e": 121150,
"s": 121031,
"text": "The transactions in the active list and failed list are undone and written onto the abort list in the transaction log."
},
{
"code": null,
"e": 121450,
"s": 121150,
"text": "Checkpoint is a point of time at which a record is written onto the database from the buffers. As a consequence, in case of a system crash, the recovery manager does not have to redo the transactions that have been committed before checkpoint. Periodical checkpointing shortens the recovery process."
},
{
"code": null,
"e": 121498,
"s": 121450,
"text": "The two types of checkpointing techniques are −"
},
{
"code": null,
"e": 121523,
"s": 121498,
"text": "Consistent checkpointing"
},
{
"code": null,
"e": 121543,
"s": 121523,
"text": "Fuzzy checkpointing"
},
{
"code": null,
"e": 121904,
"s": 121543,
"text": "Consistent checkpointing creates a consistent image of the database at checkpoint. During recovery, only those transactions which are on the right side of the last checkpoint are undone or redone. The transactions to the left side of the last consistent checkpoint are already committed and needn’t be processed again. The actions taken for checkpointing are −"
},
{
"code": null,
"e": 121955,
"s": 121904,
"text": "The active transactions are suspended temporarily."
},
{
"code": null,
"e": 122017,
"s": 121955,
"text": "All changes in main-memory buffers are written onto the disk."
},
{
"code": null,
"e": 122074,
"s": 122017,
"text": "A “checkpoint” record is written in the transaction log."
},
{
"code": null,
"e": 122118,
"s": 122074,
"text": "The transaction log is written to the disk."
},
{
"code": null,
"e": 122158,
"s": 122118,
"text": "The suspended transactions are resumed."
},
{
"code": null,
"e": 122346,
"s": 122158,
"text": "If in step 4, the transaction log is archived as well, then this checkpointing aids in recovery from disk failures and power failures, otherwise it aids recovery from only power failures."
},
{
"code": null,
"e": 122690,
"s": 122346,
"text": "In fuzzy checkpointing, at the time of checkpoint, all the active transactions are written in the log. In case of power failure, the recovery manager processes only those transactions that were active during checkpoint and later. The transactions that have been committed before checkpoint are written to the disk and hence need not be redone."
},
{
"code": null,
"e": 122857,
"s": 122690,
"text": "Let us consider that in system the time of checkpointing is tcheck and the time of system crash is tfail. Let there be four transactions Ta, Tb, Tc and Td such that −"
},
{
"code": null,
"e": 122887,
"s": 122857,
"text": "Ta commits before checkpoint."
},
{
"code": null,
"e": 122917,
"s": 122887,
"text": "Ta commits before checkpoint."
},
{
"code": null,
"e": 122978,
"s": 122917,
"text": "Tb starts before checkpoint and commits before system crash."
},
{
"code": null,
"e": 123039,
"s": 122978,
"text": "Tb starts before checkpoint and commits before system crash."
},
{
"code": null,
"e": 123099,
"s": 123039,
"text": "Tc starts after checkpoint and commits before system crash."
},
{
"code": null,
"e": 123159,
"s": 123099,
"text": "Tc starts after checkpoint and commits before system crash."
},
{
"code": null,
"e": 123230,
"s": 123159,
"text": "Td starts after checkpoint and was active at the time of system crash."
},
{
"code": null,
"e": 123301,
"s": 123230,
"text": "Td starts after checkpoint and was active at the time of system crash."
},
{
"code": null,
"e": 123354,
"s": 123301,
"text": "The situation is depicted in the following diagram −"
},
{
"code": null,
"e": 123411,
"s": 123354,
"text": "The actions that are taken by the recovery manager are −"
},
{
"code": null,
"e": 123436,
"s": 123411,
"text": "Nothing is done with Ta."
},
{
"code": null,
"e": 123481,
"s": 123436,
"text": "Transaction redo is performed for Tb and Tc."
},
{
"code": null,
"e": 123519,
"s": 123481,
"text": "Transaction undo is performed for Td."
},
{
"code": null,
"e": 123819,
"s": 123519,
"text": "Transaction recovery is done to eliminate the adverse effects of faulty transactions rather than to recover from a failure. Faulty transactions include all transactions that have changed the database into undesired state and the transactions that have used values written by the faulty transactions."
},
{
"code": null,
"e": 123879,
"s": 123819,
"text": "Transaction recovery in these cases is a two-step process −"
},
{
"code": null,
"e": 123974,
"s": 123879,
"text": "UNDO all faulty transactions and transactions that may be affected by the faulty transactions."
},
{
"code": null,
"e": 124069,
"s": 123974,
"text": "UNDO all faulty transactions and transactions that may be affected by the faulty transactions."
},
{
"code": null,
"e": 124164,
"s": 124069,
"text": "REDO all transactions that are not faulty but have been undone due to the faulty transactions."
},
{
"code": null,
"e": 124259,
"s": 124164,
"text": "REDO all transactions that are not faulty but have been undone due to the faulty transactions."
},
{
"code": null,
"e": 124294,
"s": 124259,
"text": "Steps for the UNDO operation are −"
},
{
"code": null,
"e": 124393,
"s": 124294,
"text": "If the faulty transaction has done INSERT, the recovery manager deletes the data item(s) inserted."
},
{
"code": null,
"e": 124492,
"s": 124393,
"text": "If the faulty transaction has done INSERT, the recovery manager deletes the data item(s) inserted."
},
{
"code": null,
"e": 124603,
"s": 124492,
"text": "If the faulty transaction has done DELETE, the recovery manager inserts the deleted data item(s) from the log."
},
{
"code": null,
"e": 124714,
"s": 124603,
"text": "If the faulty transaction has done DELETE, the recovery manager inserts the deleted data item(s) from the log."
},
{
"code": null,
"e": 124848,
"s": 124714,
"text": "If the faulty transaction has done UPDATE, the recovery manager eliminates the value by writing the before-update value from the log."
},
{
"code": null,
"e": 124982,
"s": 124848,
"text": "If the faulty transaction has done UPDATE, the recovery manager eliminates the value by writing the before-update value from the log."
},
{
"code": null,
"e": 125017,
"s": 124982,
"text": "Steps for the REDO operation are −"
},
{
"code": null,
"e": 125108,
"s": 125017,
"text": "If the transaction has done INSERT, the recovery manager generates an insert from the log."
},
{
"code": null,
"e": 125199,
"s": 125108,
"text": "If the transaction has done INSERT, the recovery manager generates an insert from the log."
},
{
"code": null,
"e": 125289,
"s": 125199,
"text": "If the transaction has done DELETE, the recovery manager generates a delete from the log."
},
{
"code": null,
"e": 125379,
"s": 125289,
"text": "If the transaction has done DELETE, the recovery manager generates a delete from the log."
},
{
"code": null,
"e": 125470,
"s": 125379,
"text": "If the transaction has done UPDATE, the recovery manager generates an update from the log."
},
{
"code": null,
"e": 125561,
"s": 125470,
"text": "If the transaction has done UPDATE, the recovery manager generates an update from the log."
},
{
"code": null,
"e": 126257,
"s": 125561,
"text": "In a local database system, for committing a transaction, the transaction manager has to only convey the decision to commit to the recovery manager. However, in a distributed system, the transaction manager should convey the decision to commit to all the servers in the various sites where the transaction is being executed and uniformly enforce the decision. When processing is complete at each site, it reaches the partially committed transaction state and waits for all other transactions to reach their partially committed states. When it receives the message that all the sites are ready to commit, it starts to commit. In a distributed system, either all sites commit or none of them does."
},
{
"code": null,
"e": 126306,
"s": 126257,
"text": "The different distributed commit protocols are −"
},
{
"code": null,
"e": 126323,
"s": 126306,
"text": "One-phase commit"
},
{
"code": null,
"e": 126340,
"s": 126323,
"text": "Two-phase commit"
},
{
"code": null,
"e": 126359,
"s": 126340,
"text": "Three-phase commit"
},
{
"code": null,
"e": 126577,
"s": 126359,
"text": "Distributed one-phase commit is the simplest commit protocol. Let us consider that there is a controlling site and a number of slave sites where the transaction is being executed. The steps in distributed commit are −"
},
{
"code": null,
"e": 126684,
"s": 126577,
"text": "After each slave has locally completed its transaction, it sends a “DONE” message to the controlling site."
},
{
"code": null,
"e": 126791,
"s": 126684,
"text": "After each slave has locally completed its transaction, it sends a “DONE” message to the controlling site."
},
{
"code": null,
"e": 126919,
"s": 126791,
"text": "The slaves wait for “Commit” or “Abort” message from the controlling site. This waiting time is called window of vulnerability."
},
{
"code": null,
"e": 127047,
"s": 126919,
"text": "The slaves wait for “Commit” or “Abort” message from the controlling site. This waiting time is called window of vulnerability."
},
{
"code": null,
"e": 127234,
"s": 127047,
"text": "When the controlling site receives “DONE” message from each slave, it makes a decision to commit or abort. This is called the commit point. Then, it sends this message to all the slaves."
},
{
"code": null,
"e": 127421,
"s": 127234,
"text": "When the controlling site receives “DONE” message from each slave, it makes a decision to commit or abort. This is called the commit point. Then, it sends this message to all the slaves."
},
{
"code": null,
"e": 127548,
"s": 127421,
"text": "On receiving this message, a slave either commits or aborts and then sends an acknowledgement message to the controlling site."
},
{
"code": null,
"e": 127675,
"s": 127548,
"text": "On receiving this message, a slave either commits or aborts and then sends an acknowledgement message to the controlling site."
},
{
"code": null,
"e": 127816,
"s": 127675,
"text": "Distributed two-phase commit reduces the vulnerability of one-phase commit protocols. The steps performed in the two phases are as follows −"
},
{
"code": null,
"e": 127839,
"s": 127816,
"text": "Phase 1: Prepare Phase"
},
{
"code": null,
"e": 128061,
"s": 127839,
"text": "After each slave has locally completed its transaction, it sends a “DONE” message to the controlling site. When the controlling site has received “DONE” message from all slaves, it sends a “Prepare” message to the slaves."
},
{
"code": null,
"e": 128283,
"s": 128061,
"text": "After each slave has locally completed its transaction, it sends a “DONE” message to the controlling site. When the controlling site has received “DONE” message from all slaves, it sends a “Prepare” message to the slaves."
},
{
"code": null,
"e": 128400,
"s": 128283,
"text": "The slaves vote on whether they still want to commit or not. If a slave wants to commit, it sends a “Ready” message."
},
{
"code": null,
"e": 128517,
"s": 128400,
"text": "The slaves vote on whether they still want to commit or not. If a slave wants to commit, it sends a “Ready” message."
},
{
"code": null,
"e": 128677,
"s": 128517,
"text": "A slave that does not want to commit sends a “Not Ready” message. This may happen when the slave has conflicting concurrent transactions or there is a timeout."
},
{
"code": null,
"e": 128837,
"s": 128677,
"text": "A slave that does not want to commit sends a “Not Ready” message. This may happen when the slave has conflicting concurrent transactions or there is a timeout."
},
{
"code": null,
"e": 128865,
"s": 128837,
"text": "Phase 2: Commit/Abort Phase"
},
{
"code": null,
"e": 129224,
"s": 128865,
"text": "After the controlling site has received “Ready” message from all the slaves −\n\nThe controlling site sends a “Global Commit” message to the slaves.\nThe slaves apply the transaction and send a “Commit ACK” message to the controlling site.\nWhen the controlling site receives “Commit ACK” message from all the slaves, it considers the transaction as committed.\n\n"
},
{
"code": null,
"e": 129302,
"s": 129224,
"text": "After the controlling site has received “Ready” message from all the slaves −"
},
{
"code": null,
"e": 129370,
"s": 129302,
"text": "The controlling site sends a “Global Commit” message to the slaves."
},
{
"code": null,
"e": 129438,
"s": 129370,
"text": "The controlling site sends a “Global Commit” message to the slaves."
},
{
"code": null,
"e": 129528,
"s": 129438,
"text": "The slaves apply the transaction and send a “Commit ACK” message to the controlling site."
},
{
"code": null,
"e": 129618,
"s": 129528,
"text": "The slaves apply the transaction and send a “Commit ACK” message to the controlling site."
},
{
"code": null,
"e": 129738,
"s": 129618,
"text": "When the controlling site receives “Commit ACK” message from all the slaves, it considers the transaction as committed."
},
{
"code": null,
"e": 129858,
"s": 129738,
"text": "When the controlling site receives “Commit ACK” message from all the slaves, it considers the transaction as committed."
},
{
"code": null,
"e": 130221,
"s": 129858,
"text": "After the controlling site has received the first “Not Ready” message from any slave −\n\nThe controlling site sends a “Global Abort” message to the slaves.\nThe slaves abort the transaction and send a “Abort ACK” message to the controlling site.\nWhen the controlling site receives “Abort ACK” message from all the slaves, it considers the transaction as aborted.\n\n"
},
{
"code": null,
"e": 130308,
"s": 130221,
"text": "After the controlling site has received the first “Not Ready” message from any slave −"
},
{
"code": null,
"e": 130375,
"s": 130308,
"text": "The controlling site sends a “Global Abort” message to the slaves."
},
{
"code": null,
"e": 130442,
"s": 130375,
"text": "The controlling site sends a “Global Abort” message to the slaves."
},
{
"code": null,
"e": 130531,
"s": 130442,
"text": "The slaves abort the transaction and send a “Abort ACK” message to the controlling site."
},
{
"code": null,
"e": 130620,
"s": 130531,
"text": "The slaves abort the transaction and send a “Abort ACK” message to the controlling site."
},
{
"code": null,
"e": 130737,
"s": 130620,
"text": "When the controlling site receives “Abort ACK” message from all the slaves, it considers the transaction as aborted."
},
{
"code": null,
"e": 130854,
"s": 130737,
"text": "When the controlling site receives “Abort ACK” message from all the slaves, it considers the transaction as aborted."
},
{
"code": null,
"e": 130915,
"s": 130854,
"text": "The steps in distributed three-phase commit are as follows −"
},
{
"code": null,
"e": 130938,
"s": 130915,
"text": "Phase 1: Prepare Phase"
},
{
"code": null,
"e": 130993,
"s": 130938,
"text": "The steps are same as in distributed two-phase commit."
},
{
"code": null,
"e": 131026,
"s": 130993,
"text": "Phase 2: Prepare to Commit Phase"
},
{
"code": null,
"e": 131099,
"s": 131026,
"text": "The controlling site issues an “Enter Prepared State” broadcast message."
},
{
"code": null,
"e": 131138,
"s": 131099,
"text": "The slave sites vote “OK” in response."
},
{
"code": null,
"e": 131168,
"s": 131138,
"text": "Phase 3: Commit / Abort Phase"
},
{
"code": null,
"e": 131269,
"s": 131168,
"text": "The steps are same as two-phase commit except that “Commit ACK”/”Abort ACK” message is not required."
},
{
"code": null,
"e": 131426,
"s": 131269,
"text": "In this chapter, we will look into the threats that a database system faces and the measures of control. We will also study cryptography as a security tool."
},
{
"code": null,
"e": 131648,
"s": 131426,
"text": "Data security is an imperative aspect of any database system. It is of particular importance in distributed systems because of large number of users, fragmented and replicated data, multiple sites and distributed control."
},
{
"code": null,
"e": 131754,
"s": 131648,
"text": "Availability loss − Availability loss refers to non-availability of database objects by legitimate users."
},
{
"code": null,
"e": 131860,
"s": 131754,
"text": "Availability loss − Availability loss refers to non-availability of database objects by legitimate users."
},
{
"code": null,
"e": 132127,
"s": 131860,
"text": "Integrity loss − Integrity loss occurs when unacceptable operations are performed upon the database either accidentally or maliciously. This may happen while creating, inserting, updating or deleting data. It results in corrupted data leading to incorrect decisions."
},
{
"code": null,
"e": 132394,
"s": 132127,
"text": "Integrity loss − Integrity loss occurs when unacceptable operations are performed upon the database either accidentally or maliciously. This may happen while creating, inserting, updating or deleting data. It results in corrupted data leading to incorrect decisions."
},
{
"code": null,
"e": 132604,
"s": 132394,
"text": "Confidentiality loss − Confidentiality loss occurs due to unauthorized or unintentional disclosure of confidential information. It may result in illegal actions, security threats and loss in public confidence."
},
{
"code": null,
"e": 132814,
"s": 132604,
"text": "Confidentiality loss − Confidentiality loss occurs due to unauthorized or unintentional disclosure of confidential information. It may result in illegal actions, security threats and loss in public confidence."
},
{
"code": null,
"e": 132893,
"s": 132814,
"text": "The measures of control can be broadly divided into the following categories −"
},
{
"code": null,
"e": 133173,
"s": 132893,
"text": "Access Control − Access control includes security mechanisms in a database management system to protect against unauthorized access. A user can gain access to the database after clearing the login process through only valid user accounts. Each user account is password protected."
},
{
"code": null,
"e": 133453,
"s": 133173,
"text": "Access Control − Access control includes security mechanisms in a database management system to protect against unauthorized access. A user can gain access to the database after clearing the login process through only valid user accounts. Each user account is password protected."
},
{
"code": null,
"e": 133818,
"s": 133453,
"text": "Flow Control − Distributed systems encompass a lot of data flow from one site to another and also within a site. Flow control prevents data from being transferred in such a way that it can be accessed by unauthorized agents. A flow policy lists out the channels through which information can flow. It also defines security classes for data as well as transactions."
},
{
"code": null,
"e": 134183,
"s": 133818,
"text": "Flow Control − Distributed systems encompass a lot of data flow from one site to another and also within a site. Flow control prevents data from being transferred in such a way that it can be accessed by unauthorized agents. A flow policy lists out the channels through which information can flow. It also defines security classes for data as well as transactions."
},
{
"code": null,
"e": 134426,
"s": 134183,
"text": "Data Encryption − Data encryption refers to coding data when sensitive data is to be communicated over public channels. Even if an unauthorized agent gains access of the data, he cannot understand it since it is in an incomprehensible format."
},
{
"code": null,
"e": 134669,
"s": 134426,
"text": "Data Encryption − Data encryption refers to coding data when sensitive data is to be communicated over public channels. Even if an unauthorized agent gains access of the data, he cannot understand it since it is in an incomprehensible format."
},
{
"code": null,
"e": 134830,
"s": 134669,
"text": "Cryptography is the science of encoding information before sending via unreliable communication paths so that only an authorized receiver can decode and use it."
},
{
"code": null,
"e": 135119,
"s": 134830,
"text": "The coded message is called cipher text and the original message is called plain text. The process of converting plain text to cipher text by the sender is called encoding or encryption. The process of converting cipher text to plain text by the receiver is called decoding or decryption."
},
{
"code": null,
"e": 135227,
"s": 135119,
"text": "The entire procedure of communicating using cryptography can be illustrated through the following diagram −"
},
{
"code": null,
"e": 135622,
"s": 135227,
"text": "In conventional cryptography, the encryption and decryption is done using the same secret key. Here, the sender encrypts the message with an encryption algorithm using a copy of the secret key. The encrypted message is then send over public communication channels. On receiving the encrypted message, the receiver decrypts it with a corresponding decryption algorithm using the same secret key."
},
{
"code": null,
"e": 135685,
"s": 135622,
"text": "Security in conventional cryptography depends on two factors −"
},
{
"code": null,
"e": 135726,
"s": 135685,
"text": "A sound algorithm which is known to all."
},
{
"code": null,
"e": 135767,
"s": 135726,
"text": "A sound algorithm which is known to all."
},
{
"code": null,
"e": 135859,
"s": 135767,
"text": "A randomly generated, preferably long secret key known only by the sender and the receiver."
},
{
"code": null,
"e": 135951,
"s": 135859,
"text": "A randomly generated, preferably long secret key known only by the sender and the receiver."
},
{
"code": null,
"e": 136039,
"s": 135951,
"text": "The most famous conventional cryptography algorithm is Data Encryption Standard or DES."
},
{
"code": null,
"e": 136296,
"s": 136039,
"text": "The advantage of this method is its easy applicability. However, the greatest problem of conventional cryptography is sharing the secret key between the communicating parties. The ways to send the key are cumbersome and highly susceptible to eavesdropping."
},
{
"code": null,
"e": 136849,
"s": 136296,
"text": "In contrast to conventional cryptography, public key cryptography uses two different keys, referred to as public key and the private key. Each user generates the pair of public key and private key. The user then puts the public key in an accessible place. When a sender wants to sends a message, he encrypts it using the public key of the receiver. On receiving the encrypted message, the receiver decrypts it using his private key. Since the private key is not known to anyone but the receiver, no other person who receives the message can decrypt it."
},
{
"code": null,
"e": 137113,
"s": 136849,
"text": "The most popular public key cryptography algorithms are RSA algorithm and Diffie– Hellman algorithm. This method is very secure to send private messages. However, the problem is, it involves a lot of computations and so proves to be inefficient for long messages."
},
{
"code": null,
"e": 137400,
"s": 137113,
"text": "The solution is to use a combination of conventional and public key cryptography. The secret key is encrypted using public key cryptography before sharing between the communicating parties. Then, the message is send using conventional cryptography with the aid of the shared secret key."
},
{
"code": null,
"e": 137660,
"s": 137400,
"text": "A Digital Signature (DS) is an authentication technique based on public key cryptography used in e-commerce applications. It associates a unique mark to an individual within the body of his message. This helps others to authenticate valid senders of messages."
},
{
"code": null,
"e": 137809,
"s": 137660,
"text": "Typically, a user’s digital signature varies from message to message in order to provide security against counterfeiting. The method is as follows −"
},
{
"code": null,
"e": 137922,
"s": 137809,
"text": "The sender takes a message, calculates the message digest of the message and signs it digest with a private key."
},
{
"code": null,
"e": 138035,
"s": 137922,
"text": "The sender takes a message, calculates the message digest of the message and signs it digest with a private key."
},
{
"code": null,
"e": 138111,
"s": 138035,
"text": "The sender then appends the signed digest along with the plaintext message."
},
{
"code": null,
"e": 138187,
"s": 138111,
"text": "The sender then appends the signed digest along with the plaintext message."
},
{
"code": null,
"e": 138235,
"s": 138187,
"text": "The message is sent over communication channel."
},
{
"code": null,
"e": 138283,
"s": 138235,
"text": "The message is sent over communication channel."
},
{
"code": null,
"e": 138391,
"s": 138283,
"text": "The receiver removes the appended signed digest and verifies the digest using the corresponding public key."
},
{
"code": null,
"e": 138499,
"s": 138391,
"text": "The receiver removes the appended signed digest and verifies the digest using the corresponding public key."
},
{
"code": null,
"e": 138600,
"s": 138499,
"text": "The receiver then takes the plaintext message and runs it through the same message digest algorithm."
},
{
"code": null,
"e": 138701,
"s": 138600,
"text": "The receiver then takes the plaintext message and runs it through the same message digest algorithm."
},
{
"code": null,
"e": 138814,
"s": 138701,
"text": "If the results of step 4 and step 5 match, then the receiver knows that the message has integrity and authentic."
},
{
"code": null,
"e": 138927,
"s": 138814,
"text": "If the results of step 4 and step 5 match, then the receiver knows that the message has integrity and authentic."
},
{
"code": null,
"e": 139182,
"s": 138927,
"text": "A distributed system needs additional security measures than centralized system, since there are many users, diversified data, multiple sites and distributed control. In this chapter, we will look into the various facets of distributed database security."
},
{
"code": null,
"e": 139255,
"s": 139182,
"text": "In distributed communication systems, there are two types of intruders −"
},
{
"code": null,
"e": 139342,
"s": 139255,
"text": "Passive eavesdroppers − They monitor the messages and get hold of private information."
},
{
"code": null,
"e": 139429,
"s": 139342,
"text": "Passive eavesdroppers − They monitor the messages and get hold of private information."
},
{
"code": null,
"e": 139555,
"s": 139429,
"text": "Active attackers − They not only monitor the messages but also corrupt data by inserting new data or modifying existing data."
},
{
"code": null,
"e": 139681,
"s": 139555,
"text": "Active attackers − They not only monitor the messages but also corrupt data by inserting new data or modifying existing data."
},
{
"code": null,
"e": 139773,
"s": 139681,
"text": "Security measures encompass security in communications, security in data and data auditing."
},
{
"code": null,
"e": 140020,
"s": 139773,
"text": "In a distributed database, a lot of data communication takes place owing to the diversified location of data, users and transactions. So, it demands secure communication between users and databases and between the different database environments."
},
{
"code": null,
"e": 140074,
"s": 140020,
"text": "Security in communication encompasses the following −"
},
{
"code": null,
"e": 140118,
"s": 140074,
"text": "Data should not be corrupt during transfer."
},
{
"code": null,
"e": 140162,
"s": 140118,
"text": "Data should not be corrupt during transfer."
},
{
"code": null,
"e": 140265,
"s": 140162,
"text": "The communication channel should be protected against both passive eavesdroppers and active attackers."
},
{
"code": null,
"e": 140368,
"s": 140265,
"text": "The communication channel should be protected against both passive eavesdroppers and active attackers."
},
{
"code": null,
"e": 140485,
"s": 140368,
"text": "In order to achieve the above stated requirements, well-defined security algorithms and protocols should be adopted."
},
{
"code": null,
"e": 140602,
"s": 140485,
"text": "In order to achieve the above stated requirements, well-defined security algorithms and protocols should be adopted."
},
{
"code": null,
"e": 140692,
"s": 140602,
"text": "Two popular, consistent technologies for achieving end-to-end secure communications are −"
},
{
"code": null,
"e": 140759,
"s": 140692,
"text": "Secure Socket Layer Protocol or Transport Layer Security Protocol."
},
{
"code": null,
"e": 140791,
"s": 140759,
"text": "Virtual Private Networks (VPN)."
},
{
"code": null,
"e": 140924,
"s": 140791,
"text": "In distributed systems, it is imperative to adopt measure to secure data apart from communications. The data security measures are −"
},
{
"code": null,
"e": 141188,
"s": 140924,
"text": "Authentication and authorization − These are the access control measures adopted to ensure that only authentic users can use the database. To provide authentication digital certificates are used. Besides, login is restricted through username/password combination."
},
{
"code": null,
"e": 141452,
"s": 141188,
"text": "Authentication and authorization − These are the access control measures adopted to ensure that only authentic users can use the database. To provide authentication digital certificates are used. Besides, login is restricted through username/password combination."
},
{
"code": null,
"e": 142016,
"s": 141452,
"text": "Data encryption − The two approaches for data encryption in distributed systems are −\n\nInternal to distributed database approach: The user applications encrypt the data and then store the encrypted data in the database. For using the stored data, the applications fetch the encrypted data from the database and then decrypt it.\nExternal to distributed database: The distributed database system has its own encryption capabilities. The user applications store data and retrieve them without realizing that the data is stored in an encrypted form in the database.\n\n"
},
{
"code": null,
"e": 142102,
"s": 142016,
"text": "Data encryption − The two approaches for data encryption in distributed systems are −"
},
{
"code": null,
"e": 142343,
"s": 142102,
"text": "Internal to distributed database approach: The user applications encrypt the data and then store the encrypted data in the database. For using the stored data, the applications fetch the encrypted data from the database and then decrypt it."
},
{
"code": null,
"e": 142584,
"s": 142343,
"text": "Internal to distributed database approach: The user applications encrypt the data and then store the encrypted data in the database. For using the stored data, the applications fetch the encrypted data from the database and then decrypt it."
},
{
"code": null,
"e": 142818,
"s": 142584,
"text": "External to distributed database: The distributed database system has its own encryption capabilities. The user applications store data and retrieve them without realizing that the data is stored in an encrypted form in the database."
},
{
"code": null,
"e": 143052,
"s": 142818,
"text": "External to distributed database: The distributed database system has its own encryption capabilities. The user applications store data and retrieve them without realizing that the data is stored in an encrypted form in the database."
},
{
"code": null,
"e": 143330,
"s": 143052,
"text": "Validated input − In this security measure, the user application checks for each input before it can be used for updating the database. An un-validated input can cause a wide range of exploits like buffer overrun, command injection, cross-site scripting and corruption in data."
},
{
"code": null,
"e": 143608,
"s": 143330,
"text": "Validated input − In this security measure, the user application checks for each input before it can be used for updating the database. An un-validated input can cause a wide range of exploits like buffer overrun, command injection, cross-site scripting and corruption in data."
},
{
"code": null,
"e": 143939,
"s": 143608,
"text": "A database security system needs to detect and monitor security violations, in order to ascertain the security measures it should adopt. It is often very difficult to detect breach of security at the time of occurrences. One method to identify security violations is to examine audit logs. Audit logs contain information such as −"
},
{
"code": null,
"e": 143986,
"s": 143939,
"text": "Date, time and site of failed access attempts."
},
{
"code": null,
"e": 144025,
"s": 143986,
"text": "Details of successful access attempts."
},
{
"code": null,
"e": 144069,
"s": 144025,
"text": "Vital modifications in the database system."
},
{
"code": null,
"e": 144148,
"s": 144069,
"text": "Access of huge amounts of data, particularly from databases in multiple sites."
},
{
"code": null,
"e": 144433,
"s": 144148,
"text": "All the above information gives an insight of the activities in the database. A periodical analysis of the log helps to identify any unnatural activity along with its site and time of occurrence. This log is ideally stored in a separate server so that it is inaccessible to attackers."
},
{
"code": null,
"e": 144467,
"s": 144433,
"text": "\n 49 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 144483,
"s": 144467,
"text": " Hussein Rashad"
},
{
"code": null,
"e": 144490,
"s": 144483,
"text": " Print"
},
{
"code": null,
"e": 144501,
"s": 144490,
"text": " Add Notes"
}
] |
Give the examples of a context free language that are not regular?
|
A context-free grammar (CFG) consisting of a finite set of grammar rules is a quadruple (V, T, P, S)
Where,
V is a variable (non terminals).
V is a variable (non terminals).
T is a set of terminals.
T is a set of terminals.
P is a set of rules, P: V→ (V ∪ T)*, i.e., the left-hand sides of the production rule. P does have any right context or left context.
P is a set of rules, P: V→ (V ∪ T)*, i.e., the left-hand sides of the production rule. P does have any right context or left context.
S is the start symbol.
S is the start symbol.
By using the rules of any language, we can derive any strings in that language.
For language a* CFG is as follows −
S -> aS
S -> ɛ
Here,
S are the variables.
S are the variables.
a and ɛ terminals.
a and ɛ terminals.
S is the start symbol.
S is the start symbol.
By using these rules, we can derive any number of a's.
For Example, consider string aaaaa as CFG as shown below −
S
aS rule 1
aaS rule 1
aaaS rule 1
aaaaS rule 1
aaaaaS rule 1
aaaaaɛ rule 2
aaaaa
Context free language is created by context free grammar and it includes regular languages.
The same context free languages can be generated by multiple context free grammars.
Example 1
Example of language that is not regular but it is context free is { anbn | n >= 0 }
The above example is of all strings that have equal number of a's and b's and the notation a3b3 can be expanded out to aaabbb, where there are three a's and three b's.
The pumping Lemma provides the ability to perform negative test. If the language does not satisfy the pumping lemma, then it can be said that it is not context free. Pumping lemma is mathematical proof which takes time to apply it on context free languages.
Example 2
Consider another example of context free that is not regular.
S -> aSb | ɛ
This example is not regular because we cannot express it with a finite state machine or regular expression. We should be able to count the number of A's and check that number of B's matches. Moreover, it cannot be done with finite state as n could be anything.
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "A context-free grammar (CFG) consisting of a finite set of grammar rules is a quadruple (V, T, P, S)"
},
{
"code": null,
"e": 1170,
"s": 1163,
"text": "Where,"
},
{
"code": null,
"e": 1203,
"s": 1170,
"text": "V is a variable (non terminals)."
},
{
"code": null,
"e": 1236,
"s": 1203,
"text": "V is a variable (non terminals)."
},
{
"code": null,
"e": 1261,
"s": 1236,
"text": "T is a set of terminals."
},
{
"code": null,
"e": 1286,
"s": 1261,
"text": "T is a set of terminals."
},
{
"code": null,
"e": 1420,
"s": 1286,
"text": "P is a set of rules, P: V→ (V ∪ T)*, i.e., the left-hand sides of the production rule. P does have any right context or left context."
},
{
"code": null,
"e": 1554,
"s": 1420,
"text": "P is a set of rules, P: V→ (V ∪ T)*, i.e., the left-hand sides of the production rule. P does have any right context or left context."
},
{
"code": null,
"e": 1577,
"s": 1554,
"text": "S is the start symbol."
},
{
"code": null,
"e": 1600,
"s": 1577,
"text": "S is the start symbol."
},
{
"code": null,
"e": 1680,
"s": 1600,
"text": "By using the rules of any language, we can derive any strings in that language."
},
{
"code": null,
"e": 1716,
"s": 1680,
"text": "For language a* CFG is as follows −"
},
{
"code": null,
"e": 1724,
"s": 1716,
"text": "S -> aS"
},
{
"code": null,
"e": 1731,
"s": 1724,
"text": "S -> ɛ"
},
{
"code": null,
"e": 1737,
"s": 1731,
"text": "Here,"
},
{
"code": null,
"e": 1758,
"s": 1737,
"text": "S are the variables."
},
{
"code": null,
"e": 1779,
"s": 1758,
"text": "S are the variables."
},
{
"code": null,
"e": 1798,
"s": 1779,
"text": "a and ɛ terminals."
},
{
"code": null,
"e": 1817,
"s": 1798,
"text": "a and ɛ terminals."
},
{
"code": null,
"e": 1840,
"s": 1817,
"text": "S is the start symbol."
},
{
"code": null,
"e": 1863,
"s": 1840,
"text": "S is the start symbol."
},
{
"code": null,
"e": 1918,
"s": 1863,
"text": "By using these rules, we can derive any number of a's."
},
{
"code": null,
"e": 1977,
"s": 1918,
"text": "For Example, consider string aaaaa as CFG as shown below −"
},
{
"code": null,
"e": 2092,
"s": 1977,
"text": "S\naS rule 1\naaS rule 1\naaaS rule 1\naaaaS rule 1\naaaaaS rule 1\naaaaaɛ rule 2\naaaaa"
},
{
"code": null,
"e": 2184,
"s": 2092,
"text": "Context free language is created by context free grammar and it includes regular languages."
},
{
"code": null,
"e": 2268,
"s": 2184,
"text": "The same context free languages can be generated by multiple context free grammars."
},
{
"code": null,
"e": 2278,
"s": 2268,
"text": "Example 1"
},
{
"code": null,
"e": 2362,
"s": 2278,
"text": "Example of language that is not regular but it is context free is { anbn | n >= 0 }"
},
{
"code": null,
"e": 2530,
"s": 2362,
"text": "The above example is of all strings that have equal number of a's and b's and the notation a3b3 can be expanded out to aaabbb, where there are three a's and three b's."
},
{
"code": null,
"e": 2788,
"s": 2530,
"text": "The pumping Lemma provides the ability to perform negative test. If the language does not satisfy the pumping lemma, then it can be said that it is not context free. Pumping lemma is mathematical proof which takes time to apply it on context free languages."
},
{
"code": null,
"e": 2798,
"s": 2788,
"text": "Example 2"
},
{
"code": null,
"e": 2860,
"s": 2798,
"text": "Consider another example of context free that is not regular."
},
{
"code": null,
"e": 2873,
"s": 2860,
"text": "S -> aSb | ɛ"
},
{
"code": null,
"e": 3134,
"s": 2873,
"text": "This example is not regular because we cannot express it with a finite state machine or regular expression. We should be able to count the number of A's and check that number of B's matches. Moreover, it cannot be done with finite state as n could be anything."
}
] |
Linear Regression. A unification of Maximum Likelihood... | by William Fleshman | Towards Data Science
|
I recently wrote about maximum likelihood estimation in my ongoing series on the fundamentals of machine learning:
towardsdatascience.com
In that post, we learned what it means to “model” data, and then how to use MLE to find the parameters of our model. In this post, we’re going to dive into linear regression, one of the most important models in statistics, and learn how to frame it in terms of MLE. The solution is a beautiful piece of mathematics, which like most MLE models, is rich with intuition. I’ll be assuming you’ve got a handle on the vocabulary I’ve covered in the other series (probability densities, conditional probabilities, likelihood function, iid data, etc.). If you see something here that you’re uncomfortable with, check out the Probability and MLE posts from that series for clarity.
We use linear regression when our data has a linear relationship between the independent variables (our features) and the dependent variable (our target). In the MLE post, we saw some data that looked similar too this:
We observed that there appears to be a linear relationship between x and y, but it’s not perfect. We think of these imperfections as coming from some error or noise process. Imagine drawing a line right through the cloud of points. The error for each point would be the distance from the point to our line. We’d like to explicitly include those errors in our model. One method of doing this, is to assume the errors are distributed from a Gaussian distribution with a mean of 0 and some unknown variance σ2. The Gaussian seems like a good choice, because our errors look like they’re symmetric about were the line would be, and that small errors are more likely than large errors. We write our linear model with Gaussian noise like this:
The error term is draw from our Gaussian, and then our observed y is then calculated by adding the error to the output of the linear equation. This model has three parameters: the slope and intercept of our line and the variance of the noise distribution. Our main goal is to find the best parameters for the slope and intercept of our line.
To apply maximum likelihood, we first need to derive the likelihood function. First, let’s rewrite our model from above as a single conditional distribution given x:
This is equivalent to pushing our x through the equation of the line and then adding noise from the 0 mean Gaussian.
Now, we can write the conditional distribution of y given x in terms of this Gaussian. This is just the equation of a Gaussian distribution’s probability density function, with our linear equation in place of the mean:
The semicolon in the conditional distribution acts just like a comma, but it’s a useful notation for separating our observed data from the parameters.
Each point is independent and identically distributed (iid), so we can write the likelihood function with respect to all of our observed points as the product of each individual probability density. Since σ2 is the same for each data point, we can factor out the term of the Gaussian which doesn’t include x or y from the product:
(Note: Thanks to Tongxin for catching an error here. The term before the product should be raised to the number of data points because I factored it from the product.)
The next step in MLE, is to find the parameters which maximize this function. To make our equation simpler, let’s take the log of our likelihood. Recall, that maximizing the log-likelihood is the same as maximizing the likelihood since the log is monotonic. The natural log cancels out with the exponential, turns products into sums of logs, and division into subtraction of logs; so our log-likelihood looks much simpler:
To clean things up a bit more, let’s write the output of our line as a single value:
Now our log-likelihood can be written as:
To remove the negative signs, let’s recall that maximizing a number is the same thing as minimizing the negative of the number. So instead of maximizing the likelihood, let’s minimize the negative log-likelihood:
Our ultimate goal is to find the parameters of our line. To minimize the negative log-likelihood with respect to the linear parameters (the θs), we can imagine that our variance term is a fixed constant.
Removing any constant’s which don’t include our θs won’t alter the solution. Therefore, we can throw out any constant terms and elegantly write what we’re trying to minimize as:
The maximum likelihood estimate for our linear model is the line which minimizes the sum of squared errors! This is a beautiful result, and you’ll see that minimizing squared errors crops up everywhere in machine learning and statistics.
We’ve concluded that the maximum likelihood estimates for our slope and intercept can be found by minimizing the sum of squared errors. Let’s expand out our minimization objective and use i as our index over our n data points:
The square in the SSE formula makes it quadratic with a single minimum. The minimum can be found by taking the derivative with respect to each of the parameters, setting it equal to 0, and solving for the parameters in turn.
Let’s start by solving for the intercept. Taking the partial derivative with respect to the intercept and working through gives us:
The horizontal bars over the variables indicate the mean of those variables. We used the fact that the sum over the values of a variable is equal to the mean of those values multiplied by how many values we have. Setting the derivative equal to 0 and solving for the intercept gives us:
This is a pretty neat result. It’s the equation of the line, with the means of the x’s and y’s in place of those variables. The intercept still depends on the slope, so we’ll need to find that next.
We start by taking the partial derivative of the SSE with respect to our slope. We plug in our solution for the intercept and use algebra to isolate the slope term:
Setting this equal to 0 and solving for the slope gives us:
While we’re technically done, we can use some fancier algebra to rewrite this without having to use the n:
We can use these derived equations to write a simple function in python for solving the parameters for any line given at least two points:
def find_line(xs, ys): """Calculates the slope and intercept""" # number of points n = len(xs) # calculate means x_bar = sum(xs)/n y_bar = sum(ys)/n # calculate slope num = 0 denom = 0 for i in range(n): num += (xs[i]-x_bar)*(ys[i]-y_bar) denom += (xs[i]-x_bar)**2 slope = num/denom # calculate intercept intercept = y_bar - slope*x_bar return slope, intercept
Using this code, we can fit a line to our original data (see below). This is the maximum likelihood estimator for our data. The line minimizes the sum of squared errors, which is why this method of linear regression is often called ordinary least squares.
I wanted to write this post mostly to highlight the link between minimizing the sum of squared error and the maximum likelihood estimation approach to linear regression. Most people first learn to solve linear regression by minimizing the squared error, but it’s not generally understood that this is derived from a probabilistic model with baked in assumptions (like Gaussian distributed errors).
There is a more elegant solution for finding the parameters of this model, but it requires linear algebra. I plan to revisit linear regression after covering linear algebra in my fundamentals series, and show how it can be used to fit more complex curves like polynomials and exponentials.
See you next time!
|
[
{
"code": null,
"e": 162,
"s": 47,
"text": "I recently wrote about maximum likelihood estimation in my ongoing series on the fundamentals of machine learning:"
},
{
"code": null,
"e": 185,
"s": 162,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 858,
"s": 185,
"text": "In that post, we learned what it means to “model” data, and then how to use MLE to find the parameters of our model. In this post, we’re going to dive into linear regression, one of the most important models in statistics, and learn how to frame it in terms of MLE. The solution is a beautiful piece of mathematics, which like most MLE models, is rich with intuition. I’ll be assuming you’ve got a handle on the vocabulary I’ve covered in the other series (probability densities, conditional probabilities, likelihood function, iid data, etc.). If you see something here that you’re uncomfortable with, check out the Probability and MLE posts from that series for clarity."
},
{
"code": null,
"e": 1077,
"s": 858,
"text": "We use linear regression when our data has a linear relationship between the independent variables (our features) and the dependent variable (our target). In the MLE post, we saw some data that looked similar too this:"
},
{
"code": null,
"e": 1815,
"s": 1077,
"text": "We observed that there appears to be a linear relationship between x and y, but it’s not perfect. We think of these imperfections as coming from some error or noise process. Imagine drawing a line right through the cloud of points. The error for each point would be the distance from the point to our line. We’d like to explicitly include those errors in our model. One method of doing this, is to assume the errors are distributed from a Gaussian distribution with a mean of 0 and some unknown variance σ2. The Gaussian seems like a good choice, because our errors look like they’re symmetric about were the line would be, and that small errors are more likely than large errors. We write our linear model with Gaussian noise like this:"
},
{
"code": null,
"e": 2157,
"s": 1815,
"text": "The error term is draw from our Gaussian, and then our observed y is then calculated by adding the error to the output of the linear equation. This model has three parameters: the slope and intercept of our line and the variance of the noise distribution. Our main goal is to find the best parameters for the slope and intercept of our line."
},
{
"code": null,
"e": 2323,
"s": 2157,
"text": "To apply maximum likelihood, we first need to derive the likelihood function. First, let’s rewrite our model from above as a single conditional distribution given x:"
},
{
"code": null,
"e": 2440,
"s": 2323,
"text": "This is equivalent to pushing our x through the equation of the line and then adding noise from the 0 mean Gaussian."
},
{
"code": null,
"e": 2659,
"s": 2440,
"text": "Now, we can write the conditional distribution of y given x in terms of this Gaussian. This is just the equation of a Gaussian distribution’s probability density function, with our linear equation in place of the mean:"
},
{
"code": null,
"e": 2810,
"s": 2659,
"text": "The semicolon in the conditional distribution acts just like a comma, but it’s a useful notation for separating our observed data from the parameters."
},
{
"code": null,
"e": 3141,
"s": 2810,
"text": "Each point is independent and identically distributed (iid), so we can write the likelihood function with respect to all of our observed points as the product of each individual probability density. Since σ2 is the same for each data point, we can factor out the term of the Gaussian which doesn’t include x or y from the product:"
},
{
"code": null,
"e": 3309,
"s": 3141,
"text": "(Note: Thanks to Tongxin for catching an error here. The term before the product should be raised to the number of data points because I factored it from the product.)"
},
{
"code": null,
"e": 3732,
"s": 3309,
"text": "The next step in MLE, is to find the parameters which maximize this function. To make our equation simpler, let’s take the log of our likelihood. Recall, that maximizing the log-likelihood is the same as maximizing the likelihood since the log is monotonic. The natural log cancels out with the exponential, turns products into sums of logs, and division into subtraction of logs; so our log-likelihood looks much simpler:"
},
{
"code": null,
"e": 3817,
"s": 3732,
"text": "To clean things up a bit more, let’s write the output of our line as a single value:"
},
{
"code": null,
"e": 3859,
"s": 3817,
"text": "Now our log-likelihood can be written as:"
},
{
"code": null,
"e": 4072,
"s": 3859,
"text": "To remove the negative signs, let’s recall that maximizing a number is the same thing as minimizing the negative of the number. So instead of maximizing the likelihood, let’s minimize the negative log-likelihood:"
},
{
"code": null,
"e": 4276,
"s": 4072,
"text": "Our ultimate goal is to find the parameters of our line. To minimize the negative log-likelihood with respect to the linear parameters (the θs), we can imagine that our variance term is a fixed constant."
},
{
"code": null,
"e": 4454,
"s": 4276,
"text": "Removing any constant’s which don’t include our θs won’t alter the solution. Therefore, we can throw out any constant terms and elegantly write what we’re trying to minimize as:"
},
{
"code": null,
"e": 4692,
"s": 4454,
"text": "The maximum likelihood estimate for our linear model is the line which minimizes the sum of squared errors! This is a beautiful result, and you’ll see that minimizing squared errors crops up everywhere in machine learning and statistics."
},
{
"code": null,
"e": 4919,
"s": 4692,
"text": "We’ve concluded that the maximum likelihood estimates for our slope and intercept can be found by minimizing the sum of squared errors. Let’s expand out our minimization objective and use i as our index over our n data points:"
},
{
"code": null,
"e": 5144,
"s": 4919,
"text": "The square in the SSE formula makes it quadratic with a single minimum. The minimum can be found by taking the derivative with respect to each of the parameters, setting it equal to 0, and solving for the parameters in turn."
},
{
"code": null,
"e": 5276,
"s": 5144,
"text": "Let’s start by solving for the intercept. Taking the partial derivative with respect to the intercept and working through gives us:"
},
{
"code": null,
"e": 5563,
"s": 5276,
"text": "The horizontal bars over the variables indicate the mean of those variables. We used the fact that the sum over the values of a variable is equal to the mean of those values multiplied by how many values we have. Setting the derivative equal to 0 and solving for the intercept gives us:"
},
{
"code": null,
"e": 5762,
"s": 5563,
"text": "This is a pretty neat result. It’s the equation of the line, with the means of the x’s and y’s in place of those variables. The intercept still depends on the slope, so we’ll need to find that next."
},
{
"code": null,
"e": 5927,
"s": 5762,
"text": "We start by taking the partial derivative of the SSE with respect to our slope. We plug in our solution for the intercept and use algebra to isolate the slope term:"
},
{
"code": null,
"e": 5987,
"s": 5927,
"text": "Setting this equal to 0 and solving for the slope gives us:"
},
{
"code": null,
"e": 6094,
"s": 5987,
"text": "While we’re technically done, we can use some fancier algebra to rewrite this without having to use the n:"
},
{
"code": null,
"e": 6233,
"s": 6094,
"text": "We can use these derived equations to write a simple function in python for solving the parameters for any line given at least two points:"
},
{
"code": null,
"e": 6670,
"s": 6233,
"text": "def find_line(xs, ys): \"\"\"Calculates the slope and intercept\"\"\" # number of points n = len(xs) # calculate means x_bar = sum(xs)/n y_bar = sum(ys)/n # calculate slope num = 0 denom = 0 for i in range(n): num += (xs[i]-x_bar)*(ys[i]-y_bar) denom += (xs[i]-x_bar)**2 slope = num/denom # calculate intercept intercept = y_bar - slope*x_bar return slope, intercept"
},
{
"code": null,
"e": 6926,
"s": 6670,
"text": "Using this code, we can fit a line to our original data (see below). This is the maximum likelihood estimator for our data. The line minimizes the sum of squared errors, which is why this method of linear regression is often called ordinary least squares."
},
{
"code": null,
"e": 7324,
"s": 6926,
"text": "I wanted to write this post mostly to highlight the link between minimizing the sum of squared error and the maximum likelihood estimation approach to linear regression. Most people first learn to solve linear regression by minimizing the squared error, but it’s not generally understood that this is derived from a probabilistic model with baked in assumptions (like Gaussian distributed errors)."
},
{
"code": null,
"e": 7614,
"s": 7324,
"text": "There is a more elegant solution for finding the parameters of this model, but it requires linear algebra. I plan to revisit linear regression after covering linear algebra in my fundamentals series, and show how it can be used to fit more complex curves like polynomials and exponentials."
}
] |
MySQL - CONVERT_TZ() Function
|
The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time. MySQL provides a set of functions to manipulate these values.
UTC stands for Co-ordinated Universal Time. It is time standard and is commonly used across the world. The MYSQL CURDATE() is used to convert the given date from one time zone to another time zone. This function accepts 3 parameters −
date − The date value you need to convert.
date − The date value you need to convert.
from_tz − Current time zone of the date
from_tz − Current time zone of the date
to_tz − Time zone to which you need to convert the current date.
to_tz − Time zone to which you need to convert the current date.
Following is the list of various time zones –
GMT
Greenwich Mean Time
UTC
Universal Coordinated Time
ECT
European Central Time
EET
Eastern European Time
ART
(Arabic) Egypt Standard Time
EAT
Eastern African Time
MET
Middle East Time
NET
Near East Time
PLT
Pakistan Lahore Time
IST
India Standard Time
BST
Bangladesh Standard Time
VST
Vietnam Standard Time
CTT
China Taiwan Time
JST
Japan Standard Time
ACT
Australia Central Time
AET
Australia Eastern Time
SST
Solomon Standard Time
NST
New Zealand Standard Time
MIT
Midway Islands Time
HST
Hawaii Standard Time
AST
Alaska Standard Time
PST
Pacific Standard Time
PNT
Phoenix Standard Time
MST
Mountain Standard Time
CST
Central Standard Time
EST
Eastern Standard Time
IET
Indiana Eastern Standard Time
PRT
Puerto Rico and US Virgin Islands Time
CNT
Canada Newfoundland Time
AGT
Argentina Standard Time
BET
Brazil Eastern Time
CAT
Central African Time
Following is the syntax of the above function –
CONVERT_TZ(dt,from_tz,to_tz)
Following example demonstrates the usage of the CONVERT_TZ() function –
mysql> SELECT CONVERT_TZ('15:30:00','+00:00','+10:00');
+-----------------------------------------------------+
| CONVERT_TZ('2019-11-21 15:30:00','+00:00','+10:00') |
+-----------------------------------------------------+
| 2019-11-22 01:30:00 |
+-----------------------------------------------------+
1 row in set (0.00 sec)
Following is another example of this function –
mysql> SELECT CONVERT_TZ('1919-06-21 21:00:00','+00:00','+10:00');
+-----------------------------------------------------+
| CONVERT_TZ('1919-06-21 21:00:00','+00:00','+10:00') |
+-----------------------------------------------------+
| 1919-06-21 21:00:00 |
+-----------------------------------------------------+
1 row in set (0.00 sec)
Following query converts GMT(Greenwich Mean Time) to IST(Indian Standard time) –
mysql> SELECT CONVERT_TZ('1886-11-20 16:29:30', '+00:00','+05:30');
+------------------------------------------------------+
| CONVERT_TZ('1886-11-20 16:29:30', '+00:00','+05:30') |
+------------------------------------------------------+
| 1886-11-20 16:29:30 |
+------------------------------------------------------+
1 row in set (0.00 sec)
Following query converts IST(Indian Standard Time) to GMT(Gulf standard Time)
mysql> SELECT CONVERT_TZ('1886-11-20 16:29:30', '+05:30','+04:00');
+------------------------------------------------------+
| CONVERT_TZ('1886-11-20 16:29:30', '+05:30','+04:00') |
+------------------------------------------------------+
| 1886-11-20 16:29:30 |
+------------------------------------------------------+
1 row in set (0.00 sec)
Suppose we have created a table named dispatches_data with 5 records in it using the following queries –
mysql> CREATE TABLE dispatches_data(
ProductName VARCHAR(255),
CustomerName VARCHAR(255),
DispatchTimeStamp timestamp,
Price INT,
Location VARCHAR(255)
);
insert into dispatches_data values('Key-Board', 'Raja', TIMESTAMP('2019-05-04', '15:02:45'), 7000, 'Hyderabad');
insert into dispatches_data values('Earphones', 'Roja', TIMESTAMP('2019-06-26', '14:13:12'), 2000, 'Vishakhapatnam');
insert into dispatches_data values('Mouse', 'Puja', TIMESTAMP('2019-12-07', '07:50:37'), 3000, 'Vijayawada');
insert into dispatches_data values('Mobile', 'Vanaja' , TIMESTAMP ('2018-03-21', '16:00:45'), 9000, 'Chennai');
insert into dispatches_data values('Headset', 'Jalaja' , TIMESTAMP('2018-12-30', '10:49:27'), 6000, 'Goa');
Following query converts the date in DispatchTimeStamp from column GMT(Greenwich Mean Time) to IST(Indian Standard time) —
mysql> SELECT ProductName, CustomerName, DispatchTimeStamp, Price, CONVERT_TZ(DispatchTimeStamp, '+00:00','+05:30') FROM dispatches_data;
+-------------+--------------+---------------------+-------+--------------------------------------------------+
| ProductName | CustomerName | DispatchTimeStamp | Price | CONVERT_TZ(DispatchTimeStamp, '+00:00','+05:30') |
+-------------+--------------+---------------------+-------+--------------------------------------------------+
| Key-Board | Raja | 2019-05-04 15:02:45 | 7000 | 2019-05-04 20:32:45 |
| Earphones | Roja | 2019-06-26 14:13:12 | 2000 | 2019-06-26 19:43:12 |
| Mouse | Puja | 2019-12-07 07:50:37 | 3000 | 2019-12-07 13:20:37 |
| Mobile | Vanaja | 2018-03-21 16:00:45 | 9000 | 2018-03-21 21:30:45 |
| Headset | Jalaja | 2018-12-30 10:49:27 | 6000 | 2018-12-30 16:19:27 |
+-------------+--------------+---------------------+-------+--------------------------------------------------+
5 rows in set (0.00 sec)
Suppose we have created a table named SubscriberDetails with 5 records in it using the following queries –
mysql> CREATE TABLE SubscriberDetails (
SubscriberName VARCHAR(255),
PackageName VARCHAR(255),
SubscriptionTimeStamp timestamp
);
insert into SubscriberDetails values('Raja', 'Premium', TimeStamp('2020-10-21 20:53:49'));
insert into SubscriberDetails values('Roja', 'Basic', TimeStamp('2020-11-26 10:13:19'));
insert into SubscriberDetails values('Puja', 'Moderate', TimeStamp('2021-03-07 05:43:20'));
insert into SubscriberDetails values('Vanaja', 'Basic', TimeStamp('2021-02-21 16:36:39'));
insert into SubscriberDetails values('Jalaja', 'Premium', TimeStamp('2021-01-30 12:45:45'));
Following query converts the SubscriptionTimeStamp from GMT(Greenwich Mean Time) to PST(Pacific Standard Time) for all the records —
mysql> SELECT SubscriberName, PackageName, SubscriptionTimeStamp, CONVERT_TZ(SubscriptionTimeStamp, '+00:00','+08:00') FROM SubscriberDetails;
+----------------+-------------+-----------------------+------------------------------------------------------+
| SubscriberName | PackageName | SubscriptionTimeStamp | CONVERT_TZ(SubscriptionTimeStamp, '+00:00','+08:00') |
+----------------+-------------+-----------------------+------------------------------------------------------+
| Raja | Premium | 2020-10-21 20:53:49 | 2020-10-22 04:53:49 |
| Roja | Basic | 2020-11-26 10:13:19 | 2020-11-26 18:13:19 |
| Puja | Moderate | 2021-03-07 05:43:20 | 2021-03-07 13:43:20 |
| Vanaja | Basic | 2021-02-21 16:36:39 | 2021-02-22 00:36:39 |
| Jalaja | Premium | 2021-01-30 12:45:45 | 2021-01-30 20:45:45 |
+----------------+-------------+-----------------------+------------------------------------------------------+
5 rows 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": 2664,
"s": 2333,
"text": "The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time. MySQL provides a set of functions to manipulate these values."
},
{
"code": null,
"e": 2899,
"s": 2664,
"text": "UTC stands for Co-ordinated Universal Time. It is time standard and is commonly used across the world. The MYSQL CURDATE() is used to convert the given date from one time zone to another time zone. This function accepts 3 parameters −"
},
{
"code": null,
"e": 2942,
"s": 2899,
"text": "date − The date value you need to convert."
},
{
"code": null,
"e": 2985,
"s": 2942,
"text": "date − The date value you need to convert."
},
{
"code": null,
"e": 3025,
"s": 2985,
"text": "from_tz − Current time zone of the date"
},
{
"code": null,
"e": 3065,
"s": 3025,
"text": "from_tz − Current time zone of the date"
},
{
"code": null,
"e": 3130,
"s": 3065,
"text": "to_tz − Time zone to which you need to convert the current date."
},
{
"code": null,
"e": 3195,
"s": 3130,
"text": "to_tz − Time zone to which you need to convert the current date."
},
{
"code": null,
"e": 3241,
"s": 3195,
"text": "Following is the list of various time zones –"
},
{
"code": null,
"e": 3245,
"s": 3241,
"text": "GMT"
},
{
"code": null,
"e": 3265,
"s": 3245,
"text": "Greenwich Mean Time"
},
{
"code": null,
"e": 3269,
"s": 3265,
"text": "UTC"
},
{
"code": null,
"e": 3296,
"s": 3269,
"text": "Universal Coordinated Time"
},
{
"code": null,
"e": 3300,
"s": 3296,
"text": "ECT"
},
{
"code": null,
"e": 3322,
"s": 3300,
"text": "European Central Time"
},
{
"code": null,
"e": 3326,
"s": 3322,
"text": "EET"
},
{
"code": null,
"e": 3348,
"s": 3326,
"text": "Eastern European Time"
},
{
"code": null,
"e": 3352,
"s": 3348,
"text": "ART"
},
{
"code": null,
"e": 3381,
"s": 3352,
"text": "(Arabic) Egypt Standard Time"
},
{
"code": null,
"e": 3385,
"s": 3381,
"text": "EAT"
},
{
"code": null,
"e": 3406,
"s": 3385,
"text": "Eastern African Time"
},
{
"code": null,
"e": 3410,
"s": 3406,
"text": "MET"
},
{
"code": null,
"e": 3427,
"s": 3410,
"text": "Middle East Time"
},
{
"code": null,
"e": 3431,
"s": 3427,
"text": "NET"
},
{
"code": null,
"e": 3446,
"s": 3431,
"text": "Near East Time"
},
{
"code": null,
"e": 3450,
"s": 3446,
"text": "PLT"
},
{
"code": null,
"e": 3471,
"s": 3450,
"text": "Pakistan Lahore Time"
},
{
"code": null,
"e": 3475,
"s": 3471,
"text": "IST"
},
{
"code": null,
"e": 3495,
"s": 3475,
"text": "India Standard Time"
},
{
"code": null,
"e": 3499,
"s": 3495,
"text": "BST"
},
{
"code": null,
"e": 3524,
"s": 3499,
"text": "Bangladesh Standard Time"
},
{
"code": null,
"e": 3528,
"s": 3524,
"text": "VST"
},
{
"code": null,
"e": 3550,
"s": 3528,
"text": "Vietnam Standard Time"
},
{
"code": null,
"e": 3554,
"s": 3550,
"text": "CTT"
},
{
"code": null,
"e": 3572,
"s": 3554,
"text": "China Taiwan Time"
},
{
"code": null,
"e": 3576,
"s": 3572,
"text": "JST"
},
{
"code": null,
"e": 3596,
"s": 3576,
"text": "Japan Standard Time"
},
{
"code": null,
"e": 3600,
"s": 3596,
"text": "ACT"
},
{
"code": null,
"e": 3623,
"s": 3600,
"text": "Australia Central Time"
},
{
"code": null,
"e": 3627,
"s": 3623,
"text": "AET"
},
{
"code": null,
"e": 3650,
"s": 3627,
"text": "Australia Eastern Time"
},
{
"code": null,
"e": 3654,
"s": 3650,
"text": "SST"
},
{
"code": null,
"e": 3676,
"s": 3654,
"text": "Solomon Standard Time"
},
{
"code": null,
"e": 3680,
"s": 3676,
"text": "NST"
},
{
"code": null,
"e": 3706,
"s": 3680,
"text": "New Zealand Standard Time"
},
{
"code": null,
"e": 3710,
"s": 3706,
"text": "MIT"
},
{
"code": null,
"e": 3730,
"s": 3710,
"text": "Midway Islands Time"
},
{
"code": null,
"e": 3734,
"s": 3730,
"text": "HST"
},
{
"code": null,
"e": 3755,
"s": 3734,
"text": "Hawaii Standard Time"
},
{
"code": null,
"e": 3759,
"s": 3755,
"text": "AST"
},
{
"code": null,
"e": 3780,
"s": 3759,
"text": "Alaska Standard Time"
},
{
"code": null,
"e": 3784,
"s": 3780,
"text": "PST"
},
{
"code": null,
"e": 3806,
"s": 3784,
"text": "Pacific Standard Time"
},
{
"code": null,
"e": 3810,
"s": 3806,
"text": "PNT"
},
{
"code": null,
"e": 3832,
"s": 3810,
"text": "Phoenix Standard Time"
},
{
"code": null,
"e": 3836,
"s": 3832,
"text": "MST"
},
{
"code": null,
"e": 3859,
"s": 3836,
"text": "Mountain Standard Time"
},
{
"code": null,
"e": 3863,
"s": 3859,
"text": "CST"
},
{
"code": null,
"e": 3885,
"s": 3863,
"text": "Central Standard Time"
},
{
"code": null,
"e": 3889,
"s": 3885,
"text": "EST"
},
{
"code": null,
"e": 3911,
"s": 3889,
"text": "Eastern Standard Time"
},
{
"code": null,
"e": 3915,
"s": 3911,
"text": "IET"
},
{
"code": null,
"e": 3945,
"s": 3915,
"text": "Indiana Eastern Standard Time"
},
{
"code": null,
"e": 3949,
"s": 3945,
"text": "PRT"
},
{
"code": null,
"e": 3988,
"s": 3949,
"text": "Puerto Rico and US Virgin Islands Time"
},
{
"code": null,
"e": 3992,
"s": 3988,
"text": "CNT"
},
{
"code": null,
"e": 4017,
"s": 3992,
"text": "Canada Newfoundland Time"
},
{
"code": null,
"e": 4021,
"s": 4017,
"text": "AGT"
},
{
"code": null,
"e": 4045,
"s": 4021,
"text": "Argentina Standard Time"
},
{
"code": null,
"e": 4049,
"s": 4045,
"text": "BET"
},
{
"code": null,
"e": 4069,
"s": 4049,
"text": "Brazil Eastern Time"
},
{
"code": null,
"e": 4073,
"s": 4069,
"text": "CAT"
},
{
"code": null,
"e": 4094,
"s": 4073,
"text": "Central African Time"
},
{
"code": null,
"e": 4142,
"s": 4094,
"text": "Following is the syntax of the above function –"
},
{
"code": null,
"e": 4172,
"s": 4142,
"text": "CONVERT_TZ(dt,from_tz,to_tz)\n"
},
{
"code": null,
"e": 4244,
"s": 4172,
"text": "Following example demonstrates the usage of the CONVERT_TZ() function –"
},
{
"code": null,
"e": 4604,
"s": 4244,
"text": "mysql> SELECT CONVERT_TZ('15:30:00','+00:00','+10:00');\n+-----------------------------------------------------+\n| CONVERT_TZ('2019-11-21 15:30:00','+00:00','+10:00') |\n+-----------------------------------------------------+\n| 2019-11-22 01:30:00 |\n+-----------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 4652,
"s": 4604,
"text": "Following is another example of this function –"
},
{
"code": null,
"e": 5023,
"s": 4652,
"text": "mysql> SELECT CONVERT_TZ('1919-06-21 21:00:00','+00:00','+10:00');\n+-----------------------------------------------------+\n| CONVERT_TZ('1919-06-21 21:00:00','+00:00','+10:00') |\n+-----------------------------------------------------+\n| 1919-06-21 21:00:00 |\n+-----------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 5104,
"s": 5023,
"text": "Following query converts GMT(Greenwich Mean Time) to IST(Indian Standard time) –"
},
{
"code": null,
"e": 5481,
"s": 5104,
"text": "mysql> SELECT CONVERT_TZ('1886-11-20 16:29:30', '+00:00','+05:30');\n+------------------------------------------------------+\n| CONVERT_TZ('1886-11-20 16:29:30', '+00:00','+05:30') |\n+------------------------------------------------------+\n| 1886-11-20 16:29:30 |\n+------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 5559,
"s": 5481,
"text": "Following query converts IST(Indian Standard Time) to GMT(Gulf standard Time)"
},
{
"code": null,
"e": 5936,
"s": 5559,
"text": "mysql> SELECT CONVERT_TZ('1886-11-20 16:29:30', '+05:30','+04:00');\n+------------------------------------------------------+\n| CONVERT_TZ('1886-11-20 16:29:30', '+05:30','+04:00') |\n+------------------------------------------------------+\n| 1886-11-20 16:29:30 |\n+------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 6041,
"s": 5936,
"text": "Suppose we have created a table named dispatches_data with 5 records in it using the following queries –"
},
{
"code": null,
"e": 6762,
"s": 6041,
"text": "mysql> CREATE TABLE dispatches_data(\n\tProductName VARCHAR(255),\n\tCustomerName VARCHAR(255),\n\tDispatchTimeStamp timestamp,\n\tPrice INT,\n\tLocation VARCHAR(255)\n);\ninsert into dispatches_data values('Key-Board', 'Raja', TIMESTAMP('2019-05-04', '15:02:45'), 7000, 'Hyderabad');\ninsert into dispatches_data values('Earphones', 'Roja', TIMESTAMP('2019-06-26', '14:13:12'), 2000, 'Vishakhapatnam');\ninsert into dispatches_data values('Mouse', 'Puja', TIMESTAMP('2019-12-07', '07:50:37'), 3000, 'Vijayawada');\ninsert into dispatches_data values('Mobile', 'Vanaja' , TIMESTAMP ('2018-03-21', '16:00:45'), 9000, 'Chennai');\ninsert into dispatches_data values('Headset', 'Jalaja' , TIMESTAMP('2018-12-30', '10:49:27'), 6000, 'Goa');"
},
{
"code": null,
"e": 6885,
"s": 6762,
"text": "Following query converts the date in DispatchTimeStamp from column GMT(Greenwich Mean Time) to IST(Indian Standard time) —"
},
{
"code": null,
"e": 8056,
"s": 6885,
"text": "mysql> SELECT ProductName, CustomerName, DispatchTimeStamp, Price, CONVERT_TZ(DispatchTimeStamp, '+00:00','+05:30') FROM dispatches_data;\n+-------------+--------------+---------------------+-------+--------------------------------------------------+\n| ProductName | CustomerName | DispatchTimeStamp | Price | CONVERT_TZ(DispatchTimeStamp, '+00:00','+05:30') |\n+-------------+--------------+---------------------+-------+--------------------------------------------------+\n| Key-Board | Raja | 2019-05-04 15:02:45 | 7000 | 2019-05-04 20:32:45 |\n| Earphones | Roja | 2019-06-26 14:13:12 | 2000 | 2019-06-26 19:43:12 |\n| Mouse | Puja | 2019-12-07 07:50:37 | 3000 | 2019-12-07 13:20:37 |\n| Mobile | Vanaja | 2018-03-21 16:00:45 | 9000 | 2018-03-21 21:30:45 |\n| Headset | Jalaja | 2018-12-30 10:49:27 | 6000 | 2018-12-30 16:19:27 |\n+-------------+--------------+---------------------+-------+--------------------------------------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 8163,
"s": 8056,
"text": "Suppose we have created a table named SubscriberDetails with 5 records in it using the following queries –"
},
{
"code": null,
"e": 8752,
"s": 8163,
"text": "mysql> CREATE TABLE SubscriberDetails (\n\tSubscriberName VARCHAR(255),\n\tPackageName VARCHAR(255),\n\tSubscriptionTimeStamp timestamp\n);\ninsert into SubscriberDetails values('Raja', 'Premium', TimeStamp('2020-10-21 20:53:49'));\ninsert into SubscriberDetails values('Roja', 'Basic', TimeStamp('2020-11-26 10:13:19'));\ninsert into SubscriberDetails values('Puja', 'Moderate', TimeStamp('2021-03-07 05:43:20'));\ninsert into SubscriberDetails values('Vanaja', 'Basic', TimeStamp('2021-02-21 16:36:39'));\ninsert into SubscriberDetails values('Jalaja', 'Premium', TimeStamp('2021-01-30 12:45:45'));"
},
{
"code": null,
"e": 8885,
"s": 8752,
"text": "Following query converts the SubscriptionTimeStamp from GMT(Greenwich Mean Time) to PST(Pacific Standard Time) for all the records —"
},
{
"code": null,
"e": 10061,
"s": 8885,
"text": "mysql> SELECT SubscriberName, PackageName, SubscriptionTimeStamp, CONVERT_TZ(SubscriptionTimeStamp, '+00:00','+08:00') FROM SubscriberDetails;\n+----------------+-------------+-----------------------+------------------------------------------------------+\n| SubscriberName | PackageName | SubscriptionTimeStamp | CONVERT_TZ(SubscriptionTimeStamp, '+00:00','+08:00') |\n+----------------+-------------+-----------------------+------------------------------------------------------+\n| Raja | Premium | 2020-10-21 20:53:49 | 2020-10-22 04:53:49 |\n| Roja | Basic | 2020-11-26 10:13:19 | 2020-11-26 18:13:19 |\n| Puja | Moderate | 2021-03-07 05:43:20 | 2021-03-07 13:43:20 |\n| Vanaja | Basic | 2021-02-21 16:36:39 | 2021-02-22 00:36:39 |\n| Jalaja | Premium | 2021-01-30 12:45:45 | 2021-01-30 20:45:45 |\n+----------------+-------------+-----------------------+------------------------------------------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 10094,
"s": 10061,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10122,
"s": 10094,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10157,
"s": 10122,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 10174,
"s": 10157,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10208,
"s": 10174,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10243,
"s": 10208,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 10277,
"s": 10243,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 10305,
"s": 10277,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 10338,
"s": 10305,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10358,
"s": 10338,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 10391,
"s": 10358,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10409,
"s": 10391,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 10416,
"s": 10409,
"text": " Print"
},
{
"code": null,
"e": 10427,
"s": 10416,
"text": " Add Notes"
}
] |
Python | Convert key-value pair comma separated string into dictionary
|
19 Jun, 2020
Given a string, with different key-value pairs separated with commas, the task is to convert that string into the dictionary. These types of problems are common in web development where we fetch arguments from queries or get a response in the form of strings. Given below are a few methods to solve the task.
Method #1: Using dictionary comprehension
# Python3 code to demonstrate # converting comma separated string# into dictionary # Initialising stringini_string1 = 'name = akshat, course = btech, branch = computer' # Printing initial stringprint ("Initial String", ini_string1) # Converting string into dictionary# using dict comprehensionres = dict(item.split("=") for item in ini_string1.split(", ")) # Printing resultant stringprint ("Resultant dictionary", str(res))
Initial String name = akshat, course = btech, branch = computerResultant dictionary {‘branch ‘: ‘ computer’, ‘name ‘: ‘ akshat’, ‘course ‘: ‘ btech’}
Method #2: Using Map and lambda
# Python3 code to demonstrate # converting comma separated string# into dictionary # Initialising stringini_string1 = 'name = akshat, course = btech, branch = computer' # Printing initial stringprint ("Initial String", ini_string1) # Converting string into dictionary# using map and lambdares = dict(map(lambda x: x.split('='), ini_string1.split(', '))) # Printing resultant stringprint ("Resultant dictionary", str(res))
Initial String name = akshat, course = btech, branch = computerResultant dictionary {‘course ‘: ‘ btech’, ‘name ‘: ‘ akshat’, ‘branch ‘: ‘ computer’}
Method #3: Using eval() function
# Python3 code to demonstrate # converting comma separated string# into dictionary # Initialising stringini_string1 = 'name ="akshat", course ="btech", branch ="computer"' # Printing initial stringprint ("Initial String", ini_string1) # Converting string into dictionary# using evalres = eval('dict('+ini_string1+')') # Printing resultant stringprint ("Resultant dictionary", str(res))
Initial String name =”akshat”, course =”btech”, branch =”computer”Resultant dictionary {‘course’: ‘btech’, ‘name’: ‘akshat’, ‘branch’: ‘computer’}
nidhi_biet
Python dictionary-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jun, 2020"
},
{
"code": null,
"e": 337,
"s": 28,
"text": "Given a string, with different key-value pairs separated with commas, the task is to convert that string into the dictionary. These types of problems are common in web development where we fetch arguments from queries or get a response in the form of strings. Given below are a few methods to solve the task."
},
{
"code": null,
"e": 379,
"s": 337,
"text": "Method #1: Using dictionary comprehension"
},
{
"code": "# Python3 code to demonstrate # converting comma separated string# into dictionary # Initialising stringini_string1 = 'name = akshat, course = btech, branch = computer' # Printing initial stringprint (\"Initial String\", ini_string1) # Converting string into dictionary# using dict comprehensionres = dict(item.split(\"=\") for item in ini_string1.split(\", \")) # Printing resultant stringprint (\"Resultant dictionary\", str(res)) ",
"e": 821,
"s": 379,
"text": null
},
{
"code": null,
"e": 971,
"s": 821,
"text": "Initial String name = akshat, course = btech, branch = computerResultant dictionary {‘branch ‘: ‘ computer’, ‘name ‘: ‘ akshat’, ‘course ‘: ‘ btech’}"
},
{
"code": null,
"e": 1004,
"s": 971,
"text": " Method #2: Using Map and lambda"
},
{
"code": "# Python3 code to demonstrate # converting comma separated string# into dictionary # Initialising stringini_string1 = 'name = akshat, course = btech, branch = computer' # Printing initial stringprint (\"Initial String\", ini_string1) # Converting string into dictionary# using map and lambdares = dict(map(lambda x: x.split('='), ini_string1.split(', '))) # Printing resultant stringprint (\"Resultant dictionary\", str(res)) ",
"e": 1443,
"s": 1004,
"text": null
},
{
"code": null,
"e": 1593,
"s": 1443,
"text": "Initial String name = akshat, course = btech, branch = computerResultant dictionary {‘course ‘: ‘ btech’, ‘name ‘: ‘ akshat’, ‘branch ‘: ‘ computer’}"
},
{
"code": null,
"e": 1627,
"s": 1593,
"text": " Method #3: Using eval() function"
},
{
"code": "# Python3 code to demonstrate # converting comma separated string# into dictionary # Initialising stringini_string1 = 'name =\"akshat\", course =\"btech\", branch =\"computer\"' # Printing initial stringprint (\"Initial String\", ini_string1) # Converting string into dictionary# using evalres = eval('dict('+ini_string1+')') # Printing resultant stringprint (\"Resultant dictionary\", str(res)) ",
"e": 2028,
"s": 1627,
"text": null
},
{
"code": null,
"e": 2175,
"s": 2028,
"text": "Initial String name =”akshat”, course =”btech”, branch =”computer”Resultant dictionary {‘course’: ‘btech’, ‘name’: ‘akshat’, ‘branch’: ‘computer’}"
},
{
"code": null,
"e": 2186,
"s": 2175,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2213,
"s": 2186,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2236,
"s": 2213,
"text": "Python string-programs"
},
{
"code": null,
"e": 2243,
"s": 2236,
"text": "Python"
},
{
"code": null,
"e": 2259,
"s": 2243,
"text": "Python Programs"
}
] |
Python – Remove suffix from string list
|
14 Jun, 2022
Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings ending with specific suffix are removed. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + remove() + endswith() The combination of above functions can solve this problem. In this, we remove the elements that end with particular suffix accessed using loop and return the modified list.
Python3
# Python3 code to demonstrate working of# Suffix removal from String list# using loop + remove() + endswith() # initialize listtest_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] # printing original listprint("The original list : " + str(test_list)) # initialize suffixsuff = 'x' # Suffix removal from String list# using loop + remove() + endswith()for word in test_list[:]: if word.endswith(suff): test_list.remove(word) # printing resultprint("List after removal of suffix elements : " + str(test_list))
Method #2 : Using list comprehension + endswith() This is another way in which this task can be performed. In this, we don’t perform removal in place, instead, we recreate the list without the elements that match the suffix.
Python3
# Python3 code to demonstrate working of# Suffix removal from String list# using list comprehension + endswith() # initialize listtest_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] # printing original listprint("The original list : " + str(test_list)) # initialize suffsuff = 'x' # Suffix removal from String list# using list comprehension + endswith()res = [ele for ele in test_list if not ele.endswith(suff)] # printing resultprint("List after removal of suffix elements : " + str(res))
Method#3: Using filter function + endswith() This is another way in which task can be performed. In this, we can create new list with the help of filter function which filter out all the string which ends with defined suffix.
Python3
# Python3 code to demonstrate working of# Remove prefix strings from list# using filter + endswith() # initialize suffsuff = 'x' def eva(x): return not x.endswith(suff)# initialize listtest_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] # printing original listprint("The original list : " + str(test_list)) # Remove prefix strings from list# using filter + endswith()res = list(filter(eva, test_list)) # printing resultprint("List after removal of Kth character of each string : " + str(res))
The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of Kth character of each string : ['gfg', 'xit', 'is']
satyam00so
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 263,
"s": 28,
"text": "Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings ending with specific suffix are removed. Let’s discuss certain ways in which this task can be performed. "
},
{
"code": null,
"e": 484,
"s": 263,
"text": "Method #1 : Using loop + remove() + endswith() The combination of above functions can solve this problem. In this, we remove the elements that end with particular suffix accessed using loop and return the modified list. "
},
{
"code": null,
"e": 492,
"s": 484,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Suffix removal from String list# using loop + remove() + endswith() # initialize listtest_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] # printing original listprint(\"The original list : \" + str(test_list)) # initialize suffixsuff = 'x' # Suffix removal from String list# using loop + remove() + endswith()for word in test_list[:]: if word.endswith(suff): test_list.remove(word) # printing resultprint(\"List after removal of suffix elements : \" + str(test_list))",
"e": 1015,
"s": 492,
"text": null
},
{
"code": null,
"e": 1243,
"s": 1015,
"text": " Method #2 : Using list comprehension + endswith() This is another way in which this task can be performed. In this, we don’t perform removal in place, instead, we recreate the list without the elements that match the suffix. "
},
{
"code": null,
"e": 1251,
"s": 1243,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Suffix removal from String list# using list comprehension + endswith() # initialize listtest_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] # printing original listprint(\"The original list : \" + str(test_list)) # initialize suffsuff = 'x' # Suffix removal from String list# using list comprehension + endswith()res = [ele for ele in test_list if not ele.endswith(suff)] # printing resultprint(\"List after removal of suffix elements : \" + str(res))",
"e": 1748,
"s": 1251,
"text": null
},
{
"code": null,
"e": 1974,
"s": 1748,
"text": "Method#3: Using filter function + endswith() This is another way in which task can be performed. In this, we can create new list with the help of filter function which filter out all the string which ends with defined suffix."
},
{
"code": null,
"e": 1982,
"s": 1974,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove prefix strings from list# using filter + endswith() # initialize suffsuff = 'x' def eva(x): return not x.endswith(suff)# initialize listtest_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] # printing original listprint(\"The original list : \" + str(test_list)) # Remove prefix strings from list# using filter + endswith()res = list(filter(eva, test_list)) # printing resultprint(\"List after removal of Kth character of each string : \" + str(res))",
"e": 2486,
"s": 1982,
"text": null
},
{
"code": null,
"e": 2628,
"s": 2486,
"text": "The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']\nList after removal of Kth character of each string : ['gfg', 'xit', 'is']\n"
},
{
"code": null,
"e": 2639,
"s": 2628,
"text": "satyam00so"
},
{
"code": null,
"e": 2660,
"s": 2639,
"text": "Python list-programs"
},
{
"code": null,
"e": 2683,
"s": 2660,
"text": "Python string-programs"
},
{
"code": null,
"e": 2690,
"s": 2683,
"text": "Python"
},
{
"code": null,
"e": 2706,
"s": 2690,
"text": "Python Programs"
}
] |
Java Program to Access the Part of List as List
|
06 Jul, 2021
A List is an ordered sequence of elements stored together to form a collection. A list can contain duplicate as well as null entries. A list allows us to perform index-based operations, that is additions, deletions, manipulations, and positional access. Java provides an in-built interface <<java.util>> to perform list as well as other class-based functions.
Methods:
The naive approach by maintaining the start and end index.Using subList() method.
The naive approach by maintaining the start and end index.
Using subList() method.
Method 1
Elements are accessed at the required indexes of the list.Add them to a new empty list created.The start and end index values are used to access the part of the list required. By default, the indexes are assumed to start at 0.
Elements are accessed at the required indexes of the list.
Add them to a new empty list created.
The start and end index values are used to access the part of the list required. By default, the indexes are assumed to start at 0.
This approach requires an additional space of maintaining a new list to store the sublist desired.
Example
Java
// Java Program to Access the Part of List as List // Importing utility and input/output java classesimport java.util.*;import java.io.*;// Importing Iterator classimport java.util.Iterator; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring a list List<Integer> list1 = new ArrayList<Integer>(); // Adding elements to list1 list1.add(1); list1.add(7); list1.add(8); list1.add(2); list1.add(11); list1.add(3); list1.add(66); list1.add(30); // Print the original List System.out.println("The original list contents : "); Iterator iterator = list1.iterator(); // Iterating over elements using hasNext() // which holds true till // there is further more element in the List while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } // Declaring a new List to store sublist List<Integer> new_list = new ArrayList<Integer>(); // Maintaining and Setting counter to zero int i = 0; // Specifying the positions of the list to access // custom int start_indx = 2, end_indx = 5; // Condition check which holds true till // current counter value is less than size of List while (i < list1.size()) { // Checking if counter is in range of start and // end indx if (i >= start_indx && i <= end_indx) { // Adding element to new List new_list.add(list1.get(i)); } // Incrementing counter i++; } // Print all element of List System.out.println(); // Display message System.out.println("The sublist contents : "); // Iterator iterator = new_list.iterator(); // Iterating over elements using hasNext() method // which holds true till further element is // remaining in List else returns false while (iterator.hasNext()) { // Print the elements of subList System.out.print(iterator.next() + " "); } }}
The original list contents :
1 7 8 2 11 3 66 30
The sublist contents :
8 2 11 3
Time Complexity = O(n)
Space Complexity = O(n) where n is the size of the list.
Method 2: Java provides us with an in-built method sublist() to access the elements belonging to the specified range of index values. The method is provided by the ArrayList package.
Syntax :
public List subList(int fromIndex, int toIndex)
Parameters:
fromIndex = start index
toIndex = endIndex
Return Type: A list of the required elements. The method access all the elements in the range fromIndex to toIndex-1. If fromIndex is equal to toIndex, an empty list is returned.
Example:
Java
// Java Program to Access the Part of List as List // Importing java utility package, and// all classes of input/output libraryimport java.util.*;import java.util.Iterator;import java.io.*; class AccessSublist { // Main driver method public static void main(String[] args) { // Declaring a List of String type List<String> list1 = new ArrayList<String>(); // Adding elements to above List(List1) // Custom inputs list1.add("Are"); list1.add("you"); list1.add("working!"); list1.add("hard"); list1.add("Geeeks?"); // Display message System.out.print("The original list contents : "); // Iterator Iterator iterator = list1.iterator(); // Iterating over elements using hasNext() // which holds true till there is // further more element present in List while (iterator.hasNext()) { // Print the original List System.out.print(iterator.next() + " "); } // Extracting the contents of the list // index between 0 and 2 (custom) List<String> new_list = list1.subList(0, 3); // Print System.out.println(); // Display message System.out.print("The sublist contents : "); // Iterator iterator = new_list.iterator(); // Iterating over elements using hasNext() // which holds true till there is // further more element present in List while (iterator.hasNext()) { // Print the sublist(list2) System.out.print(iterator.next() + " "); } }}
The original list contents : Are you working! hard Geeeks?
The sublist contents : Are you working!
sweetyty
anikaseth98
java-list
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 389,
"s": 28,
"text": "A List is an ordered sequence of elements stored together to form a collection. A list can contain duplicate as well as null entries. A list allows us to perform index-based operations, that is additions, deletions, manipulations, and positional access. Java provides an in-built interface <<java.util>> to perform list as well as other class-based functions. "
},
{
"code": null,
"e": 398,
"s": 389,
"text": "Methods:"
},
{
"code": null,
"e": 480,
"s": 398,
"text": "The naive approach by maintaining the start and end index.Using subList() method."
},
{
"code": null,
"e": 539,
"s": 480,
"text": "The naive approach by maintaining the start and end index."
},
{
"code": null,
"e": 563,
"s": 539,
"text": "Using subList() method."
},
{
"code": null,
"e": 572,
"s": 563,
"text": "Method 1"
},
{
"code": null,
"e": 799,
"s": 572,
"text": "Elements are accessed at the required indexes of the list.Add them to a new empty list created.The start and end index values are used to access the part of the list required. By default, the indexes are assumed to start at 0."
},
{
"code": null,
"e": 858,
"s": 799,
"text": "Elements are accessed at the required indexes of the list."
},
{
"code": null,
"e": 896,
"s": 858,
"text": "Add them to a new empty list created."
},
{
"code": null,
"e": 1028,
"s": 896,
"text": "The start and end index values are used to access the part of the list required. By default, the indexes are assumed to start at 0."
},
{
"code": null,
"e": 1127,
"s": 1028,
"text": "This approach requires an additional space of maintaining a new list to store the sublist desired."
},
{
"code": null,
"e": 1135,
"s": 1127,
"text": "Example"
},
{
"code": null,
"e": 1140,
"s": 1135,
"text": "Java"
},
{
"code": "// Java Program to Access the Part of List as List // Importing utility and input/output java classesimport java.util.*;import java.io.*;// Importing Iterator classimport java.util.Iterator; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring a list List<Integer> list1 = new ArrayList<Integer>(); // Adding elements to list1 list1.add(1); list1.add(7); list1.add(8); list1.add(2); list1.add(11); list1.add(3); list1.add(66); list1.add(30); // Print the original List System.out.println(\"The original list contents : \"); Iterator iterator = list1.iterator(); // Iterating over elements using hasNext() // which holds true till // there is further more element in the List while (iterator.hasNext()) { System.out.print(iterator.next() + \" \"); } // Declaring a new List to store sublist List<Integer> new_list = new ArrayList<Integer>(); // Maintaining and Setting counter to zero int i = 0; // Specifying the positions of the list to access // custom int start_indx = 2, end_indx = 5; // Condition check which holds true till // current counter value is less than size of List while (i < list1.size()) { // Checking if counter is in range of start and // end indx if (i >= start_indx && i <= end_indx) { // Adding element to new List new_list.add(list1.get(i)); } // Incrementing counter i++; } // Print all element of List System.out.println(); // Display message System.out.println(\"The sublist contents : \"); // Iterator iterator = new_list.iterator(); // Iterating over elements using hasNext() method // which holds true till further element is // remaining in List else returns false while (iterator.hasNext()) { // Print the elements of subList System.out.print(iterator.next() + \" \"); } }}",
"e": 3334,
"s": 1140,
"text": null
},
{
"code": null,
"e": 3420,
"s": 3337,
"text": "The original list contents : \n1 7 8 2 11 3 66 30 \nThe sublist contents : \n8 2 11 3"
},
{
"code": null,
"e": 3443,
"s": 3420,
"text": "Time Complexity = O(n)"
},
{
"code": null,
"e": 3500,
"s": 3443,
"text": "Space Complexity = O(n) where n is the size of the list."
},
{
"code": null,
"e": 3685,
"s": 3502,
"text": "Method 2: Java provides us with an in-built method sublist() to access the elements belonging to the specified range of index values. The method is provided by the ArrayList package."
},
{
"code": null,
"e": 3697,
"s": 3687,
"text": "Syntax : "
},
{
"code": null,
"e": 3747,
"s": 3699,
"text": "public List subList(int fromIndex, int toIndex)"
},
{
"code": null,
"e": 3762,
"s": 3749,
"text": "Parameters: "
},
{
"code": null,
"e": 3788,
"s": 3764,
"text": "fromIndex = start index"
},
{
"code": null,
"e": 3807,
"s": 3788,
"text": "toIndex = endIndex"
},
{
"code": null,
"e": 3989,
"s": 3809,
"text": "Return Type: A list of the required elements. The method access all the elements in the range fromIndex to toIndex-1. If fromIndex is equal to toIndex, an empty list is returned. "
},
{
"code": null,
"e": 4000,
"s": 3991,
"text": "Example:"
},
{
"code": null,
"e": 4007,
"s": 4002,
"text": "Java"
},
{
"code": "// Java Program to Access the Part of List as List // Importing java utility package, and// all classes of input/output libraryimport java.util.*;import java.util.Iterator;import java.io.*; class AccessSublist { // Main driver method public static void main(String[] args) { // Declaring a List of String type List<String> list1 = new ArrayList<String>(); // Adding elements to above List(List1) // Custom inputs list1.add(\"Are\"); list1.add(\"you\"); list1.add(\"working!\"); list1.add(\"hard\"); list1.add(\"Geeeks?\"); // Display message System.out.print(\"The original list contents : \"); // Iterator Iterator iterator = list1.iterator(); // Iterating over elements using hasNext() // which holds true till there is // further more element present in List while (iterator.hasNext()) { // Print the original List System.out.print(iterator.next() + \" \"); } // Extracting the contents of the list // index between 0 and 2 (custom) List<String> new_list = list1.subList(0, 3); // Print System.out.println(); // Display message System.out.print(\"The sublist contents : \"); // Iterator iterator = new_list.iterator(); // Iterating over elements using hasNext() // which holds true till there is // further more element present in List while (iterator.hasNext()) { // Print the sublist(list2) System.out.print(iterator.next() + \" \"); } }}",
"e": 5626,
"s": 4007,
"text": null
},
{
"code": null,
"e": 5729,
"s": 5629,
"text": "The original list contents : Are you working! hard Geeeks? \nThe sublist contents : Are you working!"
},
{
"code": null,
"e": 5740,
"s": 5731,
"text": "sweetyty"
},
{
"code": null,
"e": 5752,
"s": 5740,
"text": "anikaseth98"
},
{
"code": null,
"e": 5762,
"s": 5752,
"text": "java-list"
},
{
"code": null,
"e": 5769,
"s": 5762,
"text": "Picked"
},
{
"code": null,
"e": 5774,
"s": 5769,
"text": "Java"
},
{
"code": null,
"e": 5788,
"s": 5774,
"text": "Java Programs"
},
{
"code": null,
"e": 5793,
"s": 5788,
"text": "Java"
}
] |
Matplotlib.pyplot.annotate() in Python
|
12 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 annotate() function in pyplot module of matplotlib library is used to annotate the point xy with text s.
Syntax: angle_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning, pad_to=None, sides=’default’, **kwargs)
Parameters: This method accept the following parameters that are described below:
s: This parameter is the text of the annotation.
xy: This parameter is the point (x, y) to annotate.
xytext: This parameter is an optional parameter. It is The position (x, y) to place the text at.
xycoords: This parameter is also an optional parameter and contains the string value.
textcoords: This parameter contains the string value.Coordinate system that xytext is given, which may be different than the coordinate system used for xy
arrowprops : This parameter is also an optional parameter and contains dict type.Its default value is None.
annotation_clip : This parameter is also an optional parameter and contains boolean value.Its default value is None which behaves as True.
Returns: This method returns the annotation.
Below examples illustrate the matplotlib.pyplot.annotate() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib.pyplot.annotate()# function import matplotlib.pyplot as pltimport numpy as np fig, geeeks = plt.subplots() t = np.arange(0.0, 5.0, 0.001)s = np.cos(3 * np.pi * t)line = geeeks.plot(t, s, lw = 2) # Annotationgeeeks.annotate('Local Max', xy =(3.3, 1), xytext =(3, 1.8), arrowprops = dict(facecolor ='green', shrink = 0.05),) geeeks.set_ylim(-2, 2) # Plot the Annotation in the graphplt.show()
Output:
Example #2:
# Implementation of matplotlib.pyplot.annotate()# function import numpy as npimport matplotlib.pyplot as plt x = np.arange(0, 10, 0.005)y = np.exp(-x / 3.) * np.sin(3 * np.pi * x) fig, ax = plt.subplots()ax.plot(x, y)ax.set_xlim(0, 10)ax.set_ylim(-1, 1) # Setting up the parametersxdata, ydata = 5, 0xdisplay, ydisplay = ax.transData.transform((xdata, ydata)) bbox = dict(boxstyle ="round", fc ="0.8")arrowprops = dict( arrowstyle = "->", connectionstyle = "angle, angleA = 0, angleB = 90,\ rad = 10") offset = 72 # Annotationax.annotate('data = (%.1f, %.1f)'%(xdata, ydata), (xdata, ydata), xytext =(-2 * offset, offset), textcoords ='offset points', bbox = bbox, arrowprops = arrowprops) disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay), (xdisplay, ydisplay), xytext =(0.5 * offset, -offset), xycoords ='figure pixels', textcoords ='offset points', bbox = bbox, arrowprops = arrowprops) # To display the annotationplt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 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": 332,
"s": 223,
"text": "The annotate() function in pyplot module of matplotlib library is used to annotate the point xy with text s."
},
{
"code": null,
"e": 438,
"s": 332,
"text": "Syntax: angle_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning, pad_to=None, sides=’default’, **kwargs)"
},
{
"code": null,
"e": 520,
"s": 438,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 569,
"s": 520,
"text": "s: This parameter is the text of the annotation."
},
{
"code": null,
"e": 621,
"s": 569,
"text": "xy: This parameter is the point (x, y) to annotate."
},
{
"code": null,
"e": 718,
"s": 621,
"text": "xytext: This parameter is an optional parameter. It is The position (x, y) to place the text at."
},
{
"code": null,
"e": 804,
"s": 718,
"text": "xycoords: This parameter is also an optional parameter and contains the string value."
},
{
"code": null,
"e": 959,
"s": 804,
"text": "textcoords: This parameter contains the string value.Coordinate system that xytext is given, which may be different than the coordinate system used for xy"
},
{
"code": null,
"e": 1067,
"s": 959,
"text": "arrowprops : This parameter is also an optional parameter and contains dict type.Its default value is None."
},
{
"code": null,
"e": 1206,
"s": 1067,
"text": "annotation_clip : This parameter is also an optional parameter and contains boolean value.Its default value is None which behaves as True."
},
{
"code": null,
"e": 1251,
"s": 1206,
"text": "Returns: This method returns the annotation."
},
{
"code": null,
"e": 1341,
"s": 1251,
"text": "Below examples illustrate the matplotlib.pyplot.annotate() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 1353,
"s": 1341,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib.pyplot.annotate()# function import matplotlib.pyplot as pltimport numpy as np fig, geeeks = plt.subplots() t = np.arange(0.0, 5.0, 0.001)s = np.cos(3 * np.pi * t)line = geeeks.plot(t, s, lw = 2) # Annotationgeeeks.annotate('Local Max', xy =(3.3, 1), xytext =(3, 1.8), arrowprops = dict(facecolor ='green', shrink = 0.05),) geeeks.set_ylim(-2, 2) # Plot the Annotation in the graphplt.show()",
"e": 1847,
"s": 1353,
"text": null
},
{
"code": null,
"e": 1855,
"s": 1847,
"text": "Output:"
},
{
"code": null,
"e": 1867,
"s": 1855,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib.pyplot.annotate()# function import numpy as npimport matplotlib.pyplot as plt x = np.arange(0, 10, 0.005)y = np.exp(-x / 3.) * np.sin(3 * np.pi * x) fig, ax = plt.subplots()ax.plot(x, y)ax.set_xlim(0, 10)ax.set_ylim(-1, 1) # Setting up the parametersxdata, ydata = 5, 0xdisplay, ydisplay = ax.transData.transform((xdata, ydata)) bbox = dict(boxstyle =\"round\", fc =\"0.8\")arrowprops = dict( arrowstyle = \"->\", connectionstyle = \"angle, angleA = 0, angleB = 90,\\ rad = 10\") offset = 72 # Annotationax.annotate('data = (%.1f, %.1f)'%(xdata, ydata), (xdata, ydata), xytext =(-2 * offset, offset), textcoords ='offset points', bbox = bbox, arrowprops = arrowprops) disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay), (xdisplay, ydisplay), xytext =(0.5 * offset, -offset), xycoords ='figure pixels', textcoords ='offset points', bbox = bbox, arrowprops = arrowprops) # To display the annotationplt.show()",
"e": 2907,
"s": 1867,
"text": null
},
{
"code": null,
"e": 2915,
"s": 2907,
"text": "Output:"
},
{
"code": null,
"e": 2933,
"s": 2915,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2940,
"s": 2933,
"text": "Python"
}
] |
time.Minutes() Function in Golang With Examples
|
21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Minutes() function in Go language is used to find the duration of time in the form of a floating-point number of minutes. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (d Duration) Minutes() float64
Here, d is the duration of time.
Return Value: It returns the duration value as float64.
Example 1:
// Golang program to illustrate the usage of// Minutes() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Calling mainfunc main() { // Defining duration // of Minutes method min, _ := time.ParseDuration("34h") // Prints duration as a // floating point number fmt.Printf("Only %.1f minutes of"+ " task is remaining.", min.Minutes())}
Output:
Only 2040.0 minutes of task is remaining.
Example 2:
// Golang program to illustrate the usage of// Minutes() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Calling mainfunc main() { // Defining duration of // Minutes method min, _ := time.ParseDuration("3m4534s64376378ns") // Prints duration as a // floating point number fmt.Printf("Only %.1f minutes of"+ " task is remaining.", min.Minutes())}
Output:
Only 78.6 minutes of task is remaining.
GoLang-time
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": "\n21 Apr, 2020"
},
{
"code": null,
"e": 384,
"s": 28,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Minutes() function in Go language is used to find the duration of time in the form of a floating-point number of minutes. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 392,
"s": 384,
"text": "Syntax:"
},
{
"code": null,
"e": 429,
"s": 392,
"text": "func (d Duration) Minutes() float64\n"
},
{
"code": null,
"e": 462,
"s": 429,
"text": "Here, d is the duration of time."
},
{
"code": null,
"e": 518,
"s": 462,
"text": "Return Value: It returns the duration value as float64."
},
{
"code": null,
"e": 529,
"s": 518,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// Minutes() function // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Calling mainfunc main() { // Defining duration // of Minutes method min, _ := time.ParseDuration(\"34h\") // Prints duration as a // floating point number fmt.Printf(\"Only %.1f minutes of\"+ \" task is remaining.\", min.Minutes())}",
"e": 948,
"s": 529,
"text": null
},
{
"code": null,
"e": 956,
"s": 948,
"text": "Output:"
},
{
"code": null,
"e": 999,
"s": 956,
"text": "Only 2040.0 minutes of task is remaining.\n"
},
{
"code": null,
"e": 1010,
"s": 999,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// Minutes() function // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Calling mainfunc main() { // Defining duration of // Minutes method min, _ := time.ParseDuration(\"3m4534s64376378ns\") // Prints duration as a // floating point number fmt.Printf(\"Only %.1f minutes of\"+ \" task is remaining.\", min.Minutes())}",
"e": 1441,
"s": 1010,
"text": null
},
{
"code": null,
"e": 1449,
"s": 1441,
"text": "Output:"
},
{
"code": null,
"e": 1490,
"s": 1449,
"text": "Only 78.6 minutes of task is remaining.\n"
},
{
"code": null,
"e": 1502,
"s": 1490,
"text": "GoLang-time"
},
{
"code": null,
"e": 1514,
"s": 1502,
"text": "Go Language"
}
] |
PHP | checkdate() Function
|
10 Sep, 2021
The checkdate() function is a built-in function in PHP which checks the validity of the date passed in the arguments. It accepts the date in the format mm/dd/yyyy. The function returns a boolean value. It returns true if the date is a valid one, else it returns false.
Syntax:
checkdate ( $month, $day, $year )
Parameters: The function accepts three mandatory parameters as shown above and described below:
$month – This parameter specifies the month. The month has to be in between 1 to 12 for a valid date.$day – This parameter specifies the day. The day can be in range 1-31 depending on the month entered for it to be a valid day. In case of a leap year, the day is in range 1-29 and for a non-leap year the day is in range 1-28.$year – This parameter specifies the year. The year has to be in range 1-32767 inclusive depending on the $month and $day for it to be a valid date.
$month – This parameter specifies the month. The month has to be in between 1 to 12 for a valid date.
$day – This parameter specifies the day. The day can be in range 1-31 depending on the month entered for it to be a valid day. In case of a leap year, the day is in range 1-29 and for a non-leap year the day is in range 1-28.
$year – This parameter specifies the year. The year has to be in range 1-32767 inclusive depending on the $month and $day for it to be a valid date.
Return Value: The function returns a boolean value. It returns true if the passed date is a valid date. It returns false if the passed date is not a valid one. Examples:
Input : $month = 12 $day = 31 $year = 2017
Output : true
Input : $month = 2 $day = 29 $year = 2016
Output : true
Input : $month = 2 $day = 29 $year = 2017
Output : false
Below programs illustrate the checkdate() function in PHP :Program 1: The program below check if the date is a valid one or not.
php
<?php// PHP program to demonstrate the checkdate() function $month = 12;$day = 31;$year = 2017; // returns a boolean value after validation of datevar_dump(checkdate($month, $day, $year)); ?>
Output:
bool(true)
Program 2: The program below check if the date is a valid one or not in case of a leap year and non-leap year.
php
<?php// PHP program to demonstrate the checkdate() function// in case of leap year $month = 2;$day = 29;$year = 2016; // returns a boolean value after validation of date// leap yearvar_dump(checkdate($month, $day, $year)); $month = 2;$day = 29;$year = 2017; // returns a boolean value after validation of date// non-leap yearvar_dump(checkdate($month, $day, $year)); ?>
Output:
bool(true)
bool(false)
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
adnanirshad158
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 299,
"s": 28,
"text": "The checkdate() function is a built-in function in PHP which checks the validity of the date passed in the arguments. It accepts the date in the format mm/dd/yyyy. The function returns a boolean value. It returns true if the date is a valid one, else it returns false. "
},
{
"code": null,
"e": 309,
"s": 299,
"text": "Syntax: "
},
{
"code": null,
"e": 343,
"s": 309,
"text": "checkdate ( $month, $day, $year )"
},
{
"code": null,
"e": 441,
"s": 343,
"text": "Parameters: The function accepts three mandatory parameters as shown above and described below: "
},
{
"code": null,
"e": 916,
"s": 441,
"text": "$month – This parameter specifies the month. The month has to be in between 1 to 12 for a valid date.$day – This parameter specifies the day. The day can be in range 1-31 depending on the month entered for it to be a valid day. In case of a leap year, the day is in range 1-29 and for a non-leap year the day is in range 1-28.$year – This parameter specifies the year. The year has to be in range 1-32767 inclusive depending on the $month and $day for it to be a valid date."
},
{
"code": null,
"e": 1018,
"s": 916,
"text": "$month – This parameter specifies the month. The month has to be in between 1 to 12 for a valid date."
},
{
"code": null,
"e": 1244,
"s": 1018,
"text": "$day – This parameter specifies the day. The day can be in range 1-31 depending on the month entered for it to be a valid day. In case of a leap year, the day is in range 1-29 and for a non-leap year the day is in range 1-28."
},
{
"code": null,
"e": 1393,
"s": 1244,
"text": "$year – This parameter specifies the year. The year has to be in range 1-32767 inclusive depending on the $month and $day for it to be a valid date."
},
{
"code": null,
"e": 1565,
"s": 1393,
"text": "Return Value: The function returns a boolean value. It returns true if the passed date is a valid date. It returns false if the passed date is not a valid one. Examples: "
},
{
"code": null,
"e": 1738,
"s": 1565,
"text": "Input : $month = 12 $day = 31 $year = 2017\nOutput : true\n\nInput : $month = 2 $day = 29 $year = 2016\nOutput : true \n\nInput : $month = 2 $day = 29 $year = 2017\nOutput : false"
},
{
"code": null,
"e": 1868,
"s": 1738,
"text": "Below programs illustrate the checkdate() function in PHP :Program 1: The program below check if the date is a valid one or not. "
},
{
"code": null,
"e": 1872,
"s": 1868,
"text": "php"
},
{
"code": "<?php// PHP program to demonstrate the checkdate() function $month = 12;$day = 31;$year = 2017; // returns a boolean value after validation of datevar_dump(checkdate($month, $day, $year)); ?>",
"e": 2064,
"s": 1872,
"text": null
},
{
"code": null,
"e": 2073,
"s": 2064,
"text": "Output: "
},
{
"code": null,
"e": 2084,
"s": 2073,
"text": "bool(true)"
},
{
"code": null,
"e": 2197,
"s": 2084,
"text": "Program 2: The program below check if the date is a valid one or not in case of a leap year and non-leap year. "
},
{
"code": null,
"e": 2201,
"s": 2197,
"text": "php"
},
{
"code": "<?php// PHP program to demonstrate the checkdate() function// in case of leap year $month = 2;$day = 29;$year = 2016; // returns a boolean value after validation of date// leap yearvar_dump(checkdate($month, $day, $year)); $month = 2;$day = 29;$year = 2017; // returns a boolean value after validation of date// non-leap yearvar_dump(checkdate($month, $day, $year)); ?>",
"e": 2572,
"s": 2201,
"text": null
},
{
"code": null,
"e": 2582,
"s": 2572,
"text": "Output: "
},
{
"code": null,
"e": 2605,
"s": 2582,
"text": "bool(true)\nbool(false)"
},
{
"code": null,
"e": 2774,
"s": 2605,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 2789,
"s": 2774,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2793,
"s": 2789,
"text": "PHP"
},
{
"code": null,
"e": 2810,
"s": 2793,
"text": "Web Technologies"
},
{
"code": null,
"e": 2814,
"s": 2810,
"text": "PHP"
}
] |
HTML5 <header> Tag
|
17 Mar, 2022
The <header> tag in HTML is used to define the header for a document or a section as it contains the information related to the title and heading of the related content. The <header> element is intended to usually contain the section’s heading (an h1-h6 element or an <hgroup> element), but this is not required. It can also be used to wrap a section’s table of contents, a search form, or any relevant logos. The <header> tag is a new tag in HTML5 and it is a container tag ie., it contains a starting tag, content & the end tag. There can be several <header> elements in one document. This tag cannot be placed within a <footer>, <address> or another <header> element.
Syntax:
<header> ...</header>
Attributes: This tag supports all the global attributes in HTML.
The below examples illustrate the <header> element in HTML.
Example 1: This example illustrates the use of the <header> tag that makes the container for the head section of the document.
HTML
<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML Header Tag</h3> <hr> <article> <header> <h3>GeeksforGeeks Learning</h3> <p>Posted by GFG</p> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. </p> </header> </article></body></html>
Output:
HTML <header> Tag
Example 2: In this example, we have used the <header> tag to contain the surrounding section’s heading, but not required every time.
HTML
<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML Header Tag</h3> <!--HTML header tag starts here--> <header> <h1>This is the heading.</h1> <h4>This is the sub-heading.</h4> <p>This is the metadata.</p> </header> <!--HTML header tag ends here--></body></html>
Output:
HTML <header> Tag
Example 3: In this example, we have represented navigational aids by using the <header> tag.
HTML
<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML Header Tag</h3> <!--HTML header tag starts here--> <header> <a href="https://www.geeksforgeeks.org/fundamentals-of-algorithms/"> Algo</a> | <a href="https://www.geeksforgeeks.org/data-structures/"> DS</a> | <a href="https://www.geeksforgeeks.org/category/program-output/"> Languages</a> | <a href="https://www.geeksforgeeks.org/company-interview-corner/"> Interview</a> | <a href="https://www.geeksforgeeks.org/student-corner/"> Students</a> | <a href="https://www.geeksforgeeks.org/gate-cs-notes-gq/"> Gate</a> | <a href="https://www.geeksforgeeks.org/articles-on-computer-science-subjects-gq/"> CS Subjects</a> | <a href="https://www.geeksforgeeks.org/quiz-corner-gq/"> Quizzes</a> </header> <!--HTML header tag ends here--></body></html>
Output:
HTML <header> Tag
Supported Browsers:
Google Chrome 93.0 & above
Internet Explorer 11.0
Microsoft Edge 93.0
Firefox 92.0 & above
Opera 79.0
Safari 14.1
HTML is the foundation of web pages, is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
shubhamyadav4
bhaskargeeksforgeeks
HTML-Tags
HTML5
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 724,
"s": 53,
"text": "The <header> tag in HTML is used to define the header for a document or a section as it contains the information related to the title and heading of the related content. The <header> element is intended to usually contain the section’s heading (an h1-h6 element or an <hgroup> element), but this is not required. It can also be used to wrap a section’s table of contents, a search form, or any relevant logos. The <header> tag is a new tag in HTML5 and it is a container tag ie., it contains a starting tag, content & the end tag. There can be several <header> elements in one document. This tag cannot be placed within a <footer>, <address> or another <header> element."
},
{
"code": null,
"e": 732,
"s": 724,
"text": "Syntax:"
},
{
"code": null,
"e": 754,
"s": 732,
"text": "<header> ...</header>"
},
{
"code": null,
"e": 819,
"s": 754,
"text": "Attributes: This tag supports all the global attributes in HTML."
},
{
"code": null,
"e": 879,
"s": 819,
"text": "The below examples illustrate the <header> element in HTML."
},
{
"code": null,
"e": 1006,
"s": 879,
"text": "Example 1: This example illustrates the use of the <header> tag that makes the container for the head section of the document."
},
{
"code": null,
"e": 1011,
"s": 1006,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML Header Tag</h3> <hr> <article> <header> <h3>GeeksforGeeks Learning</h3> <p>Posted by GFG</p> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. </p> </header> </article></body></html>",
"e": 1482,
"s": 1011,
"text": null
},
{
"code": null,
"e": 1491,
"s": 1482,
"text": " Output:"
},
{
"code": null,
"e": 1509,
"s": 1491,
"text": "HTML <header> Tag"
},
{
"code": null,
"e": 1642,
"s": 1509,
"text": "Example 2: In this example, we have used the <header> tag to contain the surrounding section’s heading, but not required every time."
},
{
"code": null,
"e": 1647,
"s": 1642,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML Header Tag</h3> <!--HTML header tag starts here--> <header> <h1>This is the heading.</h1> <h4>This is the sub-heading.</h4> <p>This is the metadata.</p> </header> <!--HTML header tag ends here--></body></html>",
"e": 1966,
"s": 1647,
"text": null
},
{
"code": null,
"e": 1974,
"s": 1966,
"text": "Output:"
},
{
"code": null,
"e": 1992,
"s": 1974,
"text": "HTML <header> Tag"
},
{
"code": null,
"e": 2085,
"s": 1992,
"text": "Example 3: In this example, we have represented navigational aids by using the <header> tag."
},
{
"code": null,
"e": 2090,
"s": 2085,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML Header Tag</h3> <!--HTML header tag starts here--> <header> <a href=\"https://www.geeksforgeeks.org/fundamentals-of-algorithms/\"> Algo</a> | <a href=\"https://www.geeksforgeeks.org/data-structures/\"> DS</a> | <a href=\"https://www.geeksforgeeks.org/category/program-output/\"> Languages</a> | <a href=\"https://www.geeksforgeeks.org/company-interview-corner/\"> Interview</a> | <a href=\"https://www.geeksforgeeks.org/student-corner/\"> Students</a> | <a href=\"https://www.geeksforgeeks.org/gate-cs-notes-gq/\"> Gate</a> | <a href=\"https://www.geeksforgeeks.org/articles-on-computer-science-subjects-gq/\"> CS Subjects</a> | <a href=\"https://www.geeksforgeeks.org/quiz-corner-gq/\"> Quizzes</a> </header> <!--HTML header tag ends here--></body></html>",
"e": 3036,
"s": 2090,
"text": null
},
{
"code": null,
"e": 3044,
"s": 3036,
"text": "Output:"
},
{
"code": null,
"e": 3062,
"s": 3044,
"text": "HTML <header> Tag"
},
{
"code": null,
"e": 3082,
"s": 3062,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 3109,
"s": 3082,
"text": "Google Chrome 93.0 & above"
},
{
"code": null,
"e": 3132,
"s": 3109,
"text": "Internet Explorer 11.0"
},
{
"code": null,
"e": 3152,
"s": 3132,
"text": "Microsoft Edge 93.0"
},
{
"code": null,
"e": 3173,
"s": 3152,
"text": "Firefox 92.0 & above"
},
{
"code": null,
"e": 3184,
"s": 3173,
"text": "Opera 79.0"
},
{
"code": null,
"e": 3196,
"s": 3184,
"text": "Safari 14.1"
},
{
"code": null,
"e": 3392,
"s": 3196,
"text": "HTML is the foundation of web pages, is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 3406,
"s": 3392,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 3427,
"s": 3406,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 3437,
"s": 3427,
"text": "HTML-Tags"
},
{
"code": null,
"e": 3443,
"s": 3437,
"text": "HTML5"
},
{
"code": null,
"e": 3448,
"s": 3443,
"text": "HTML"
},
{
"code": null,
"e": 3453,
"s": 3448,
"text": "HTML"
}
] |
Download music tracks, playlists, albums from Spotify using spotDL
|
23 Sep, 2021
SpotDL is a cross-platform command-line utility written in Python via which we can download albums, playlists, individual tracks from Spotify. It is open-sourced and made available under the MIT License. It also applies metadata gathered from Spotify such as:
Track Name and Number
Album Name
Album Cover
Artist Name
Genre
Music Label
Release Date
Before installing spotdl make sure that the latest version of python, pip, and FFmpeg is already installed on your machine. To download and configure the above prerequisites, click on the following links.
python 3: To compile and execute the application.
pip: To download and install spotdl on your machine.
FFmpeg: To convert playlist file format such as m3u to an mp3 file.
Now let’s begin with the installation process.
For Windows, open cmd as an administrator and execute:
pip install spotdl
For Linux/Mac, execute the following command in the terminal
sudo pip3 install spotdl
To verify the installation, run:
spotdl --version
verify version
Open Spotify in your browser and copy the URL of the track you want to download
Replace $url with the URL you just copied and run the following command :
spotdl $url
Open Spotify in your browser and copy the URL of the album you want to download
Replace $url with the URL you just copied and run the following command :
spotdl $url
Open Spotify in your browser and copy the URL of the playlist you want to download
Replace $url with the URL you just copied and run the following command :
spotdl $url
spotdl 'query'
Here, replace query with the name of the song.
spotdl 'path to the .spotdlTrackingFile'
.spotDlTrackingFile are automatically created once the download process starts, and they are deleted after the process gets completed. You can give the path to the .spotDlTrackingFile file in case of a failed/incomplete download and spotdl will automatically resume the incomplete download.
spotdl $trackUrl $albumUrl $playlistUrl 'query' ...
You can chain up multiple download tasks by separating the URL/query with spaces.
For Windows, open cmd as an administrator and execute:
pip uninstall spotdl
For Linux/Mac, execute the following command in the terminal
sudo pip3 install spotdl
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 314,
"s": 54,
"text": "SpotDL is a cross-platform command-line utility written in Python via which we can download albums, playlists, individual tracks from Spotify. It is open-sourced and made available under the MIT License. It also applies metadata gathered from Spotify such as:"
},
{
"code": null,
"e": 336,
"s": 314,
"text": "Track Name and Number"
},
{
"code": null,
"e": 347,
"s": 336,
"text": "Album Name"
},
{
"code": null,
"e": 359,
"s": 347,
"text": "Album Cover"
},
{
"code": null,
"e": 371,
"s": 359,
"text": "Artist Name"
},
{
"code": null,
"e": 377,
"s": 371,
"text": "Genre"
},
{
"code": null,
"e": 389,
"s": 377,
"text": "Music Label"
},
{
"code": null,
"e": 402,
"s": 389,
"text": "Release Date"
},
{
"code": null,
"e": 607,
"s": 402,
"text": "Before installing spotdl make sure that the latest version of python, pip, and FFmpeg is already installed on your machine. To download and configure the above prerequisites, click on the following links."
},
{
"code": null,
"e": 657,
"s": 607,
"text": "python 3: To compile and execute the application."
},
{
"code": null,
"e": 710,
"s": 657,
"text": "pip: To download and install spotdl on your machine."
},
{
"code": null,
"e": 778,
"s": 710,
"text": "FFmpeg: To convert playlist file format such as m3u to an mp3 file."
},
{
"code": null,
"e": 825,
"s": 778,
"text": "Now let’s begin with the installation process."
},
{
"code": null,
"e": 880,
"s": 825,
"text": "For Windows, open cmd as an administrator and execute:"
},
{
"code": null,
"e": 899,
"s": 880,
"text": "pip install spotdl"
},
{
"code": null,
"e": 960,
"s": 899,
"text": "For Linux/Mac, execute the following command in the terminal"
},
{
"code": null,
"e": 985,
"s": 960,
"text": "sudo pip3 install spotdl"
},
{
"code": null,
"e": 1019,
"s": 985,
"text": "To verify the installation, run:"
},
{
"code": null,
"e": 1036,
"s": 1019,
"text": "spotdl --version"
},
{
"code": null,
"e": 1051,
"s": 1036,
"text": "verify version"
},
{
"code": null,
"e": 1131,
"s": 1051,
"text": "Open Spotify in your browser and copy the URL of the track you want to download"
},
{
"code": null,
"e": 1205,
"s": 1131,
"text": "Replace $url with the URL you just copied and run the following command :"
},
{
"code": null,
"e": 1217,
"s": 1205,
"text": "spotdl $url"
},
{
"code": null,
"e": 1297,
"s": 1217,
"text": "Open Spotify in your browser and copy the URL of the album you want to download"
},
{
"code": null,
"e": 1371,
"s": 1297,
"text": "Replace $url with the URL you just copied and run the following command :"
},
{
"code": null,
"e": 1383,
"s": 1371,
"text": "spotdl $url"
},
{
"code": null,
"e": 1466,
"s": 1383,
"text": "Open Spotify in your browser and copy the URL of the playlist you want to download"
},
{
"code": null,
"e": 1540,
"s": 1466,
"text": "Replace $url with the URL you just copied and run the following command :"
},
{
"code": null,
"e": 1552,
"s": 1540,
"text": "spotdl $url"
},
{
"code": null,
"e": 1567,
"s": 1552,
"text": "spotdl 'query'"
},
{
"code": null,
"e": 1614,
"s": 1567,
"text": "Here, replace query with the name of the song."
},
{
"code": null,
"e": 1655,
"s": 1614,
"text": "spotdl 'path to the .spotdlTrackingFile'"
},
{
"code": null,
"e": 1946,
"s": 1655,
"text": ".spotDlTrackingFile are automatically created once the download process starts, and they are deleted after the process gets completed. You can give the path to the .spotDlTrackingFile file in case of a failed/incomplete download and spotdl will automatically resume the incomplete download."
},
{
"code": null,
"e": 1998,
"s": 1946,
"text": "spotdl $trackUrl $albumUrl $playlistUrl 'query' ..."
},
{
"code": null,
"e": 2080,
"s": 1998,
"text": "You can chain up multiple download tasks by separating the URL/query with spaces."
},
{
"code": null,
"e": 2135,
"s": 2080,
"text": "For Windows, open cmd as an administrator and execute:"
},
{
"code": null,
"e": 2156,
"s": 2135,
"text": "pip uninstall spotdl"
},
{
"code": null,
"e": 2217,
"s": 2156,
"text": "For Linux/Mac, execute the following command in the terminal"
},
{
"code": null,
"e": 2242,
"s": 2217,
"text": "sudo pip3 install spotdl"
},
{
"code": null,
"e": 2254,
"s": 2242,
"text": "Linux-Tools"
},
{
"code": null,
"e": 2265,
"s": 2254,
"text": "Linux-Unix"
}
] |
Perl | Classes in OOP
|
11 Mar, 2022
In this modern world, where the use of programming has moved to its maximum and has its application in each and every work of our lives, we need to adapt ourselves to such programming paradigms that are directly linked to the real-world examples. There has been a drastic change in the competitiveness and the complexity of the real-world problems, thus the industry now requires some versatile approaches towards these complexities. The concept of Object-Oriented Programming language copes up comfortably with these complexities and is a perfect way of shaping up any programming language in a way that the real-world examples become very easy to solve. Object-Oriented Programming(OOP) uses the methodology of emphasizing more on objects rather than the procedure. The OOPs concept is about working in terms of objects and the interaction between objects.
Note: Object-oriented programming aims to implement real-world entities like inheritance, encapsulation, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.
An object is an instance of a class of the data structure with some characteristics and behavior. For Example, we say an “Apple” is an object. Its characteristics are:it is a fruit, its color is red, etc. Its behavior is:”it tastes good“. In the concept of OOPs, the characteristics of an object are represented by its data and the behavior is represented by its associated functions. Thus an object is an entity that stores data and has its interface through functions.
A class is an expanded concept of data structures. It defines a prototype blueprint of objects comprising of data. And an object is an instance of a class. A class comprises of the data members and data functions and it is a pre-defined data type made as per the user’s requirements which can be accessed and used by creating an instance of that class.
Example: Consider a class of School. There may be schools with different names and structure but all of them share some common characteristics like students, teachers, staff, etc. So here school is the class with teachers, students, and Parents as the data members, and the member functions can be calculate_students_marks(), calculate_teachers_salary(), and Parents_Database().
Data Member: Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions define the properties and behavior of the objects in a Class.
It is very easy to define a class in Perl. In Perl, a Class corresponds to a package. To define a class we first load and build a Package. A Package is a pre-contained unit of user-defined variables and subroutines, which can be used throughout the program.
Syntax:
package Class_name
A class in Perl can be created by using the keyword package but to create an object, a constructor is called. A constructor is defined in a class as a method.
Creating an instance of a class A class name and a constructor name can be as per user’s requirement. Most of the programmers prefer to use ‘new’ as a constructor name for their programs as it is easy to remember and is more feasible to use than any other complex constructor name.
Perl
package student // This is the class studentsub Student_data // Constructor to class{ my $class = shift; my $self = { _StudentFirstName => shift; _StudentLastName => shift; }; print "Student's First Name is $self ->{_StudentFirstName}\n"; print "Student's Last Name is $self ->{_StudentLastName}\n"; bless $self, $class; return $self;}
In the above example code, a function named bless is used. This function is used to attach an object to a class which is passed to it as an argument.
Syntax:
bless Object_name, Class Name
Creating an Object An object in Perl is instantiated by using the constructor defined in the class. An object name can be any variable as per user’s requirement, but it is conventional to name it with respect to the relevancy with the class.
Perl
$Data = Student_data student( "Shikhar", "Mathur");
Example:
Perl
use strict;use warnings; package student; # constructorsub student_data{ # shift will take package name 'student' # and assign it to variable 'class' my $class_name = shift; my $self = { 'StudentFirstName' => shift, 'StudentLastName' => shift }; # Using bless function bless $self, $class_name; # returning object from constructor return $self;} # Object creating and constructor callingmy $Data = new student_data student("Geeks","forGeeks"); # Printing the dataprint "$Data->{'StudentFirstName'}\n";print "$Data->{'StudentLastName'}\n";
Geeks
forGeeks
The concept of using classes in Object-Oriented Programming is very important as it completely depicts the real-world applications and can be adopted in real-world problems.
adnanirshad158
csk111165
Perl-OOP
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Mar, 2022"
},
{
"code": null,
"e": 888,
"s": 28,
"text": "In this modern world, where the use of programming has moved to its maximum and has its application in each and every work of our lives, we need to adapt ourselves to such programming paradigms that are directly linked to the real-world examples. There has been a drastic change in the competitiveness and the complexity of the real-world problems, thus the industry now requires some versatile approaches towards these complexities. The concept of Object-Oriented Programming language copes up comfortably with these complexities and is a perfect way of shaping up any programming language in a way that the real-world examples become very easy to solve. Object-Oriented Programming(OOP) uses the methodology of emphasizing more on objects rather than the procedure. The OOPs concept is about working in terms of objects and the interaction between objects. "
},
{
"code": null,
"e": 1192,
"s": 888,
"text": "Note: Object-oriented programming aims to implement real-world entities like inheritance, encapsulation, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function."
},
{
"code": null,
"e": 1663,
"s": 1192,
"text": "An object is an instance of a class of the data structure with some characteristics and behavior. For Example, we say an “Apple” is an object. Its characteristics are:it is a fruit, its color is red, etc. Its behavior is:”it tastes good“. In the concept of OOPs, the characteristics of an object are represented by its data and the behavior is represented by its associated functions. Thus an object is an entity that stores data and has its interface through functions."
},
{
"code": null,
"e": 2016,
"s": 1663,
"text": "A class is an expanded concept of data structures. It defines a prototype blueprint of objects comprising of data. And an object is an instance of a class. A class comprises of the data members and data functions and it is a pre-defined data type made as per the user’s requirements which can be accessed and used by creating an instance of that class."
},
{
"code": null,
"e": 2396,
"s": 2016,
"text": "Example: Consider a class of School. There may be schools with different names and structure but all of them share some common characteristics like students, teachers, staff, etc. So here school is the class with teachers, students, and Parents as the data members, and the member functions can be calculate_students_marks(), calculate_teachers_salary(), and Parents_Database(). "
},
{
"code": null,
"e": 2635,
"s": 2396,
"text": "Data Member: Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions define the properties and behavior of the objects in a Class. "
},
{
"code": null,
"e": 2893,
"s": 2635,
"text": "It is very easy to define a class in Perl. In Perl, a Class corresponds to a package. To define a class we first load and build a Package. A Package is a pre-contained unit of user-defined variables and subroutines, which can be used throughout the program."
},
{
"code": null,
"e": 2903,
"s": 2893,
"text": "Syntax: "
},
{
"code": null,
"e": 2922,
"s": 2903,
"text": "package Class_name"
},
{
"code": null,
"e": 3082,
"s": 2922,
"text": "A class in Perl can be created by using the keyword package but to create an object, a constructor is called. A constructor is defined in a class as a method. "
},
{
"code": null,
"e": 3366,
"s": 3082,
"text": "Creating an instance of a class A class name and a constructor name can be as per user’s requirement. Most of the programmers prefer to use ‘new’ as a constructor name for their programs as it is easy to remember and is more feasible to use than any other complex constructor name. "
},
{
"code": null,
"e": 3371,
"s": 3366,
"text": "Perl"
},
{
"code": "package student // This is the class studentsub Student_data // Constructor to class{ my $class = shift; my $self = { _StudentFirstName => shift; _StudentLastName => shift; }; print \"Student's First Name is $self ->{_StudentFirstName}\\n\"; print \"Student's Last Name is $self ->{_StudentLastName}\\n\"; bless $self, $class; return $self;}",
"e": 3792,
"s": 3371,
"text": null
},
{
"code": null,
"e": 3943,
"s": 3792,
"text": "In the above example code, a function named bless is used. This function is used to attach an object to a class which is passed to it as an argument. "
},
{
"code": null,
"e": 3952,
"s": 3943,
"text": "Syntax: "
},
{
"code": null,
"e": 3982,
"s": 3952,
"text": "bless Object_name, Class Name"
},
{
"code": null,
"e": 4226,
"s": 3982,
"text": "Creating an Object An object in Perl is instantiated by using the constructor defined in the class. An object name can be any variable as per user’s requirement, but it is conventional to name it with respect to the relevancy with the class. "
},
{
"code": null,
"e": 4231,
"s": 4226,
"text": "Perl"
},
{
"code": "$Data = Student_data student( \"Shikhar\", \"Mathur\");",
"e": 4283,
"s": 4231,
"text": null
},
{
"code": null,
"e": 4293,
"s": 4283,
"text": "Example: "
},
{
"code": null,
"e": 4298,
"s": 4293,
"text": "Perl"
},
{
"code": "use strict;use warnings; package student; # constructorsub student_data{ # shift will take package name 'student' # and assign it to variable 'class' my $class_name = shift; my $self = { 'StudentFirstName' => shift, 'StudentLastName' => shift }; # Using bless function bless $self, $class_name; # returning object from constructor return $self;} # Object creating and constructor callingmy $Data = new student_data student(\"Geeks\",\"forGeeks\"); # Printing the dataprint \"$Data->{'StudentFirstName'}\\n\";print \"$Data->{'StudentLastName'}\\n\";",
"e": 4911,
"s": 4298,
"text": null
},
{
"code": null,
"e": 4926,
"s": 4911,
"text": "Geeks\nforGeeks"
},
{
"code": null,
"e": 5103,
"s": 4928,
"text": "The concept of using classes in Object-Oriented Programming is very important as it completely depicts the real-world applications and can be adopted in real-world problems. "
},
{
"code": null,
"e": 5118,
"s": 5103,
"text": "adnanirshad158"
},
{
"code": null,
"e": 5128,
"s": 5118,
"text": "csk111165"
},
{
"code": null,
"e": 5137,
"s": 5128,
"text": "Perl-OOP"
},
{
"code": null,
"e": 5144,
"s": 5137,
"text": "Picked"
},
{
"code": null,
"e": 5149,
"s": 5144,
"text": "Perl"
},
{
"code": null,
"e": 5154,
"s": 5149,
"text": "Perl"
}
] |
How to Show all Columns in the SQLite Database using Python ?
|
30 Apr, 2021
In this article, we will discuss how we can show all columns of a table in the SQLite database from Python using the sqlite3 module.
Connect to a database using the connect() method.
Create a cursor object and use that cursor object created to execute queries in order to create a table and insert values into it.
Use the description keyword of the cursor object to get the column names. The description keyword specifies only the columns of a table in a two-dimensional tuple consisting of none values and the column names only.
data=cursor.execute('''SELECT * FROM table_name''')
print(data.description)
The above code displays all the columns of a given table in a two-dimensional tuple.
Display the data in the table by executing the below query using the cursor object.
SELECT * FROM table_name
Finally, commit the changes in the database and close the connection.
Creating the table
In the below program we connect to a database named gfg.db, then we create an EMPLOYEE table and insert values into it. Finally, we commit the changes in the database and terminate the connection.
Python3
# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg1.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable ="""CREATE TABLE EMPLOYEE(FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), AGE int, SEX CHAR(1), INCOME int);"""cursor.execute(table)print('Table Created!') # Queries to INSERT records.cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Anand', 'Choubey', 25, 'M', 10000)''')cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mukesh', 'Sharma', 20, 'M', 9000)''')cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ankit', 'Pandey', 24, 'M', 6300)''')cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Subhdra ', 'Singh', 26, 'F', 8000)''')cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tanu', 'Mishra', 24, 'F', 6500)''') print('Data inserted into the table') # Commit your changes in the database conn.commit() # Closing the connectionconn.close()
Output:
Table Created!
Data inserted into the table
Retrieving columns from the table:
Now as we have already created a table and inserted values into the table in a database. We will connect to the previous database where the EMPLOYEE table is created. Then we will first display all the columns and then the data values in the column.
Python3
# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Display columnsprint('\nColumns in EMPLOYEE table:')data=cursor.execute('''SELECT * FROM EMPLOYEE''')for column in data.description: print(column[0]) # Display dataprint('\nData in EMPLOYEE table:')data=cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()
Output:
SQLite:
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 162,
"s": 28,
"text": "In this article, we will discuss how we can show all columns of a table in the SQLite database from Python using the sqlite3 module. "
},
{
"code": null,
"e": 212,
"s": 162,
"text": "Connect to a database using the connect() method."
},
{
"code": null,
"e": 343,
"s": 212,
"text": "Create a cursor object and use that cursor object created to execute queries in order to create a table and insert values into it."
},
{
"code": null,
"e": 559,
"s": 343,
"text": "Use the description keyword of the cursor object to get the column names. The description keyword specifies only the columns of a table in a two-dimensional tuple consisting of none values and the column names only."
},
{
"code": null,
"e": 635,
"s": 559,
"text": "data=cursor.execute('''SELECT * FROM table_name''')\nprint(data.description)"
},
{
"code": null,
"e": 720,
"s": 635,
"text": "The above code displays all the columns of a given table in a two-dimensional tuple."
},
{
"code": null,
"e": 804,
"s": 720,
"text": "Display the data in the table by executing the below query using the cursor object."
},
{
"code": null,
"e": 829,
"s": 804,
"text": "SELECT * FROM table_name"
},
{
"code": null,
"e": 899,
"s": 829,
"text": "Finally, commit the changes in the database and close the connection."
},
{
"code": null,
"e": 918,
"s": 899,
"text": "Creating the table"
},
{
"code": null,
"e": 1115,
"s": 918,
"text": "In the below program we connect to a database named gfg.db, then we create an EMPLOYEE table and insert values into it. Finally, we commit the changes in the database and terminate the connection."
},
{
"code": null,
"e": 1123,
"s": 1115,
"text": "Python3"
},
{
"code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg1.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Creating tabletable =\"\"\"CREATE TABLE EMPLOYEE(FIRST_NAME VARCHAR(255), LAST_NAME VARCHAR(255), AGE int, SEX CHAR(1), INCOME int);\"\"\"cursor.execute(table)print('Table Created!') # Queries to INSERT records.cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Anand', 'Choubey', 25, 'M', 10000)''')cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mukesh', 'Sharma', 20, 'M', 9000)''')cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ankit', 'Pandey', 24, 'M', 6300)''')cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Subhdra ', 'Singh', 26, 'F', 8000)''')cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tanu', 'Mishra', 24, 'F', 6500)''') print('Data inserted into the table') # Commit your changes in the database conn.commit() # Closing the connectionconn.close()",
"e": 2488,
"s": 1123,
"text": null
},
{
"code": null,
"e": 2496,
"s": 2488,
"text": "Output:"
},
{
"code": null,
"e": 2540,
"s": 2496,
"text": "Table Created!\nData inserted into the table"
},
{
"code": null,
"e": 2575,
"s": 2540,
"text": "Retrieving columns from the table:"
},
{
"code": null,
"e": 2826,
"s": 2575,
"text": "Now as we have already created a table and inserted values into the table in a database. We will connect to the previous database where the EMPLOYEE table is created. Then we will first display all the columns and then the data values in the column. "
},
{
"code": null,
"e": 2834,
"s": 2826,
"text": "Python3"
},
{
"code": "# Import moduleimport sqlite3 # Connecting to sqliteconn = sqlite3.connect('gfg.db') # Creating a cursor object using the cursor() methodcursor = conn.cursor() # Display columnsprint('\\nColumns in EMPLOYEE table:')data=cursor.execute('''SELECT * FROM EMPLOYEE''')for column in data.description: print(column[0]) # Display dataprint('\\nData in EMPLOYEE table:')data=cursor.execute('''SELECT * FROM EMPLOYEE''')for row in data: print(row) # Commit your changes in the database conn.commit() # Closing the connectionconn.close()",
"e": 3385,
"s": 2834,
"text": null
},
{
"code": null,
"e": 3393,
"s": 3385,
"text": "Output:"
},
{
"code": null,
"e": 3401,
"s": 3393,
"text": "SQLite:"
},
{
"code": null,
"e": 3408,
"s": 3401,
"text": "Picked"
},
{
"code": null,
"e": 3422,
"s": 3408,
"text": "Python-SQLite"
},
{
"code": null,
"e": 3429,
"s": 3422,
"text": "Python"
}
] |
NVIDIA DALI: Speeding up PyTorch. Some techniques to improve DALI... | by Pieterluitjens | Towards Data Science
|
TL;DR: I showcase some techniques to improve DALI resource usage & create a completely CPU-based pipeline. These techniques stabilize long-term memory usage and allow for ~50% larger batch size compared to the example CPU & GPU pipelines provided with the DALI package. Testing with a Tesla V100 accelerator shows that PyTorch+DALI can reach processing speeds of nearly 4000 images/s, ~4X faster than native PyTorch.
Update 20/3/2019: DALI 0.19 features improved memory management, eliminating the gradual rise in memory usage (278). I’d still recommend to re-import DALI when using the GPU pipeline however in order to reduce GPU memory usage.
The last couple of years have seen tremendous progress on the Deep Learning hardware front. Nvidia’s latest offerings, the Tesla V100 & Geforce RTX series, contain dedicated tensor cores to accelerate the operations commonly used in neural networks. The V100, in particular, has enough power to train neural networks at thousands of images per second, bringing single-GPU training on the ImageNet dataset down to just a few hours for small models. That’s a far cry from the 5 days it took to train the AlexNet model on ImageNet in 2012!
Such powerful GPUs strain the data preprocessing pipeline. To account for this, Tensorflow released a new data loader: tf.data.Dataset. The pipeline is written in C++ and uses a graph-based approach whereby multiple preprocessing operations are chained together to form a pipeline. PyTorch on the other hand uses a data loader written in Python on top of the PIL library — great for ease of use and flexibility, not so great for speed. Although the PIL-SIMD library does improve the situation a bit.
Enter the NVIDIA Data Loading Library (DALI): designed to remove the data preprocessing bottleneck, allowing for training and inference to run at full speed. DALI is primarily designed to do preprocessing on a GPU, but most operations also have a fast CPU implementation. This articles focuses on PyTorch, however DALI also supports Tensorflow, MXNet & TensorRT. TensorRT support, in particular, is great. It allows for both the training and inference steps to use the exact same preprocessing code. Different frameworks like Tensorflow & PyTorch typically feature small differences between the data loaders, which might end up affecting accuracy.
Below are some great resources to get started with DALI:
DALI Home
Fast AI Data Preprocessing with NVIDIA DALI
DALI Developer Guide
Getting Started
For the remainder of this article I’m going to assume a basic familiarity with ImageNet preprocessing and the DALI ImageNet example. I’ll discuss some issues that I ran up against whilst using DALI, along with how I got around them. We’ll look at both CPU and GPU pipelines.
Update 20/3/2019: This issue has been fixed in DALI 0.19
The first issue I encountered with DALI is that RAM usage increases with every training epoch, causing OOM errors (even on a VM with 78GB RAM). This has been flagged (278, 344, 486), but has yet to be fixed.
The only solution I could find wasn’t pretty — reimport DALI & recreate the train & validation pipelines at every epoch:
del self.train_loader, self.val_loader, self.train_pipe, self.val_pipetorch.cuda.synchronize()torch.cuda.empty_cache()gc.collect()importlib.reload(dali)from dali import HybridTrainPipe, HybridValPipe, DaliIteratorCPU, DaliIteratorGPU<rebuild DALI pipeline>
Note that, with this workaround, DALI still requires a lot of RAM to get the best results. Given how cheap RAM is nowadays (relative to Nvidia GPUs at least) this isn’t much of a concern; rather, GPU memory is more of a problem. As can be seen from the table below, the maximum batch size possible whilst using DALI is as much as 50% lower than TorchVision:
In the following sections, I’ll cover some approaches to reduce GPU memory usage.
Let’s look at the example CPU pipeline first. The CPU-based pipeline is useful for when peak throughput isn’t required (e.g., when working with medium & large sized models like ResNet50). The CPU training pipeline only does the decoding & resizing operations on CPU however, with the CropMirrorNormalize operation running on GPU. This is significant. I found that even just transferring the output to GPU with DALI used a lot of GPU memory. To circumvent this, I modified the example CPU pipeline to run entirely on CPU:
class HybridTrainPipe(Pipeline): def __init__(self, batch_size, num_threads, device_id, data_dir, crop, mean, std, local_rank=0, world_size=1, dali_cpu=False, shuffle=True, fp16=False, min_crop_size=0.08): # As we're recreating the Pipeline at every epoch, the seed must be -1 (random seed) super(HybridTrainPipe, self).__init__(batch_size, num_threads, device_id, seed=-1) # Enabling read_ahead slowed down processing ~40% self.input = ops.FileReader(file_root=data_dir, shard_id=local_rank, num_shards=world_size, random_shuffle=shuffle) # Let user decide which pipeline works best with the chosen model if dali_cpu: decode_device = "cpu" self.dali_device = "cpu" self.flip = ops.Flip(device=self.dali_device) else: decode_device = "mixed" self.dali_device = "gpu" output_dtype = types.FLOAT if self.dali_device == "gpu" and fp16: output_dtype = types.FLOAT16 self.cmn = ops.CropMirrorNormalize(device="gpu", output_dtype=output_dtype, output_layout=types.NCHW, crop=(crop, crop), image_type=types.RGB, mean=mean, std=std,) # To be able to handle all images from full-sized ImageNet, this padding sets the size of the internal nvJPEG buffers without additional reallocations device_memory_padding = 211025920 if decode_device == 'mixed' else 0 host_memory_padding = 140544512 if decode_device == 'mixed' else 0 self.decode = ops.ImageDecoderRandomCrop(device=decode_device, output_type=types.RGB, device_memory_padding=device_memory_padding, host_memory_padding=host_memory_padding, random_aspect_ratio=[0.8, 1.25], random_area=[min_crop_size, 1.0], num_attempts=100) # Resize as desired. To match torchvision data loader, use triangular interpolation. self.res = ops.Resize(device=self.dali_device, resize_x=crop, resize_y=crop, interp_type=types.INTERP_TRIANGULAR) self.coin = ops.CoinFlip(probability=0.5) print('DALI "{0}" variant'.format(self.dali_device)) def define_graph(self): rng = self.coin() self.jpegs, self.labels = self.input(name="Reader") # Combined decode & random crop images = self.decode(self.jpegs) # Resize as desired images = self.res(images) if self.dali_device == "gpu": output = self.cmn(images, mirror=rng) else: # CPU backend uses torch to apply mean & std output = self.flip(images, horizontal=rng) self.labels = self.labels.gpu() return [output, self.labels]
The DALI pipeline now outputs an 8-bit tensor on the CPU. We need to use PyTorch to do the CPU-> GPU transfer, the conversion to floating point numbers, and the normalization. These last two ops are done on GPU, given that, in practice, they’re very fast and they reduce the CPU -> GPU memory bandwidth requirement. I tried pinning the tensor before transferring to GPU, but didn’t manage to get any performance uplift from doing so. Putting it together with a prefetcher:
def _preproc_worker(dali_iterator, cuda_stream, fp16, mean, std, output_queue, proc_next_input, done_event, pin_memory): """ Worker function to parse DALI output & apply final preprocessing steps """ while not done_event.is_set(): # Wait until main thread signals to proc_next_input -- normally once it has taken the last processed input proc_next_input.wait() proc_next_input.clear() if done_event.is_set(): print('Shutting down preproc thread') break try: data = next(dali_iterator) # Decode the data output input_orig = data[0]['data'] target = data[0]['label'].squeeze().long() # DALI should already output target on device # Copy to GPU and apply final processing in separate CUDA stream with torch.cuda.stream(cuda_stream): input = input_orig if pin_memory: input = input.pin_memory() del input_orig # Save memory input = input.cuda(non_blocking=True) input = input.permute(0, 3, 1, 2) # Input tensor is kept as 8-bit integer for transfer to GPU, to save bandwidth if fp16: input = input.half() else: input = input.float() input = input.sub_(mean).div_(std) # Put the result on the queue output_queue.put((input, target)) except StopIteration: print('Resetting DALI loader') dali_iterator.reset() output_queue.put(None)class DaliIteratorCPU(DaliIterator): """ Wrapper class to decode the DALI iterator output & provide iterator that functions in the same way as TorchVision. Note that permutation to channels first, converting from 8-bit integer to float & normalization are all performed on GPU pipelines (Pipeline): DALI pipelines size (int): Number of examples in set fp16 (bool): Use fp16 as output format, f32 otherwise mean (tuple): Image mean value for each channel std (tuple): Image standard deviation value for each channel pin_memory (bool): Transfer input tensor to pinned memory, before moving to GPU """ def __init__(self, fp16=False, mean=(0., 0., 0.), std=(1., 1., 1.), pin_memory=True, **kwargs): super().__init__(**kwargs) print('Using DALI CPU iterator') self.stream = torch.cuda.Stream() self.fp16 = fp16 self.mean = torch.tensor(mean).cuda().view(1, 3, 1, 1) self.std = torch.tensor(std).cuda().view(1, 3, 1, 1) self.pin_memory = pin_memory if self.fp16: self.mean = self.mean.half() self.std = self.std.half() self.proc_next_input = Event() self.done_event = Event() self.output_queue = queue.Queue(maxsize=5) self.preproc_thread = threading.Thread( target=_preproc_worker, kwargs={'dali_iterator': self._dali_iterator, 'cuda_stream': self.stream, 'fp16': self.fp16, 'mean': self.mean, 'std': self.std, 'proc_next_input': self.proc_next_input, 'done_event': self.done_event, 'output_queue': self.output_queue, 'pin_memory': self.pin_memory}) self.preproc_thread.daemon = True self.preproc_thread.start() self.proc_next_input.set() def __next__(self): torch.cuda.current_stream().wait_stream(self.stream) data = self.output_queue.get() self.proc_next_input.set() if data is None: raise StopIteration return data def __del__(self): self.done_event.set() self.proc_next_input.set() torch.cuda.current_stream().wait_stream(self.stream) self.preproc_thread.join()
In my testing, the new full CPU pipeline detailed above is about twice as fast as TorchVision’s data loader, whilst achieving nearly the same maximum batch size. The CPU pipeline works great with large models like ResNet50; however, when using small models like AlexNet or ResNet18, the CPU pipeline still isn’t able to keep up with the GPU. For these cases, the example GPU pipeline works best. The trouble is that the GPU pipeline reduces the maximum possible batch size by almost 50%, limiting throughput.
One way to significantly reduce GPU memory usage is by keeping the validation pipeline off the GPU until it’s actually needed at the end of an epoch. This is easy to do as we’re already reimporting the DALI library and recreating data loaders at every epoch.
More tips for using DALI:
* For validation, a batch size that evenly divides the dataset size works best e.g. 500 instead of 512 for a validation set size of 50000 — this avoids a partial batch at the end of the validation dataset.
* Similar to the Tensorflow & PyTorch data loaders, the TorchVision and DALI pipelines don’t produce bit-identical outputs — you’ll see the validation accuracies differ slightly. I found that this is due to different JPEG image decoders. There was previously an issue with resizing but this is now fixed. The flipside is that DALI supports TensorRT, allowing for the exact same preprocessing to be used for training & inference.
* For peak throughput, try setting the number of data loader workers to number_of_virtual_CPU cores. 2 gave the best performance (2 virtual cores = 1 physical core)
* If you want absolute best performance and don’t care about having outputs similar to TorchVision, try turning off triangular interpolation on the DALI image resize
* Don’t forget about disk IO. Make sure you have enough RAM to cache the dataset and/or a really fast SSD. DALI can pull up to 400Mb/s from disk!
To help integrate these modifications easily, I created a data loader class with all the modifications described here, including both DALI and TorchVision backends. Usage is simple. Instantiate the data loader:
dataset = Dataset(data_dir, batch_size, val_batch_size workers, use_dali, dali_cpu, fp16)
Then get the train & validation data loaders:
train_loader = dataset.get_train_loader()val_loader = dataset.get_val_loader()
Reset the data loader at the end of every training epoch:
dataset.reset()
Optionally, the validation pipeline can be recreated on GPU prior to model validation:
dataset.prep_for_val()
Here are the max batch sizes I was able to use with ResNet18:
So, by applying these modifications, the max batch size DALI can use in both CPU & GPU modes is increased by ~50%!
Here are some throughput figures with Shufflenet V2 0.5 & batch size 512:
And here are some results of using the DALI GPU pipeline to train various networks included in TorchVision:
All tests were run on a Google Cloud V100 instance with 12 vCPUs (6 physical cores), 78GB RAM & using Apex FP16 training. To reproduce these results, use the following arguments: — fp16 — batch-size 512 — workers 10 — arch “shufflenet_v2_x0_5 or resnet18” — prof — use-dali
So, with DALI, a single Tesla V100 can reach speeds of nearly 4000 image/s! That’s just over half of what Nvidia’s super expensive DGX-1 with 8 V100 GPUs can do (albeit using small models). For me, being able to do an ImageNet training run on a single GPU in a few hours was a productivity game changer. Hopefully it will be for you as well. Feedback appreciated!
The code presented in this article is here
Many thanks to Patricia Thaine for her feedback on an earlier draft of this post.
Cover image by Jacek Abramowicz
|
[
{
"code": null,
"e": 464,
"s": 47,
"text": "TL;DR: I showcase some techniques to improve DALI resource usage & create a completely CPU-based pipeline. These techniques stabilize long-term memory usage and allow for ~50% larger batch size compared to the example CPU & GPU pipelines provided with the DALI package. Testing with a Tesla V100 accelerator shows that PyTorch+DALI can reach processing speeds of nearly 4000 images/s, ~4X faster than native PyTorch."
},
{
"code": null,
"e": 692,
"s": 464,
"text": "Update 20/3/2019: DALI 0.19 features improved memory management, eliminating the gradual rise in memory usage (278). I’d still recommend to re-import DALI when using the GPU pipeline however in order to reduce GPU memory usage."
},
{
"code": null,
"e": 1229,
"s": 692,
"text": "The last couple of years have seen tremendous progress on the Deep Learning hardware front. Nvidia’s latest offerings, the Tesla V100 & Geforce RTX series, contain dedicated tensor cores to accelerate the operations commonly used in neural networks. The V100, in particular, has enough power to train neural networks at thousands of images per second, bringing single-GPU training on the ImageNet dataset down to just a few hours for small models. That’s a far cry from the 5 days it took to train the AlexNet model on ImageNet in 2012!"
},
{
"code": null,
"e": 1729,
"s": 1229,
"text": "Such powerful GPUs strain the data preprocessing pipeline. To account for this, Tensorflow released a new data loader: tf.data.Dataset. The pipeline is written in C++ and uses a graph-based approach whereby multiple preprocessing operations are chained together to form a pipeline. PyTorch on the other hand uses a data loader written in Python on top of the PIL library — great for ease of use and flexibility, not so great for speed. Although the PIL-SIMD library does improve the situation a bit."
},
{
"code": null,
"e": 2377,
"s": 1729,
"text": "Enter the NVIDIA Data Loading Library (DALI): designed to remove the data preprocessing bottleneck, allowing for training and inference to run at full speed. DALI is primarily designed to do preprocessing on a GPU, but most operations also have a fast CPU implementation. This articles focuses on PyTorch, however DALI also supports Tensorflow, MXNet & TensorRT. TensorRT support, in particular, is great. It allows for both the training and inference steps to use the exact same preprocessing code. Different frameworks like Tensorflow & PyTorch typically feature small differences between the data loaders, which might end up affecting accuracy."
},
{
"code": null,
"e": 2434,
"s": 2377,
"text": "Below are some great resources to get started with DALI:"
},
{
"code": null,
"e": 2444,
"s": 2434,
"text": "DALI Home"
},
{
"code": null,
"e": 2488,
"s": 2444,
"text": "Fast AI Data Preprocessing with NVIDIA DALI"
},
{
"code": null,
"e": 2509,
"s": 2488,
"text": "DALI Developer Guide"
},
{
"code": null,
"e": 2525,
"s": 2509,
"text": "Getting Started"
},
{
"code": null,
"e": 2800,
"s": 2525,
"text": "For the remainder of this article I’m going to assume a basic familiarity with ImageNet preprocessing and the DALI ImageNet example. I’ll discuss some issues that I ran up against whilst using DALI, along with how I got around them. We’ll look at both CPU and GPU pipelines."
},
{
"code": null,
"e": 2857,
"s": 2800,
"text": "Update 20/3/2019: This issue has been fixed in DALI 0.19"
},
{
"code": null,
"e": 3065,
"s": 2857,
"text": "The first issue I encountered with DALI is that RAM usage increases with every training epoch, causing OOM errors (even on a VM with 78GB RAM). This has been flagged (278, 344, 486), but has yet to be fixed."
},
{
"code": null,
"e": 3186,
"s": 3065,
"text": "The only solution I could find wasn’t pretty — reimport DALI & recreate the train & validation pipelines at every epoch:"
},
{
"code": null,
"e": 3443,
"s": 3186,
"text": "del self.train_loader, self.val_loader, self.train_pipe, self.val_pipetorch.cuda.synchronize()torch.cuda.empty_cache()gc.collect()importlib.reload(dali)from dali import HybridTrainPipe, HybridValPipe, DaliIteratorCPU, DaliIteratorGPU<rebuild DALI pipeline>"
},
{
"code": null,
"e": 3801,
"s": 3443,
"text": "Note that, with this workaround, DALI still requires a lot of RAM to get the best results. Given how cheap RAM is nowadays (relative to Nvidia GPUs at least) this isn’t much of a concern; rather, GPU memory is more of a problem. As can be seen from the table below, the maximum batch size possible whilst using DALI is as much as 50% lower than TorchVision:"
},
{
"code": null,
"e": 3883,
"s": 3801,
"text": "In the following sections, I’ll cover some approaches to reduce GPU memory usage."
},
{
"code": null,
"e": 4404,
"s": 3883,
"text": "Let’s look at the example CPU pipeline first. The CPU-based pipeline is useful for when peak throughput isn’t required (e.g., when working with medium & large sized models like ResNet50). The CPU training pipeline only does the decoding & resizing operations on CPU however, with the CropMirrorNormalize operation running on GPU. This is significant. I found that even just transferring the output to GPU with DALI used a lot of GPU memory. To circumvent this, I modified the example CPU pipeline to run entirely on CPU:"
},
{
"code": null,
"e": 7626,
"s": 4404,
"text": "class HybridTrainPipe(Pipeline): def __init__(self, batch_size, num_threads, device_id, data_dir, crop, mean, std, local_rank=0, world_size=1, dali_cpu=False, shuffle=True, fp16=False, min_crop_size=0.08): # As we're recreating the Pipeline at every epoch, the seed must be -1 (random seed) super(HybridTrainPipe, self).__init__(batch_size, num_threads, device_id, seed=-1) # Enabling read_ahead slowed down processing ~40% self.input = ops.FileReader(file_root=data_dir, shard_id=local_rank, num_shards=world_size, random_shuffle=shuffle) # Let user decide which pipeline works best with the chosen model if dali_cpu: decode_device = \"cpu\" self.dali_device = \"cpu\" self.flip = ops.Flip(device=self.dali_device) else: decode_device = \"mixed\" self.dali_device = \"gpu\" output_dtype = types.FLOAT if self.dali_device == \"gpu\" and fp16: output_dtype = types.FLOAT16 self.cmn = ops.CropMirrorNormalize(device=\"gpu\", output_dtype=output_dtype, output_layout=types.NCHW, crop=(crop, crop), image_type=types.RGB, mean=mean, std=std,) # To be able to handle all images from full-sized ImageNet, this padding sets the size of the internal nvJPEG buffers without additional reallocations device_memory_padding = 211025920 if decode_device == 'mixed' else 0 host_memory_padding = 140544512 if decode_device == 'mixed' else 0 self.decode = ops.ImageDecoderRandomCrop(device=decode_device, output_type=types.RGB, device_memory_padding=device_memory_padding, host_memory_padding=host_memory_padding, random_aspect_ratio=[0.8, 1.25], random_area=[min_crop_size, 1.0], num_attempts=100) # Resize as desired. To match torchvision data loader, use triangular interpolation. self.res = ops.Resize(device=self.dali_device, resize_x=crop, resize_y=crop, interp_type=types.INTERP_TRIANGULAR) self.coin = ops.CoinFlip(probability=0.5) print('DALI \"{0}\" variant'.format(self.dali_device)) def define_graph(self): rng = self.coin() self.jpegs, self.labels = self.input(name=\"Reader\") # Combined decode & random crop images = self.decode(self.jpegs) # Resize as desired images = self.res(images) if self.dali_device == \"gpu\": output = self.cmn(images, mirror=rng) else: # CPU backend uses torch to apply mean & std output = self.flip(images, horizontal=rng) self.labels = self.labels.gpu() return [output, self.labels]"
},
{
"code": null,
"e": 8099,
"s": 7626,
"text": "The DALI pipeline now outputs an 8-bit tensor on the CPU. We need to use PyTorch to do the CPU-> GPU transfer, the conversion to floating point numbers, and the normalization. These last two ops are done on GPU, given that, in practice, they’re very fast and they reduce the CPU -> GPU memory bandwidth requirement. I tried pinning the tensor before transferring to GPU, but didn’t manage to get any performance uplift from doing so. Putting it together with a prefetcher:"
},
{
"code": null,
"e": 11843,
"s": 8099,
"text": "def _preproc_worker(dali_iterator, cuda_stream, fp16, mean, std, output_queue, proc_next_input, done_event, pin_memory): \"\"\" Worker function to parse DALI output & apply final preprocessing steps \"\"\" while not done_event.is_set(): # Wait until main thread signals to proc_next_input -- normally once it has taken the last processed input proc_next_input.wait() proc_next_input.clear() if done_event.is_set(): print('Shutting down preproc thread') break try: data = next(dali_iterator) # Decode the data output input_orig = data[0]['data'] target = data[0]['label'].squeeze().long() # DALI should already output target on device # Copy to GPU and apply final processing in separate CUDA stream with torch.cuda.stream(cuda_stream): input = input_orig if pin_memory: input = input.pin_memory() del input_orig # Save memory input = input.cuda(non_blocking=True) input = input.permute(0, 3, 1, 2) # Input tensor is kept as 8-bit integer for transfer to GPU, to save bandwidth if fp16: input = input.half() else: input = input.float() input = input.sub_(mean).div_(std) # Put the result on the queue output_queue.put((input, target)) except StopIteration: print('Resetting DALI loader') dali_iterator.reset() output_queue.put(None)class DaliIteratorCPU(DaliIterator): \"\"\" Wrapper class to decode the DALI iterator output & provide iterator that functions in the same way as TorchVision. Note that permutation to channels first, converting from 8-bit integer to float & normalization are all performed on GPU pipelines (Pipeline): DALI pipelines size (int): Number of examples in set fp16 (bool): Use fp16 as output format, f32 otherwise mean (tuple): Image mean value for each channel std (tuple): Image standard deviation value for each channel pin_memory (bool): Transfer input tensor to pinned memory, before moving to GPU \"\"\" def __init__(self, fp16=False, mean=(0., 0., 0.), std=(1., 1., 1.), pin_memory=True, **kwargs): super().__init__(**kwargs) print('Using DALI CPU iterator') self.stream = torch.cuda.Stream() self.fp16 = fp16 self.mean = torch.tensor(mean).cuda().view(1, 3, 1, 1) self.std = torch.tensor(std).cuda().view(1, 3, 1, 1) self.pin_memory = pin_memory if self.fp16: self.mean = self.mean.half() self.std = self.std.half() self.proc_next_input = Event() self.done_event = Event() self.output_queue = queue.Queue(maxsize=5) self.preproc_thread = threading.Thread( target=_preproc_worker, kwargs={'dali_iterator': self._dali_iterator, 'cuda_stream': self.stream, 'fp16': self.fp16, 'mean': self.mean, 'std': self.std, 'proc_next_input': self.proc_next_input, 'done_event': self.done_event, 'output_queue': self.output_queue, 'pin_memory': self.pin_memory}) self.preproc_thread.daemon = True self.preproc_thread.start() self.proc_next_input.set() def __next__(self): torch.cuda.current_stream().wait_stream(self.stream) data = self.output_queue.get() self.proc_next_input.set() if data is None: raise StopIteration return data def __del__(self): self.done_event.set() self.proc_next_input.set() torch.cuda.current_stream().wait_stream(self.stream) self.preproc_thread.join()"
},
{
"code": null,
"e": 12352,
"s": 11843,
"text": "In my testing, the new full CPU pipeline detailed above is about twice as fast as TorchVision’s data loader, whilst achieving nearly the same maximum batch size. The CPU pipeline works great with large models like ResNet50; however, when using small models like AlexNet or ResNet18, the CPU pipeline still isn’t able to keep up with the GPU. For these cases, the example GPU pipeline works best. The trouble is that the GPU pipeline reduces the maximum possible batch size by almost 50%, limiting throughput."
},
{
"code": null,
"e": 12611,
"s": 12352,
"text": "One way to significantly reduce GPU memory usage is by keeping the validation pipeline off the GPU until it’s actually needed at the end of an epoch. This is easy to do as we’re already reimporting the DALI library and recreating data loaders at every epoch."
},
{
"code": null,
"e": 12637,
"s": 12611,
"text": "More tips for using DALI:"
},
{
"code": null,
"e": 12843,
"s": 12637,
"text": "* For validation, a batch size that evenly divides the dataset size works best e.g. 500 instead of 512 for a validation set size of 50000 — this avoids a partial batch at the end of the validation dataset."
},
{
"code": null,
"e": 13272,
"s": 12843,
"text": "* Similar to the Tensorflow & PyTorch data loaders, the TorchVision and DALI pipelines don’t produce bit-identical outputs — you’ll see the validation accuracies differ slightly. I found that this is due to different JPEG image decoders. There was previously an issue with resizing but this is now fixed. The flipside is that DALI supports TensorRT, allowing for the exact same preprocessing to be used for training & inference."
},
{
"code": null,
"e": 13437,
"s": 13272,
"text": "* For peak throughput, try setting the number of data loader workers to number_of_virtual_CPU cores. 2 gave the best performance (2 virtual cores = 1 physical core)"
},
{
"code": null,
"e": 13603,
"s": 13437,
"text": "* If you want absolute best performance and don’t care about having outputs similar to TorchVision, try turning off triangular interpolation on the DALI image resize"
},
{
"code": null,
"e": 13749,
"s": 13603,
"text": "* Don’t forget about disk IO. Make sure you have enough RAM to cache the dataset and/or a really fast SSD. DALI can pull up to 400Mb/s from disk!"
},
{
"code": null,
"e": 13960,
"s": 13749,
"text": "To help integrate these modifications easily, I created a data loader class with all the modifications described here, including both DALI and TorchVision backends. Usage is simple. Instantiate the data loader:"
},
{
"code": null,
"e": 14153,
"s": 13960,
"text": "dataset = Dataset(data_dir, batch_size, val_batch_size workers, use_dali, dali_cpu, fp16)"
},
{
"code": null,
"e": 14199,
"s": 14153,
"text": "Then get the train & validation data loaders:"
},
{
"code": null,
"e": 14278,
"s": 14199,
"text": "train_loader = dataset.get_train_loader()val_loader = dataset.get_val_loader()"
},
{
"code": null,
"e": 14336,
"s": 14278,
"text": "Reset the data loader at the end of every training epoch:"
},
{
"code": null,
"e": 14352,
"s": 14336,
"text": "dataset.reset()"
},
{
"code": null,
"e": 14439,
"s": 14352,
"text": "Optionally, the validation pipeline can be recreated on GPU prior to model validation:"
},
{
"code": null,
"e": 14462,
"s": 14439,
"text": "dataset.prep_for_val()"
},
{
"code": null,
"e": 14524,
"s": 14462,
"text": "Here are the max batch sizes I was able to use with ResNet18:"
},
{
"code": null,
"e": 14639,
"s": 14524,
"text": "So, by applying these modifications, the max batch size DALI can use in both CPU & GPU modes is increased by ~50%!"
},
{
"code": null,
"e": 14713,
"s": 14639,
"text": "Here are some throughput figures with Shufflenet V2 0.5 & batch size 512:"
},
{
"code": null,
"e": 14821,
"s": 14713,
"text": "And here are some results of using the DALI GPU pipeline to train various networks included in TorchVision:"
},
{
"code": null,
"e": 15095,
"s": 14821,
"text": "All tests were run on a Google Cloud V100 instance with 12 vCPUs (6 physical cores), 78GB RAM & using Apex FP16 training. To reproduce these results, use the following arguments: — fp16 — batch-size 512 — workers 10 — arch “shufflenet_v2_x0_5 or resnet18” — prof — use-dali"
},
{
"code": null,
"e": 15459,
"s": 15095,
"text": "So, with DALI, a single Tesla V100 can reach speeds of nearly 4000 image/s! That’s just over half of what Nvidia’s super expensive DGX-1 with 8 V100 GPUs can do (albeit using small models). For me, being able to do an ImageNet training run on a single GPU in a few hours was a productivity game changer. Hopefully it will be for you as well. Feedback appreciated!"
},
{
"code": null,
"e": 15502,
"s": 15459,
"text": "The code presented in this article is here"
},
{
"code": null,
"e": 15584,
"s": 15502,
"text": "Many thanks to Patricia Thaine for her feedback on an earlier draft of this post."
}
] |
SWING - MouseEvent Class
|
This event indicates that a mouse action occurred in a component. This low-level event is generated by a component object for Mouse Events and Mouse motion events. This event is generated when −
A mouse button is pressed.
A mouse button is pressed.
A mouse button is released.
A mouse button is released.
A mouse button is clicked (pressed and released).
A mouse button is clicked (pressed and released).
A mouse cursor enters the unobscured part of component's geometry.
A mouse cursor enters the unobscured part of component's geometry.
A mouse cursor exits the unobscured part of component's geometry.
A mouse cursor exits the unobscured part of component's geometry.
A mouse is moved.
A mouse is moved.
A mouse is dragged.
A mouse is dragged.
Following is the declaration for java.awt.event.MouseEvent class −
public class MouseEvent
extends InputEvent
Following are the fields for java.awt.event.MouseEvent class −
static int BUTTON1 − Indicates mouse button #1; used by getButton()
static int BUTTON1 − Indicates mouse button #1; used by getButton()
static int BUTTON2 − Indicates mouse button #2; used by getButton()
static int BUTTON2 − Indicates mouse button #2; used by getButton()
static int BUTTON3 − Indicates mouse button #3; used by getButton()
static int BUTTON3 − Indicates mouse button #3; used by getButton()
static int MOUSE_CLICKED − The "mouse clicked" event
static int MOUSE_CLICKED − The "mouse clicked" event
static int MOUSE_DRAGGED − The "mouse dragged" event
static int MOUSE_DRAGGED − The "mouse dragged" event
static int MOUSE_ENTERED − The "mouse entered" event
static int MOUSE_ENTERED − The "mouse entered" event
static int MOUSE_EXITED − The "mouse exited" event
static int MOUSE_EXITED − The "mouse exited" event
static int MOUSE_FIRST − The first number in the range of IDs used for mouse events
static int MOUSE_FIRST − The first number in the range of IDs used for mouse events
static int MOUSE_LAST − The last number in the range of IDs used for mouse events
static int MOUSE_LAST − The last number in the range of IDs used for mouse events
static int MOUSE_MOVED − The "mouse moved" event
static int MOUSE_MOVED − The "mouse moved" event
static int MOUSE_PRESSED − The "mouse pressed" event
static int MOUSE_PRESSED − The "mouse pressed" event
static int MOUSE_RELEASED − The "mouse released" event
static int MOUSE_RELEASED − The "mouse released" event
static int MOUSE_WHEEL − The "mouse wheel" event
static int MOUSE_WHEEL − The "mouse wheel" event
static int NOBUTTON − Indicates no mouse buttons; used by getButton()
static int NOBUTTON − Indicates no mouse buttons; used by getButton()
static int VK_WINDOWS − Constant for the Microsoft Windows "Windows" key.
static int VK_WINDOWS − Constant for the Microsoft Windows "Windows" key.
MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger)
Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.
MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger, int button)
Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.
MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int xAbs, int yAbs, int clickCount, boolean popupTrigger, int button)
Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, absolute coordinates, and click count.
int getButton()
Returns which, if any, of the mouse buttons has changed state.
int getClickCount()
Returns the number of mouse clicks associated with this event.
Point getLocationOnScreen()
Returns the absolute x, y position of the event.
static String getMouseModifiersText(int modifiers)
Returns a String describing the modifier keys and mouse buttons that were down during the event, such as "Shift", or "Ctrl+Shift".
Point getPoint()
Returns the x,y position of the event relative to the source component.
int getX()
Returns the horizontal x position of the event relative to the source component.
int getXOnScreen()
Returns the absolute horizontal x position of the event.
int getY()
Returns the vertical y position of the event relative to the source component.
int getYOnScreen()
Returns the absolute vertical y position of the event.
boolean isPopupTrigger()
Returns whether or not this mouse event is the popup menu trigger event for the platform.
String paramString()
Returns a parameter string identifying this event.
void translatePoint(int x, int y)
Translates the event's coordinates to a new position by adding specified x (horizontal) and y (vertical) offsets.
This class inherits methods from the following classes −
java.awt.event.InputEvent
java.awt.event.ComponentEvent
java.awt.AWTEvent
java.util.EventObject
java.lang.Object
30 Lectures
3.5 hours
Pranjal Srivastava
13 Lectures
1 hours
Pranjal Srivastava
25 Lectures
4.5 hours
Emenwa Global, Ejike IfeanyiChukwu
14 Lectures
1.5 hours
Travis Rose
14 Lectures
1 hours
Travis Rose
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1958,
"s": 1763,
"text": "This event indicates that a mouse action occurred in a component. This low-level event is generated by a component object for Mouse Events and Mouse motion events. This event is generated when −"
},
{
"code": null,
"e": 1985,
"s": 1958,
"text": "A mouse button is pressed."
},
{
"code": null,
"e": 2012,
"s": 1985,
"text": "A mouse button is pressed."
},
{
"code": null,
"e": 2040,
"s": 2012,
"text": "A mouse button is released."
},
{
"code": null,
"e": 2068,
"s": 2040,
"text": "A mouse button is released."
},
{
"code": null,
"e": 2118,
"s": 2068,
"text": "A mouse button is clicked (pressed and released)."
},
{
"code": null,
"e": 2168,
"s": 2118,
"text": "A mouse button is clicked (pressed and released)."
},
{
"code": null,
"e": 2235,
"s": 2168,
"text": "A mouse cursor enters the unobscured part of component's geometry."
},
{
"code": null,
"e": 2302,
"s": 2235,
"text": "A mouse cursor enters the unobscured part of component's geometry."
},
{
"code": null,
"e": 2368,
"s": 2302,
"text": "A mouse cursor exits the unobscured part of component's geometry."
},
{
"code": null,
"e": 2434,
"s": 2368,
"text": "A mouse cursor exits the unobscured part of component's geometry."
},
{
"code": null,
"e": 2452,
"s": 2434,
"text": "A mouse is moved."
},
{
"code": null,
"e": 2470,
"s": 2452,
"text": "A mouse is moved."
},
{
"code": null,
"e": 2490,
"s": 2470,
"text": "A mouse is dragged."
},
{
"code": null,
"e": 2510,
"s": 2490,
"text": "A mouse is dragged."
},
{
"code": null,
"e": 2577,
"s": 2510,
"text": "Following is the declaration for java.awt.event.MouseEvent class −"
},
{
"code": null,
"e": 2624,
"s": 2577,
"text": "public class MouseEvent\n extends InputEvent\n"
},
{
"code": null,
"e": 2687,
"s": 2624,
"text": "Following are the fields for java.awt.event.MouseEvent class −"
},
{
"code": null,
"e": 2755,
"s": 2687,
"text": "static int BUTTON1 − Indicates mouse button #1; used by getButton()"
},
{
"code": null,
"e": 2823,
"s": 2755,
"text": "static int BUTTON1 − Indicates mouse button #1; used by getButton()"
},
{
"code": null,
"e": 2891,
"s": 2823,
"text": "static int BUTTON2 − Indicates mouse button #2; used by getButton()"
},
{
"code": null,
"e": 2959,
"s": 2891,
"text": "static int BUTTON2 − Indicates mouse button #2; used by getButton()"
},
{
"code": null,
"e": 3027,
"s": 2959,
"text": "static int BUTTON3 − Indicates mouse button #3; used by getButton()"
},
{
"code": null,
"e": 3095,
"s": 3027,
"text": "static int BUTTON3 − Indicates mouse button #3; used by getButton()"
},
{
"code": null,
"e": 3148,
"s": 3095,
"text": "static int MOUSE_CLICKED − The \"mouse clicked\" event"
},
{
"code": null,
"e": 3201,
"s": 3148,
"text": "static int MOUSE_CLICKED − The \"mouse clicked\" event"
},
{
"code": null,
"e": 3254,
"s": 3201,
"text": "static int MOUSE_DRAGGED − The \"mouse dragged\" event"
},
{
"code": null,
"e": 3307,
"s": 3254,
"text": "static int MOUSE_DRAGGED − The \"mouse dragged\" event"
},
{
"code": null,
"e": 3360,
"s": 3307,
"text": "static int MOUSE_ENTERED − The \"mouse entered\" event"
},
{
"code": null,
"e": 3413,
"s": 3360,
"text": "static int MOUSE_ENTERED − The \"mouse entered\" event"
},
{
"code": null,
"e": 3464,
"s": 3413,
"text": "static int MOUSE_EXITED − The \"mouse exited\" event"
},
{
"code": null,
"e": 3515,
"s": 3464,
"text": "static int MOUSE_EXITED − The \"mouse exited\" event"
},
{
"code": null,
"e": 3599,
"s": 3515,
"text": "static int MOUSE_FIRST − The first number in the range of IDs used for mouse events"
},
{
"code": null,
"e": 3683,
"s": 3599,
"text": "static int MOUSE_FIRST − The first number in the range of IDs used for mouse events"
},
{
"code": null,
"e": 3765,
"s": 3683,
"text": "static int MOUSE_LAST − The last number in the range of IDs used for mouse events"
},
{
"code": null,
"e": 3847,
"s": 3765,
"text": "static int MOUSE_LAST − The last number in the range of IDs used for mouse events"
},
{
"code": null,
"e": 3896,
"s": 3847,
"text": "static int MOUSE_MOVED − The \"mouse moved\" event"
},
{
"code": null,
"e": 3945,
"s": 3896,
"text": "static int MOUSE_MOVED − The \"mouse moved\" event"
},
{
"code": null,
"e": 3998,
"s": 3945,
"text": "static int MOUSE_PRESSED − The \"mouse pressed\" event"
},
{
"code": null,
"e": 4051,
"s": 3998,
"text": "static int MOUSE_PRESSED − The \"mouse pressed\" event"
},
{
"code": null,
"e": 4106,
"s": 4051,
"text": "static int MOUSE_RELEASED − The \"mouse released\" event"
},
{
"code": null,
"e": 4161,
"s": 4106,
"text": "static int MOUSE_RELEASED − The \"mouse released\" event"
},
{
"code": null,
"e": 4210,
"s": 4161,
"text": "static int MOUSE_WHEEL − The \"mouse wheel\" event"
},
{
"code": null,
"e": 4259,
"s": 4210,
"text": "static int MOUSE_WHEEL − The \"mouse wheel\" event"
},
{
"code": null,
"e": 4329,
"s": 4259,
"text": "static int NOBUTTON − Indicates no mouse buttons; used by getButton()"
},
{
"code": null,
"e": 4399,
"s": 4329,
"text": "static int NOBUTTON − Indicates no mouse buttons; used by getButton()"
},
{
"code": null,
"e": 4473,
"s": 4399,
"text": "static int VK_WINDOWS − Constant for the Microsoft Windows \"Windows\" key."
},
{
"code": null,
"e": 4547,
"s": 4473,
"text": "static int VK_WINDOWS − Constant for the Microsoft Windows \"Windows\" key."
},
{
"code": null,
"e": 4662,
"s": 4547,
"text": "MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger)"
},
{
"code": null,
"e": 4777,
"s": 4662,
"text": "Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count."
},
{
"code": null,
"e": 4904,
"s": 4777,
"text": "MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger, int button)"
},
{
"code": null,
"e": 5019,
"s": 4904,
"text": "Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count."
},
{
"code": null,
"e": 5166,
"s": 5019,
"text": "MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int xAbs, int yAbs, int clickCount, boolean popupTrigger, int button)"
},
{
"code": null,
"e": 5303,
"s": 5166,
"text": "Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, absolute coordinates, and click count."
},
{
"code": null,
"e": 5319,
"s": 5303,
"text": "int getButton()"
},
{
"code": null,
"e": 5382,
"s": 5319,
"text": "Returns which, if any, of the mouse buttons has changed state."
},
{
"code": null,
"e": 5402,
"s": 5382,
"text": "int getClickCount()"
},
{
"code": null,
"e": 5465,
"s": 5402,
"text": "Returns the number of mouse clicks associated with this event."
},
{
"code": null,
"e": 5493,
"s": 5465,
"text": "Point getLocationOnScreen()"
},
{
"code": null,
"e": 5542,
"s": 5493,
"text": "Returns the absolute x, y position of the event."
},
{
"code": null,
"e": 5593,
"s": 5542,
"text": "static String getMouseModifiersText(int modifiers)"
},
{
"code": null,
"e": 5724,
"s": 5593,
"text": "Returns a String describing the modifier keys and mouse buttons that were down during the event, such as \"Shift\", or \"Ctrl+Shift\"."
},
{
"code": null,
"e": 5741,
"s": 5724,
"text": "Point getPoint()"
},
{
"code": null,
"e": 5813,
"s": 5741,
"text": "Returns the x,y position of the event relative to the source component."
},
{
"code": null,
"e": 5824,
"s": 5813,
"text": "int getX()"
},
{
"code": null,
"e": 5905,
"s": 5824,
"text": "Returns the horizontal x position of the event relative to the source component."
},
{
"code": null,
"e": 5924,
"s": 5905,
"text": "int getXOnScreen()"
},
{
"code": null,
"e": 5981,
"s": 5924,
"text": "Returns the absolute horizontal x position of the event."
},
{
"code": null,
"e": 5992,
"s": 5981,
"text": "int getY()"
},
{
"code": null,
"e": 6071,
"s": 5992,
"text": "Returns the vertical y position of the event relative to the source component."
},
{
"code": null,
"e": 6090,
"s": 6071,
"text": "int getYOnScreen()"
},
{
"code": null,
"e": 6145,
"s": 6090,
"text": "Returns the absolute vertical y position of the event."
},
{
"code": null,
"e": 6170,
"s": 6145,
"text": "boolean isPopupTrigger()"
},
{
"code": null,
"e": 6260,
"s": 6170,
"text": "Returns whether or not this mouse event is the popup menu trigger event for the platform."
},
{
"code": null,
"e": 6281,
"s": 6260,
"text": "String paramString()"
},
{
"code": null,
"e": 6332,
"s": 6281,
"text": "Returns a parameter string identifying this event."
},
{
"code": null,
"e": 6366,
"s": 6332,
"text": "void translatePoint(int x, int y)"
},
{
"code": null,
"e": 6480,
"s": 6366,
"text": "Translates the event's coordinates to a new position by adding specified x (horizontal) and y (vertical) offsets."
},
{
"code": null,
"e": 6537,
"s": 6480,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 6563,
"s": 6537,
"text": "java.awt.event.InputEvent"
},
{
"code": null,
"e": 6593,
"s": 6563,
"text": "java.awt.event.ComponentEvent"
},
{
"code": null,
"e": 6611,
"s": 6593,
"text": "java.awt.AWTEvent"
},
{
"code": null,
"e": 6633,
"s": 6611,
"text": "java.util.EventObject"
},
{
"code": null,
"e": 6650,
"s": 6633,
"text": "java.lang.Object"
},
{
"code": null,
"e": 6685,
"s": 6650,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6705,
"s": 6685,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6738,
"s": 6705,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6758,
"s": 6738,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6793,
"s": 6758,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6829,
"s": 6793,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 6864,
"s": 6829,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6877,
"s": 6864,
"text": " Travis Rose"
},
{
"code": null,
"e": 6910,
"s": 6877,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6923,
"s": 6910,
"text": " Travis Rose"
},
{
"code": null,
"e": 6930,
"s": 6923,
"text": " Print"
},
{
"code": null,
"e": 6941,
"s": 6930,
"text": " Add Notes"
}
] |
How to read inputs as integers in C#?
|
To read inputs as integers in C#, use the Convert.ToInt32() method.
res = Convert.ToInt32(val);
Let us see how −
The Convert.ToInt32 converts the specified string representation of a number to an equivalent 32-bit signed integer.
Firstly, read the console input −
string val;
val = Console.ReadLine();
After reading, convert it to an integer.
int res;
res = Convert.ToInt32(val);
Let us see an example −
Live Demo
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
string val;
int res;
Console.WriteLine("Input from user: ");
val = Console.ReadLine();
// convert to integer
res = Convert.ToInt32(val);
// display the line
Console.WriteLine("Input = {0}", res);
}
}
Input from user:
Input = 0
The following is the output. The input is entered by the user.
Input from user: 2
Input = 2
|
[
{
"code": null,
"e": 1130,
"s": 1062,
"text": "To read inputs as integers in C#, use the Convert.ToInt32() method."
},
{
"code": null,
"e": 1158,
"s": 1130,
"text": "res = Convert.ToInt32(val);"
},
{
"code": null,
"e": 1175,
"s": 1158,
"text": "Let us see how −"
},
{
"code": null,
"e": 1292,
"s": 1175,
"text": "The Convert.ToInt32 converts the specified string representation of a number to an equivalent 32-bit signed integer."
},
{
"code": null,
"e": 1326,
"s": 1292,
"text": "Firstly, read the console input −"
},
{
"code": null,
"e": 1364,
"s": 1326,
"text": "string val;\nval = Console.ReadLine();"
},
{
"code": null,
"e": 1405,
"s": 1364,
"text": "After reading, convert it to an integer."
},
{
"code": null,
"e": 1442,
"s": 1405,
"text": "int res;\nres = Convert.ToInt32(val);"
},
{
"code": null,
"e": 1466,
"s": 1442,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1477,
"s": 1466,
"text": " Live Demo"
},
{
"code": null,
"e": 1820,
"s": 1477,
"text": "using System;\nusing System.Collections.Generic;\n\nclass Demo {\n static void Main() {\n string val;\n int res;\n \n Console.WriteLine(\"Input from user: \");\n val = Console.ReadLine();\n\n // convert to integer\n res = Convert.ToInt32(val);\n\n // display the line\n Console.WriteLine(\"Input = {0}\", res);\n }\n}"
},
{
"code": null,
"e": 1847,
"s": 1820,
"text": "Input from user:\nInput = 0"
},
{
"code": null,
"e": 1910,
"s": 1847,
"text": "The following is the output. The input is entered by the user."
},
{
"code": null,
"e": 1939,
"s": 1910,
"text": "Input from user: 2\nInput = 2"
}
] |
Class getDeclaredConstructors() method in Java with Examples - GeeksforGeeks
|
05 Jun, 2021
The getDeclaredConstructors() method of java.lang.Class class is used to get the constructors of this class, which are the constructors that are private, public, protected or default. The method returns the constructors of this class in the form of array of Constructor objects. Syntax:
public Constructor[] getDeclaredConstructors()
throws SecurityException
Parameter: This method does not accept any parameter.Return Value: This method returns the constructors of this class in the form of an array of Constructor objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredConstructors() method.Example 1:
Java
// Java program to demonstrate// getDeclaredConstructors() method import java.util.*; 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 constructors of myClass // using getDeclaredConstructors() method System.out.println( "DeclaredConstructors of myClass: " + Arrays.toString( myClass.getDeclaredConstructors())); }}
Class represented by myClass: class Test
DeclaredConstructors of myClass: [public Test()]
Example 2:
Java
// Java program to demonstrate//getDeclaredConstructors() method import java.util.*; class Main { public Object obj; private Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the constructors of myClass // using getDeclaredConstructors() method System.out.println( "DeclaredConstructors of myClass: " + Arrays.toString( myClass.getDeclaredConstructors())); }}
Class represented by myClass: class Main
DeclaredConstructors of myClass: [private Main()]
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredConstructors–
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.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n05 Jun, 2021"
},
{
"code": null,
"e": 23846,
"s": 23557,
"text": "The getDeclaredConstructors() method of java.lang.Class class is used to get the constructors of this class, which are the constructors that are private, public, protected or default. The method returns the constructors of this class in the form of array of Constructor objects. Syntax: "
},
{
"code": null,
"e": 23940,
"s": 23846,
"text": "public Constructor[] getDeclaredConstructors()\n throws SecurityException"
},
{
"code": null,
"e": 24302,
"s": 23940,
"text": "Parameter: This method does not accept any parameter.Return Value: This method returns the constructors of this class in the form of an array of Constructor objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredConstructors() method.Example 1: "
},
{
"code": null,
"e": 24307,
"s": 24302,
"text": "Java"
},
{
"code": "// Java program to demonstrate// getDeclaredConstructors() method import java.util.*; 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 constructors of myClass // using getDeclaredConstructors() method System.out.println( \"DeclaredConstructors of myClass: \" + Arrays.toString( myClass.getDeclaredConstructors())); }}",
"e": 24959,
"s": 24307,
"text": null
},
{
"code": null,
"e": 25049,
"s": 24959,
"text": "Class represented by myClass: class Test\nDeclaredConstructors of myClass: [public Test()]"
},
{
"code": null,
"e": 25063,
"s": 25051,
"text": "Example 2: "
},
{
"code": null,
"e": 25068,
"s": 25063,
"text": "Java"
},
{
"code": "// Java program to demonstrate//getDeclaredConstructors() method import java.util.*; class Main { public Object obj; private Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the constructors of myClass // using getDeclaredConstructors() method System.out.println( \"DeclaredConstructors of myClass: \" + Arrays.toString( myClass.getDeclaredConstructors())); }}",
"e": 25819,
"s": 25068,
"text": null
},
{
"code": null,
"e": 25910,
"s": 25819,
"text": "Class represented by myClass: class Main\nDeclaredConstructors of myClass: [private Main()]"
},
{
"code": null,
"e": 26012,
"s": 25912,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredConstructors– "
},
{
"code": null,
"e": 26027,
"s": 26012,
"text": "adnanirshad158"
},
{
"code": null,
"e": 26042,
"s": 26027,
"text": "Java-Functions"
},
{
"code": null,
"e": 26060,
"s": 26042,
"text": "Java-lang package"
},
{
"code": null,
"e": 26076,
"s": 26060,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 26081,
"s": 26076,
"text": "Java"
},
{
"code": null,
"e": 26086,
"s": 26081,
"text": "Java"
},
{
"code": null,
"e": 26184,
"s": 26086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26193,
"s": 26184,
"text": "Comments"
},
{
"code": null,
"e": 26206,
"s": 26193,
"text": "Old Comments"
},
{
"code": null,
"e": 26236,
"s": 26206,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26251,
"s": 26236,
"text": "Stream In Java"
},
{
"code": null,
"e": 26272,
"s": 26251,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26318,
"s": 26272,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26337,
"s": 26318,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26354,
"s": 26337,
"text": "Generics in Java"
},
{
"code": null,
"e": 26397,
"s": 26354,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26413,
"s": 26397,
"text": "Strings in Java"
},
{
"code": null,
"e": 26462,
"s": 26413,
"text": "How to remove an element from ArrayList in Java?"
}
] |
How to change the number of breaks on a datetime axis with R and ggplot2 | by Douglas Watson | Towards Data Science
|
It took me a surprising amount of time to find how to change the tick interval on ggplot2 datetime axes, without manually specifying the date of each position. The solution is surprisingly simple and clear once you know the syntax:
scale_x_datetime(breaks = date_breaks("12 hours"))
This places a break every 12 hours. The interval can be any value accepted by the scales package: “sec”, “min”, “hour”, “day”, “week”, “month”, or “year”. The trailing s is ignored. Read along for examples and instructions on how to rotate the label text.
Let’s illustrate with some fake data. I’ve re-used the CSV data from my Shiny tutorial. You can download the file here. The format looks like this:
"timestamp","date","origin","variable","value" 1448315085.07,2015-11-23 21:44:45,"kitchen","temperature",24.4 1448315085.07,2015-11-23 21:44:45,"kitchen","humidity",44.9 1448315085.07,2015-11-23 21:44:45,"bedroom","temperature",24.8 1448315085.07,2015-11-23 21:44:45,"bedroom","humidity",46.1 1448318685.07,2015-11-23 22:44:45,"kitchen","temperature",23 1448318685.07,2015-11-23 22:44:45,"kitchen","humidity",41.1 1448318685.07,2015-11-23 22:44:45,"bedroom","temperature",23.6 1448318685.07,2015-11-23 22:44:45,"bedroom","humidity",45.7 1448322285.07,2015-11-23 23:44:45,"kitchen","temperature",23.4 ...
Let’s load it into an R dataframe, making sure to convert the date column to an R datetime object (see my previous post on the subject), then create a simple plot of temperature versus time:
library(ggplot2) library(dplyr) data <- read.csv("data.csv") data$date <- as.POSIXct(data$date) temperatures <- filter(data, variable == "temperature", origin == "kitchen") qplot(date, value, data = temperatures, geom="line", ylab = "Temperature [C]")
The default breaks are quite sensible, but for the sake of illustration let’s change them to a break every two days. The label format follows strftime syntax (see http://www.foragoodstrftime.com/ for help building them):
qplot(date, value, data = temperatures, geom="line", ylab = "Temperature [C]") + scale_x_datetime(breaks = date_breaks("2 day"), labels = date_format("%b %d"))
You can see the number of breaks has changed. Most of the time, I’m more interested in increasing their density. Let’s switch to an interval in hours, and also include the time in the labels:
qplot(date, value, data = temperatures, geom="line", ylab = "Temperature [C]") + scale_x_datetime(breaks = date_breaks("12 hour"), labels = date_format("%b %d - %H:%M"))
Ouch! The labels are unreadable. Thankfully we can rotate the text to prevent them from overlapping:
qplot(date, value, data = temperatures, geom="line", ylab = "Temperature [C]") + scale_x_datetime(breaks = date_breaks("12 hour"), labels = date_format("%b %d - %H:%M")) + theme(axis.text.x = element_text(angle = 25, vjust = 1.0, hjust = 1.0))
That’s a lot better! If you set the angle to 90 degrees, or if you have an older version of R, you will need to play with the vjust and hjust values until the labels line up correctly. Try adding debug = TRUE to element_text to display the text anchor point.
I found myself loading the same data format and making similar graphs across many R notebooks, so I wrote a small library of functions that I could re-use in all of my analyses. Hillary Parker’s guide explains everything you need to write your own. My functions resemble the code below, where I can optionally specify a tick interval. The labels include the time automatically if I specify an interval in hours. If I leave the argument blank, ggplot keeps its defaults:
plot_temperature <- function(data, title = "", breaks = "", angle = 25) { p <- ggplot2::qplot(date, value, data = data, ylab="Temperature [C]") if (title != '') { p <- p + ggplot2::ggtitle(title) } if ( breaks != '' ) { if ( grepl("hour", breaks) ) { fmt <- "%b %d - %H:%M" } else { fmt <- "%b %d" } p <- p + ggplot2::scale_x_datetime(date_breaks = breaks, date_labels = fmt) + ggplot2::theme(axis.text.x = ggplot2::element_text( angle = angle, vjust = 1.0, hjust = 1.0 )) } return(p)}
When you move your function to an external library, it’s important to specify the namespace of every function you call. Hence the ggplot2:: scattered all over.
Originally published at douglas-watson.github.io.
|
[
{
"code": null,
"e": 403,
"s": 171,
"text": "It took me a surprising amount of time to find how to change the tick interval on ggplot2 datetime axes, without manually specifying the date of each position. The solution is surprisingly simple and clear once you know the syntax:"
},
{
"code": null,
"e": 454,
"s": 403,
"text": "scale_x_datetime(breaks = date_breaks(\"12 hours\"))"
},
{
"code": null,
"e": 710,
"s": 454,
"text": "This places a break every 12 hours. The interval can be any value accepted by the scales package: “sec”, “min”, “hour”, “day”, “week”, “month”, or “year”. The trailing s is ignored. Read along for examples and instructions on how to rotate the label text."
},
{
"code": null,
"e": 858,
"s": 710,
"text": "Let’s illustrate with some fake data. I’ve re-used the CSV data from my Shiny tutorial. You can download the file here. The format looks like this:"
},
{
"code": null,
"e": 1462,
"s": 858,
"text": "\"timestamp\",\"date\",\"origin\",\"variable\",\"value\" 1448315085.07,2015-11-23 21:44:45,\"kitchen\",\"temperature\",24.4 1448315085.07,2015-11-23 21:44:45,\"kitchen\",\"humidity\",44.9 1448315085.07,2015-11-23 21:44:45,\"bedroom\",\"temperature\",24.8 1448315085.07,2015-11-23 21:44:45,\"bedroom\",\"humidity\",46.1 1448318685.07,2015-11-23 22:44:45,\"kitchen\",\"temperature\",23 1448318685.07,2015-11-23 22:44:45,\"kitchen\",\"humidity\",41.1 1448318685.07,2015-11-23 22:44:45,\"bedroom\",\"temperature\",23.6 1448318685.07,2015-11-23 22:44:45,\"bedroom\",\"humidity\",45.7 1448322285.07,2015-11-23 23:44:45,\"kitchen\",\"temperature\",23.4 ..."
},
{
"code": null,
"e": 1653,
"s": 1462,
"text": "Let’s load it into an R dataframe, making sure to convert the date column to an R datetime object (see my previous post on the subject), then create a simple plot of temperature versus time:"
},
{
"code": null,
"e": 1934,
"s": 1653,
"text": "library(ggplot2) library(dplyr) data <- read.csv(\"data.csv\") data$date <- as.POSIXct(data$date) temperatures <- filter(data, variable == \"temperature\", origin == \"kitchen\") qplot(date, value, data = temperatures, geom=\"line\", ylab = \"Temperature [C]\")"
},
{
"code": null,
"e": 2155,
"s": 1934,
"text": "The default breaks are quite sensible, but for the sake of illustration let’s change them to a break every two days. The label format follows strftime syntax (see http://www.foragoodstrftime.com/ for help building them):"
},
{
"code": null,
"e": 2346,
"s": 2155,
"text": "qplot(date, value, data = temperatures, geom=\"line\", ylab = \"Temperature [C]\") + scale_x_datetime(breaks = date_breaks(\"2 day\"), labels = date_format(\"%b %d\"))"
},
{
"code": null,
"e": 2538,
"s": 2346,
"text": "You can see the number of breaks has changed. Most of the time, I’m more interested in increasing their density. Let’s switch to an interval in hours, and also include the time in the labels:"
},
{
"code": null,
"e": 2739,
"s": 2538,
"text": "qplot(date, value, data = temperatures, geom=\"line\", ylab = \"Temperature [C]\") + scale_x_datetime(breaks = date_breaks(\"12 hour\"), labels = date_format(\"%b %d - %H:%M\"))"
},
{
"code": null,
"e": 2840,
"s": 2739,
"text": "Ouch! The labels are unreadable. Thankfully we can rotate the text to prevent them from overlapping:"
},
{
"code": null,
"e": 3155,
"s": 2840,
"text": "qplot(date, value, data = temperatures, geom=\"line\", ylab = \"Temperature [C]\") + scale_x_datetime(breaks = date_breaks(\"12 hour\"), labels = date_format(\"%b %d - %H:%M\")) + theme(axis.text.x = element_text(angle = 25, vjust = 1.0, hjust = 1.0))"
},
{
"code": null,
"e": 3414,
"s": 3155,
"text": "That’s a lot better! If you set the angle to 90 degrees, or if you have an older version of R, you will need to play with the vjust and hjust values until the labels line up correctly. Try adding debug = TRUE to element_text to display the text anchor point."
},
{
"code": null,
"e": 3884,
"s": 3414,
"text": "I found myself loading the same data format and making similar graphs across many R notebooks, so I wrote a small library of functions that I could re-use in all of my analyses. Hillary Parker’s guide explains everything you need to write your own. My functions resemble the code below, where I can optionally specify a tick interval. The labels include the time automatically if I specify an interval in hours. If I leave the argument blank, ggplot keeps its defaults:"
},
{
"code": null,
"e": 4524,
"s": 3884,
"text": "plot_temperature <- function(data, title = \"\", breaks = \"\", angle = 25) { p <- ggplot2::qplot(date, value, data = data, ylab=\"Temperature [C]\") if (title != '') { p <- p + ggplot2::ggtitle(title) } if ( breaks != '' ) { if ( grepl(\"hour\", breaks) ) { fmt <- \"%b %d - %H:%M\" } else { fmt <- \"%b %d\" } p <- p + ggplot2::scale_x_datetime(date_breaks = breaks, date_labels = fmt) + ggplot2::theme(axis.text.x = ggplot2::element_text( angle = angle, vjust = 1.0, hjust = 1.0 )) } return(p)}"
},
{
"code": null,
"e": 4684,
"s": 4524,
"text": "When you move your function to an external library, it’s important to specify the namespace of every function you call. Hence the ggplot2:: scattered all over."
}
] |
A very simple demo of interactive controls on Jupyter notebook | by Tirthajyoti Sarkar | Towards Data Science
|
Project Jupyter/IPython has left one of the biggest degrees of impact on how a data scientist can quickly test and prototype his/her idea and showcase the work to peers and open-source community. It is a non-profit, open-source project, born out of the IPython Project in 2014, which rapidly evolved to support interactive data science and scientific computing across all major programming languages.
Jupyter allows a data scientist/analyst to play with a complex data set and test the model using any of the leading programming paradigms (Python, C++, R, Julia, Ruby, Lua, Haskell, and many more) of his/her choice. Behind its apparent simplicity, Jupyter offers powerful rendering capability to produce beautiful markup text and crisp graphics to make a data science/machine learning project come alive in all its glory. Here is an example of the entire basic set algebra tutorial written in Jupyter notebook.
However, learning and experimenting with data become truly immersive when user can interactively control the parameters of the model and see the effect (almost) real-time. Most of the common rendering in Jupyter are static. However, there is a big effort to introduce elements called ipywidgets, which renders fun and interactive controls on the Jupyter notebook. Based on these core elements, several 2D and 3D dynamic data visualization projects (e.g. bqplot, ipyleaflet) are also growing in size and scope.
In this article, I am showing a demo notebook with one of the simplest interactive control elements and how it can be integrated in a data modeling task to dynamically visualize the impact of model parameter tuning.
Widgets are eventful python objects that have a representation in the browser, often as a control like a slider, textbox, etc., through a front-end (HTML/Javascript) rendering channel. They use Jupyter ‘comms’ API, which is a symmetric, asynchronous, fire and forget style messaging API allowing the programmer to send JSON-able blobs between the front-end and the back-end and hiding the complexity of the web server, ZMQ, and web-sockets. Here is a detailed discussion.
You have two options for installing ipywidgets. They differ slightly, so note the difference. Basically, if you use pip, you also have to enable the ipywidget extension in your notebook to render it next time you start the notebook. You can enable it within any virtual environment you use, so that the extension does not impact any other environment.
pip install ipywidgetsjupyter nbextension enable --py widgetsnbextension
Or, you can do a Conda install (if you use Anaconda), it will be enabled automatically.
conda install -c conda-forge ipywidgets
The interact function (ipywidgets.interact) automatically creates user interface (UI) controls for exploring code and data interactively. It is the easiest way to get started using IPython’s widgets.
In addition to interact, IPython provides another function, interactive, that is useful when you want to reuse the widgets that are produced or access the data that is bound to the UI controls. Note that unlike interact, the return value of the function will not be displayed automatically, but you can display a value inside the function with IPython.display.display.
Boiler plate code is available on my GitHub repository. Please feel free to fork/download and play with it. We are essentially generating a Gaussian data with noise and playing with various model parameters with the help of interactive slide-bar or drop-down menu controls. After passing the function and rendering the display with the object, returned by the ipywidget.interactive (), here is what it looks like...
Next, we call curve-fitting optimizer function from Scipy package and fit a ideal Gaussian distribution function to the data. The code describes exactly how to extract the data from the ipywidget object and pass it on to the optimizer. You can play with various model parameters and see how the optimizer fitted/estimated parameters differ from the ideal values as the noise parameters are changed, all by sliding the controls left or right!
We discussed some basics about IPython widgets or interactive controls and why they can turn a dry data science code notebook into a fun, living document. We also showed a simple demo code to illustrate the idea in a statistical model fitting exercise. In future, we hope to show some more cool applications of widgets in machine learning model tuning or deep learning hyperparameter optimization.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
|
[
{
"code": null,
"e": 572,
"s": 171,
"text": "Project Jupyter/IPython has left one of the biggest degrees of impact on how a data scientist can quickly test and prototype his/her idea and showcase the work to peers and open-source community. It is a non-profit, open-source project, born out of the IPython Project in 2014, which rapidly evolved to support interactive data science and scientific computing across all major programming languages."
},
{
"code": null,
"e": 1083,
"s": 572,
"text": "Jupyter allows a data scientist/analyst to play with a complex data set and test the model using any of the leading programming paradigms (Python, C++, R, Julia, Ruby, Lua, Haskell, and many more) of his/her choice. Behind its apparent simplicity, Jupyter offers powerful rendering capability to produce beautiful markup text and crisp graphics to make a data science/machine learning project come alive in all its glory. Here is an example of the entire basic set algebra tutorial written in Jupyter notebook."
},
{
"code": null,
"e": 1593,
"s": 1083,
"text": "However, learning and experimenting with data become truly immersive when user can interactively control the parameters of the model and see the effect (almost) real-time. Most of the common rendering in Jupyter are static. However, there is a big effort to introduce elements called ipywidgets, which renders fun and interactive controls on the Jupyter notebook. Based on these core elements, several 2D and 3D dynamic data visualization projects (e.g. bqplot, ipyleaflet) are also growing in size and scope."
},
{
"code": null,
"e": 1809,
"s": 1593,
"text": "In this article, I am showing a demo notebook with one of the simplest interactive control elements and how it can be integrated in a data modeling task to dynamically visualize the impact of model parameter tuning."
},
{
"code": null,
"e": 2281,
"s": 1809,
"text": "Widgets are eventful python objects that have a representation in the browser, often as a control like a slider, textbox, etc., through a front-end (HTML/Javascript) rendering channel. They use Jupyter ‘comms’ API, which is a symmetric, asynchronous, fire and forget style messaging API allowing the programmer to send JSON-able blobs between the front-end and the back-end and hiding the complexity of the web server, ZMQ, and web-sockets. Here is a detailed discussion."
},
{
"code": null,
"e": 2633,
"s": 2281,
"text": "You have two options for installing ipywidgets. They differ slightly, so note the difference. Basically, if you use pip, you also have to enable the ipywidget extension in your notebook to render it next time you start the notebook. You can enable it within any virtual environment you use, so that the extension does not impact any other environment."
},
{
"code": null,
"e": 2706,
"s": 2633,
"text": "pip install ipywidgetsjupyter nbextension enable --py widgetsnbextension"
},
{
"code": null,
"e": 2794,
"s": 2706,
"text": "Or, you can do a Conda install (if you use Anaconda), it will be enabled automatically."
},
{
"code": null,
"e": 2834,
"s": 2794,
"text": "conda install -c conda-forge ipywidgets"
},
{
"code": null,
"e": 3034,
"s": 2834,
"text": "The interact function (ipywidgets.interact) automatically creates user interface (UI) controls for exploring code and data interactively. It is the easiest way to get started using IPython’s widgets."
},
{
"code": null,
"e": 3403,
"s": 3034,
"text": "In addition to interact, IPython provides another function, interactive, that is useful when you want to reuse the widgets that are produced or access the data that is bound to the UI controls. Note that unlike interact, the return value of the function will not be displayed automatically, but you can display a value inside the function with IPython.display.display."
},
{
"code": null,
"e": 3819,
"s": 3403,
"text": "Boiler plate code is available on my GitHub repository. Please feel free to fork/download and play with it. We are essentially generating a Gaussian data with noise and playing with various model parameters with the help of interactive slide-bar or drop-down menu controls. After passing the function and rendering the display with the object, returned by the ipywidget.interactive (), here is what it looks like..."
},
{
"code": null,
"e": 4261,
"s": 3819,
"text": "Next, we call curve-fitting optimizer function from Scipy package and fit a ideal Gaussian distribution function to the data. The code describes exactly how to extract the data from the ipywidget object and pass it on to the optimizer. You can play with various model parameters and see how the optimizer fitted/estimated parameters differ from the ideal values as the noise parameters are changed, all by sliding the controls left or right!"
},
{
"code": null,
"e": 4659,
"s": 4261,
"text": "We discussed some basics about IPython widgets or interactive controls and why they can turn a dry data science code notebook into a fun, living document. We also showed a simple demo code to illustrate the idea in a statistical model fitting exercise. In future, we hope to show some more cool applications of widgets in machine learning model tuning or deep learning hyperparameter optimization."
}
] |
Apache Commons CLI - Quick Guide
|
The Apache Commons CLI are the components of the Apache Commons which are derived from Java API and provides an API to parse command line arguments/options which are passed to the programs. This API also enables to print help related to options available.
Command line processing comprises of three stages. These stages are explained below −
Definition Stage
Parsing Stage
Interrogation Stage
In definition stage, we define the options that an application can take and act accordingly. Commons CLI provides Options class, which is a container for Option objects.
// create Options object
Options options = new Options();
// add a option
options.addOption("a", false, "add two numbers");
Here we have added an option flag a, while false as second parameter, signifies that option is not mandatory and third parameter states the description of option.
In parsing stage, we parse the options passed using command line arguments after creating a parser instance.
//Create a parser
CommandLineParser parser = new DefaultParser();
//parse the options passed as command line arguments
CommandLine cmd = parser.parse( options, args);
In Interrogation stage, we check if a particular option is present or not and then, process the command accordingly.
//hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
// add the two numbers
} else if(cmd.hasOption("m")) {
// multiply the two numbers
}
In this chapter, we will learn about the local environment setup of Apache Commons CLI and how to set up the path of Commons CLI for Windows 2000/XP, Windows 95/98/ME etc. We will also understand about some popular java editors and how to download Commons CLI archive.
If you are still willing to set up your environment for Java programming language, then this chapter will guide you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment.
Java SE is freely available from the link https://www.oracle.com/java/technologies/oracle-java-archive-downloads.html. So you can download a version based on your operating system.
Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.
We are assuming that you have installed Java in c:\Program Files\java\jdk directory.
Right-click on 'My Computer' and select 'Properties'.
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, alter the 'Path' variable, so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Now, alter the 'Path' variable, so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
We are assuming that you have installed Java in c:\Program Files\java\jdk directory.
Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'.
Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'.
Environment variable PATH should be set to point, where the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'
To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −
Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.
Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.
Download the latest version of Apache Common CLI jar file from commons-cli-1.4-bin.zip. At the time of writing this tutorial, we have downloaded commons-cli-1.4-bin.zip and copied it into C:\>Apache folder.
Set the APACHE_HOME environment variable to point to the base directory location where, Apache jar is stored on your machine. Assume that we have extracted commonscollections4-4.1-bin.zip in Apache folder on various Operating Systems as follows −
Set the CLASSPATH environment variable to point to the Common CLI jar location. Assume that you have stored commons-cli-1.4.jar in Apache folder on various Operating Systems as follows −
Let's create a sample console based application, whose purpose is to get either sum of passed numbers or multiplication of passed numbers based on the options used.
Create a java class named CLITester.
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
//***Definition Stage***
// create Options object
Options options = new Options();
// add option "-a"
options.addOption("a", false, "add numbers");
// add option "-m"
options.addOption("m", false, "multiply numbers");
//***Parsing Stage***
//Create a parser
CommandLineParser parser = new DefaultParser();
//parse the options passed as command line arguments
CommandLine cmd = parser.parse( options, args);
//***Interrogation Stage***
//hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
System.out.println("Sum of the numbers: " + getSum(args));
} else if(cmd.hasOption("m")) {
System.out.println("Multiplication of the numbers: " + getMultiplication(args));
}
}
public static int getSum(String[] args) {
int sum = 0;
for(int i = 1; i < args.length ; i++) {
sum += Integer.parseInt(args[i]);
}
return sum;
}
public static int getMultiplication(String[] args) {
int multiplication = 1;
for(int i = 1; i < args.length ; i++) {
multiplication *= Integer.parseInt(args[i]);
}
return multiplication;
}
}
Run the file, while passing -a as option and numbers to get the sum of the numbers as result.
java CLITester -a 1 2 3 4 5
Sum of the numbers: 15
Run the file, while passing -m as option and numbers to get the multiplication of the numbers as result.
java CLITester -m 1 2 3 4 5
Multiplication of the numbers: 120
Option object is used to represent the Option passed to command line program. Following are various properties that an Option object possess.
opt (String)
Identification string of the Option.
longOpt (String)
Alias and more descriptive identification string.
description (String)
Description of the function of the option.
required (boolean)
Flag to check whether the option must appear on the command line.
arg (boolean)
Flag to check whether the option takes an argument.
args (boolean)
Flag to check whether the option takes more than one argument.
optionalArg (boolean)
Flag to check whether the option's argument is optional.
argName (String)
Name of the argument value for the usage statement.
valueSeparator (char)
The character value used to split the argument string.
type (Object)
Argument type.
value (String)
Option value.
values (String[])
Values of the option.
A boolean option is represented on a command line by its presence. For example, if option is present, then its value is true, otherwise, it is considered as false. Consider the following example, where we are printing current date and if -t flag is present. Then, we will print time too.
CLITester.java
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption("t", false, "display time");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
Calendar date = Calendar.getInstance();
int day = date.get(Calendar.DAY_OF_MONTH);
int month = date.get(Calendar.MONTH);
int year = date.get(Calendar.YEAR);
int hour = date.get(Calendar.HOUR);
int min = date.get(Calendar.MINUTE);
int sec = date.get(Calendar.SECOND);
System.out.print(day + "/" + month + "/" + year);
if(cmd.hasOption("t")) {
System.out.print(" " + hour + ":" + min + ":" + sec);
}
}
}
Run the file without passing any option and see the result.
java CLITester
12/11/2017
Run the file, while passing -t as option and see the result.
java CLITester
12/11/2017 4:13:10
An Argument option is represented on a command line by its name and its corresponding value. For example, if option is present, then user has to pass its value. Consider the following example, if we are printing logs to some file, for which, we want user to enter name of the log file with the argument option logFile.
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
Option logfile = Option.builder()
.longOpt("logFile")
.argName("file" )
.hasArg()
.desc("use given file for log" )
.build();
options.addOption(logfile);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
// has the logFile argument been passed?
if(cmd.hasOption("logFile")) {
//get the logFile argument passed
System.out.println( cmd.getOptionValue( "logFile" ) );
}
}
}
Run the file, while passing --logFile as option, name of the file as value of the option and see the result.
java CLITester --logFile test.log
test.log
A Properties option is represented on a command line by its name and its corresponding properties like syntax, which is similar to java properties file. Consider the following example, if we are passing options like -DrollNo = 1 -Dclass = VI -Dname = Mahesh, we should process each value as properties. Let's see the implementation logic in action.
CLITester.java
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
Option propertyOption = Option.builder()
.longOpt("D")
.argName("property=value" )
.hasArgs()
.valueSeparator()
.numberOfArgs(2)
.desc("use value for given properties" )
.build();
options.addOption(propertyOption);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
if(cmd.hasOption("D")) {
Properties properties = cmd.getOptionProperties("D");
System.out.println("Class: " + properties.getProperty("class"));
System.out.println("Roll No: " + properties.getProperty("rollNo"));
System.out.println("Name: " + properties.getProperty("name"));
}
}
}
Run the file, while passing options as key value pairs and see the result.
java CLITester -DrollNo = 1 -Dclass = VI -Dname = Mahesh
Class: VI
Roll No: 1
Name: Mahesh
A Posix parser is use to parse Posix like arguments passed. It is now deprecated and is replaced by DefaultParser.
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
public class CLITester {
public static void main(String[] args) throws ParseException {
//Create posix like options
Options posixOptions = new Options();
posixOptions.addOption("D", false, "Display");
posixOptions.addOption("A", false, "Act");
CommandLineParser posixParser = new PosixParser();
CommandLine cmd = posixParser.parse(posixOptions, args);
if( cmd.hasOption("D") ) {
System.out.println("D option was used.");
}
if( cmd.hasOption("A") ) {
System.out.println("A option was used.");
}
}
}
Run the file while passing -D -A as options and see the result.
java CLITester -D -A
D option was used.
A option was used.
Run the file while passing --D as option and see the result.
java CLITester --D
D option was used.
A GNU parser is use to parse gnu like arguments passed. It is now deprecated and is replaced by DefaultParser.
CLITester.java
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
//Create GNU like options
Options gnuOptions = new Options();
gnuOptions.addOption("p", "print", false, "Print")
.addOption("g", "gui", false, "GUI")
.addOption("n", true, "Scale");
CommandLineParser gnuParser = new GnuParser();
CommandLine cmd = gnuParser.parse(gnuOptions, args);
if( cmd.hasOption("p") ) {
System.out.println("p option was used.");
}
if( cmd.hasOption("g") ) {
System.out.println("g option was used.");
}
if( cmd.hasOption("n") ) {
System.out.println("Value passed: " + cmd.getOptionValue("n"));
}
}
}
Run the file while passing -p -g -n 10 as option and see the result.
java CLITester -p -g -n 10
p option was used.
g option was used.
Value passed: 10
Apache Commons CLI provides HelpFormatter class to print the usage guide of command line arguments. See the example given below −
CLITester.java
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption("p", "print", false, "Send print request to printer.")
.addOption("g", "gui", false, "Show GUI Application")
.addOption("n", true, "No. of copies to print");
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("CLITester", options);
}
}
Run the file and see the result.
java CLITester
usage: CLITester
-g,--gui Show GUI Application
-n <arg> No. of copies to print
-p,--print Send print request to printer.
Apache Commons CLI provides HelpFormatter class to print the help related to command line arguments. See the example.
CLITester.java
import java.io.PrintWriter;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption("p", "print", false, "Send print request to printer.")
.addOption("g", "gui", false, "Show GUI Application")
.addOption("n", true, "No. of copies to print");
HelpFormatter formatter = new HelpFormatter();
final PrintWriter writer = new PrintWriter(System.out);
formatter.printUsage(writer,80,"CLITester", options);
writer.flush();
}
}
Run the file and see the result.
java CLITester
usage: CLITester [-g] [-n <arg>] [-p]
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1975,
"s": 1719,
"text": "The Apache Commons CLI are the components of the Apache Commons which are derived from Java API and provides an API to parse command line arguments/options which are passed to the programs. This API also enables to print help related to options available."
},
{
"code": null,
"e": 2061,
"s": 1975,
"text": "Command line processing comprises of three stages. These stages are explained below −"
},
{
"code": null,
"e": 2078,
"s": 2061,
"text": "Definition Stage"
},
{
"code": null,
"e": 2092,
"s": 2078,
"text": "Parsing Stage"
},
{
"code": null,
"e": 2112,
"s": 2092,
"text": "Interrogation Stage"
},
{
"code": null,
"e": 2282,
"s": 2112,
"text": "In definition stage, we define the options that an application can take and act accordingly. Commons CLI provides Options class, which is a container for Option objects."
},
{
"code": null,
"e": 2408,
"s": 2282,
"text": "// create Options object\nOptions options = new Options();\n\n// add a option\noptions.addOption(\"a\", false, \"add two numbers\");\n"
},
{
"code": null,
"e": 2571,
"s": 2408,
"text": "Here we have added an option flag a, while false as second parameter, signifies that option is not mandatory and third parameter states the description of option."
},
{
"code": null,
"e": 2680,
"s": 2571,
"text": "In parsing stage, we parse the options passed using command line arguments after creating a parser instance."
},
{
"code": null,
"e": 2849,
"s": 2680,
"text": "//Create a parser\nCommandLineParser parser = new DefaultParser();\n\n//parse the options passed as command line arguments\nCommandLine cmd = parser.parse( options, args);\n"
},
{
"code": null,
"e": 2966,
"s": 2849,
"text": "In Interrogation stage, we check if a particular option is present or not and then, process the command accordingly."
},
{
"code": null,
"e": 3131,
"s": 2966,
"text": "//hasOptions checks if option is present or not\nif(cmd.hasOption(\"a\")) {\n // add the two numbers\n} else if(cmd.hasOption(\"m\")) {\n // multiply the two numbers\n}\n"
},
{
"code": null,
"e": 3400,
"s": 3131,
"text": "In this chapter, we will learn about the local environment setup of Apache Commons CLI and how to set up the path of Commons CLI for Windows 2000/XP, Windows 95/98/ME etc. We will also understand about some popular java editors and how to download Commons CLI archive."
},
{
"code": null,
"e": 3635,
"s": 3400,
"text": "If you are still willing to set up your environment for Java programming language, then this chapter will guide you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment."
},
{
"code": null,
"e": 3816,
"s": 3635,
"text": "Java SE is freely available from the link https://www.oracle.com/java/technologies/oracle-java-archive-downloads.html. So you can download a version based on your operating system."
},
{
"code": null,
"e": 4043,
"s": 3816,
"text": "Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories."
},
{
"code": null,
"e": 4128,
"s": 4043,
"text": "We are assuming that you have installed Java in c:\\Program Files\\java\\jdk directory."
},
{
"code": null,
"e": 4182,
"s": 4128,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 4236,
"s": 4182,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 4306,
"s": 4236,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 4376,
"s": 4306,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 4613,
"s": 4376,
"text": "Now, alter the 'Path' variable, so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'."
},
{
"code": null,
"e": 4850,
"s": 4613,
"text": "Now, alter the 'Path' variable, so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'."
},
{
"code": null,
"e": 4935,
"s": 4850,
"text": "We are assuming that you have installed Java in c:\\Program Files\\java\\jdk directory."
},
{
"code": null,
"e": 5056,
"s": 4935,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'."
},
{
"code": null,
"e": 5177,
"s": 5056,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'."
},
{
"code": null,
"e": 5339,
"s": 5177,
"text": "Environment variable PATH should be set to point, where the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this."
},
{
"code": null,
"e": 5479,
"s": 5339,
"text": "Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'"
},
{
"code": null,
"e": 5644,
"s": 5479,
"text": "To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −"
},
{
"code": null,
"e": 5763,
"s": 5644,
"text": "Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad."
},
{
"code": null,
"e": 5882,
"s": 5763,
"text": "Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad."
},
{
"code": null,
"e": 5997,
"s": 5882,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html."
},
{
"code": null,
"e": 6112,
"s": 5997,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html."
},
{
"code": null,
"e": 6235,
"s": 6112,
"text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org."
},
{
"code": null,
"e": 6358,
"s": 6235,
"text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org."
},
{
"code": null,
"e": 6565,
"s": 6358,
"text": "Download the latest version of Apache Common CLI jar file from commons-cli-1.4-bin.zip. At the time of writing this tutorial, we have downloaded commons-cli-1.4-bin.zip and copied it into C:\\>Apache folder."
},
{
"code": null,
"e": 6812,
"s": 6565,
"text": "Set the APACHE_HOME environment variable to point to the base directory location where, Apache jar is stored on your machine. Assume that we have extracted commonscollections4-4.1-bin.zip in Apache folder on various Operating Systems as follows −"
},
{
"code": null,
"e": 6999,
"s": 6812,
"text": "Set the CLASSPATH environment variable to point to the Common CLI jar location. Assume that you have stored commons-cli-1.4.jar in Apache folder on various Operating Systems as follows −"
},
{
"code": null,
"e": 7164,
"s": 6999,
"text": "Let's create a sample console based application, whose purpose is to get either sum of passed numbers or multiplication of passed numbers based on the options used."
},
{
"code": null,
"e": 7201,
"s": 7164,
"text": "Create a java class named CLITester."
},
{
"code": null,
"e": 7216,
"s": 7201,
"text": "CLITester.java"
},
{
"code": null,
"e": 8767,
"s": 7216,
"text": "import org.apache.commons.cli.CommandLine;\nimport org.apache.commons.cli.CommandLineParser;\nimport org.apache.commons.cli.DefaultParser;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\npublic class CLITester {\n public static void main(String[] args) throws ParseException {\n //***Definition Stage***\n // create Options object\n Options options = new Options();\n \n // add option \"-a\"\n options.addOption(\"a\", false, \"add numbers\");\n \n // add option \"-m\"\n options.addOption(\"m\", false, \"multiply numbers\");\n\n //***Parsing Stage***\n //Create a parser\n CommandLineParser parser = new DefaultParser();\n\n //parse the options passed as command line arguments\n CommandLine cmd = parser.parse( options, args);\n\n //***Interrogation Stage***\n //hasOptions checks if option is present or not\n if(cmd.hasOption(\"a\")) {\n System.out.println(\"Sum of the numbers: \" + getSum(args));\n } else if(cmd.hasOption(\"m\")) {\n System.out.println(\"Multiplication of the numbers: \" + getMultiplication(args));\n }\n }\n public static int getSum(String[] args) {\n int sum = 0;\n for(int i = 1; i < args.length ; i++) {\n sum += Integer.parseInt(args[i]);\n }\n return sum;\n }\n public static int getMultiplication(String[] args) {\n int multiplication = 1;\n for(int i = 1; i < args.length ; i++) {\n multiplication *= Integer.parseInt(args[i]);\n }\n return multiplication;\n }\n}"
},
{
"code": null,
"e": 8861,
"s": 8767,
"text": "Run the file, while passing -a as option and numbers to get the sum of the numbers as result."
},
{
"code": null,
"e": 8913,
"s": 8861,
"text": "java CLITester -a 1 2 3 4 5\nSum of the numbers: 15\n"
},
{
"code": null,
"e": 9018,
"s": 8913,
"text": "Run the file, while passing -m as option and numbers to get the multiplication of the numbers as result."
},
{
"code": null,
"e": 9082,
"s": 9018,
"text": "java CLITester -m 1 2 3 4 5\nMultiplication of the numbers: 120\n"
},
{
"code": null,
"e": 9224,
"s": 9082,
"text": "Option object is used to represent the Option passed to command line program. Following are various properties that an Option object possess."
},
{
"code": null,
"e": 9237,
"s": 9224,
"text": "opt (String)"
},
{
"code": null,
"e": 9274,
"s": 9237,
"text": "Identification string of the Option."
},
{
"code": null,
"e": 9291,
"s": 9274,
"text": "longOpt (String)"
},
{
"code": null,
"e": 9341,
"s": 9291,
"text": "Alias and more descriptive identification string."
},
{
"code": null,
"e": 9362,
"s": 9341,
"text": "description (String)"
},
{
"code": null,
"e": 9405,
"s": 9362,
"text": "Description of the function of the option."
},
{
"code": null,
"e": 9424,
"s": 9405,
"text": "required (boolean)"
},
{
"code": null,
"e": 9490,
"s": 9424,
"text": "Flag to check whether the option must appear on the command line."
},
{
"code": null,
"e": 9504,
"s": 9490,
"text": "arg (boolean)"
},
{
"code": null,
"e": 9556,
"s": 9504,
"text": "Flag to check whether the option takes an argument."
},
{
"code": null,
"e": 9571,
"s": 9556,
"text": "args (boolean)"
},
{
"code": null,
"e": 9634,
"s": 9571,
"text": "Flag to check whether the option takes more than one argument."
},
{
"code": null,
"e": 9656,
"s": 9634,
"text": "optionalArg (boolean)"
},
{
"code": null,
"e": 9713,
"s": 9656,
"text": "Flag to check whether the option's argument is optional."
},
{
"code": null,
"e": 9730,
"s": 9713,
"text": "argName (String)"
},
{
"code": null,
"e": 9782,
"s": 9730,
"text": "Name of the argument value for the usage statement."
},
{
"code": null,
"e": 9804,
"s": 9782,
"text": "valueSeparator (char)"
},
{
"code": null,
"e": 9859,
"s": 9804,
"text": "The character value used to split the argument string."
},
{
"code": null,
"e": 9873,
"s": 9859,
"text": "type (Object)"
},
{
"code": null,
"e": 9888,
"s": 9873,
"text": "Argument type."
},
{
"code": null,
"e": 9903,
"s": 9888,
"text": "value (String)"
},
{
"code": null,
"e": 9917,
"s": 9903,
"text": "Option value."
},
{
"code": null,
"e": 9935,
"s": 9917,
"text": "values (String[])"
},
{
"code": null,
"e": 9957,
"s": 9935,
"text": "Values of the option."
},
{
"code": null,
"e": 10245,
"s": 9957,
"text": "A boolean option is represented on a command line by its presence. For example, if option is present, then its value is true, otherwise, it is considered as false. Consider the following example, where we are printing current date and if -t flag is present. Then, we will print time too."
},
{
"code": null,
"e": 10260,
"s": 10245,
"text": "CLITester.java"
},
{
"code": null,
"e": 11309,
"s": 10260,
"text": "import java.util.Calendar;\nimport java.util.Date;\n\nimport org.apache.commons.cli.CommandLine;\nimport org.apache.commons.cli.CommandLineParser;\nimport org.apache.commons.cli.DefaultParser;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\n\npublic class CLITester {\n public static void main(String[] args) throws ParseException {\n Options options = new Options();\n options.addOption(\"t\", false, \"display time\");\n \n CommandLineParser parser = new DefaultParser();\n CommandLine cmd = parser.parse( options, args);\n\n Calendar date = Calendar.getInstance();\n int day = date.get(Calendar.DAY_OF_MONTH);\n int month = date.get(Calendar.MONTH);\n int year = date.get(Calendar.YEAR);\n\n int hour = date.get(Calendar.HOUR);\n int min = date.get(Calendar.MINUTE);\n int sec = date.get(Calendar.SECOND);\n\n System.out.print(day + \"/\" + month + \"/\" + year);\n if(cmd.hasOption(\"t\")) {\n System.out.print(\" \" + hour + \":\" + min + \":\" + sec);\n }\n }\n}"
},
{
"code": null,
"e": 11369,
"s": 11309,
"text": "Run the file without passing any option and see the result."
},
{
"code": null,
"e": 11396,
"s": 11369,
"text": "java CLITester\n12/11/2017\n"
},
{
"code": null,
"e": 11457,
"s": 11396,
"text": "Run the file, while passing -t as option and see the result."
},
{
"code": null,
"e": 11492,
"s": 11457,
"text": "java CLITester\n12/11/2017 4:13:10\n"
},
{
"code": null,
"e": 11811,
"s": 11492,
"text": "An Argument option is represented on a command line by its name and its corresponding value. For example, if option is present, then user has to pass its value. Consider the following example, if we are printing logs to some file, for which, we want user to enter name of the log file with the argument option logFile."
},
{
"code": null,
"e": 11826,
"s": 11811,
"text": "CLITester.java"
},
{
"code": null,
"e": 12749,
"s": 11826,
"text": "import org.apache.commons.cli.CommandLine;\nimport org.apache.commons.cli.CommandLineParser;\nimport org.apache.commons.cli.DefaultParser;\nimport org.apache.commons.cli.Option;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\n\npublic class CLITester {\n public static void main(String[] args) throws ParseException {\n Options options = new Options();\n Option logfile = Option.builder()\n .longOpt(\"logFile\")\n .argName(\"file\" )\n .hasArg()\n .desc(\"use given file for log\" )\n .build();\n\n options.addOption(logfile);\n CommandLineParser parser = new DefaultParser();\n CommandLine cmd = parser.parse( options, args);\n \n // has the logFile argument been passed?\n if(cmd.hasOption(\"logFile\")) {\n //get the logFile argument passed\n System.out.println( cmd.getOptionValue( \"logFile\" ) );\n }\n }\n}"
},
{
"code": null,
"e": 12858,
"s": 12749,
"text": "Run the file, while passing --logFile as option, name of the file as value of the option and see the result."
},
{
"code": null,
"e": 12902,
"s": 12858,
"text": "java CLITester --logFile test.log\ntest.log\n"
},
{
"code": null,
"e": 13251,
"s": 12902,
"text": "A Properties option is represented on a command line by its name and its corresponding properties like syntax, which is similar to java properties file. Consider the following example, if we are passing options like -DrollNo = 1 -Dclass = VI -Dname = Mahesh, we should process each value as properties. Let's see the implementation logic in action."
},
{
"code": null,
"e": 13266,
"s": 13251,
"text": "CLITester.java"
},
{
"code": null,
"e": 14431,
"s": 13266,
"text": "import java.util.Properties;\n\nimport org.apache.commons.cli.CommandLine;\nimport org.apache.commons.cli.CommandLineParser;\nimport org.apache.commons.cli.DefaultParser;\nimport org.apache.commons.cli.Option;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\n\npublic class CLITester {\n public static void main(String[] args) throws ParseException {\n Options options = new Options();\n Option propertyOption = Option.builder()\n .longOpt(\"D\")\n .argName(\"property=value\" )\n .hasArgs()\n .valueSeparator()\n .numberOfArgs(2)\n .desc(\"use value for given properties\" )\n .build();\n \n options.addOption(propertyOption);\n CommandLineParser parser = new DefaultParser();\n CommandLine cmd = parser.parse( options, args);\n \n if(cmd.hasOption(\"D\")) {\n Properties properties = cmd.getOptionProperties(\"D\");\n System.out.println(\"Class: \" + properties.getProperty(\"class\"));\n System.out.println(\"Roll No: \" + properties.getProperty(\"rollNo\"));\n System.out.println(\"Name: \" + properties.getProperty(\"name\"));\n }\n }\n}"
},
{
"code": null,
"e": 14506,
"s": 14431,
"text": "Run the file, while passing options as key value pairs and see the result."
},
{
"code": null,
"e": 14598,
"s": 14506,
"text": "java CLITester -DrollNo = 1 -Dclass = VI -Dname = Mahesh\nClass: VI\nRoll No: 1\nName: Mahesh\n"
},
{
"code": null,
"e": 14713,
"s": 14598,
"text": "A Posix parser is use to parse Posix like arguments passed. It is now deprecated and is replaced by DefaultParser."
},
{
"code": null,
"e": 14728,
"s": 14713,
"text": "CLITester.java"
},
{
"code": null,
"e": 15559,
"s": 14728,
"text": "import org.apache.commons.cli.CommandLine;\nimport org.apache.commons.cli.CommandLineParser;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\nimport org.apache.commons.cli.PosixParser;\n\npublic class CLITester {\n public static void main(String[] args) throws ParseException {\n \n //Create posix like options\n Options posixOptions = new Options();\n posixOptions.addOption(\"D\", false, \"Display\");\n posixOptions.addOption(\"A\", false, \"Act\");\n \n CommandLineParser posixParser = new PosixParser();\n \n CommandLine cmd = posixParser.parse(posixOptions, args);\n \n if( cmd.hasOption(\"D\") ) {\n System.out.println(\"D option was used.\");\n }\n if( cmd.hasOption(\"A\") ) {\n System.out.println(\"A option was used.\");\n }\n }\n}"
},
{
"code": null,
"e": 15623,
"s": 15559,
"text": "Run the file while passing -D -A as options and see the result."
},
{
"code": null,
"e": 15683,
"s": 15623,
"text": "java CLITester -D -A\nD option was used.\nA option was used.\n"
},
{
"code": null,
"e": 15744,
"s": 15683,
"text": "Run the file while passing --D as option and see the result."
},
{
"code": null,
"e": 15783,
"s": 15744,
"text": "java CLITester --D\nD option was used.\n"
},
{
"code": null,
"e": 15894,
"s": 15783,
"text": "A GNU parser is use to parse gnu like arguments passed. It is now deprecated and is replaced by DefaultParser."
},
{
"code": null,
"e": 15909,
"s": 15894,
"text": "CLITester.java"
},
{
"code": null,
"e": 16869,
"s": 15909,
"text": "import org.apache.commons.cli.CommandLine;\nimport org.apache.commons.cli.CommandLineParser;\nimport org.apache.commons.cli.GnuParser;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\n\npublic class CLITester {\n public static void main(String[] args) throws ParseException {\n \n //Create GNU like options\n Options gnuOptions = new Options();\n gnuOptions.addOption(\"p\", \"print\", false, \"Print\")\n .addOption(\"g\", \"gui\", false, \"GUI\")\n .addOption(\"n\", true, \"Scale\");\n\n CommandLineParser gnuParser = new GnuParser();\n CommandLine cmd = gnuParser.parse(gnuOptions, args);\n \n if( cmd.hasOption(\"p\") ) {\n System.out.println(\"p option was used.\");\n }\n if( cmd.hasOption(\"g\") ) {\n System.out.println(\"g option was used.\");\n }\n if( cmd.hasOption(\"n\") ) {\n System.out.println(\"Value passed: \" + cmd.getOptionValue(\"n\"));\n }\n }\n}"
},
{
"code": null,
"e": 16938,
"s": 16869,
"text": "Run the file while passing -p -g -n 10 as option and see the result."
},
{
"code": null,
"e": 17021,
"s": 16938,
"text": "java CLITester -p -g -n 10\np option was used.\ng option was used.\nValue passed: 10\n"
},
{
"code": null,
"e": 17151,
"s": 17021,
"text": "Apache Commons CLI provides HelpFormatter class to print the usage guide of command line arguments. See the example given below −"
},
{
"code": null,
"e": 17166,
"s": 17151,
"text": "CLITester.java"
},
{
"code": null,
"e": 17742,
"s": 17166,
"text": "import org.apache.commons.cli.HelpFormatter;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\n\npublic class CLITester {\n public static void main(String[] args) throws ParseException {\n\t\n Options options = new Options();\n options.addOption(\"p\", \"print\", false, \"Send print request to printer.\")\n .addOption(\"g\", \"gui\", false, \"Show GUI Application\")\n .addOption(\"n\", true, \"No. of copies to print\");\n\t\t\t\n HelpFormatter formatter = new HelpFormatter();\n formatter.printHelp(\"CLITester\", options);\n }\n}"
},
{
"code": null,
"e": 17775,
"s": 17742,
"text": "Run the file and see the result."
},
{
"code": null,
"e": 17912,
"s": 17775,
"text": "java CLITester\nusage: CLITester\n-g,--gui Show GUI Application\n-n <arg> No. of copies to print\n-p,--print Send print request to printer.\n"
},
{
"code": null,
"e": 18030,
"s": 17912,
"text": "Apache Commons CLI provides HelpFormatter class to print the help related to command line arguments. See the example."
},
{
"code": null,
"e": 18045,
"s": 18030,
"text": "CLITester.java"
},
{
"code": null,
"e": 18754,
"s": 18045,
"text": "import java.io.PrintWriter;\n\nimport org.apache.commons.cli.HelpFormatter;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\n\npublic class CLITester {\n public static void main(String[] args) throws ParseException {\n \n Options options = new Options();\n options.addOption(\"p\", \"print\", false, \"Send print request to printer.\")\n .addOption(\"g\", \"gui\", false, \"Show GUI Application\")\n .addOption(\"n\", true, \"No. of copies to print\");\n \n HelpFormatter formatter = new HelpFormatter();\n\n final PrintWriter writer = new PrintWriter(System.out);\n formatter.printUsage(writer,80,\"CLITester\", options);\n writer.flush();\n }\n}"
},
{
"code": null,
"e": 18787,
"s": 18754,
"text": "Run the file and see the result."
},
{
"code": null,
"e": 18841,
"s": 18787,
"text": "java CLITester\nusage: CLITester [-g] [-n <arg>] [-p]\n"
},
{
"code": null,
"e": 18848,
"s": 18841,
"text": " Print"
},
{
"code": null,
"e": 18859,
"s": 18848,
"text": " Add Notes"
}
] |
How to convert comma seperated java string to an array.
|
Yes, use String.split() method to do it. See the example below −
public class Tester {
public static void main(String[] args) {
String text = "This,is,a,comma,seperated,string.";
String[] array = text.split(",");
for(String value:array) {
System.out.print(value + " ");
}
}
}
This is a comma seperated string.
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "Yes, use String.split() method to do it. See the example below −"
},
{
"code": null,
"e": 1377,
"s": 1127,
"text": "public class Tester {\n public static void main(String[] args) {\n String text = \"This,is,a,comma,seperated,string.\";\n String[] array = text.split(\",\");\n for(String value:array) {\n System.out.print(value + \" \");\n }\n }\n}"
},
{
"code": null,
"e": 1411,
"s": 1377,
"text": "This is a comma seperated string."
}
] |
Difference between mutable and immutable object
|
In Java, state of the immutable object can’t be modified after it is created b ut definitely reference other objects. They are very useful in multithreading environment because multiple threads can’t change the state of the object so immutable objects are thread safe. Immutable objects are very helpful to avoid temporal coupling and always have failure atomicity.
On the other hand, Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created.
public final class ImmutableClass {
private String laptop;
public String getLaptop() {
return laptop;
}
public ImmutableClass(String laptop) {
super();
this.laptop = laptop;
}
}
public class Main {
public static void main(String args[]) {
ImmutableClass immutableClass = new ImmutableClass("Dell");
System.out.println(immutableClass.getLaptop());
}
}
public class MuttableClass {
private String laptop;
public String getLaptop() {
return laptop;
}
public void setLaptop(String laptop) {
this.laptop = laptop;
}
public MuttableClass(String laptop) {
super();
this.laptop = laptop;
}
}
public class Main {
public static void main(String args[]) {
MuttableClass muttableClass = new MuttableClass("Dell");
System.out.println(muttableClass.getLaptop());
muttableClass.setLaptop("IBM");
System.out.println(muttableClass.getLaptop());
}
}
|
[
{
"code": null,
"e": 1428,
"s": 1062,
"text": "In Java, state of the immutable object can’t be modified after it is created b ut definitely reference other objects. They are very useful in multithreading environment because multiple threads can’t change the state of the object so immutable objects are thread safe. Immutable objects are very helpful to avoid temporal coupling and always have failure atomicity."
},
{
"code": null,
"e": 1578,
"s": 1428,
"text": "On the other hand, Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created."
},
{
"code": null,
"e": 1980,
"s": 1578,
"text": "public final class ImmutableClass {\n private String laptop;\n public String getLaptop() {\n return laptop;\n }\n public ImmutableClass(String laptop) {\n super();\n this.laptop = laptop;\n }\n}\npublic class Main {\n public static void main(String args[]) {\n ImmutableClass immutableClass = new ImmutableClass(\"Dell\");\n System.out.println(immutableClass.getLaptop());\n }\n}"
},
{
"code": null,
"e": 2536,
"s": 1980,
"text": "public class MuttableClass {\n private String laptop;\n public String getLaptop() {\n return laptop;\n }\n public void setLaptop(String laptop) {\n this.laptop = laptop;\n }\n public MuttableClass(String laptop) {\n super();\n this.laptop = laptop;\n }\n}\npublic class Main {\n public static void main(String args[]) {\n MuttableClass muttableClass = new MuttableClass(\"Dell\");\n System.out.println(muttableClass.getLaptop());\n muttableClass.setLaptop(\"IBM\");\n System.out.println(muttableClass.getLaptop());\n }\n}"
}
] |
How to predict the success of your marketing campaign | by Nikolas Schriefer | Towards Data Science
|
In this article I am going to walk you through the process of building, training and evaluating a prediction model for the number of ad impressions delivered in a digital marketing campaign. All the techniques can be analogously applied to other regression problems, especially to predict various campaign performance metrics. The predictions can be used to evaluate future marketing campaigns before launch as well as to determine the best parameters including e.g. timeline and budget size for such campaigns. You can use your own campaign data or a provided sample data set to code along in Python. Next to all source code I also provide a simple app to predict impressions, clicks and conversions for purchase-based digital marketing campaigns.
App: predictor.stagelink.comCode: github.com/kinosal/predictor
RequirementsDefine your goalsGet the datasetThe first glancePre-process your dataTrain your modelsEvaluate your modelsPredict the results for your next campaignBONUS: Ready-to-use trained model
Requirements
Define your goals
Get the dataset
The first glance
Pre-process your data
Train your models
Evaluate your models
Predict the results for your next campaign
BONUS: Ready-to-use trained model
We will use data from past marketing campaigns in order to predict the outcome of future campaigns. And generally speaking, the more data, i.e. campaigns, the more accurate the predictions. The exact number depends i.a. on the homogeneity of your campaigns, but it is likely that you will need data of at least a few hundred campaigns. Also, since we’ll use supervised learning techniques you need the same inputs, i.e. dimensions or features, for the future campaigns for which you want to estimate the outcome.
In case you do not have a suitable dataset at hand right now, don’t worry: You can download a CSV with the sample I am going to use for this article here:
https://github.com/kinosal/predictor/blob/master/model/impressions.csv
What do we actually mean when we refer to the success or outcome of a campaign? This obviously depends on your specific situation. For this article, we will try to predict the number of impressions of a single campaign. Similarly, clicks and conversions can be predicted to complete the classic marketing funnel:
We are presented with several past campaigns that each provide one observation or row in a table with several dimensions or columns including the dependent variable we want to predict as well as multiple explaining independent variables or features:
Since the campaigns of which we would like to predict the outcome lie in the future, the features in this case do not include any prior performance data but different observable qualities of a campaign. As we usually don’t know beforehand which features will turn out to be good predictors, I recommend to also use variables that might seem only remotely related to your campaigns and to invest some time in finding or constructing new features. Although there are also arguments to reduce the feature space, this can usually still be handled at a later stage.
You can load the CSV and save into a Pandas data frame with a very simple function:
import pandas as pddata = pd.read_csv('impressions.csv')
Before building and training the prediction model, I always take a first look at the data to get an idea of what I am dealing with and to already spot potential peculiarities. We will use the sample data to predict the number of impressions for a marketing campaign, hence “impressions.csv” contains one row per campaign, each of their total number of impressions as well as metric and categorical features to help us predict the number of impressions for future campaigns. We will confirm this by loading the data and showing its shape, columns and first 5 rows:
>>> data.shape(241, 13)>>> data.columnsIndex(['impressions', 'budget', 'start_month', 'end_month', 'start_week', 'end_week', 'days', 'region', 'category', 'facebook', 'instagram', 'google_search', 'google_display'], dtype='object')>>> data.head(5)impressions budget start_month ... google search google_display9586 600 7 ... 1 0...
The first column contains the dependent (to be predicted) variable “impressions” while there are 12 feature columns for 241 records (rows) in total. We can also use data.describe() to display count, mean, standard deviation, range and quartiles for every metric column.
We can further observe that we are dealing with ten numerical features and two categorical ones, while four of the numerical columns are binary:
Now let us plot the histograms for the numerical features. We’ll use two very handy data visualization libraries, Matplotlib and Seaborn (which builds upon Matplotlib):
import matplotlib.pyplot as pltimport seaborn as snsquan = list(data.loc[:, data.dtypes != 'object'].columns.values)grid = sns.FacetGrid(pd.melt(data, value_vars=quan), col='variable', col_wrap=4, height=3, aspect=1, sharex=False, sharey=False)grid.map(plt.hist, 'value', color="steelblue")plt.show()
As a final glance we will have a look at basic linear correlations between the numerical features. First, let us visualize those with a Seaborn heatmap:
sns.heatmap(data._get_numeric_data().astype(float).corr(), square=True, cmap='RdBu_r', linewidths=.5, annot=True, fmt='.2f').figure.tight_layout()plt.show()
In addition, we can also output the correlations of each feature with the dependent variable:
>>> data.corr(method='pearson').iloc[0].sort_values(ascending=False)impressions 1.000000budget 0.556317days 0.449491google_display 0.269616google_search 0.164593instagram 0.073916start_month 0.039573start_week 0.029295end_month 0.014446end_week 0.012436facebook -0.382057
Here we can see that the number of impressions is positively correlated with the budget amount and the campaign duration in days, and negatively correlated with the binary option to use Facebook as a channel. However, this only shows us a pair-wise linear relationship and can merely serve as a crude initial observation.
Before we can begin to construct a predictive model, we need to make sure our data is clean and usable, since here applies: “Garbage in, garbage out.”
We are lucky to be presented with a fairly well-structured dataset in this case, but we should still go through a quick pre-processing pipeline specific to the challenge at hand:
Only keep rows where the dependent variable is greater than zero since we only want to predict outcomes larger than zero (theoretically values equal to zero are possible, but they won’t help our predictions).Check for columns with missing data and decide whether to drop or fill them. Here we’ll drop columns with more than 50% missing data since these features cannot add much to the model.Check for rows with missing values and decide whether to drop or fill them (doesn’t apply for the sample data).Put rare categorical values (e.g. with a share of less than 10%) into one “other” bucket to prevent overfitting our model to those specific occurrences.Encode categorical data into one-hot dummy variables since the models we will use require numerical inputs. There are various ways to encode categorical data, this article provides a very good overview in case you’re interested to learn more.Specify dependent variable vector and independent variable matrix.Split dataset into training and test set to properly evaluate your models’ goodness of fit after training.Scale features as required for one of the models we are going to build.
Only keep rows where the dependent variable is greater than zero since we only want to predict outcomes larger than zero (theoretically values equal to zero are possible, but they won’t help our predictions).
Check for columns with missing data and decide whether to drop or fill them. Here we’ll drop columns with more than 50% missing data since these features cannot add much to the model.
Check for rows with missing values and decide whether to drop or fill them (doesn’t apply for the sample data).
Put rare categorical values (e.g. with a share of less than 10%) into one “other” bucket to prevent overfitting our model to those specific occurrences.
Encode categorical data into one-hot dummy variables since the models we will use require numerical inputs. There are various ways to encode categorical data, this article provides a very good overview in case you’re interested to learn more.
Specify dependent variable vector and independent variable matrix.
Split dataset into training and test set to properly evaluate your models’ goodness of fit after training.
Scale features as required for one of the models we are going to build.
Here’s the full pre-processing code:
Finally, we can proceed to build and train multiple regressors to ultimately predict the outcome (value of the dependent variable), i.e. the number of impressions for the marketing campaign in question. We will try four different supervised learning techniques — linear regression, decision trees, random forest (of decision trees) and support vector regression — and will implement those with the respective classes provided by the Scikit-learn library, which was already used to scale and split the data during pre-processing.
There are many more models we could potentially use to develop regressors, e.g. artificial neural networks, which might yield even better predictors. However, the focus of this article is rather to explain some of the core principles of such regression in a — for the most part — intuitive and interpretable way than to produce the most accurate predictions.
Constructing a linear regressor with Scikit-learn is very simple and only requires two lines of code, importing the required function from Scikit’s linear model class and assigning it to a variable:
from sklearn.linear_model import LinearRegressionlinear_regressor = LinearRegression(fit_intercept=True, normalize=False, copy_X=True)
We want to keep the default parameters since we need an intercept (result when all features are 0) to be calculated and we do not require normalization preferring interpretability. The regressor will calculate the independent variable coefficients and the intercept by minimizing the sum of the squared errors, i.e. the deviations of the predicted from the true outcome, which is known as the Ordinary Least Squares method.
We can also output the coefficients and their respective p-values, the probability of the output being independent from (here also uncorrelated to) a specific feature (which would be the null-hypothesis of the coefficient equaling 0), and hence a measure of statistical significance (the lower the more significant).
Having visualized the correlations between the numerical features earlier during our “first glance”, we expect the features “budget”, “days” and “facebook” to carry relatively small p-values with “budget” and “days” having positive and “facebook” a negative coefficient. The statsmodels module provides an easy way to output this data:
model = sm.OLS(self.y_train, sm.add_constant(self.X_train)).fit()print(model.summary())
The p-value here was calculated using a t-statistic or -score based on the t-distribution. The summary also gives us a first hint at the accuracy or goodness of fit for the whole model, scored by the coefficient of determination R-squared measuring the share of variance in the output explained by the input variables, here 54.6%.
However, in order to compare all models and to suit our particular challenge we will use a different scoring method which I call “Mean Relative Accuracy”, defined as 1 - mean percentage error = 1 - mean(|(prediction - true value) / true value|). This metric is obviously undefined if the true value is 0, but in our case this is not relevant as we check this condition in the pre-processing step (see above) and we will thus obtain good interpretability matching an intuitive definition of accuracy. We will calculate this score for all models using five-fold cross-validation, randomly splitting the dataset five times and taking the mean of each of the scores. Scitkit-learn also provides a handy method for this:
linear_score = np.mean(cross_val_score(estimator=linear_regressor, X=X_train, y=y_train, cv=5, scoring=mean_relative_accuracy))
The training score we obtain for the linear regressor is 0.18; ergo the best fit we were able to produce with this model results only in a 18% prediction accuracy. Let’s hope the other models are able to outperform this.
Next up is a regressor made from a single decision tree. Here we will use a Scikit-learn function with a few more arguments, so-called hyperparameters, than for the linear model, including some we don’t know the desired settings for yet. That’s why we are going to introduce a concept called Grid Search. Grid Search, again available from Scikit-learn, lets us define a grid or matrix of parameters to test when training the prediction model and returns the best parameters, i.e. the ones yielding the highest score. This way we could test all available parameters for the Decision Tree Model, but we will focus on two of those, the “criterion” to measure the quality of a split of one branch into two and the minimum number of samples (data points) for one leaf (final node) of the tree. This will help us to find a good model with the training data while limiting overfitting, i.e. failing to generalize from the training data to new samples. From now on we will also set a random state equal to one for all stochastic calculations so that you will receive the same values coding along. The rest works similar to the linear regression we’ve built earlier:
tree_parameters = [{'min_samples_leaf': list(range(2, 10, 1)), 'criterion': ['mae', 'mse'], 'random_state': [1]}]tree_grid = GridSearchCV(estimator=DecisionTreeRegressor(), param_grid=tree_parameters, scoring=mean_relative_accuracy, cv=5, n_jobs=-1, iid=False)tree_grid_result = tree_grid.fit(X_train, y_train)best_tree_parameters = tree_grid_result.best_params_tree_score = tree_grid_result.best_score_
The best parameters chosen from the grid we defined include the mean squared error as the criterion to determine the optimal split at each node and a minimum of nine samples for each leaf, yielding a mean relative (training) accuracy of 67% — which is already a lot better compared to the 18% from the linear regression.
One of the advantages of a decision tree is that we can easily visualize and intuitively understand the model. With Scikit-learn and two lines of code you can generate a DOT representation of the fitted decision tree which you can then convert into a PNG image:
from sklearn.tree import export_graphvizexport_graphviz(regressor, out_file='tree.dot', feature_names=X_train.columns)
As you can see, only 4 of all 16 features have been used to construct this model: budget, days, category_concert and start_month.
The main challenges of single decision trees lie in finding the optimal split at each node and overfitting to the training data. Both can be mitigated when combining multiple trees into a random forest ensemble. Here, the trees of a forest will be trained on different (random) subsets of the data and each node of a tree will consider a (again random) subset of the available features.
The random forest regressor is built almost exactly like the decision tree. We only need to add the number of trees, here called estimators, as a parameter. Since we do not know the optimal number, we will add another element to the grid search to determine the best regressor:
forest_parameters = [{'n_estimators': helpers.powerlist(10, 2, 4), 'min_samples_leaf': list(range(2, 10, 1)), 'criterion': ['mae', 'mse'], 'random_state': [1], 'n_jobs': [-1]}]forest_grid = GridSearchCV(estimator=RandomForestRegressor(), param_grid=forest_parameters, scoring=mean_relative_accuracy, cv=5, n_jobs=-1, iid=False)forest_grid_result = forest_grid.fit(X_train, y_train)best_forest_parameters = forest_grid_result.best_params_forest_score = forest_grid_result.best_score_
The best parameters for the forest model according to the grid search we defined include the mean absolute error criterion, a minimum leaf sample size of three and 80 estimators (trees). With these settings we can again — compared to the single decision tree — increase the training accuracy to 70%.
The last regressor we are going to build is based on support vector machines, a beautiful mathematical concept developed by Vladimir Vapnik between the 1960s and 90s. Unfortunately, explaining their inner workings would go beyond the scope of this article. Still, I strongly recommend to check them out; one good introductory resource is professor Winston’s lecture at MIT.
A very rudimentary summary: Support vector regressors try to fit given samples into a multi-dimensional (with the order of the number of features) hyperplane of a diameter defined by linear boundaries while minimizing the error or cost.
Although this type of model is fundamentally different from decision trees and forests, the implementation with Scikit-learn is similar:
svr_parameters = [{'kernel': ['linear', 'rbf'], 'C': helpers.powerlist(0.1, 2, 10), 'epsilon': helpers.powerlist(0.01, 2, 10), 'gamma': ['scale']}, {'kernel': ['poly'], 'degree': list(range(2, 5, 1)), 'C': helpers.powerlist(0.1, 2, 10), 'epsilon': helpers.powerlist(0.01, 2, 10), 'gamma': ['scale']}]svr_grid = GridSearchCV(estimator=SVR(), param_grid=svr_parameters, scoring=mean_relative_accuracy, cv=5, n_jobs=-1, iid=False)svr_grid_result = svr_grid.fit(X_train_scaled, y_train_scaled)best_svr_parameters = svr_grid_result.best_params_svr_score = svr_grid_result.best_score_
We can use grid search again to find the optimal values for some model parameters. The most important here is the kernel that transforms the samples into a feature space of higher dimensions where the data can be separated or approximated linearly, i.e. by the hyperplane described above. We are testing a linear kernel, a polynomial one and a radial basis function. With an epsilon of 0.08, the maximum (scaled) distance of the prediction from the true value where no error is associated with it, and a penalty parameter C of 12.8, the linear kernel performs best, reaching a (scaled) training accuracy of 23%.
After we have now identified the best parameters for our models based on the training data at hand, we can use these to eventually predict the outcomes of the test set and calculate their respective test accuracies. First, we need to fit our models with the desired hyperparameters to the training data. This time, we don’t need cross-validation anymore and will fit the models to the full training set. Then we can use the fitted regressors to predict training and test set results and calculate their accuracies.
training_accuracies = {}test_accuracies = {}for regressor in regressors: if 'SVR' in str(regressor): regressor.fit(X_train_scaled, y_train_scaled) training_accuracies[regressor] = hel.mean_relative_accuracy( y_scaler.inverse_transform(regressor.predict( X_train_scaled)), y_train) test_accuracies[regressor] = hel.mean_relative_accuracy( y_scaler.inverse_transform(regressor.predict( X_test_scaled)), y_test) else: regressor.fit(X_train, y_train) training_accuracies[regressor] = hel.mean_relative_accuracy( regressor.predict(X_train), y_train) test_accuracies[regressor] = hel.mean_relative_accuracy( regressor.predict(X_test), y_test)
Here are the results:
Training accuracies: Linear 0.34, Tree 0.67, Forest 0.75, SVR 0.63Test accuracies: Linear 0.32, Tree 0.64, Forest 0.66, SVR 0.61
Our best regressor is the random forest with the highest test accuracy of 66%. It seems to be a little overfit though since the deviation from its training accuracy is relatively large. Feel free to experiment with other values for the hyperparameters to further improve all of the models.
Before finally saving our model to make predictions on new data, we will fit it to all available data (training and test set) to incorporate as much information as possible.
Now we have a model ready to predict the results of future marketing campaigns. We only have to call the predict method on it passing a specific feature vector and will receive the respective prediction for the metric we trained our regressor on. We can also compare the true impressions from the existing dataset to their predictions based on our new model:
The average relative deviation of a prediction from its actual, true value equals 26%, ergo we reached an accuracy of 74%. With only 14% the median deviation is even smaller.
We were able to build and train regressors that allow us to predict the number of impressions (and other performance metrics in an analogue fashion) for future marketing campaigns from historical campaign data.
The highest prediction accuracy has been achieved with a random forest model.
We can now use these predictions to evaluate a new marketing campaign even before its start. Also, this allows us to determine the best parameters including e.g. timeline and budget size for our campaigns since we can calculate the predictions with different values for those features.
You don’t (yet) have the data at hand to build an accurate prediction model for your planned digital marketing campaigns? Don’t worry: I have trained multiple models to predict impressions, clicks and purchases with the data from more than 1,000 campaigns. With a combination of different models those predictions reach an accuracy of up to 90%. At predictor.stagelink.com you find a simple app to predict the results of your future campaigns with just a few inputs. The models are mainly trained on data from digital marketing campaigns promoting event ticket sales, so that is where they will likely perform best.
In addition to that you can find all the code used for the discussed marketing performance predictor on my Github: github.com/kinosal/predictor
Thank you for reading - I look forward to any feedback you might have!
|
[
{
"code": null,
"e": 921,
"s": 172,
"text": "In this article I am going to walk you through the process of building, training and evaluating a prediction model for the number of ad impressions delivered in a digital marketing campaign. All the techniques can be analogously applied to other regression problems, especially to predict various campaign performance metrics. The predictions can be used to evaluate future marketing campaigns before launch as well as to determine the best parameters including e.g. timeline and budget size for such campaigns. You can use your own campaign data or a provided sample data set to code along in Python. Next to all source code I also provide a simple app to predict impressions, clicks and conversions for purchase-based digital marketing campaigns."
},
{
"code": null,
"e": 984,
"s": 921,
"text": "App: predictor.stagelink.comCode: github.com/kinosal/predictor"
},
{
"code": null,
"e": 1178,
"s": 984,
"text": "RequirementsDefine your goalsGet the datasetThe first glancePre-process your dataTrain your modelsEvaluate your modelsPredict the results for your next campaignBONUS: Ready-to-use trained model"
},
{
"code": null,
"e": 1191,
"s": 1178,
"text": "Requirements"
},
{
"code": null,
"e": 1209,
"s": 1191,
"text": "Define your goals"
},
{
"code": null,
"e": 1225,
"s": 1209,
"text": "Get the dataset"
},
{
"code": null,
"e": 1242,
"s": 1225,
"text": "The first glance"
},
{
"code": null,
"e": 1264,
"s": 1242,
"text": "Pre-process your data"
},
{
"code": null,
"e": 1282,
"s": 1264,
"text": "Train your models"
},
{
"code": null,
"e": 1303,
"s": 1282,
"text": "Evaluate your models"
},
{
"code": null,
"e": 1346,
"s": 1303,
"text": "Predict the results for your next campaign"
},
{
"code": null,
"e": 1380,
"s": 1346,
"text": "BONUS: Ready-to-use trained model"
},
{
"code": null,
"e": 1893,
"s": 1380,
"text": "We will use data from past marketing campaigns in order to predict the outcome of future campaigns. And generally speaking, the more data, i.e. campaigns, the more accurate the predictions. The exact number depends i.a. on the homogeneity of your campaigns, but it is likely that you will need data of at least a few hundred campaigns. Also, since we’ll use supervised learning techniques you need the same inputs, i.e. dimensions or features, for the future campaigns for which you want to estimate the outcome."
},
{
"code": null,
"e": 2048,
"s": 1893,
"text": "In case you do not have a suitable dataset at hand right now, don’t worry: You can download a CSV with the sample I am going to use for this article here:"
},
{
"code": null,
"e": 2119,
"s": 2048,
"text": "https://github.com/kinosal/predictor/blob/master/model/impressions.csv"
},
{
"code": null,
"e": 2432,
"s": 2119,
"text": "What do we actually mean when we refer to the success or outcome of a campaign? This obviously depends on your specific situation. For this article, we will try to predict the number of impressions of a single campaign. Similarly, clicks and conversions can be predicted to complete the classic marketing funnel:"
},
{
"code": null,
"e": 2682,
"s": 2432,
"text": "We are presented with several past campaigns that each provide one observation or row in a table with several dimensions or columns including the dependent variable we want to predict as well as multiple explaining independent variables or features:"
},
{
"code": null,
"e": 3243,
"s": 2682,
"text": "Since the campaigns of which we would like to predict the outcome lie in the future, the features in this case do not include any prior performance data but different observable qualities of a campaign. As we usually don’t know beforehand which features will turn out to be good predictors, I recommend to also use variables that might seem only remotely related to your campaigns and to invest some time in finding or constructing new features. Although there are also arguments to reduce the feature space, this can usually still be handled at a later stage."
},
{
"code": null,
"e": 3327,
"s": 3243,
"text": "You can load the CSV and save into a Pandas data frame with a very simple function:"
},
{
"code": null,
"e": 3384,
"s": 3327,
"text": "import pandas as pddata = pd.read_csv('impressions.csv')"
},
{
"code": null,
"e": 3948,
"s": 3384,
"text": "Before building and training the prediction model, I always take a first look at the data to get an idea of what I am dealing with and to already spot potential peculiarities. We will use the sample data to predict the number of impressions for a marketing campaign, hence “impressions.csv” contains one row per campaign, each of their total number of impressions as well as metric and categorical features to help us predict the number of impressions for future campaigns. We will confirm this by loading the data and showing its shape, columns and first 5 rows:"
},
{
"code": null,
"e": 4329,
"s": 3948,
"text": ">>> data.shape(241, 13)>>> data.columnsIndex(['impressions', 'budget', 'start_month', 'end_month', 'start_week', 'end_week', 'days', 'region', 'category', 'facebook', 'instagram', 'google_search', 'google_display'], dtype='object')>>> data.head(5)impressions budget start_month ... google search google_display9586 600 7 ... 1 0..."
},
{
"code": null,
"e": 4599,
"s": 4329,
"text": "The first column contains the dependent (to be predicted) variable “impressions” while there are 12 feature columns for 241 records (rows) in total. We can also use data.describe() to display count, mean, standard deviation, range and quartiles for every metric column."
},
{
"code": null,
"e": 4744,
"s": 4599,
"text": "We can further observe that we are dealing with ten numerical features and two categorical ones, while four of the numerical columns are binary:"
},
{
"code": null,
"e": 4913,
"s": 4744,
"text": "Now let us plot the histograms for the numerical features. We’ll use two very handy data visualization libraries, Matplotlib and Seaborn (which builds upon Matplotlib):"
},
{
"code": null,
"e": 5254,
"s": 4913,
"text": "import matplotlib.pyplot as pltimport seaborn as snsquan = list(data.loc[:, data.dtypes != 'object'].columns.values)grid = sns.FacetGrid(pd.melt(data, value_vars=quan), col='variable', col_wrap=4, height=3, aspect=1, sharex=False, sharey=False)grid.map(plt.hist, 'value', color=\"steelblue\")plt.show()"
},
{
"code": null,
"e": 5407,
"s": 5254,
"text": "As a final glance we will have a look at basic linear correlations between the numerical features. First, let us visualize those with a Seaborn heatmap:"
},
{
"code": null,
"e": 5586,
"s": 5407,
"text": "sns.heatmap(data._get_numeric_data().astype(float).corr(), square=True, cmap='RdBu_r', linewidths=.5, annot=True, fmt='.2f').figure.tight_layout()plt.show()"
},
{
"code": null,
"e": 5680,
"s": 5586,
"text": "In addition, we can also output the correlations of each feature with the dependent variable:"
},
{
"code": null,
"e": 6035,
"s": 5680,
"text": ">>> data.corr(method='pearson').iloc[0].sort_values(ascending=False)impressions 1.000000budget 0.556317days 0.449491google_display 0.269616google_search 0.164593instagram 0.073916start_month 0.039573start_week 0.029295end_month 0.014446end_week 0.012436facebook -0.382057"
},
{
"code": null,
"e": 6357,
"s": 6035,
"text": "Here we can see that the number of impressions is positively correlated with the budget amount and the campaign duration in days, and negatively correlated with the binary option to use Facebook as a channel. However, this only shows us a pair-wise linear relationship and can merely serve as a crude initial observation."
},
{
"code": null,
"e": 6508,
"s": 6357,
"text": "Before we can begin to construct a predictive model, we need to make sure our data is clean and usable, since here applies: “Garbage in, garbage out.”"
},
{
"code": null,
"e": 6687,
"s": 6508,
"text": "We are lucky to be presented with a fairly well-structured dataset in this case, but we should still go through a quick pre-processing pipeline specific to the challenge at hand:"
},
{
"code": null,
"e": 7827,
"s": 6687,
"text": "Only keep rows where the dependent variable is greater than zero since we only want to predict outcomes larger than zero (theoretically values equal to zero are possible, but they won’t help our predictions).Check for columns with missing data and decide whether to drop or fill them. Here we’ll drop columns with more than 50% missing data since these features cannot add much to the model.Check for rows with missing values and decide whether to drop or fill them (doesn’t apply for the sample data).Put rare categorical values (e.g. with a share of less than 10%) into one “other” bucket to prevent overfitting our model to those specific occurrences.Encode categorical data into one-hot dummy variables since the models we will use require numerical inputs. There are various ways to encode categorical data, this article provides a very good overview in case you’re interested to learn more.Specify dependent variable vector and independent variable matrix.Split dataset into training and test set to properly evaluate your models’ goodness of fit after training.Scale features as required for one of the models we are going to build."
},
{
"code": null,
"e": 8036,
"s": 7827,
"text": "Only keep rows where the dependent variable is greater than zero since we only want to predict outcomes larger than zero (theoretically values equal to zero are possible, but they won’t help our predictions)."
},
{
"code": null,
"e": 8220,
"s": 8036,
"text": "Check for columns with missing data and decide whether to drop or fill them. Here we’ll drop columns with more than 50% missing data since these features cannot add much to the model."
},
{
"code": null,
"e": 8332,
"s": 8220,
"text": "Check for rows with missing values and decide whether to drop or fill them (doesn’t apply for the sample data)."
},
{
"code": null,
"e": 8485,
"s": 8332,
"text": "Put rare categorical values (e.g. with a share of less than 10%) into one “other” bucket to prevent overfitting our model to those specific occurrences."
},
{
"code": null,
"e": 8728,
"s": 8485,
"text": "Encode categorical data into one-hot dummy variables since the models we will use require numerical inputs. There are various ways to encode categorical data, this article provides a very good overview in case you’re interested to learn more."
},
{
"code": null,
"e": 8795,
"s": 8728,
"text": "Specify dependent variable vector and independent variable matrix."
},
{
"code": null,
"e": 8902,
"s": 8795,
"text": "Split dataset into training and test set to properly evaluate your models’ goodness of fit after training."
},
{
"code": null,
"e": 8974,
"s": 8902,
"text": "Scale features as required for one of the models we are going to build."
},
{
"code": null,
"e": 9011,
"s": 8974,
"text": "Here’s the full pre-processing code:"
},
{
"code": null,
"e": 9540,
"s": 9011,
"text": "Finally, we can proceed to build and train multiple regressors to ultimately predict the outcome (value of the dependent variable), i.e. the number of impressions for the marketing campaign in question. We will try four different supervised learning techniques — linear regression, decision trees, random forest (of decision trees) and support vector regression — and will implement those with the respective classes provided by the Scikit-learn library, which was already used to scale and split the data during pre-processing."
},
{
"code": null,
"e": 9899,
"s": 9540,
"text": "There are many more models we could potentially use to develop regressors, e.g. artificial neural networks, which might yield even better predictors. However, the focus of this article is rather to explain some of the core principles of such regression in a — for the most part — intuitive and interpretable way than to produce the most accurate predictions."
},
{
"code": null,
"e": 10098,
"s": 9899,
"text": "Constructing a linear regressor with Scikit-learn is very simple and only requires two lines of code, importing the required function from Scikit’s linear model class and assigning it to a variable:"
},
{
"code": null,
"e": 10233,
"s": 10098,
"text": "from sklearn.linear_model import LinearRegressionlinear_regressor = LinearRegression(fit_intercept=True, normalize=False, copy_X=True)"
},
{
"code": null,
"e": 10657,
"s": 10233,
"text": "We want to keep the default parameters since we need an intercept (result when all features are 0) to be calculated and we do not require normalization preferring interpretability. The regressor will calculate the independent variable coefficients and the intercept by minimizing the sum of the squared errors, i.e. the deviations of the predicted from the true outcome, which is known as the Ordinary Least Squares method."
},
{
"code": null,
"e": 10974,
"s": 10657,
"text": "We can also output the coefficients and their respective p-values, the probability of the output being independent from (here also uncorrelated to) a specific feature (which would be the null-hypothesis of the coefficient equaling 0), and hence a measure of statistical significance (the lower the more significant)."
},
{
"code": null,
"e": 11310,
"s": 10974,
"text": "Having visualized the correlations between the numerical features earlier during our “first glance”, we expect the features “budget”, “days” and “facebook” to carry relatively small p-values with “budget” and “days” having positive and “facebook” a negative coefficient. The statsmodels module provides an easy way to output this data:"
},
{
"code": null,
"e": 11398,
"s": 11310,
"text": "model = sm.OLS(self.y_train, sm.add_constant(self.X_train)).fit()print(model.summary())"
},
{
"code": null,
"e": 11729,
"s": 11398,
"text": "The p-value here was calculated using a t-statistic or -score based on the t-distribution. The summary also gives us a first hint at the accuracy or goodness of fit for the whole model, scored by the coefficient of determination R-squared measuring the share of variance in the output explained by the input variables, here 54.6%."
},
{
"code": null,
"e": 12445,
"s": 11729,
"text": "However, in order to compare all models and to suit our particular challenge we will use a different scoring method which I call “Mean Relative Accuracy”, defined as 1 - mean percentage error = 1 - mean(|(prediction - true value) / true value|). This metric is obviously undefined if the true value is 0, but in our case this is not relevant as we check this condition in the pre-processing step (see above) and we will thus obtain good interpretability matching an intuitive definition of accuracy. We will calculate this score for all models using five-fold cross-validation, randomly splitting the dataset five times and taking the mean of each of the scores. Scitkit-learn also provides a handy method for this:"
},
{
"code": null,
"e": 12617,
"s": 12445,
"text": "linear_score = np.mean(cross_val_score(estimator=linear_regressor, X=X_train, y=y_train, cv=5, scoring=mean_relative_accuracy))"
},
{
"code": null,
"e": 12838,
"s": 12617,
"text": "The training score we obtain for the linear regressor is 0.18; ergo the best fit we were able to produce with this model results only in a 18% prediction accuracy. Let’s hope the other models are able to outperform this."
},
{
"code": null,
"e": 13996,
"s": 12838,
"text": "Next up is a regressor made from a single decision tree. Here we will use a Scikit-learn function with a few more arguments, so-called hyperparameters, than for the linear model, including some we don’t know the desired settings for yet. That’s why we are going to introduce a concept called Grid Search. Grid Search, again available from Scikit-learn, lets us define a grid or matrix of parameters to test when training the prediction model and returns the best parameters, i.e. the ones yielding the highest score. This way we could test all available parameters for the Decision Tree Model, but we will focus on two of those, the “criterion” to measure the quality of a split of one branch into two and the minimum number of samples (data points) for one leaf (final node) of the tree. This will help us to find a good model with the training data while limiting overfitting, i.e. failing to generalize from the training data to new samples. From now on we will also set a random state equal to one for all stochastic calculations so that you will receive the same values coding along. The rest works similar to the linear regression we’ve built earlier:"
},
{
"code": null,
"e": 14510,
"s": 13996,
"text": "tree_parameters = [{'min_samples_leaf': list(range(2, 10, 1)), 'criterion': ['mae', 'mse'], 'random_state': [1]}]tree_grid = GridSearchCV(estimator=DecisionTreeRegressor(), param_grid=tree_parameters, scoring=mean_relative_accuracy, cv=5, n_jobs=-1, iid=False)tree_grid_result = tree_grid.fit(X_train, y_train)best_tree_parameters = tree_grid_result.best_params_tree_score = tree_grid_result.best_score_"
},
{
"code": null,
"e": 14831,
"s": 14510,
"text": "The best parameters chosen from the grid we defined include the mean squared error as the criterion to determine the optimal split at each node and a minimum of nine samples for each leaf, yielding a mean relative (training) accuracy of 67% — which is already a lot better compared to the 18% from the linear regression."
},
{
"code": null,
"e": 15093,
"s": 14831,
"text": "One of the advantages of a decision tree is that we can easily visualize and intuitively understand the model. With Scikit-learn and two lines of code you can generate a DOT representation of the fitted decision tree which you can then convert into a PNG image:"
},
{
"code": null,
"e": 15228,
"s": 15093,
"text": "from sklearn.tree import export_graphvizexport_graphviz(regressor, out_file='tree.dot', feature_names=X_train.columns)"
},
{
"code": null,
"e": 15358,
"s": 15228,
"text": "As you can see, only 4 of all 16 features have been used to construct this model: budget, days, category_concert and start_month."
},
{
"code": null,
"e": 15745,
"s": 15358,
"text": "The main challenges of single decision trees lie in finding the optimal split at each node and overfitting to the training data. Both can be mitigated when combining multiple trees into a random forest ensemble. Here, the trees of a forest will be trained on different (random) subsets of the data and each node of a tree will consider a (again random) subset of the available features."
},
{
"code": null,
"e": 16023,
"s": 15745,
"text": "The random forest regressor is built almost exactly like the decision tree. We only need to add the number of trees, here called estimators, as a parameter. Since we do not know the optimal number, we will add another element to the grid search to determine the best regressor:"
},
{
"code": null,
"e": 16647,
"s": 16023,
"text": "forest_parameters = [{'n_estimators': helpers.powerlist(10, 2, 4), 'min_samples_leaf': list(range(2, 10, 1)), 'criterion': ['mae', 'mse'], 'random_state': [1], 'n_jobs': [-1]}]forest_grid = GridSearchCV(estimator=RandomForestRegressor(), param_grid=forest_parameters, scoring=mean_relative_accuracy, cv=5, n_jobs=-1, iid=False)forest_grid_result = forest_grid.fit(X_train, y_train)best_forest_parameters = forest_grid_result.best_params_forest_score = forest_grid_result.best_score_"
},
{
"code": null,
"e": 16947,
"s": 16647,
"text": "The best parameters for the forest model according to the grid search we defined include the mean absolute error criterion, a minimum leaf sample size of three and 80 estimators (trees). With these settings we can again — compared to the single decision tree — increase the training accuracy to 70%."
},
{
"code": null,
"e": 17321,
"s": 16947,
"text": "The last regressor we are going to build is based on support vector machines, a beautiful mathematical concept developed by Vladimir Vapnik between the 1960s and 90s. Unfortunately, explaining their inner workings would go beyond the scope of this article. Still, I strongly recommend to check them out; one good introductory resource is professor Winston’s lecture at MIT."
},
{
"code": null,
"e": 17558,
"s": 17321,
"text": "A very rudimentary summary: Support vector regressors try to fit given samples into a multi-dimensional (with the order of the number of features) hyperplane of a diameter defined by linear boundaries while minimizing the error or cost."
},
{
"code": null,
"e": 17695,
"s": 17558,
"text": "Although this type of model is fundamentally different from decision trees and forests, the implementation with Scikit-learn is similar:"
},
{
"code": null,
"e": 18486,
"s": 17695,
"text": "svr_parameters = [{'kernel': ['linear', 'rbf'], 'C': helpers.powerlist(0.1, 2, 10), 'epsilon': helpers.powerlist(0.01, 2, 10), 'gamma': ['scale']}, {'kernel': ['poly'], 'degree': list(range(2, 5, 1)), 'C': helpers.powerlist(0.1, 2, 10), 'epsilon': helpers.powerlist(0.01, 2, 10), 'gamma': ['scale']}]svr_grid = GridSearchCV(estimator=SVR(), param_grid=svr_parameters, scoring=mean_relative_accuracy, cv=5, n_jobs=-1, iid=False)svr_grid_result = svr_grid.fit(X_train_scaled, y_train_scaled)best_svr_parameters = svr_grid_result.best_params_svr_score = svr_grid_result.best_score_"
},
{
"code": null,
"e": 19098,
"s": 18486,
"text": "We can use grid search again to find the optimal values for some model parameters. The most important here is the kernel that transforms the samples into a feature space of higher dimensions where the data can be separated or approximated linearly, i.e. by the hyperplane described above. We are testing a linear kernel, a polynomial one and a radial basis function. With an epsilon of 0.08, the maximum (scaled) distance of the prediction from the true value where no error is associated with it, and a penalty parameter C of 12.8, the linear kernel performs best, reaching a (scaled) training accuracy of 23%."
},
{
"code": null,
"e": 19613,
"s": 19098,
"text": "After we have now identified the best parameters for our models based on the training data at hand, we can use these to eventually predict the outcomes of the test set and calculate their respective test accuracies. First, we need to fit our models with the desired hyperparameters to the training data. This time, we don’t need cross-validation anymore and will fit the models to the full training set. Then we can use the fitted regressors to predict training and test set results and calculate their accuracies."
},
{
"code": null,
"e": 20372,
"s": 19613,
"text": "training_accuracies = {}test_accuracies = {}for regressor in regressors: if 'SVR' in str(regressor): regressor.fit(X_train_scaled, y_train_scaled) training_accuracies[regressor] = hel.mean_relative_accuracy( y_scaler.inverse_transform(regressor.predict( X_train_scaled)), y_train) test_accuracies[regressor] = hel.mean_relative_accuracy( y_scaler.inverse_transform(regressor.predict( X_test_scaled)), y_test) else: regressor.fit(X_train, y_train) training_accuracies[regressor] = hel.mean_relative_accuracy( regressor.predict(X_train), y_train) test_accuracies[regressor] = hel.mean_relative_accuracy( regressor.predict(X_test), y_test)"
},
{
"code": null,
"e": 20394,
"s": 20372,
"text": "Here are the results:"
},
{
"code": null,
"e": 20523,
"s": 20394,
"text": "Training accuracies: Linear 0.34, Tree 0.67, Forest 0.75, SVR 0.63Test accuracies: Linear 0.32, Tree 0.64, Forest 0.66, SVR 0.61"
},
{
"code": null,
"e": 20813,
"s": 20523,
"text": "Our best regressor is the random forest with the highest test accuracy of 66%. It seems to be a little overfit though since the deviation from its training accuracy is relatively large. Feel free to experiment with other values for the hyperparameters to further improve all of the models."
},
{
"code": null,
"e": 20987,
"s": 20813,
"text": "Before finally saving our model to make predictions on new data, we will fit it to all available data (training and test set) to incorporate as much information as possible."
},
{
"code": null,
"e": 21346,
"s": 20987,
"text": "Now we have a model ready to predict the results of future marketing campaigns. We only have to call the predict method on it passing a specific feature vector and will receive the respective prediction for the metric we trained our regressor on. We can also compare the true impressions from the existing dataset to their predictions based on our new model:"
},
{
"code": null,
"e": 21521,
"s": 21346,
"text": "The average relative deviation of a prediction from its actual, true value equals 26%, ergo we reached an accuracy of 74%. With only 14% the median deviation is even smaller."
},
{
"code": null,
"e": 21732,
"s": 21521,
"text": "We were able to build and train regressors that allow us to predict the number of impressions (and other performance metrics in an analogue fashion) for future marketing campaigns from historical campaign data."
},
{
"code": null,
"e": 21810,
"s": 21732,
"text": "The highest prediction accuracy has been achieved with a random forest model."
},
{
"code": null,
"e": 22096,
"s": 21810,
"text": "We can now use these predictions to evaluate a new marketing campaign even before its start. Also, this allows us to determine the best parameters including e.g. timeline and budget size for our campaigns since we can calculate the predictions with different values for those features."
},
{
"code": null,
"e": 22712,
"s": 22096,
"text": "You don’t (yet) have the data at hand to build an accurate prediction model for your planned digital marketing campaigns? Don’t worry: I have trained multiple models to predict impressions, clicks and purchases with the data from more than 1,000 campaigns. With a combination of different models those predictions reach an accuracy of up to 90%. At predictor.stagelink.com you find a simple app to predict the results of your future campaigns with just a few inputs. The models are mainly trained on data from digital marketing campaigns promoting event ticket sales, so that is where they will likely perform best."
},
{
"code": null,
"e": 22856,
"s": 22712,
"text": "In addition to that you can find all the code used for the discussed marketing performance predictor on my Github: github.com/kinosal/predictor"
}
] |
Angular 10 (blur) Event - GeeksforGeeks
|
04 Jul, 2021
In this article, we are going to see what is blur event in Angular 10 and how to use it. The blur event is triggered when an element loses its focus.
Syntax:
<input (blur)='functionName()'/>
NgModule: Module used by blur event is:
CommonModule
Approach:
Create an Angular app to be used.
In app.component.ts make a function that triggers on blur event.
In app.component.html make an input element and set blur event.
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { onBlur(): void { console.log('Focus Is Lost for this Element'); }}
app.component.html
<br><form> <input placeholder="Name" (blur) = 'onBlur()'></form>
Output:
Example 2:
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { onBlur(): void { console.log('Focus Is Lost for this Element'); }}
app.component.html
<br><form> <button (blur) = 'onBlur()'>Click Here!!</button></form>
Output:
Angular10
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (focus) Event
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 26354,
"s": 26326,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 26504,
"s": 26354,
"text": "In this article, we are going to see what is blur event in Angular 10 and how to use it. The blur event is triggered when an element loses its focus."
},
{
"code": null,
"e": 26512,
"s": 26504,
"text": "Syntax:"
},
{
"code": null,
"e": 26545,
"s": 26512,
"text": "<input (blur)='functionName()'/>"
},
{
"code": null,
"e": 26585,
"s": 26545,
"text": "NgModule: Module used by blur event is:"
},
{
"code": null,
"e": 26598,
"s": 26585,
"text": "CommonModule"
},
{
"code": null,
"e": 26608,
"s": 26598,
"text": "Approach:"
},
{
"code": null,
"e": 26642,
"s": 26608,
"text": "Create an Angular app to be used."
},
{
"code": null,
"e": 26707,
"s": 26642,
"text": "In app.component.ts make a function that triggers on blur event."
},
{
"code": null,
"e": 26771,
"s": 26707,
"text": "In app.component.html make an input element and set blur event."
},
{
"code": null,
"e": 26827,
"s": 26771,
"text": "Serve the angular app using ng serve to see the output."
},
{
"code": null,
"e": 26840,
"s": 26829,
"text": "Example 1:"
},
{
"code": null,
"e": 26857,
"s": 26840,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { onBlur(): void { console.log('Focus Is Lost for this Element'); }}",
"e": 27128,
"s": 26857,
"text": null
},
{
"code": null,
"e": 27147,
"s": 27128,
"text": "app.component.html"
},
{
"code": "<br><form> <input placeholder=\"Name\" (blur) = 'onBlur()'></form>",
"e": 27215,
"s": 27147,
"text": null
},
{
"code": null,
"e": 27223,
"s": 27215,
"text": "Output:"
},
{
"code": null,
"e": 27234,
"s": 27223,
"text": "Example 2:"
},
{
"code": null,
"e": 27251,
"s": 27234,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { onBlur(): void { console.log('Focus Is Lost for this Element'); }}",
"e": 27522,
"s": 27251,
"text": null
},
{
"code": null,
"e": 27541,
"s": 27522,
"text": "app.component.html"
},
{
"code": "<br><form> <button (blur) = 'onBlur()'>Click Here!!</button></form>",
"e": 27613,
"s": 27541,
"text": null
},
{
"code": null,
"e": 27621,
"s": 27613,
"text": "Output:"
},
{
"code": null,
"e": 27631,
"s": 27621,
"text": "Angular10"
},
{
"code": null,
"e": 27641,
"s": 27631,
"text": "AngularJS"
},
{
"code": null,
"e": 27658,
"s": 27641,
"text": "Web Technologies"
},
{
"code": null,
"e": 27756,
"s": 27658,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27791,
"s": 27756,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 27826,
"s": 27791,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 27861,
"s": 27826,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 27914,
"s": 27861,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 27939,
"s": 27914,
"text": "Angular 10 (focus) Event"
},
{
"code": null,
"e": 27979,
"s": 27939,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28012,
"s": 27979,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28057,
"s": 28012,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28100,
"s": 28057,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Create Animated Navigation Bar with Hover Effect using HTML and CSS ? - GeeksforGeeks
|
11 May, 2020
The Navigation bar or navbar or menu-bar is the most important component of any web or mobile application. The user can only navigate from one page to another page through this menu. It is usually provided at the top of the website to provide a better UX (user experience).
Approach: The approach is to create a navbar first and then animate a line below on each item using before and hover selectors.
HTML Code: In this section, we have created a simple navigation bar menu using unordered-list(ul).
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Animated Navbar </title></head> <body> <h1>GeeksforGeeks</h1> <h3>Animated Navigation Bar Design</h3> <ul> <li><a href="#">Home</a></li> <li><a href="#">Contribute</a></li> <li><a href="#">Careers</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Contact</a></li> </ul></body> </html>
CSS Code: In this section, we have used some CSS property to make attractive animated navigation bar.
Step 1: First, we have used flex property to align our list in a horizontal way.
Step 2: Then remove all the text decoration and provide required margin and paddings.
Step 3: Then we have used before selector to align a line below each element keeping it’s width at 0.
Step 4: Now, use hover with before selector to provide width to the line and transform it on x-axis to get the desired effect.
<style> body { margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } h1 { color: green; } h1, h3 { text-align: center; } ul { margin: 0 10%; padding: 10px 0px 10px 100px; display: flex; background: green; } ul li { list-style: none; padding: 10px 20px; } ul li a { text-decoration: none; font-size: 24px; font-weight: bold; color: black; position: relative; } ul li a::before { content: ""; width: 0px; height: 10px; background: black; position: absolute; top: 100%; left: 0; transition: .5s; } ul li a:hover::before { width: 50%; transform: translateX(100%); }</style>
Complete Code: In this section, we will combine the above two sections to create an animated navigation bar.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Animated Navbar </title> <style> body { margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } h1 { color: green; } h1, h3 { text-align: center; } ul { margin: 0 10%; padding: 10px 0px 10px 100px; display: flex; background: green; } ul li { list-style: none; padding: 10px 20px; } ul li a { text-decoration: none; font-size: 24px; font-weight: bold; color: black; position: relative; } ul li a::before { content: ""; width: 0px; height: 10px; background: black; position: absolute; top: 100%; left: 0; transition: .5s; } ul li a:hover::before { width: 50%; transform: translateX(100%); } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>Animated Navigation Bar Design</h3> <ul> <li><a href="#">Home</a></li> <li><a href="#">Contribute</a></li> <li><a href="#">Careers</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Contact</a></li> </ul></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
Making a div vertically scrollable using CSS
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26433,
"s": 26405,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 26707,
"s": 26433,
"text": "The Navigation bar or navbar or menu-bar is the most important component of any web or mobile application. The user can only navigate from one page to another page through this menu. It is usually provided at the top of the website to provide a better UX (user experience)."
},
{
"code": null,
"e": 26835,
"s": 26707,
"text": "Approach: The approach is to create a navbar first and then animate a line below on each item using before and hover selectors."
},
{
"code": null,
"e": 26934,
"s": 26835,
"text": "HTML Code: In this section, we have created a simple navigation bar menu using unordered-list(ul)."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Animated Navbar </title></head> <body> <h1>GeeksforGeeks</h1> <h3>Animated Navigation Bar Design</h3> <ul> <li><a href=\"#\">Home</a></li> <li><a href=\"#\">Contribute</a></li> <li><a href=\"#\">Careers</a></li> <li><a href=\"#\">About Us</a></li> <li><a href=\"#\">Contact</a></li> </ul></body> </html>",
"e": 27437,
"s": 26934,
"text": null
},
{
"code": null,
"e": 27539,
"s": 27437,
"text": "CSS Code: In this section, we have used some CSS property to make attractive animated navigation bar."
},
{
"code": null,
"e": 27620,
"s": 27539,
"text": "Step 1: First, we have used flex property to align our list in a horizontal way."
},
{
"code": null,
"e": 27706,
"s": 27620,
"text": "Step 2: Then remove all the text decoration and provide required margin and paddings."
},
{
"code": null,
"e": 27808,
"s": 27706,
"text": "Step 3: Then we have used before selector to align a line below each element keeping it’s width at 0."
},
{
"code": null,
"e": 27935,
"s": 27808,
"text": "Step 4: Now, use hover with before selector to provide width to the line and transform it on x-axis to get the desired effect."
},
{
"code": "<style> body { margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } h1 { color: green; } h1, h3 { text-align: center; } ul { margin: 0 10%; padding: 10px 0px 10px 100px; display: flex; background: green; } ul li { list-style: none; padding: 10px 20px; } ul li a { text-decoration: none; font-size: 24px; font-weight: bold; color: black; position: relative; } ul li a::before { content: \"\"; width: 0px; height: 10px; background: black; position: absolute; top: 100%; left: 0; transition: .5s; } ul li a:hover::before { width: 50%; transform: translateX(100%); }</style>",
"e": 28770,
"s": 27935,
"text": null
},
{
"code": null,
"e": 28879,
"s": 28770,
"text": "Complete Code: In this section, we will combine the above two sections to create an animated navigation bar."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Animated Navbar </title> <style> body { margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } h1 { color: green; } h1, h3 { text-align: center; } ul { margin: 0 10%; padding: 10px 0px 10px 100px; display: flex; background: green; } ul li { list-style: none; padding: 10px 20px; } ul li a { text-decoration: none; font-size: 24px; font-weight: bold; color: black; position: relative; } ul li a::before { content: \"\"; width: 0px; height: 10px; background: black; position: absolute; top: 100%; left: 0; transition: .5s; } ul li a:hover::before { width: 50%; transform: translateX(100%); } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>Animated Navigation Bar Design</h3> <ul> <li><a href=\"#\">Home</a></li> <li><a href=\"#\">Contribute</a></li> <li><a href=\"#\">Careers</a></li> <li><a href=\"#\">About Us</a></li> <li><a href=\"#\">Contact</a></li> </ul></body> </html>",
"e": 30398,
"s": 28879,
"text": null
},
{
"code": null,
"e": 30406,
"s": 30398,
"text": "Output:"
},
{
"code": null,
"e": 30543,
"s": 30406,
"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": 30552,
"s": 30543,
"text": "CSS-Misc"
},
{
"code": null,
"e": 30562,
"s": 30552,
"text": "HTML-Misc"
},
{
"code": null,
"e": 30566,
"s": 30562,
"text": "CSS"
},
{
"code": null,
"e": 30571,
"s": 30566,
"text": "HTML"
},
{
"code": null,
"e": 30588,
"s": 30571,
"text": "Web Technologies"
},
{
"code": null,
"e": 30615,
"s": 30588,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30620,
"s": 30615,
"text": "HTML"
},
{
"code": null,
"e": 30718,
"s": 30620,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30773,
"s": 30718,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 30812,
"s": 30773,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30849,
"s": 30812,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30890,
"s": 30849,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 30935,
"s": 30890,
"text": "Making a div vertically scrollable using CSS"
},
{
"code": null,
"e": 30995,
"s": 30935,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31048,
"s": 30995,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 31109,
"s": 31048,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31133,
"s": 31109,
"text": "REST API (Introduction)"
}
] |
java.nio.file.FileSystems Class in Java - GeeksforGeeks
|
21 Apr, 2021
java.nio.file.FileSystems class acts as a factory for creating new file systems. This class provides methods for creating file systems. This file system act as factories for creating different objects like Path, PathMatcher, UserPrincipalLookupService, and WatchService. This object helps to access the files and other objects in the file system.
Syntax: Class declaration
public final class FileSystems extends Object
Methods of this class is as follows:
Example 1:
Java
// Java Program to illustrate FileSystems Class by// creating a new file system using getDefault() method and// printing its file stores and root directories // Importing classes from java.nio package// for network linkingimport java.nio.file.FileStore;import java.nio.file.FileSystem;import java.nio.file.FileSystems;import java.nio.file.Path; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Create a new file system by // creating object of FileSystem class // using getDefault() method FileSystem filesystem = FileSystems.getDefault(); // Display commands only System.out.println( "File System created successfully"); System.out.println( "Underlying file stores of this FileSystem :"); // Printing the underlying file stores of this // FileSystem using for each loop for (FileStore store : filesystem.getFileStores()) { // Print statement System.out.println(store.toString()); } // Display message only System.out.println( "Root directories of this FileSystem :"); // Printing the root directories of this // FileSystem using for each loop for (Path rootdir : filesystem.getRootDirectories()) { // Print statement System.out.println(rootdir.toString()); } } // Catch block to handle the exceptions catch (Exception e) { // Print the exception along with line number // using printStackTrace() method e.printStackTrace(); } }}
Output:
Example 2:
Java
// Java Program to illustrate FileSystems Class by// creating new file system using newFileSystem() method // Importing URI class from java.net packageimport java.net.URI;// Importing required file classes from java.nio packageimport java.nio.file.FileSystem;import java.nio.file.FileSystems;import java.nio.file.Path;import java.nio.file.Paths;// Importing Map and HashMap classes from java.util packageimport java.util.HashMap;import java.util.Map; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating object of Map class // Declaring object of string types Map<String, String> env = new HashMap<>(); // Getting path of zip file Path zipPath = Paths.get("ZipFile.zip"); // Creating URI from zip path received URI Uri = new URI("jar:file", zipPath.toUri().getPath(), null); // Create new file system from uri FileSystem filesystem = FileSystems.newFileSystem(Uri, env); // Display message for better readability System.out.println( "FileSystem created successfully"); // Checking if file system is open or not // using isOpen() method if (filesystem.isOpen()) // Print statement System.out.println("File system is open"); else // Print statement System.out.println("File system is close"); } // Catch block to handle the exceptions catch (Exception e) { // Print the exception with line number // using the printStack() method e.printStackTrace(); } }}
Output:
File System created successfully
File system is open
Java-NIO package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25572,
"s": 25225,
"text": "java.nio.file.FileSystems class acts as a factory for creating new file systems. This class provides methods for creating file systems. This file system act as factories for creating different objects like Path, PathMatcher, UserPrincipalLookupService, and WatchService. This object helps to access the files and other objects in the file system."
},
{
"code": null,
"e": 25598,
"s": 25572,
"text": "Syntax: Class declaration"
},
{
"code": null,
"e": 25644,
"s": 25598,
"text": "public final class FileSystems extends Object"
},
{
"code": null,
"e": 25681,
"s": 25644,
"text": "Methods of this class is as follows:"
},
{
"code": null,
"e": 25692,
"s": 25681,
"text": "Example 1:"
},
{
"code": null,
"e": 25697,
"s": 25692,
"text": "Java"
},
{
"code": "// Java Program to illustrate FileSystems Class by// creating a new file system using getDefault() method and// printing its file stores and root directories // Importing classes from java.nio package// for network linkingimport java.nio.file.FileStore;import java.nio.file.FileSystem;import java.nio.file.FileSystems;import java.nio.file.Path; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Create a new file system by // creating object of FileSystem class // using getDefault() method FileSystem filesystem = FileSystems.getDefault(); // Display commands only System.out.println( \"File System created successfully\"); System.out.println( \"Underlying file stores of this FileSystem :\"); // Printing the underlying file stores of this // FileSystem using for each loop for (FileStore store : filesystem.getFileStores()) { // Print statement System.out.println(store.toString()); } // Display message only System.out.println( \"Root directories of this FileSystem :\"); // Printing the root directories of this // FileSystem using for each loop for (Path rootdir : filesystem.getRootDirectories()) { // Print statement System.out.println(rootdir.toString()); } } // Catch block to handle the exceptions catch (Exception e) { // Print the exception along with line number // using printStackTrace() method e.printStackTrace(); } }}",
"e": 27569,
"s": 25697,
"text": null
},
{
"code": null,
"e": 27577,
"s": 27569,
"text": "Output:"
},
{
"code": null,
"e": 27588,
"s": 27577,
"text": "Example 2:"
},
{
"code": null,
"e": 27593,
"s": 27588,
"text": "Java"
},
{
"code": "// Java Program to illustrate FileSystems Class by// creating new file system using newFileSystem() method // Importing URI class from java.net packageimport java.net.URI;// Importing required file classes from java.nio packageimport java.nio.file.FileSystem;import java.nio.file.FileSystems;import java.nio.file.Path;import java.nio.file.Paths;// Importing Map and HashMap classes from java.util packageimport java.util.HashMap;import java.util.Map; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating object of Map class // Declaring object of string types Map<String, String> env = new HashMap<>(); // Getting path of zip file Path zipPath = Paths.get(\"ZipFile.zip\"); // Creating URI from zip path received URI Uri = new URI(\"jar:file\", zipPath.toUri().getPath(), null); // Create new file system from uri FileSystem filesystem = FileSystems.newFileSystem(Uri, env); // Display message for better readability System.out.println( \"FileSystem created successfully\"); // Checking if file system is open or not // using isOpen() method if (filesystem.isOpen()) // Print statement System.out.println(\"File system is open\"); else // Print statement System.out.println(\"File system is close\"); } // Catch block to handle the exceptions catch (Exception e) { // Print the exception with line number // using the printStack() method e.printStackTrace(); } }}",
"e": 29452,
"s": 27593,
"text": null
},
{
"code": null,
"e": 29460,
"s": 29452,
"text": "Output:"
},
{
"code": null,
"e": 29513,
"s": 29460,
"text": "File System created successfully\nFile system is open"
},
{
"code": null,
"e": 29530,
"s": 29513,
"text": "Java-NIO package"
},
{
"code": null,
"e": 29537,
"s": 29530,
"text": "Picked"
},
{
"code": null,
"e": 29542,
"s": 29537,
"text": "Java"
},
{
"code": null,
"e": 29547,
"s": 29542,
"text": "Java"
},
{
"code": null,
"e": 29645,
"s": 29547,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29660,
"s": 29645,
"text": "Stream In Java"
},
{
"code": null,
"e": 29681,
"s": 29660,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29700,
"s": 29681,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29730,
"s": 29700,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29776,
"s": 29730,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29793,
"s": 29776,
"text": "Generics in Java"
},
{
"code": null,
"e": 29814,
"s": 29793,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29857,
"s": 29814,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29893,
"s": 29857,
"text": "Internal Working of HashMap in Java"
}
] |
How to Install Scala IDE For Eclipse? - GeeksforGeeks
|
06 Dec, 2021
In this tutorial, we’ll look at how to set up the Eclipse IDE for Scala. This tutorial is for those who are new to Scala.
Eclipse (Install link) if you don’t know how to install Eclipse then refer to this article.
JDK 11 (you may use JDK 6 onwards)
Note: If you do not have JDK installed, you may get them from this link.
Follow the below steps to install Scala IDE for Eclipse
Step 1: Open the eclipse and click on the “Help” and select “Install New Software”
Step 2: Now click the “Add” button to add the new repository.
Step 3: Add Scala IDE update site, You can use the most recent Scala update site
Step 4: Select Scala IDE for Eclipse to download it, you can choose which Scala IDE you want to download
Step 5: After installation, the system will ask you to restart the Eclipse.
Using the Eclipse IDE, we will create a simple Hello World program in Scala.
Open the Eclipse, click on the menu and click on the “New” ->Scala project.
Give the name to your project.
Create a new Scala Object, File -> New -> Scala Object
Give your Scala application a name and then click Finish to create the file.
Add code that prints Hello World
Scala
// Scala program to print Hello World!object Geeks{ // Main Method def main(args: Array[String]) { // prints Hello World println("Hello World!") }}
Output:
how-to-install
Picked
Scala
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to create a nested RecyclerView in Android
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
|
[
{
"code": null,
"e": 26197,
"s": 26169,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 26319,
"s": 26197,
"text": "In this tutorial, we’ll look at how to set up the Eclipse IDE for Scala. This tutorial is for those who are new to Scala."
},
{
"code": null,
"e": 26411,
"s": 26319,
"text": "Eclipse (Install link) if you don’t know how to install Eclipse then refer to this article."
},
{
"code": null,
"e": 26446,
"s": 26411,
"text": "JDK 11 (you may use JDK 6 onwards)"
},
{
"code": null,
"e": 26519,
"s": 26446,
"text": "Note: If you do not have JDK installed, you may get them from this link."
},
{
"code": null,
"e": 26575,
"s": 26519,
"text": "Follow the below steps to install Scala IDE for Eclipse"
},
{
"code": null,
"e": 26658,
"s": 26575,
"text": "Step 1: Open the eclipse and click on the “Help” and select “Install New Software”"
},
{
"code": null,
"e": 26720,
"s": 26658,
"text": "Step 2: Now click the “Add” button to add the new repository."
},
{
"code": null,
"e": 26801,
"s": 26720,
"text": "Step 3: Add Scala IDE update site, You can use the most recent Scala update site"
},
{
"code": null,
"e": 26906,
"s": 26801,
"text": "Step 4: Select Scala IDE for Eclipse to download it, you can choose which Scala IDE you want to download"
},
{
"code": null,
"e": 26982,
"s": 26906,
"text": "Step 5: After installation, the system will ask you to restart the Eclipse."
},
{
"code": null,
"e": 27059,
"s": 26982,
"text": "Using the Eclipse IDE, we will create a simple Hello World program in Scala."
},
{
"code": null,
"e": 27135,
"s": 27059,
"text": "Open the Eclipse, click on the menu and click on the “New” ->Scala project."
},
{
"code": null,
"e": 27166,
"s": 27135,
"text": "Give the name to your project."
},
{
"code": null,
"e": 27222,
"s": 27166,
"text": "Create a new Scala Object, File -> New -> Scala Object "
},
{
"code": null,
"e": 27299,
"s": 27222,
"text": "Give your Scala application a name and then click Finish to create the file."
},
{
"code": null,
"e": 27332,
"s": 27299,
"text": "Add code that prints Hello World"
},
{
"code": null,
"e": 27338,
"s": 27332,
"text": "Scala"
},
{
"code": "// Scala program to print Hello World!object Geeks{ // Main Method def main(args: Array[String]) { // prints Hello World println(\"Hello World!\") }}",
"e": 27512,
"s": 27338,
"text": null
},
{
"code": null,
"e": 27520,
"s": 27512,
"text": "Output:"
},
{
"code": null,
"e": 27535,
"s": 27520,
"text": "how-to-install"
},
{
"code": null,
"e": 27542,
"s": 27535,
"text": "Picked"
},
{
"code": null,
"e": 27548,
"s": 27542,
"text": "Scala"
},
{
"code": null,
"e": 27555,
"s": 27548,
"text": "How To"
},
{
"code": null,
"e": 27574,
"s": 27555,
"text": "Installation Guide"
},
{
"code": null,
"e": 27672,
"s": 27574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27706,
"s": 27672,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27764,
"s": 27706,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27813,
"s": 27764,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 27855,
"s": 27813,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 27902,
"s": 27855,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 27935,
"s": 27902,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27969,
"s": 27935,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28004,
"s": 27969,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 28062,
"s": 28004,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
Pendant Vertices, Non-Pendant Vertices, Pendant Edges and Non-Pendant Edges in Graph - GeeksforGeeks
|
06 Apr, 2022
Pre-requisites: Handshaking theorem.
Let G be a graph, A vertex v of G is called a pendant vertex if and only if v has degree 1. In other words, pendant vertices are the vertices that have degree 1, also called pendant vertex.
Note: Degree = number of edges connected to a vertex
In the case of trees, a pendant vertex is known as a terminal node or leaf node, or leaf since it has only 1 degree. Remember leaf nodes have only 1 degree so pendant vertex is called a leaf node in the case of trees.
Example: In the given diagram A and B are pendant vertices because each of them has degree 1.
Graph 1.0
Let’s take this example to print all the pendant vertices in the graph.
C++
Python3
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print all the pendant// verticesvoid printPendantVertices(map<char, vector<char> > graph){ // All the vectors which contain only 1 // vertex i.e, size 1 has only 1 edge // hence a pendant vertex. for (auto x : graph) { if (x.second.size() == 1) { cout << x.first << " "; } }} // Driver Codeint main(){ map<char, vector<char> > graph; graph['A'].push_back('B'); graph['B'].push_back('A'); graph['C'].push_back('B'); graph['B'].push_back('C'); printPendantVertices(graph); return 0;}
# Python program for the above approach # Function to print all the pendant# verticesdef printPendantVertices(graph): # All the vectors which contain only 1# vertex i.e, size 1 has only 1 edge# hence a pendant vertex. for x,y in graph.items(): if (len(y) == 1): print(x, end = " ") # Driver Code graph ={}graph["A"] = ["B"]graph["B"] = ["A"]graph["C"] = ["B"]graph["B"].append("A") printPendantVertices(graph) # This code is contributed by shinjanpatra
<script>// Javascript program for the above approach // Function to print all the pendant// verticesfunction printPendantVertices(graph) { // All the vectors which contain only 1 // vertex i.e, size 1 has only 1 edge // hence a pendant vertex. for (x of graph) { if (x[1].length == 1) { document.write(x[0] + " "); } }} // Driver Code let graph = new Map();graph.set("A", ["B"]);graph.set("B", ["A"]);graph.set("C", ["B"]);graph.set("B", [...graph.get("B")].push("A")); printPendantVertices(graph); // This code is contributed by saurabh_jaiswal.</script>
A C
Non-Pendant Vertices are the vertices that have degrees other than 1. In the case of trees, a non-pendant vertex is a non-leaf node, since it does not have degree 1 ( leaf nodes have degree 1).
Example: In the given diagram A and C are pendant vertices because A and C have degree 1, B is a non-pendant vertex because it contains degrees other than 1 which is 2.
Graph 2.0
An edge of a graph is said to be a pendant edge if and only if one of its vertices is a pendant vertex.
Example: In the given diagram AB is a pendant edge since it contains pendant vertex as one of its vertexes.
Graph 3.0
An edge of a graph is said to be a non-pendant edge if it does not contain a pendant vertex as one of its vertexes.
Example: in the given diagram AB is a pendant edge since it has pendant vertex (A) as one of its vertexes. BD, BC, DC are non-pendant vertices.
Graph 4.0
Let us see some questions based examples on the above topics:
Q1. Suppose that a tree T has 2 vertices of degree 2, 4 vertices of degree 3, and 3 vertices of degree 4. find the number of pendant vertices in T.
Finding number pendant vertices is nothing but finding the number of leaf nodes. Let’s use the Handshaking Theorem formula
Sum of all degrees = 2 * (Sum of Edges)
(2 vertices) * (2 degrees) + (4 vertices) * (3 degrees) + (3 vertices) * (4 degrees) + (k vertices) * (1 degree) = (2 * edges)
where k is pendant vertices or leaf nodes which have degree 1 e is total number of edges in the tree
2*2 + 4*3 + 3*4 + k*1 = 2*e ——-(1)
remember : number of edges = number of vertices – 1
e=(2+4+3+k)-1
e=9+k-1
e=8+k ——-(2)
putting equation 2 in 1 gives
4 + 12 + 12 + k = 2(8+k)
28 + k = 16 + 2k
-2k + k = 16 – 28
-k = -12
k = 12
so total number of pendant vertices are 12
Q2. If a tree T has 4 vertices of degree 2, 1 vertex of degree 3 and 2 vertices of degree 4 and 1 vertex of degree 5. find the number of pendant vertices in T.
Finding number pendant vertices is nothing but finding the number of leaf nodes.
Let’s use the Handshaking Theorem formula
Sum of all degrees = 2 * (Sum of Edges)
(4 vertices)*(2 degrees) + (1 vertex)*(3 degrees) + (2 vertices)*(4 degrees) + (1 vertex)*(5 degree) + (k vertices)*(1 degree) = (2 * edges)
where k is pendant vertices or leaf nodes which have degree 1 e is total number of edges in the tree
4*2 + 1*3 + 2*4 + 1*5 + k*1 = 2*e ——-(1)
remember number of edges = number of vertices – 1
e=(4+1+2+1+k)-1
e=8+k-1
e=7+k ——-(2)
putting equation 2 in 1 gives
8 + 3 + 8 + 5 + k = 2(7+k)
24 + k = 14 + 2k
-2k + k = 14 – 24
-k = -10
k = 10
so total number of pendant vertices are 10
_saurabh_jaiswal
clintra
shinjanpatra
Data Structures-Graph
Graph
Tree
Graph
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Path in a Directed Acyclic Graph
Best First Search (Informed Search)
Graph Coloring | Set 2 (Greedy Algorithm)
Find if there is a path between two vertices in a directed graph
Graph Coloring | Set 1 (Introduction and Applications)
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
|
[
{
"code": null,
"e": 26311,
"s": 26283,
"text": "\n06 Apr, 2022"
},
{
"code": null,
"e": 26348,
"s": 26311,
"text": "Pre-requisites: Handshaking theorem."
},
{
"code": null,
"e": 26539,
"s": 26348,
"text": "Let G be a graph, A vertex v of G is called a pendant vertex if and only if v has degree 1. In other words, pendant vertices are the vertices that have degree 1, also called pendant vertex. "
},
{
"code": null,
"e": 26592,
"s": 26539,
"text": "Note: Degree = number of edges connected to a vertex"
},
{
"code": null,
"e": 26810,
"s": 26592,
"text": "In the case of trees, a pendant vertex is known as a terminal node or leaf node, or leaf since it has only 1 degree. Remember leaf nodes have only 1 degree so pendant vertex is called a leaf node in the case of trees."
},
{
"code": null,
"e": 26904,
"s": 26810,
"text": "Example: In the given diagram A and B are pendant vertices because each of them has degree 1."
},
{
"code": null,
"e": 26914,
"s": 26904,
"text": "Graph 1.0"
},
{
"code": null,
"e": 26986,
"s": 26914,
"text": "Let’s take this example to print all the pendant vertices in the graph."
},
{
"code": null,
"e": 26990,
"s": 26986,
"text": "C++"
},
{
"code": null,
"e": 26998,
"s": 26990,
"text": "Python3"
},
{
"code": null,
"e": 27009,
"s": 26998,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print all the pendant// verticesvoid printPendantVertices(map<char, vector<char> > graph){ // All the vectors which contain only 1 // vertex i.e, size 1 has only 1 edge // hence a pendant vertex. for (auto x : graph) { if (x.second.size() == 1) { cout << x.first << \" \"; } }} // Driver Codeint main(){ map<char, vector<char> > graph; graph['A'].push_back('B'); graph['B'].push_back('A'); graph['C'].push_back('B'); graph['B'].push_back('C'); printPendantVertices(graph); return 0;}",
"e": 27653,
"s": 27009,
"text": null
},
{
"code": "# Python program for the above approach # Function to print all the pendant# verticesdef printPendantVertices(graph): # All the vectors which contain only 1# vertex i.e, size 1 has only 1 edge# hence a pendant vertex. for x,y in graph.items(): if (len(y) == 1): print(x, end = \" \") # Driver Code graph ={}graph[\"A\"] = [\"B\"]graph[\"B\"] = [\"A\"]graph[\"C\"] = [\"B\"]graph[\"B\"].append(\"A\") printPendantVertices(graph) # This code is contributed by shinjanpatra",
"e": 28130,
"s": 27653,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to print all the pendant// verticesfunction printPendantVertices(graph) { // All the vectors which contain only 1 // vertex i.e, size 1 has only 1 edge // hence a pendant vertex. for (x of graph) { if (x[1].length == 1) { document.write(x[0] + \" \"); } }} // Driver Code let graph = new Map();graph.set(\"A\", [\"B\"]);graph.set(\"B\", [\"A\"]);graph.set(\"C\", [\"B\"]);graph.set(\"B\", [...graph.get(\"B\")].push(\"A\")); printPendantVertices(graph); // This code is contributed by saurabh_jaiswal.</script>",
"e": 28702,
"s": 28130,
"text": null
},
{
"code": null,
"e": 28710,
"s": 28705,
"text": "A C "
},
{
"code": null,
"e": 28906,
"s": 28712,
"text": "Non-Pendant Vertices are the vertices that have degrees other than 1. In the case of trees, a non-pendant vertex is a non-leaf node, since it does not have degree 1 ( leaf nodes have degree 1)."
},
{
"code": null,
"e": 29077,
"s": 28908,
"text": "Example: In the given diagram A and C are pendant vertices because A and C have degree 1, B is a non-pendant vertex because it contains degrees other than 1 which is 2."
},
{
"code": null,
"e": 29089,
"s": 29079,
"text": "Graph 2.0"
},
{
"code": null,
"e": 29197,
"s": 29093,
"text": "An edge of a graph is said to be a pendant edge if and only if one of its vertices is a pendant vertex."
},
{
"code": null,
"e": 29307,
"s": 29199,
"text": "Example: In the given diagram AB is a pendant edge since it contains pendant vertex as one of its vertexes."
},
{
"code": null,
"e": 29319,
"s": 29309,
"text": "Graph 3.0"
},
{
"code": null,
"e": 29437,
"s": 29321,
"text": "An edge of a graph is said to be a non-pendant edge if it does not contain a pendant vertex as one of its vertexes."
},
{
"code": null,
"e": 29583,
"s": 29439,
"text": "Example: in the given diagram AB is a pendant edge since it has pendant vertex (A) as one of its vertexes. BD, BC, DC are non-pendant vertices."
},
{
"code": null,
"e": 29595,
"s": 29585,
"text": "Graph 4.0"
},
{
"code": null,
"e": 29663,
"s": 29601,
"text": "Let us see some questions based examples on the above topics:"
},
{
"code": null,
"e": 29813,
"s": 29665,
"text": "Q1. Suppose that a tree T has 2 vertices of degree 2, 4 vertices of degree 3, and 3 vertices of degree 4. find the number of pendant vertices in T."
},
{
"code": null,
"e": 29947,
"s": 29815,
"text": "Finding number pendant vertices is nothing but finding the number of leaf nodes. Let’s use the Handshaking Theorem formula "
},
{
"code": null,
"e": 29997,
"s": 29947,
"text": " Sum of all degrees = 2 * (Sum of Edges)"
},
{
"code": null,
"e": 30124,
"s": 29997,
"text": "(2 vertices) * (2 degrees) + (4 vertices) * (3 degrees) + (3 vertices) * (4 degrees) + (k vertices) * (1 degree) = (2 * edges)"
},
{
"code": null,
"e": 30244,
"s": 30124,
"text": "where k is pendant vertices or leaf nodes which have degree 1 e is total number of edges in the tree"
},
{
"code": null,
"e": 30292,
"s": 30244,
"text": " 2*2 + 4*3 + 3*4 + k*1 = 2*e ——-(1)"
},
{
"code": null,
"e": 30345,
"s": 30292,
"text": "remember : number of edges = number of vertices – 1 "
},
{
"code": null,
"e": 30367,
"s": 30345,
"text": " e=(2+4+3+k)-1"
},
{
"code": null,
"e": 30383,
"s": 30367,
"text": " e=9+k-1"
},
{
"code": null,
"e": 30444,
"s": 30383,
"text": " e=8+k ——-(2)"
},
{
"code": null,
"e": 30482,
"s": 30444,
"text": " putting equation 2 in 1 gives"
},
{
"code": null,
"e": 30515,
"s": 30482,
"text": " 4 + 12 + 12 + k = 2(8+k)"
},
{
"code": null,
"e": 30540,
"s": 30515,
"text": " 28 + k = 16 + 2k"
},
{
"code": null,
"e": 30565,
"s": 30540,
"text": " -2k + k = 16 – 28"
},
{
"code": null,
"e": 30581,
"s": 30565,
"text": " -k = -12"
},
{
"code": null,
"e": 30596,
"s": 30581,
"text": " k = 12"
},
{
"code": null,
"e": 30647,
"s": 30596,
"text": " so total number of pendant vertices are 12"
},
{
"code": null,
"e": 30809,
"s": 30649,
"text": "Q2. If a tree T has 4 vertices of degree 2, 1 vertex of degree 3 and 2 vertices of degree 4 and 1 vertex of degree 5. find the number of pendant vertices in T."
},
{
"code": null,
"e": 30892,
"s": 30811,
"text": "Finding number pendant vertices is nothing but finding the number of leaf nodes."
},
{
"code": null,
"e": 30942,
"s": 30892,
"text": " Let’s use the Handshaking Theorem formula"
},
{
"code": null,
"e": 30991,
"s": 30942,
"text": " Sum of all degrees = 2 * (Sum of Edges)"
},
{
"code": null,
"e": 31132,
"s": 30991,
"text": "(4 vertices)*(2 degrees) + (1 vertex)*(3 degrees) + (2 vertices)*(4 degrees) + (1 vertex)*(5 degree) + (k vertices)*(1 degree) = (2 * edges)"
},
{
"code": null,
"e": 31251,
"s": 31132,
"text": "where k is pendant vertices or leaf nodes which have degree 1 e is total number of edges in the tree"
},
{
"code": null,
"e": 31305,
"s": 31251,
"text": " 4*2 + 1*3 + 2*4 + 1*5 + k*1 = 2*e ——-(1)"
},
{
"code": null,
"e": 31363,
"s": 31305,
"text": " remember number of edges = number of vertices – 1"
},
{
"code": null,
"e": 31387,
"s": 31363,
"text": " e=(4+1+2+1+k)-1"
},
{
"code": null,
"e": 31403,
"s": 31387,
"text": " e=8+k-1"
},
{
"code": null,
"e": 31464,
"s": 31403,
"text": " e=7+k ——-(2)"
},
{
"code": null,
"e": 31502,
"s": 31464,
"text": " putting equation 2 in 1 gives"
},
{
"code": null,
"e": 31537,
"s": 31502,
"text": " 8 + 3 + 8 + 5 + k = 2(7+k)"
},
{
"code": null,
"e": 31561,
"s": 31537,
"text": " 24 + k = 14 + 2k"
},
{
"code": null,
"e": 31586,
"s": 31561,
"text": " -2k + k = 14 – 24"
},
{
"code": null,
"e": 31602,
"s": 31586,
"text": " -k = -10"
},
{
"code": null,
"e": 31617,
"s": 31602,
"text": " k = 10"
},
{
"code": null,
"e": 31667,
"s": 31617,
"text": " so total number of pendant vertices are 10"
},
{
"code": null,
"e": 31686,
"s": 31669,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 31694,
"s": 31686,
"text": "clintra"
},
{
"code": null,
"e": 31707,
"s": 31694,
"text": "shinjanpatra"
},
{
"code": null,
"e": 31729,
"s": 31707,
"text": "Data Structures-Graph"
},
{
"code": null,
"e": 31735,
"s": 31729,
"text": "Graph"
},
{
"code": null,
"e": 31740,
"s": 31735,
"text": "Tree"
},
{
"code": null,
"e": 31746,
"s": 31740,
"text": "Graph"
},
{
"code": null,
"e": 31751,
"s": 31746,
"text": "Tree"
},
{
"code": null,
"e": 31849,
"s": 31751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31890,
"s": 31849,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 31926,
"s": 31890,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 31968,
"s": 31926,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 32033,
"s": 31968,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 32088,
"s": 32033,
"text": "Graph Coloring | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 32138,
"s": 32088,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 32173,
"s": 32138,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 32202,
"s": 32173,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 32236,
"s": 32202,
"text": "Level Order Binary Tree Traversal"
}
] |
Reading Images With Python - Tkinter - GeeksforGeeks
|
20 Oct, 2021
There are numerous tools for designing GUI (Graphical User Interface) in Python such as tkinter, wxPython, JPython, etc where Tkinter is the standard Python GUI library, it provides a simple and efficient way to create GUI applications in Python.
In order to do various operations and manipulations on images, we require Python Pillow package. If the Pillow package is not present in the system then it can be installed using the below command.
In Command prompt:pip install Pillow
pip install Pillow
In Anaconda prompt:conda install -c anaconda pillow
conda install -c anaconda pillow
Example 1: The below program demonstrates how to read images with tkinter using PIL.
# importing required packagesimport tkinterfrom PIL import ImageTk, Imageimport os # creating main windowroot = tkinter.Tk() # loading the imageimg = ImageTk.PhotoImage(Image.open("gfg.jpeg")) # reading the imagepanel = tkinter.Label(root, image = img) # setting the applicationpanel.pack(side = "bottom", fill = "both", expand = "yes") # running the applicationroot.mainloop()
Output:
In the above program, an image is loaded using the PhotoImage() method and then it is read by using the Label() method.The pack() method arranges the main window and the mainloop() function is used to run the application in an infinite loop.
Example 2: Let us look at another example where we arrange the image parameters along with application parameters.
# importing required packagesimport tkinter from PIL import ImageTk, Image # creating main windowroot = tkinter.Tk() # arranging application parameterscanvas = tkinter.Canvas(root, width = 500, height = 250) canvas.pack() # loading the imageimg = ImageTk.PhotoImage(Image.open("gfg.ppm")) # arranging image parameters # in the applicationcanvas.create_image(135, 20, anchor = NW, image = img) # running the applicationroot.mainloop()
Output:
In the above program, the application parameters are handled by using the Canvas() method and the image parameters are handled using create_image() method such that the image gfg.ppm is displayed in the main window having defined height and width.Note: The Canvas method create_image(x0,y0, options ...) is used to draw an image on a canvas. create_image doesn’t accept an image directly. It uses an object which is created by the PhotoImage() method. The PhotoImage class can only read GIF and PGM/PPM images from files.
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25693,
"s": 25665,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 25940,
"s": 25693,
"text": "There are numerous tools for designing GUI (Graphical User Interface) in Python such as tkinter, wxPython, JPython, etc where Tkinter is the standard Python GUI library, it provides a simple and efficient way to create GUI applications in Python."
},
{
"code": null,
"e": 26138,
"s": 25940,
"text": "In order to do various operations and manipulations on images, we require Python Pillow package. If the Pillow package is not present in the system then it can be installed using the below command."
},
{
"code": null,
"e": 26175,
"s": 26138,
"text": "In Command prompt:pip install Pillow"
},
{
"code": null,
"e": 26194,
"s": 26175,
"text": "pip install Pillow"
},
{
"code": null,
"e": 26246,
"s": 26194,
"text": "In Anaconda prompt:conda install -c anaconda pillow"
},
{
"code": null,
"e": 26279,
"s": 26246,
"text": "conda install -c anaconda pillow"
},
{
"code": null,
"e": 26364,
"s": 26279,
"text": "Example 1: The below program demonstrates how to read images with tkinter using PIL."
},
{
"code": "# importing required packagesimport tkinterfrom PIL import ImageTk, Imageimport os # creating main windowroot = tkinter.Tk() # loading the imageimg = ImageTk.PhotoImage(Image.open(\"gfg.jpeg\")) # reading the imagepanel = tkinter.Label(root, image = img) # setting the applicationpanel.pack(side = \"bottom\", fill = \"both\", expand = \"yes\") # running the applicationroot.mainloop()",
"e": 26757,
"s": 26364,
"text": null
},
{
"code": null,
"e": 26765,
"s": 26757,
"text": "Output:"
},
{
"code": null,
"e": 27007,
"s": 26765,
"text": "In the above program, an image is loaded using the PhotoImage() method and then it is read by using the Label() method.The pack() method arranges the main window and the mainloop() function is used to run the application in an infinite loop."
},
{
"code": null,
"e": 27122,
"s": 27007,
"text": "Example 2: Let us look at another example where we arrange the image parameters along with application parameters."
},
{
"code": "# importing required packagesimport tkinter from PIL import ImageTk, Image # creating main windowroot = tkinter.Tk() # arranging application parameterscanvas = tkinter.Canvas(root, width = 500, height = 250) canvas.pack() # loading the imageimg = ImageTk.PhotoImage(Image.open(\"gfg.ppm\")) # arranging image parameters # in the applicationcanvas.create_image(135, 20, anchor = NW, image = img) # running the applicationroot.mainloop() ",
"e": 27617,
"s": 27122,
"text": null
},
{
"code": null,
"e": 27625,
"s": 27617,
"text": "Output:"
},
{
"code": null,
"e": 28147,
"s": 27625,
"text": "In the above program, the application parameters are handled by using the Canvas() method and the image parameters are handled using create_image() method such that the image gfg.ppm is displayed in the main window having defined height and width.Note: The Canvas method create_image(x0,y0, options ...) is used to draw an image on a canvas. create_image doesn’t accept an image directly. It uses an object which is created by the PhotoImage() method. The PhotoImage class can only read GIF and PGM/PPM images from files."
},
{
"code": null,
"e": 28158,
"s": 28147,
"text": "Python-gui"
},
{
"code": null,
"e": 28173,
"s": 28158,
"text": "Python-tkinter"
},
{
"code": null,
"e": 28180,
"s": 28173,
"text": "Python"
},
{
"code": null,
"e": 28278,
"s": 28180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28296,
"s": 28278,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28331,
"s": 28296,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28363,
"s": 28331,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28385,
"s": 28363,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28427,
"s": 28385,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28457,
"s": 28427,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28483,
"s": 28457,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28512,
"s": 28483,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28556,
"s": 28512,
"text": "Reading and Writing to text files in Python"
}
] |
Star Height of Regular Expression and Regular Language - GeeksforGeeks
|
19 Mar, 2018
The star height relates to the field of theoretical of computation (TOC). It is used to indicate the structural complexity of regular expressions and regular languages. Here complexity, relates to the maximum nesting depth of Kleene stars present in a regular expression.It may be noted here that a regular language may be represented by regular expressions that are not unique, yet equivalent. These regular expressions may have different star heights depending on their structural complexity(i.e nesting). But star height of a regular language is a unique number and is equal to the least star height of any regular expression representing that language. In this context generalized star height is an appropriate terminology, that defines the minimum nesting depth of Kleene stars to describe the language by means of a generalized regular expression. For example:
The language “aba” over the set of alphabets {a, b} can be generated using regular expressions,
(a + b)* ...... (1) Star height = 1
(a* b*)* ...... (2) Star height = 2
But we consider the least star height. Therefore the star height of the regular language “aba” is one.
Star height is also defined for regular expressions as the maximum nesting depth of Kleene stars appearing in that expression. In order to state star height, “h” of a regular expression formally, one can write as,
h() = 0, where is the empty seth() = 0, where is the empty stringh(t) = 0, where t may be any terminal symbol of an alphabet seth(EF) = max(h(E), h(F)), where E, F denotes regular expressionsh(E*) = h(E) + 1
Some examples are:
h(a*(b a*)*) = 2
h((a b*) + (a* a b*)*b)*) = 3
h(a) = 0
Prof. Eggan tried to give a relationship between the loop complexity of an automaton that accepts a language L, and the star height of the language, L.The star height of a language, L is equal to the minimal loop complexity of an automaton that accepts, L. It can also be stated that the loop complexity of an automata that is both accessible (i.e automata constructed by deleting all non-accessible states and any transitions to or from them) and co-accessible (i.e a state q of an automaton is said to be co-accessible if there is a string s that takes us from q to a marked state) is the minimum of star heights of regular expressions obtained by different possible executions of the state elimination method (or BMC algorithm).
It is apparent that a regular language of star height zero can represent only a finite number of regular languages. The generalized star height considers that taking complement of a regular expression would not lead to an increase in star height. This consideration yields interesting results at its disposal.
For example – consider the set of alphabets {x, y}. The star height of the regular expression for the regular language “all strings beginning and ending with x”, i.e
h(x(x + y)*x+x) = 1, since only one level of Kleene nesting exists
But the same language can also be represented by the regular expression x ^c x + x, because ^c denotes set of all strings over the input alphabets.
Now, h(x ^c x + x) = 0, as no Kleene nesting present
Therefore the generalized star height of the language is 0 even though its star height is 1.
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between DFA and NFA
Regular expression to ∈-NFA
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Design 101 sequence detector (Mealy machine)
Closure properties of Regular languages
Conversion of Epsilon-NFA to NFA
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Last Minute Notes - Theory of Computation
Difference between Pushdown Automata and Finite Automata
|
[
{
"code": null,
"e": 31055,
"s": 31027,
"text": "\n19 Mar, 2018"
},
{
"code": null,
"e": 31922,
"s": 31055,
"text": "The star height relates to the field of theoretical of computation (TOC). It is used to indicate the structural complexity of regular expressions and regular languages. Here complexity, relates to the maximum nesting depth of Kleene stars present in a regular expression.It may be noted here that a regular language may be represented by regular expressions that are not unique, yet equivalent. These regular expressions may have different star heights depending on their structural complexity(i.e nesting). But star height of a regular language is a unique number and is equal to the least star height of any regular expression representing that language. In this context generalized star height is an appropriate terminology, that defines the minimum nesting depth of Kleene stars to describe the language by means of a generalized regular expression. For example:"
},
{
"code": null,
"e": 32018,
"s": 31922,
"text": "The language “aba” over the set of alphabets {a, b} can be generated using regular expressions,"
},
{
"code": null,
"e": 32090,
"s": 32018,
"text": "(a + b)* ...... (1) Star height = 1\n(a* b*)* ...... (2) Star height = 2"
},
{
"code": null,
"e": 32193,
"s": 32090,
"text": "But we consider the least star height. Therefore the star height of the regular language “aba” is one."
},
{
"code": null,
"e": 32407,
"s": 32193,
"text": "Star height is also defined for regular expressions as the maximum nesting depth of Kleene stars appearing in that expression. In order to state star height, “h” of a regular expression formally, one can write as,"
},
{
"code": null,
"e": 32617,
"s": 32407,
"text": "h() = 0, where is the empty seth() = 0, where is the empty stringh(t) = 0, where t may be any terminal symbol of an alphabet seth(EF) = max(h(E), h(F)), where E, F denotes regular expressionsh(E*) = h(E) + 1"
},
{
"code": null,
"e": 32636,
"s": 32617,
"text": "Some examples are:"
},
{
"code": null,
"e": 32653,
"s": 32636,
"text": "h(a*(b a*)*) = 2"
},
{
"code": null,
"e": 32683,
"s": 32653,
"text": "h((a b*) + (a* a b*)*b)*) = 3"
},
{
"code": null,
"e": 32692,
"s": 32683,
"text": "h(a) = 0"
},
{
"code": null,
"e": 33424,
"s": 32692,
"text": "Prof. Eggan tried to give a relationship between the loop complexity of an automaton that accepts a language L, and the star height of the language, L.The star height of a language, L is equal to the minimal loop complexity of an automaton that accepts, L. It can also be stated that the loop complexity of an automata that is both accessible (i.e automata constructed by deleting all non-accessible states and any transitions to or from them) and co-accessible (i.e a state q of an automaton is said to be co-accessible if there is a string s that takes us from q to a marked state) is the minimum of star heights of regular expressions obtained by different possible executions of the state elimination method (or BMC algorithm)."
},
{
"code": null,
"e": 33734,
"s": 33424,
"text": "It is apparent that a regular language of star height zero can represent only a finite number of regular languages. The generalized star height considers that taking complement of a regular expression would not lead to an increase in star height. This consideration yields interesting results at its disposal."
},
{
"code": null,
"e": 33900,
"s": 33734,
"text": "For example – consider the set of alphabets {x, y}. The star height of the regular expression for the regular language “all strings beginning and ending with x”, i.e"
},
{
"code": null,
"e": 33967,
"s": 33900,
"text": "h(x(x + y)*x+x) = 1, since only one level of Kleene nesting exists"
},
{
"code": null,
"e": 34115,
"s": 33967,
"text": "But the same language can also be represented by the regular expression x ^c x + x, because ^c denotes set of all strings over the input alphabets."
},
{
"code": null,
"e": 34168,
"s": 34115,
"text": "Now, h(x ^c x + x) = 0, as no Kleene nesting present"
},
{
"code": null,
"e": 34261,
"s": 34168,
"text": "Therefore the generalized star height of the language is 0 even though its star height is 1."
},
{
"code": null,
"e": 34294,
"s": 34261,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 34392,
"s": 34294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34423,
"s": 34392,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 34451,
"s": 34423,
"text": "Regular expression to ∈-NFA"
},
{
"code": null,
"e": 34506,
"s": 34451,
"text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}"
},
{
"code": null,
"e": 34551,
"s": 34506,
"text": "Design 101 sequence detector (Mealy machine)"
},
{
"code": null,
"e": 34591,
"s": 34551,
"text": "Closure properties of Regular languages"
},
{
"code": null,
"e": 34624,
"s": 34591,
"text": "Conversion of Epsilon-NFA to NFA"
},
{
"code": null,
"e": 34662,
"s": 34624,
"text": "Boyer-Moore Majority Voting Algorithm"
},
{
"code": null,
"e": 34690,
"s": 34662,
"text": "Variation of Turing Machine"
},
{
"code": null,
"e": 34732,
"s": 34690,
"text": "Last Minute Notes - Theory of Computation"
}
] |
Splitting a Numeric String - GeeksforGeeks
|
23 Feb, 2022
Given a numeric string (length <= 32), split it into two or more integers( if possible), such that 1) Difference between current and previous number is 1.2) No number contains leading zeroes If it is possible to separate a given numeric string then print “Possible” followed by the first number of the increasing sequence, else print “Not Possible“. Examples:
Input : 1234
Output : Possible 1
Explanation: String can be split as "1", "2",
"3", "4"
Input : 99100
Output :Possible 99
Explanation: String can be split as "99",
"100"
Input : 101103
Output : Not Possible
Explanation: It is not possible to split this
string under given constraint.
Approach : The idea is to take a substring from index 0 to any index i (i starting from 1) of the numeric string and convert it to long data type. Add 1 to it and convert the increased number back to string. Check if the next occurring substring is equal to the increased one. If yes, then carry on the procedure else increase the value of i and repeat the steps.
C++
Java
Python3
C#
Javascript
// C++ program to split a numeric// string in an Increasing// sequence if possible#include <bits/stdc++.h>using namespace std; // Function accepts a string and// checks if string can be split.void split(string str){ int len = str.length(); // if there is only 1 number // in the string then // it is not possible to split it if (len == 1) { cout << ("Not Possible"); return; } string s1 = "", s2 = ""; long num1, num2; for (int i = 0; i <= len / 2; i++) { int flag = 0; // storing the substring from // 0 to i+1 to form initial // number of the increasing sequence s1 = str.substr(0, i + 1); num1 = stoi((s1)); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = to_string(num2); int k = i + 1; while (flag == 0) { int l = s2.length(); // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next substring // of the numeric string if ((str.substr(k, k + l) == s2)) { flag = 0; // Increase num2 by 1 i.e the // next number to be looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = to_string(num2); l = s2.length(); if (k + 1 > len) { // If next string doesnot occurs // in a given numeric string // then it is not possible flag = 1; break; } } else flag = 1; } // if the string was fully traversed // and conditions were satisfied if (flag == 0) { cout << "Possible " << s1 << endl; break; } // if conditions failed to hold else if (flag == 1 && i > len / 2 - 1) { cout << "Not Possible" << endl; break; } }} // Driver codeint main(){ string str = "99100"; // Call the split function // for splitting the string split(str); return 0;} // This code is contributed by divyeshrabadiya07
// Java program to split a numeric// string in an Increasing// sequence if possibleimport java.io.*;import java.util.*; class GFG { // Function accepts a string and // checks if string can be split. public static void split(String str) { int len = str.length(); // if there is only 1 number // in the string then // it is not possible to split it if (len == 1) { System.out.println("Not Possible"); return; } String s1 = "", s2 = ""; long num1, num2; for (int i = 0; i <= len / 2; i++) { int flag = 0; // storing the substring from // 0 to i+1 to form initial // number of the increasing sequence s1 = str.substring(0, i + 1); num1 = Long.parseLong((s1)); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = Long.toString(num2); int k = i + 1; while (flag == 0) { int l = s2.length(); // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next substring // of the numeric string if ((str.substring(k, k + l).equals(s2))) { flag = 0; // Increase num2 by 1 i.e the // next number to be looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = Long.toString(num2); l = s2.length(); if (k + 1 > len) { // If next string doesnot occurs // in a given numeric string // then it is not possible flag = 1; break; } } else flag = 1; } // if the string was fully traversed // and conditions were satisfied if (flag == 0) { System.out.println("Possible" + " " + s1); break; } // if conditions failed to hold else if (flag == 1 && i > len / 2 - 1) { System.out.println("Not Possible"); break; } } } // Driver Code public static void main(String args[]) { Scanner in = new Scanner(System.in); String str = "99100"; // Call the split function // for splitting the string split(str); }}
# Python3 program to split a numeric# string in an Increasing# sequence if possible # Function accepts a string and# checks if string can be split.def split(Str) : Len = len(Str) # if there is only 1 number # in the string then # it is not possible to split it if (Len == 1) : print("Not Possible") return s1, s2 = "", "" for i in range((Len // 2) + 1) : flag = 0 # storing the substring from # 0 to i+1 to form initial # number of the increasing sequence s1 = Str[0 : i + 1] num1 = int(s1) num2 = num1 + 1 # convert string to integer # and add 1 and again convert # back to string s2 s2 = str(num2) k = i + 1 while (flag == 0) : l = len(s2) # if s2 is not a substring # of number than not possible if (k + l > Len) : flag = 1 break # if s2 is the next substring # of the numeric string if ((Str[k : k + l] == s2)) : flag = 0 # Increase num2 by 1 i.e the # next number to be looked for num2 += 1 k = k + l # check if string is fully # traversed then break if (k == Len) : break s2 = str(num2) l = len(s2) if (k + 1 > len) : # If next string doesnot occurs # in a given numeric string # then it is not possible flag = 1 break else : flag = 1 # if the string was fully traversed # and conditions were satisfied if (flag == 0) : print("Possible", s1) break # if conditions failed to hold elif (flag == 1 and i > (Len // 2) - 1) : print("Not Possible") break # Driver code Str = "99100" # Call the split function# for splitting the stringsplit(Str) # This code is contributed by divyesh072019.
// C# program to split a numeric// string in an Increasing// sequence if possibleusing System; class GFG{ // Function accepts a// string and checks if// string can be split.static void split(string str){ int len = str.Length; // if there is only 1 // number in the string // then it is not possible // to split it if (len == 1) { Console.WriteLine("Not Possible"); return; } string s1 = "", s2 = ""; long num1, num2; for (int i = 0; i < len / 2; i++) { int flag = 0; // storing the substring // from 0 to i+1 to form // initial number of the // increasing sequence s1 = str.Substring(0, i + 1); num1 = Convert.ToInt64((s1)); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = num2.ToString(); int k = i + 1; while (flag == 0) { int l = s2.Length; // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next // substring of the // numeric string if ((str.Substring(k, l).Equals(s2))) { flag = 0; // Increase num2 by 1 i.e // the next number to be // looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = num2.ToString(); l = s2.Length; if (k + 1 > len) { // If next string doesnot // occurs in a given numeric // string then it is not // possible flag = 1; break; } } else flag = 1; } // if the string was fully // traversed and conditions // were satisfied if (flag == 0) { Console.WriteLine("Possible" + " " + s1); break; } // if conditions // failed to hold else if (flag == 1 && i > len / 2 - 1) { Console.WriteLine("Not Possible"); break; } }} // Driver Codestatic void Main(){ string str = "99100"; // Call the split function // for splitting the string split(str);}} // This code is contributed by// Manish Shaw(manishshaw1)
<script> // JavaScript program to split a numeric// string in an Increasing// sequence if possible // Function accepts a string and// checks if string can be split.function split(str){ let len = str.length; // if there is only 1 number // in the string then // it is not possible to split it if (len == 1) { document.write("Not Possible","</br>"); return; } let s1 = "", s2 = ""; let num1, num2; for (let i = 0; i <= Math.floor(len / 2); i++) { let flag = 0; // storing the substring from // 0 to i+1 to form initial // number of the increasing sequence s1 = str.substring(0, i + 1); num1 = parseInt(s1); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = num2.toString(10); let k = i + 1; while (flag == 0) { let l = s2.length; // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next substring // of the numeric string if (str.substring(k, 2*k + l) == s2) { flag = 0; // Increase num2 by 1 i.e the // next number to be looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = num2.toString(10); l = s2.length; if (k + 1 > len) { // If next string doesnot occurs // in a given numeric string // then it is not possible flag = 1; break; } } else flag = 1; } // if the string was fully traversed // and conditions were satisfied if (flag == 0) { document.write("Possible " + s1,"</br>"); break; } // if conditions failed to hold else if (flag == 1 && i > Math.floor(len / 2)- 1) { document.write("Not Possible","</br>"); break; } }} // Driver codelet str = "99100"; // Call the split function// for splitting the stringsplit(str); // This code is contributed by shinjanpatra </script>
Output:
Possible 99
manishshaw1
divyeshrabadiya07
divyesh072019
simmytarika5
kk773572498
shinjanpatra
Java-Strings
Pattern Searching
Strings
Java-Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Removing string that is an anagram of an earlier string
Check if a string contains uppercase, lowercase, special characters and numeric values
Applications of String Matching Algorithms
Suffix Array | Set 1 (Introduction)
Finite Automata algorithm for Pattern Searching
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
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 26517,
"s": 26489,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 26878,
"s": 26517,
"text": "Given a numeric string (length <= 32), split it into two or more integers( if possible), such that 1) Difference between current and previous number is 1.2) No number contains leading zeroes If it is possible to separate a given numeric string then print “Possible” followed by the first number of the increasing sequence, else print “Not Possible“. Examples: "
},
{
"code": null,
"e": 27166,
"s": 26878,
"text": "Input : 1234\nOutput : Possible 1\nExplanation: String can be split as \"1\", \"2\", \n\"3\", \"4\"\n\nInput : 99100\nOutput :Possible 99\nExplanation: String can be split as \"99\",\n\"100\"\n\nInput : 101103\nOutput : Not Possible\nExplanation: It is not possible to split this \nstring under given constraint."
},
{
"code": null,
"e": 27531,
"s": 27166,
"text": "Approach : The idea is to take a substring from index 0 to any index i (i starting from 1) of the numeric string and convert it to long data type. Add 1 to it and convert the increased number back to string. Check if the next occurring substring is equal to the increased one. If yes, then carry on the procedure else increase the value of i and repeat the steps. "
},
{
"code": null,
"e": 27535,
"s": 27531,
"text": "C++"
},
{
"code": null,
"e": 27540,
"s": 27535,
"text": "Java"
},
{
"code": null,
"e": 27548,
"s": 27540,
"text": "Python3"
},
{
"code": null,
"e": 27551,
"s": 27548,
"text": "C#"
},
{
"code": null,
"e": 27562,
"s": 27551,
"text": "Javascript"
},
{
"code": "// C++ program to split a numeric// string in an Increasing// sequence if possible#include <bits/stdc++.h>using namespace std; // Function accepts a string and// checks if string can be split.void split(string str){ int len = str.length(); // if there is only 1 number // in the string then // it is not possible to split it if (len == 1) { cout << (\"Not Possible\"); return; } string s1 = \"\", s2 = \"\"; long num1, num2; for (int i = 0; i <= len / 2; i++) { int flag = 0; // storing the substring from // 0 to i+1 to form initial // number of the increasing sequence s1 = str.substr(0, i + 1); num1 = stoi((s1)); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = to_string(num2); int k = i + 1; while (flag == 0) { int l = s2.length(); // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next substring // of the numeric string if ((str.substr(k, k + l) == s2)) { flag = 0; // Increase num2 by 1 i.e the // next number to be looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = to_string(num2); l = s2.length(); if (k + 1 > len) { // If next string doesnot occurs // in a given numeric string // then it is not possible flag = 1; break; } } else flag = 1; } // if the string was fully traversed // and conditions were satisfied if (flag == 0) { cout << \"Possible \" << s1 << endl; break; } // if conditions failed to hold else if (flag == 1 && i > len / 2 - 1) { cout << \"Not Possible\" << endl; break; } }} // Driver codeint main(){ string str = \"99100\"; // Call the split function // for splitting the string split(str); return 0;} // This code is contributed by divyeshrabadiya07",
"e": 30029,
"s": 27562,
"text": null
},
{
"code": "// Java program to split a numeric// string in an Increasing// sequence if possibleimport java.io.*;import java.util.*; class GFG { // Function accepts a string and // checks if string can be split. public static void split(String str) { int len = str.length(); // if there is only 1 number // in the string then // it is not possible to split it if (len == 1) { System.out.println(\"Not Possible\"); return; } String s1 = \"\", s2 = \"\"; long num1, num2; for (int i = 0; i <= len / 2; i++) { int flag = 0; // storing the substring from // 0 to i+1 to form initial // number of the increasing sequence s1 = str.substring(0, i + 1); num1 = Long.parseLong((s1)); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = Long.toString(num2); int k = i + 1; while (flag == 0) { int l = s2.length(); // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next substring // of the numeric string if ((str.substring(k, k + l).equals(s2))) { flag = 0; // Increase num2 by 1 i.e the // next number to be looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = Long.toString(num2); l = s2.length(); if (k + 1 > len) { // If next string doesnot occurs // in a given numeric string // then it is not possible flag = 1; break; } } else flag = 1; } // if the string was fully traversed // and conditions were satisfied if (flag == 0) { System.out.println(\"Possible\" + \" \" + s1); break; } // if conditions failed to hold else if (flag == 1 && i > len / 2 - 1) { System.out.println(\"Not Possible\"); break; } } } // Driver Code public static void main(String args[]) { Scanner in = new Scanner(System.in); String str = \"99100\"; // Call the split function // for splitting the string split(str); }}",
"e": 32930,
"s": 30029,
"text": null
},
{
"code": "# Python3 program to split a numeric# string in an Increasing# sequence if possible # Function accepts a string and# checks if string can be split.def split(Str) : Len = len(Str) # if there is only 1 number # in the string then # it is not possible to split it if (Len == 1) : print(\"Not Possible\") return s1, s2 = \"\", \"\" for i in range((Len // 2) + 1) : flag = 0 # storing the substring from # 0 to i+1 to form initial # number of the increasing sequence s1 = Str[0 : i + 1] num1 = int(s1) num2 = num1 + 1 # convert string to integer # and add 1 and again convert # back to string s2 s2 = str(num2) k = i + 1 while (flag == 0) : l = len(s2) # if s2 is not a substring # of number than not possible if (k + l > Len) : flag = 1 break # if s2 is the next substring # of the numeric string if ((Str[k : k + l] == s2)) : flag = 0 # Increase num2 by 1 i.e the # next number to be looked for num2 += 1 k = k + l # check if string is fully # traversed then break if (k == Len) : break s2 = str(num2) l = len(s2) if (k + 1 > len) : # If next string doesnot occurs # in a given numeric string # then it is not possible flag = 1 break else : flag = 1 # if the string was fully traversed # and conditions were satisfied if (flag == 0) : print(\"Possible\", s1) break # if conditions failed to hold elif (flag == 1 and i > (Len // 2) - 1) : print(\"Not Possible\") break # Driver code Str = \"99100\" # Call the split function# for splitting the stringsplit(Str) # This code is contributed by divyesh072019.",
"e": 35077,
"s": 32930,
"text": null
},
{
"code": "// C# program to split a numeric// string in an Increasing// sequence if possibleusing System; class GFG{ // Function accepts a// string and checks if// string can be split.static void split(string str){ int len = str.Length; // if there is only 1 // number in the string // then it is not possible // to split it if (len == 1) { Console.WriteLine(\"Not Possible\"); return; } string s1 = \"\", s2 = \"\"; long num1, num2; for (int i = 0; i < len / 2; i++) { int flag = 0; // storing the substring // from 0 to i+1 to form // initial number of the // increasing sequence s1 = str.Substring(0, i + 1); num1 = Convert.ToInt64((s1)); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = num2.ToString(); int k = i + 1; while (flag == 0) { int l = s2.Length; // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next // substring of the // numeric string if ((str.Substring(k, l).Equals(s2))) { flag = 0; // Increase num2 by 1 i.e // the next number to be // looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = num2.ToString(); l = s2.Length; if (k + 1 > len) { // If next string doesnot // occurs in a given numeric // string then it is not // possible flag = 1; break; } } else flag = 1; } // if the string was fully // traversed and conditions // were satisfied if (flag == 0) { Console.WriteLine(\"Possible\" + \" \" + s1); break; } // if conditions // failed to hold else if (flag == 1 && i > len / 2 - 1) { Console.WriteLine(\"Not Possible\"); break; } }} // Driver Codestatic void Main(){ string str = \"99100\"; // Call the split function // for splitting the string split(str);}} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 37783,
"s": 35077,
"text": null
},
{
"code": "<script> // JavaScript program to split a numeric// string in an Increasing// sequence if possible // Function accepts a string and// checks if string can be split.function split(str){ let len = str.length; // if there is only 1 number // in the string then // it is not possible to split it if (len == 1) { document.write(\"Not Possible\",\"</br>\"); return; } let s1 = \"\", s2 = \"\"; let num1, num2; for (let i = 0; i <= Math.floor(len / 2); i++) { let flag = 0; // storing the substring from // 0 to i+1 to form initial // number of the increasing sequence s1 = str.substring(0, i + 1); num1 = parseInt(s1); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = num2.toString(10); let k = i + 1; while (flag == 0) { let l = s2.length; // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next substring // of the numeric string if (str.substring(k, 2*k + l) == s2) { flag = 0; // Increase num2 by 1 i.e the // next number to be looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = num2.toString(10); l = s2.length; if (k + 1 > len) { // If next string doesnot occurs // in a given numeric string // then it is not possible flag = 1; break; } } else flag = 1; } // if the string was fully traversed // and conditions were satisfied if (flag == 0) { document.write(\"Possible \" + s1,\"</br>\"); break; } // if conditions failed to hold else if (flag == 1 && i > Math.floor(len / 2)- 1) { document.write(\"Not Possible\",\"</br>\"); break; } }} // Driver codelet str = \"99100\"; // Call the split function// for splitting the stringsplit(str); // This code is contributed by shinjanpatra </script>",
"e": 40214,
"s": 37783,
"text": null
},
{
"code": null,
"e": 40223,
"s": 40214,
"text": "Output: "
},
{
"code": null,
"e": 40235,
"s": 40223,
"text": "Possible 99"
},
{
"code": null,
"e": 40247,
"s": 40235,
"text": "manishshaw1"
},
{
"code": null,
"e": 40265,
"s": 40247,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 40279,
"s": 40265,
"text": "divyesh072019"
},
{
"code": null,
"e": 40292,
"s": 40279,
"text": "simmytarika5"
},
{
"code": null,
"e": 40304,
"s": 40292,
"text": "kk773572498"
},
{
"code": null,
"e": 40317,
"s": 40304,
"text": "shinjanpatra"
},
{
"code": null,
"e": 40330,
"s": 40317,
"text": "Java-Strings"
},
{
"code": null,
"e": 40348,
"s": 40330,
"text": "Pattern Searching"
},
{
"code": null,
"e": 40356,
"s": 40348,
"text": "Strings"
},
{
"code": null,
"e": 40369,
"s": 40356,
"text": "Java-Strings"
},
{
"code": null,
"e": 40377,
"s": 40369,
"text": "Strings"
},
{
"code": null,
"e": 40395,
"s": 40377,
"text": "Pattern Searching"
},
{
"code": null,
"e": 40493,
"s": 40395,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40549,
"s": 40493,
"text": "Removing string that is an anagram of an earlier string"
},
{
"code": null,
"e": 40636,
"s": 40549,
"text": "Check if a string contains uppercase, lowercase, special characters and numeric values"
},
{
"code": null,
"e": 40679,
"s": 40636,
"text": "Applications of String Matching Algorithms"
},
{
"code": null,
"e": 40715,
"s": 40679,
"text": "Suffix Array | Set 1 (Introduction)"
},
{
"code": null,
"e": 40763,
"s": 40715,
"text": "Finite Automata algorithm for Pattern Searching"
},
{
"code": null,
"e": 40809,
"s": 40763,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 40834,
"s": 40809,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 40894,
"s": 40834,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 40909,
"s": 40894,
"text": "C++ Data Types"
}
] |
XML | Syntax - GeeksforGeeks
|
22 Apr, 2019
Prerequisite: XML | Basics
In this article, we are going to discuss XML syntax rule which is used while writing an XML document or an XML application. It is a very simple and straight forward to learn and code.Below is a complete XML document to discuss each component in detail.
<?xml version="1.0" encoding="UTF-8"?><message> <to>Students</to> <from>Teacher</from> <subject>Regarding assignment submission</subject> <text>All students will have to submit assignment by tomorrow.</text></message>
Syntax rules for XML declaration or XML Prolog:
<?xml version="1.0" encoding="UTF-8"?>
Below is the explanation of each point.
This line is called XML Prolog or XML declaration.
This line is optional i.e, it can be either used or not in an XML document. However, it should be the very first line if used.
The version=”1.0′′ is the version of the XML currently used. There are various versions of XML available.
The encoding=”UTF-8′′ specifies the character encoding used while writing an XML document, for example, êèé is for French and so on. Its default value is “UTF-8”. For more about character encoding click here.
This declaration is case sensitive for example “xml” should must be in lower case in .
Syntax rules for Root Element:
Every XML files should have one or more Root elements to avoid error.For example below code is wrong because it’s not containing Root element.<to>Students</to><from>Teacher</from><subject>Regarding assignment submission</subject><text>All students will have to submit assignment by tomorrow.</text>In the first example the Root element is <message> and all the remaining elements <to>, <from> etc is the child element and reside within the root element.It is case sensitive.Syntax rules for XML elements:The XML element should have a closing element for example <text category = “message”>Hi</text> is correct but <text category = “message”>Hi is not correct because it does not contain the closing element and it will throw an error and vice-versa.The elements in XML should be nested properly otherwise it will throw an error. For example <to><from>Geeks</from></to> is nested correctly but <to><from>Geeks</to></from> is wrong because if <from> is opened inside the <to> element then this should also end inside of the </to> element.It is also case sensitive i.e, the starting and closing element should be in the same case. For example <to>....</to> is correct but <to>.....</To> is not correct and it will throw an error.Syntax rule for XML Attributes:The XML attribute is having two part one is Name and other is its value. It resides inside of the opening of an XML element. For example: <text category = “message”>All students will have to submit the assignment by tomorrow.</text>Here category is the attribute name and message is its value and the attribute value should either be in a single quotation or in double quotation otherwise it will throw an error. The Attribute Name is written without any quotation.The XML attribute is also case sensitive.An XML element can have multiple attributes but can not have the same attribute names in the same element.For example: <text category =”message” purpose = “greet”>GeeksforGeeks</text>Above attributes is correct because of having multiple attributes with the different attribute name.<text category =”message” category = “greet”>GeeksforGeeks</text>Above attribute is wrong because of having the same attribute name in a single element.XML Comments: Correct syntax for writing XML comments are: <!– It is comment section –>Incorrect comments: <!– It is comment — section –> i.e. Two dashes in between the comment is not allowed.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
<to>Students</to><from>Teacher</from><subject>Regarding assignment submission</subject><text>All students will have to submit assignment by tomorrow.</text>
In the first example the Root element is <message> and all the remaining elements <to>, <from> etc is the child element and reside within the root element.
It is case sensitive.
Syntax rules for XML elements:
The XML element should have a closing element for example <text category = “message”>Hi</text> is correct but <text category = “message”>Hi is not correct because it does not contain the closing element and it will throw an error and vice-versa.
The elements in XML should be nested properly otherwise it will throw an error. For example <to><from>Geeks</from></to> is nested correctly but <to><from>Geeks</to></from> is wrong because if <from> is opened inside the <to> element then this should also end inside of the </to> element.
It is also case sensitive i.e, the starting and closing element should be in the same case. For example <to>....</to> is correct but <to>.....</To> is not correct and it will throw an error.
Syntax rule for XML Attributes:
The XML attribute is having two part one is Name and other is its value. It resides inside of the opening of an XML element. For example: <text category = “message”>All students will have to submit the assignment by tomorrow.</text>Here category is the attribute name and message is its value and the attribute value should either be in a single quotation or in double quotation otherwise it will throw an error. The Attribute Name is written without any quotation.
The XML attribute is also case sensitive.
An XML element can have multiple attributes but can not have the same attribute names in the same element.For example: <text category =”message” purpose = “greet”>GeeksforGeeks</text>Above attributes is correct because of having multiple attributes with the different attribute name.<text category =”message” category = “greet”>GeeksforGeeks</text>Above attribute is wrong because of having the same attribute name in a single element.
XML Comments: Correct syntax for writing XML comments are: <!– It is comment section –>Incorrect comments: <!– It is comment — section –> i.e. Two dashes in between the comment is not allowed.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML and XML
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
How to execute PHP code using command line ?
|
[
{
"code": null,
"e": 25457,
"s": 25429,
"text": "\n22 Apr, 2019"
},
{
"code": null,
"e": 25484,
"s": 25457,
"text": "Prerequisite: XML | Basics"
},
{
"code": null,
"e": 25737,
"s": 25484,
"text": "In this article, we are going to discuss XML syntax rule which is used while writing an XML document or an XML application. It is a very simple and straight forward to learn and code.Below is a complete XML document to discuss each component in detail."
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><message> <to>Students</to> <from>Teacher</from> <subject>Regarding assignment submission</subject> <text>All students will have to submit assignment by tomorrow.</text></message>",
"e": 25963,
"s": 25737,
"text": null
},
{
"code": null,
"e": 26011,
"s": 25963,
"text": "Syntax rules for XML declaration or XML Prolog:"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"e": 26050,
"s": 26011,
"text": null
},
{
"code": null,
"e": 26090,
"s": 26050,
"text": "Below is the explanation of each point."
},
{
"code": null,
"e": 26141,
"s": 26090,
"text": "This line is called XML Prolog or XML declaration."
},
{
"code": null,
"e": 26268,
"s": 26141,
"text": "This line is optional i.e, it can be either used or not in an XML document. However, it should be the very first line if used."
},
{
"code": null,
"e": 26374,
"s": 26268,
"text": "The version=”1.0′′ is the version of the XML currently used. There are various versions of XML available."
},
{
"code": null,
"e": 26586,
"s": 26374,
"text": "The encoding=”UTF-8′′ specifies the character encoding used while writing an XML document, for example, êèé is for French and so on. Its default value is “UTF-8”. For more about character encoding click here."
},
{
"code": null,
"e": 26673,
"s": 26586,
"text": "This declaration is case sensitive for example “xml” should must be in lower case in ."
},
{
"code": null,
"e": 26704,
"s": 26673,
"text": "Syntax rules for Root Element:"
},
{
"code": null,
"e": 29266,
"s": 26704,
"text": "Every XML files should have one or more Root elements to avoid error.For example below code is wrong because it’s not containing Root element.<to>Students</to><from>Teacher</from><subject>Regarding assignment submission</subject><text>All students will have to submit assignment by tomorrow.</text>In the first example the Root element is <message> and all the remaining elements <to>, <from> etc is the child element and reside within the root element.It is case sensitive.Syntax rules for XML elements:The XML element should have a closing element for example <text category = “message”>Hi</text> is correct but <text category = “message”>Hi is not correct because it does not contain the closing element and it will throw an error and vice-versa.The elements in XML should be nested properly otherwise it will throw an error. For example <to><from>Geeks</from></to> is nested correctly but <to><from>Geeks</to></from> is wrong because if <from> is opened inside the <to> element then this should also end inside of the </to> element.It is also case sensitive i.e, the starting and closing element should be in the same case. For example <to>....</to> is correct but <to>.....</To> is not correct and it will throw an error.Syntax rule for XML Attributes:The XML attribute is having two part one is Name and other is its value. It resides inside of the opening of an XML element. For example: <text category = “message”>All students will have to submit the assignment by tomorrow.</text>Here category is the attribute name and message is its value and the attribute value should either be in a single quotation or in double quotation otherwise it will throw an error. The Attribute Name is written without any quotation.The XML attribute is also case sensitive.An XML element can have multiple attributes but can not have the same attribute names in the same element.For example: <text category =”message” purpose = “greet”>GeeksforGeeks</text>Above attributes is correct because of having multiple attributes with the different attribute name.<text category =”message” category = “greet”>GeeksforGeeks</text>Above attribute is wrong because of having the same attribute name in a single element.XML Comments: Correct syntax for writing XML comments are: <!– It is comment section –>Incorrect comments: <!– It is comment — section –> i.e. Two dashes in between the comment is not allowed.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": "<to>Students</to><from>Teacher</from><subject>Regarding assignment submission</subject><text>All students will have to submit assignment by tomorrow.</text>",
"e": 29423,
"s": 29266,
"text": null
},
{
"code": null,
"e": 29579,
"s": 29423,
"text": "In the first example the Root element is <message> and all the remaining elements <to>, <from> etc is the child element and reside within the root element."
},
{
"code": null,
"e": 29601,
"s": 29579,
"text": "It is case sensitive."
},
{
"code": null,
"e": 29632,
"s": 29601,
"text": "Syntax rules for XML elements:"
},
{
"code": null,
"e": 29878,
"s": 29632,
"text": "The XML element should have a closing element for example <text category = “message”>Hi</text> is correct but <text category = “message”>Hi is not correct because it does not contain the closing element and it will throw an error and vice-versa."
},
{
"code": null,
"e": 30166,
"s": 29878,
"text": "The elements in XML should be nested properly otherwise it will throw an error. For example <to><from>Geeks</from></to> is nested correctly but <to><from>Geeks</to></from> is wrong because if <from> is opened inside the <to> element then this should also end inside of the </to> element."
},
{
"code": null,
"e": 30357,
"s": 30166,
"text": "It is also case sensitive i.e, the starting and closing element should be in the same case. For example <to>....</to> is correct but <to>.....</To> is not correct and it will throw an error."
},
{
"code": null,
"e": 30389,
"s": 30357,
"text": "Syntax rule for XML Attributes:"
},
{
"code": null,
"e": 30855,
"s": 30389,
"text": "The XML attribute is having two part one is Name and other is its value. It resides inside of the opening of an XML element. For example: <text category = “message”>All students will have to submit the assignment by tomorrow.</text>Here category is the attribute name and message is its value and the attribute value should either be in a single quotation or in double quotation otherwise it will throw an error. The Attribute Name is written without any quotation."
},
{
"code": null,
"e": 30897,
"s": 30855,
"text": "The XML attribute is also case sensitive."
},
{
"code": null,
"e": 31333,
"s": 30897,
"text": "An XML element can have multiple attributes but can not have the same attribute names in the same element.For example: <text category =”message” purpose = “greet”>GeeksforGeeks</text>Above attributes is correct because of having multiple attributes with the different attribute name.<text category =”message” category = “greet”>GeeksforGeeks</text>Above attribute is wrong because of having the same attribute name in a single element."
},
{
"code": null,
"e": 31526,
"s": 31333,
"text": "XML Comments: Correct syntax for writing XML comments are: <!– It is comment section –>Incorrect comments: <!– It is comment — section –> i.e. Two dashes in between the comment is not allowed."
},
{
"code": null,
"e": 31663,
"s": 31526,
"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": 31676,
"s": 31663,
"text": "HTML and XML"
},
{
"code": null,
"e": 31693,
"s": 31676,
"text": "Web Technologies"
},
{
"code": null,
"e": 31791,
"s": 31693,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31831,
"s": 31791,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31876,
"s": 31831,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31919,
"s": 31876,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31980,
"s": 31919,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32052,
"s": 31980,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 32110,
"s": 32052,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 32165,
"s": 32110,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 32211,
"s": 32165,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 32252,
"s": 32211,
"text": "Difference Between PUT and PATCH Request"
}
] |
Finding nth term of any Polynomial Sequence - GeeksforGeeks
|
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
School Learning
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
Software Design Patterns
System Design Tutorial
School Learning
School Programming
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Engineering Mathematics Tutorials
Mathematics | Introduction to Propositional Logic | Set 1
Mathematics | Introduction to Propositional Logic | Set 2
Mathematics | Propositional Equivalences
Mathematics | Predicates and Quantifiers | Set 1
Mathematics | Predicates and Quantifiers | Set 2
Mathematics | Some theorems on Nested Quantifiers
Mathematics | Rules of Inference
PDNF and PCNF in Discrete Mathematics
Mathematics | Introduction of Set theory
Mathematics | Set Operations (Set theory)
Inclusion-Exclusion and its various Applications
Mathematics | Power Set and its Properties
Mathematics | Partial Orders and Lattices
Mathematics | Algebraic Structure
Mathematics | Introduction and types of Relations
Discrete Mathematics | Representing Relations
Mathematics | Representations of Matrices and Graphs in Relations
Mathematics | Closure of Relations and Equivalence Relations
Number of possible Equivalence Relations on a finite set
Mathematics | Classes (Injective, surjective, Bijective) of Functions
Mathematics | Total number of possible functions
Discrete Maths | Generating Functions-Introduction and Prerequisites
Mathematics | Generating Functions – Set 2
Mathematics | Sequence, Series and Summations
Mathematics | Independent Sets, Covering and Matching
Mathematics | Introduction to Proofs
Discrete Mathematics | Hasse Diagrams
Introduction to Mojette transform
Mathematics | Rings, Integral domains and Fields
Mathematics | The Pigeonhole Principle
Mathematics | Combinatorics Basics
Mathematics | PnC and Binomial Coefficients
Mathematics | Generalized PnC Set 1
Mathematics | Generalized PnC Set 2
Corollaries of Binomial Theorem
Number of triangles in a plane if no more than two points are collinear
Mathematics | Sum of squares of even and odd natural numbers
Finding nth term of any Polynomial Sequence
Discrete Mathematics | Types of Recurrence Relations – Set 2
Mathematics | Graph Theory Basics – Set 1
Mathematics | Graph Theory Basics – Set 2
Graph Types and Applications
Mathematics | Euler and Hamiltonian Paths
Mathematics | Planar Graphs and Graph Coloring
Mathematics | Graph Isomorphisms and Connectivity
Mathematics | Matching (graph theory)
Betweenness Centrality (Centrality Measure)
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Graph measurements: length, distance, diameter, eccentricity, radius, center
Relationship between number of nodes and height of binary tree
Mathematics | Matrix Introduction
Different Operations on Matrices
Mathematics | L U Decomposition of a System of Linear Equations
Doolittle Algorithm : LU Decomposition
Mathematics | System of Linear Equations
Mathematics | Eigen Values and Eigen Vectors
Mathematics | Probability
Mathematics | Random Variables
Mathematics | Mean, Variance and Standard Deviation
Mathematics | Law of total probability
Bayes’s Theorem for Conditional Probability
Mathematics | Probability Distributions Set 1 (Uniform Distribution)
Mathematics | Probability Distributions Set 2 (Exponential Distribution)
Mathematics | Probability Distributions Set 3 (Normal Distribution)
Mathematics | Probability Distributions Set 4 (Binomial Distribution)
Mathematics | Probability Distributions Set 5 (Poisson Distribution)
Mathematics | Hypergeometric Distribution model
Mathematics | Conditional Probability
Mathematics | Covariance and Correlation
Mathematics | Limits, Continuity and Differentiability
Mathematics | Lagrange’s Mean Value Theorem
Mathematics | Rolle’s Mean Value Theorem
Cauchy’s Mean Value Theorem
Mathematics | Indefinite Integrals
Mathematics | Problems On Permutations | Set 1
Problem on permutations and combinations | Set 2
Mathematics | Graph theory practice questions
Permutation and Combination
Propositional and First Order Logic.
Set Theory & Algebra
Combinatorics
Graph Theory
Linear Algebra
Probability
Numerical Methods and Calculus
Engineering Mathematics Tutorials
Mathematics | Introduction to Propositional Logic | Set 1
Mathematics | Introduction to Propositional Logic | Set 2
Mathematics | Propositional Equivalences
Mathematics | Predicates and Quantifiers | Set 1
Mathematics | Predicates and Quantifiers | Set 2
Mathematics | Some theorems on Nested Quantifiers
Mathematics | Rules of Inference
PDNF and PCNF in Discrete Mathematics
Mathematics | Introduction of Set theory
Mathematics | Set Operations (Set theory)
Inclusion-Exclusion and its various Applications
Mathematics | Power Set and its Properties
Mathematics | Partial Orders and Lattices
Mathematics | Algebraic Structure
Mathematics | Introduction and types of Relations
Discrete Mathematics | Representing Relations
Mathematics | Representations of Matrices and Graphs in Relations
Mathematics | Closure of Relations and Equivalence Relations
Number of possible Equivalence Relations on a finite set
Mathematics | Classes (Injective, surjective, Bijective) of Functions
Mathematics | Total number of possible functions
Discrete Maths | Generating Functions-Introduction and Prerequisites
Mathematics | Generating Functions – Set 2
Mathematics | Sequence, Series and Summations
Mathematics | Independent Sets, Covering and Matching
Mathematics | Introduction to Proofs
Discrete Mathematics | Hasse Diagrams
Introduction to Mojette transform
Mathematics | Rings, Integral domains and Fields
Mathematics | The Pigeonhole Principle
Mathematics | Combinatorics Basics
Mathematics | PnC and Binomial Coefficients
Mathematics | Generalized PnC Set 1
Mathematics | Generalized PnC Set 2
Corollaries of Binomial Theorem
Number of triangles in a plane if no more than two points are collinear
Mathematics | Sum of squares of even and odd natural numbers
Finding nth term of any Polynomial Sequence
Discrete Mathematics | Types of Recurrence Relations – Set 2
Mathematics | Graph Theory Basics – Set 1
Mathematics | Graph Theory Basics – Set 2
Graph Types and Applications
Mathematics | Euler and Hamiltonian Paths
Mathematics | Planar Graphs and Graph Coloring
Mathematics | Graph Isomorphisms and Connectivity
Mathematics | Matching (graph theory)
Betweenness Centrality (Centrality Measure)
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Graph measurements: length, distance, diameter, eccentricity, radius, center
Relationship between number of nodes and height of binary tree
Mathematics | Matrix Introduction
Different Operations on Matrices
Mathematics | L U Decomposition of a System of Linear Equations
Doolittle Algorithm : LU Decomposition
Mathematics | System of Linear Equations
Mathematics | Eigen Values and Eigen Vectors
Mathematics | Probability
Mathematics | Random Variables
Mathematics | Mean, Variance and Standard Deviation
Mathematics | Law of total probability
Bayes’s Theorem for Conditional Probability
Mathematics | Probability Distributions Set 1 (Uniform Distribution)
Mathematics | Probability Distributions Set 2 (Exponential Distribution)
Mathematics | Probability Distributions Set 3 (Normal Distribution)
Mathematics | Probability Distributions Set 4 (Binomial Distribution)
Mathematics | Probability Distributions Set 5 (Poisson Distribution)
Mathematics | Hypergeometric Distribution model
Mathematics | Conditional Probability
Mathematics | Covariance and Correlation
Mathematics | Limits, Continuity and Differentiability
Mathematics | Lagrange’s Mean Value Theorem
Mathematics | Rolle’s Mean Value Theorem
Cauchy’s Mean Value Theorem
Mathematics | Indefinite Integrals
Mathematics | Problems On Permutations | Set 1
Problem on permutations and combinations | Set 2
Mathematics | Graph theory practice questions
Permutation and Combination
Propositional and First Order Logic.
Set Theory & Algebra
Combinatorics
Graph Theory
Linear Algebra
Probability
Numerical Methods and Calculus
Difficulty Level :
Easy
Given a few terms of a sequence, we are often asked to find the expression for the nth term of this sequence. While there is a multitude of ways to do this, In this article, we discuss an algorithmic approach which will give the correct answer for any polynomial expression. Note that this method fails for trigonometric, exponential or other transcendental sequences.
We will take a few examples and discuss the method as we solve these examples.
Example 1
Let us take the sequence
S = 3, 9, 15, 21, ....
Trivial Solution
We can easily see that this is an A.P series. The starting term is 3 and the common difference is 6. Hence the nth term of the sequence is 3 + (n-1) * 6.
Our Solution
Since we know that an nth order polynomial has the form:
Polynomial = Pn = a0 + a1*x^1 + a2*x^2 + ... + an*x^n
Since we already know a few terms of the sequence, we can substitute these values in the above expression and obtain some equations. Then we need to solve this system of linear equations and obtain the coefficients a0, a1, ... an.
The trick is to somehow know the order of the polynomial.
This is simple enough to do if we remember that the nth order forward difference is constant for an nth order polynomial. Also all higher order forward differences are 0. Let us obtain the forward differences for the series
3 9 15 21 27 ...
6 6 6 6
Since the first forward difference is constant, we conclude that the sequence is a first order polynomial.
1st order polynomial Sn = a0 + a1*n
For n = 1, Sn = 3
3 = a0 + a1 .... (1)
For n = 2, Sn = 9
9 = a0 + 2*a1 .... (2)
Solving (1) and (2) we get
a1 = 6 and a0 = -3
Hence we obtain Sn = -3 + 6*n
Note that we obtain slightly different formulations of the sequence in the above two methods. But both these formulations are correct and can easily be converted from one form to another
Example 2
Lets us take the sequence S =
9 24 47 78 117 164 219 ...
15 23 31 39 47 55
8 8 8 8 8
Since the 2n order forward difference is constant, the Sequence is a 2nd order
polynomial
S = a0 + a1*n + a2 *n*n
Substituting n = 1, 2, 3 and corresponding entries we get
9 = a0 + a1 + a2 ... (1)
24 = a0 + 2*a1 + 4*a2 ... (2)
47 = a0 + 3*a1 + 9*a3 ... (3)
Writing matrices for above equations
A = 1 1 1
1 2 4
1 3 9
B = 9 24 47
X = [a0 a1 a2] = inv(A)*B = [ 2 3 4]
Hence a0 = 2, a1 = 3, a2 = 4
Therefore S = 2 + 3*n + 4 * n * n
Example 3
S = 28, 168, 516, 1168, 2220 ...
Forward Differences
28 168 516 1168 2220
140 348 652 1052
208 304 400
96 96
The Sequence is a third order polynomial
S = a0 + a1*n + a2*n*n + a3*n*n*n
Substituting n = 1, 2, 3, 4 and corresponding values
28 = a0 + a1 + a2 + a3
168 = a0 + 2*a1 + 4*a2*a2 + 8*a3*a3*a3
516 = a0 + 3*a1 + 9*a2*a2 + 27*a3*a3*a3
1168 = a0 + 4*a1 + 16*a2*a2 + 64*a3*a3*a3
Writing matrices for above equations
A = 1 1 1 1
1 2 4 8
1 3 9 27
1 4 16 64
B = 28, 168, 516, 1168
X = [a0 a1 a2 a3] = inv(A)*B = [0, 4, 8, 16]
Therefore S = 4*n + 8*n*n + 16*n*n*n
Note: To solve an nth order Sequence we need to solve a system of n equations. These equations can either be solved by hand or by using matrix-based math calculators like MATLAB, Octave etc. A free online version of Octave is available at Octave Online.
series
Engineering Mathematics
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inequalities in LaTeX
Activation Functions
Arrow Symbols in LaTeX
Newton's Divided Difference Interpolation Formula
Set Notations in LaTeX
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": 419,
"s": 0,
"text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses"
},
{
"code": null,
"e": 600,
"s": 419,
"text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 685,
"s": 600,
"text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More"
},
{
"code": null,
"e": 702,
"s": 685,
"text": "DSA Live Classes"
},
{
"code": null,
"e": 716,
"s": 702,
"text": "System Design"
},
{
"code": null,
"e": 741,
"s": 716,
"text": "Java Backend Development"
},
{
"code": null,
"e": 757,
"s": 741,
"text": "Full Stack LIVE"
},
{
"code": null,
"e": 770,
"s": 757,
"text": "Explore More"
},
{
"code": null,
"e": 842,
"s": 770,
"text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 858,
"s": 842,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 869,
"s": 858,
"text": "SDE Theory"
},
{
"code": null,
"e": 894,
"s": 869,
"text": "Must-Do Coding Questions"
},
{
"code": null,
"e": 907,
"s": 894,
"text": "Explore More"
},
{
"code": null,
"e": 1054,
"s": 907,
"text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1130,
"s": 1054,
"text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More"
},
{
"code": null,
"e": 1154,
"s": 1130,
"text": "Competitive Programming"
},
{
"code": null,
"e": 1179,
"s": 1154,
"text": "Data Structures with C++"
},
{
"code": null,
"e": 1192,
"s": 1179,
"text": "Data Science"
},
{
"code": null,
"e": 1205,
"s": 1192,
"text": "Explore More"
},
{
"code": null,
"e": 1265,
"s": 1205,
"text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1281,
"s": 1265,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 1285,
"s": 1281,
"text": "CIP"
},
{
"code": null,
"e": 1305,
"s": 1285,
"text": "JAVA / Python / C++"
},
{
"code": null,
"e": 1318,
"s": 1305,
"text": "Explore More"
},
{
"code": null,
"e": 1393,
"s": 1318,
"text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more"
},
{
"code": null,
"e": 1406,
"s": 1393,
"text": "School Guide"
},
{
"code": null,
"e": 1425,
"s": 1406,
"text": "Python Programming"
},
{
"code": null,
"e": 1444,
"s": 1425,
"text": "Learn To Make Apps"
},
{
"code": null,
"e": 1457,
"s": 1444,
"text": "Explore more"
},
{
"code": null,
"e": 1469,
"s": 1457,
"text": "All Courses"
},
{
"code": null,
"e": 3985,
"s": 1469,
"text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 4566,
"s": 3985,
"text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms"
},
{
"code": null,
"e": 4899,
"s": 4566,
"text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question"
},
{
"code": null,
"e": 4919,
"s": 4899,
"text": "Asymptotic Analysis"
},
{
"code": null,
"e": 4949,
"s": 4919,
"text": "Worst, Average and Best Cases"
},
{
"code": null,
"e": 4970,
"s": 4949,
"text": "Asymptotic Notations"
},
{
"code": null,
"e": 5006,
"s": 4970,
"text": "Little o and little omega notations"
},
{
"code": null,
"e": 5035,
"s": 5006,
"text": "Lower and Upper Bound Theory"
},
{
"code": null,
"e": 5053,
"s": 5035,
"text": "Analysis of Loops"
},
{
"code": null,
"e": 5073,
"s": 5053,
"text": "Solving Recurrences"
},
{
"code": null,
"e": 5092,
"s": 5073,
"text": "Amortized Analysis"
},
{
"code": null,
"e": 5128,
"s": 5092,
"text": "What does 'Space Complexity' mean ?"
},
{
"code": null,
"e": 5157,
"s": 5128,
"text": "Pseudo-polynomial Algorithms"
},
{
"code": null,
"e": 5194,
"s": 5157,
"text": "Polynomial Time Approximation Scheme"
},
{
"code": null,
"e": 5221,
"s": 5194,
"text": "A Time Complexity Question"
},
{
"code": null,
"e": 5242,
"s": 5221,
"text": "Searching Algorithms"
},
{
"code": null,
"e": 5261,
"s": 5242,
"text": "Sorting Algorithms"
},
{
"code": null,
"e": 5278,
"s": 5261,
"text": "Graph Algorithms"
},
{
"code": null,
"e": 5296,
"s": 5278,
"text": "Pattern Searching"
},
{
"code": null,
"e": 5317,
"s": 5296,
"text": "Geometric Algorithms"
},
{
"code": null,
"e": 5330,
"s": 5317,
"text": "Mathematical"
},
{
"code": null,
"e": 5349,
"s": 5330,
"text": "Bitwise Algorithms"
},
{
"code": null,
"e": 5371,
"s": 5349,
"text": "Randomized Algorithms"
},
{
"code": null,
"e": 5389,
"s": 5371,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 5409,
"s": 5389,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5428,
"s": 5409,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5441,
"s": 5428,
"text": "Backtracking"
},
{
"code": null,
"e": 5458,
"s": 5441,
"text": "Branch and Bound"
},
{
"code": null,
"e": 5473,
"s": 5458,
"text": "All Algorithms"
},
{
"code": null,
"e": 5616,
"s": 5473,
"text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures"
},
{
"code": null,
"e": 5623,
"s": 5616,
"text": "Arrays"
},
{
"code": null,
"e": 5635,
"s": 5623,
"text": "Linked List"
},
{
"code": null,
"e": 5641,
"s": 5635,
"text": "Stack"
},
{
"code": null,
"e": 5647,
"s": 5641,
"text": "Queue"
},
{
"code": null,
"e": 5659,
"s": 5647,
"text": "Binary Tree"
},
{
"code": null,
"e": 5678,
"s": 5659,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 5683,
"s": 5678,
"text": "Heap"
},
{
"code": null,
"e": 5691,
"s": 5683,
"text": "Hashing"
},
{
"code": null,
"e": 5697,
"s": 5691,
"text": "Graph"
},
{
"code": null,
"e": 5721,
"s": 5697,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 5728,
"s": 5721,
"text": "Matrix"
},
{
"code": null,
"e": 5736,
"s": 5728,
"text": "Strings"
},
{
"code": null,
"e": 5756,
"s": 5736,
"text": "All Data Structures"
},
{
"code": null,
"e": 5976,
"s": 5756,
"text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes"
},
{
"code": null,
"e": 5996,
"s": 5976,
"text": "Company Preparation"
},
{
"code": null,
"e": 6007,
"s": 5996,
"text": "Top Topics"
},
{
"code": null,
"e": 6034,
"s": 6007,
"text": "Practice Company Questions"
},
{
"code": null,
"e": 6056,
"s": 6034,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6079,
"s": 6056,
"text": "Experienced Interviews"
},
{
"code": null,
"e": 6101,
"s": 6079,
"text": "Internship Interviews"
},
{
"code": null,
"e": 6126,
"s": 6101,
"text": "Competititve Programming"
},
{
"code": null,
"e": 6142,
"s": 6126,
"text": "Design Patterns"
},
{
"code": null,
"e": 6165,
"s": 6142,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 6189,
"s": 6165,
"text": "Multiple Choice Quizzes"
},
{
"code": null,
"e": 6270,
"s": 6189,
"text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin"
},
{
"code": null,
"e": 6272,
"s": 6270,
"text": "C"
},
{
"code": null,
"e": 6276,
"s": 6272,
"text": "C++"
},
{
"code": null,
"e": 6281,
"s": 6276,
"text": "Java"
},
{
"code": null,
"e": 6288,
"s": 6281,
"text": "Python"
},
{
"code": null,
"e": 6291,
"s": 6288,
"text": "C#"
},
{
"code": null,
"e": 6302,
"s": 6291,
"text": "JavaScript"
},
{
"code": null,
"e": 6309,
"s": 6302,
"text": "jQuery"
},
{
"code": null,
"e": 6313,
"s": 6309,
"text": "SQL"
},
{
"code": null,
"e": 6317,
"s": 6313,
"text": "PHP"
},
{
"code": null,
"e": 6323,
"s": 6317,
"text": "Scala"
},
{
"code": null,
"e": 6328,
"s": 6323,
"text": "Perl"
},
{
"code": null,
"e": 6340,
"s": 6328,
"text": "Go Language"
},
{
"code": null,
"e": 6345,
"s": 6340,
"text": "HTML"
},
{
"code": null,
"e": 6349,
"s": 6345,
"text": "CSS"
},
{
"code": null,
"e": 6356,
"s": 6349,
"text": "Kotlin"
},
{
"code": null,
"e": 6402,
"s": 6356,
"text": "ML & Data ScienceMachine LearningData Science"
},
{
"code": null,
"e": 6419,
"s": 6402,
"text": "Machine Learning"
},
{
"code": null,
"e": 6432,
"s": 6419,
"text": "Data Science"
},
{
"code": null,
"e": 6599,
"s": 6432,
"text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering"
},
{
"code": null,
"e": 6611,
"s": 6599,
"text": "Mathematics"
},
{
"code": null,
"e": 6628,
"s": 6611,
"text": "Operating System"
},
{
"code": null,
"e": 6633,
"s": 6628,
"text": "DBMS"
},
{
"code": null,
"e": 6651,
"s": 6633,
"text": "Computer Networks"
},
{
"code": null,
"e": 6690,
"s": 6651,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 6712,
"s": 6690,
"text": "Theory of Computation"
},
{
"code": null,
"e": 6728,
"s": 6712,
"text": "Compiler Design"
},
{
"code": null,
"e": 6742,
"s": 6728,
"text": "Digital Logic"
},
{
"code": null,
"e": 6763,
"s": 6742,
"text": "Software Engineering"
},
{
"code": null,
"e": 6938,
"s": 6763,
"text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS"
},
{
"code": null,
"e": 6966,
"s": 6938,
"text": "GATE Computer Science Notes"
},
{
"code": null,
"e": 6984,
"s": 6966,
"text": "Last Minute Notes"
},
{
"code": null,
"e": 7006,
"s": 6984,
"text": "GATE CS Solved Papers"
},
{
"code": null,
"e": 7048,
"s": 7006,
"text": "GATE CS Original Papers and Official Keys"
},
{
"code": null,
"e": 7064,
"s": 7048,
"text": "GATE 2021 Dates"
},
{
"code": null,
"e": 7086,
"s": 7064,
"text": "GATE CS 2021 Syllabus"
},
{
"code": null,
"e": 7115,
"s": 7086,
"text": "Important Topics for GATE CS"
},
{
"code": null,
"e": 7189,
"s": 7115,
"text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP"
},
{
"code": null,
"e": 7194,
"s": 7189,
"text": "HTML"
},
{
"code": null,
"e": 7198,
"s": 7194,
"text": "CSS"
},
{
"code": null,
"e": 7209,
"s": 7198,
"text": "JavaScript"
},
{
"code": null,
"e": 7219,
"s": 7209,
"text": "AngularJS"
},
{
"code": null,
"e": 7227,
"s": 7219,
"text": "ReactJS"
},
{
"code": null,
"e": 7234,
"s": 7227,
"text": "NodeJS"
},
{
"code": null,
"e": 7244,
"s": 7234,
"text": "Bootstrap"
},
{
"code": null,
"e": 7251,
"s": 7244,
"text": "jQuery"
},
{
"code": null,
"e": 7255,
"s": 7251,
"text": "PHP"
},
{
"code": null,
"e": 7318,
"s": 7255,
"text": "Software DesignsSoftware Design PatternsSystem Design Tutorial"
},
{
"code": null,
"e": 7343,
"s": 7318,
"text": "Software Design Patterns"
},
{
"code": null,
"e": 7366,
"s": 7343,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 7923,
"s": 7366,
"text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 7942,
"s": 7923,
"text": "School Programming"
},
{
"code": null,
"e": 8034,
"s": 7942,
"text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus"
},
{
"code": null,
"e": 8048,
"s": 8034,
"text": "Number System"
},
{
"code": null,
"e": 8056,
"s": 8048,
"text": "Algebra"
},
{
"code": null,
"e": 8069,
"s": 8056,
"text": "Trigonometry"
},
{
"code": null,
"e": 8080,
"s": 8069,
"text": "Statistics"
},
{
"code": null,
"e": 8092,
"s": 8080,
"text": "Probability"
},
{
"code": null,
"e": 8101,
"s": 8092,
"text": "Geometry"
},
{
"code": null,
"e": 8113,
"s": 8101,
"text": "Mensuration"
},
{
"code": null,
"e": 8122,
"s": 8113,
"text": "Calculus"
},
{
"code": null,
"e": 8215,
"s": 8122,
"text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes"
},
{
"code": null,
"e": 8229,
"s": 8215,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8243,
"s": 8229,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8258,
"s": 8243,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8273,
"s": 8258,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 8288,
"s": 8273,
"text": "Class 12 Notes"
},
{
"code": null,
"e": 8417,
"s": 8288,
"text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8440,
"s": 8417,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8463,
"s": 8440,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8487,
"s": 8463,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8511,
"s": 8487,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8535,
"s": 8511,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8668,
"s": 8535,
"text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8691,
"s": 8668,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8714,
"s": 8691,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8738,
"s": 8714,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8762,
"s": 8738,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8786,
"s": 8762,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8867,
"s": 8786,
"text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 8881,
"s": 8867,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8895,
"s": 8881,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8910,
"s": 8895,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8925,
"s": 8910,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 9131,
"s": 8925,
"text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9242,
"s": 9131,
"text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9284,
"s": 9242,
"text": "ISRO CS Original Papers and Official Keys"
},
{
"code": null,
"e": 9306,
"s": 9284,
"text": "ISRO CS Solved Papers"
},
{
"code": null,
"e": 9351,
"s": 9306,
"text": "ISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9434,
"s": 9351,
"text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9460,
"s": 9434,
"text": "UGC NET CS Notes Paper II"
},
{
"code": null,
"e": 9487,
"s": 9460,
"text": "UGC NET CS Notes Paper III"
},
{
"code": null,
"e": 9512,
"s": 9487,
"text": "UGC NET CS Solved Papers"
},
{
"code": null,
"e": 9717,
"s": 9512,
"text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 9743,
"s": 9717,
"text": "Campus Ambassador Program"
},
{
"code": null,
"e": 9769,
"s": 9743,
"text": "School Ambassador Program"
},
{
"code": null,
"e": 9777,
"s": 9769,
"text": "Project"
},
{
"code": null,
"e": 9795,
"s": 9777,
"text": "Geek of the Month"
},
{
"code": null,
"e": 9820,
"s": 9795,
"text": "Campus Geek of the Month"
},
{
"code": null,
"e": 9837,
"s": 9820,
"text": "Placement Course"
},
{
"code": null,
"e": 9862,
"s": 9837,
"text": "Competititve Programming"
},
{
"code": null,
"e": 9875,
"s": 9862,
"text": "Testimonials"
},
{
"code": null,
"e": 9891,
"s": 9875,
"text": "Student Chapter"
},
{
"code": null,
"e": 9907,
"s": 9891,
"text": "Geek on the Top"
},
{
"code": null,
"e": 9918,
"s": 9907,
"text": "Internship"
},
{
"code": null,
"e": 9926,
"s": 9918,
"text": "Careers"
},
{
"code": null,
"e": 9965,
"s": 9926,
"text": "JobsApply for JobsPost a JobJOB-A-THON"
},
{
"code": null,
"e": 9980,
"s": 9965,
"text": "Apply for Jobs"
},
{
"code": null,
"e": 9991,
"s": 9980,
"text": "Post a Job"
},
{
"code": null,
"e": 10002,
"s": 9991,
"text": "JOB-A-THON"
},
{
"code": null,
"e": 10267,
"s": 10002,
"text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10284,
"s": 10267,
"text": "All DSA Problems"
},
{
"code": null,
"e": 10303,
"s": 10284,
"text": "Problem of the Day"
},
{
"code": null,
"e": 10337,
"s": 10303,
"text": "Interview Series: Weekly Contests"
},
{
"code": null,
"e": 10371,
"s": 10337,
"text": "Bi-Wizard Coding: School Contests"
},
{
"code": null,
"e": 10391,
"s": 10371,
"text": "Contests and Events"
},
{
"code": null,
"e": 10410,
"s": 10391,
"text": "Practice SDE Sheet"
},
{
"code": null,
"e": 10530,
"s": 10410,
"text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10552,
"s": 10530,
"text": "Top 50 Array Problems"
},
{
"code": null,
"e": 10575,
"s": 10552,
"text": "Top 50 String Problems"
},
{
"code": null,
"e": 10596,
"s": 10575,
"text": "Top 50 Tree Problems"
},
{
"code": null,
"e": 10618,
"s": 10596,
"text": "Top 50 Graph Problems"
},
{
"code": null,
"e": 10637,
"s": 10618,
"text": "Top 50 DP Problems"
},
{
"code": null,
"e": 10908,
"s": 10641,
"text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri"
},
{
"code": null,
"e": 10921,
"s": 10908,
"text": "Geeks Digest"
},
{
"code": null,
"e": 10929,
"s": 10921,
"text": "Quizzes"
},
{
"code": null,
"e": 10942,
"s": 10929,
"text": "Geeks Campus"
},
{
"code": null,
"e": 10957,
"s": 10942,
"text": "Gblog Articles"
},
{
"code": null,
"e": 10961,
"s": 10957,
"text": "IDE"
},
{
"code": null,
"e": 10975,
"s": 10961,
"text": "Campus Mantri"
},
{
"code": null,
"e": 10983,
"s": 10975,
"text": "Sign In"
},
{
"code": null,
"e": 10991,
"s": 10983,
"text": "Sign In"
},
{
"code": null,
"e": 10996,
"s": 10991,
"text": "Home"
},
{
"code": null,
"e": 11009,
"s": 10996,
"text": "Saved Videos"
},
{
"code": null,
"e": 11017,
"s": 11009,
"text": "Courses"
},
{
"code": null,
"e": 15482,
"s": 11017,
"text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 15536,
"s": 15482,
"text": "\nFor Working Professionals\n \n\n"
},
{
"code": null,
"e": 15659,
"s": 15536,
"text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n"
},
{
"code": null,
"e": 15678,
"s": 15659,
"text": "\nDSA Live Classes\n"
},
{
"code": null,
"e": 15694,
"s": 15678,
"text": "\nSystem Design\n"
},
{
"code": null,
"e": 15721,
"s": 15694,
"text": "\nJava Backend Development\n"
},
{
"code": null,
"e": 15739,
"s": 15721,
"text": "\nFull Stack LIVE\n"
},
{
"code": null,
"e": 15754,
"s": 15739,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15862,
"s": 15754,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n"
},
{
"code": null,
"e": 15880,
"s": 15862,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 15893,
"s": 15880,
"text": "\nSDE Theory\n"
},
{
"code": null,
"e": 15920,
"s": 15893,
"text": "\nMust-Do Coding Questions\n"
},
{
"code": null,
"e": 15935,
"s": 15920,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15976,
"s": 15935,
"text": "\nFor Students\n \n\n"
},
{
"code": null,
"e": 16088,
"s": 15976,
"text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n"
},
{
"code": null,
"e": 16114,
"s": 16088,
"text": "\nCompetitive Programming\n"
},
{
"code": null,
"e": 16141,
"s": 16114,
"text": "\nData Structures with C++\n"
},
{
"code": null,
"e": 16156,
"s": 16141,
"text": "\nData Science\n"
},
{
"code": null,
"e": 16171,
"s": 16156,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16267,
"s": 16171,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n"
},
{
"code": null,
"e": 16285,
"s": 16267,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 16291,
"s": 16285,
"text": "\nCIP\n"
},
{
"code": null,
"e": 16313,
"s": 16291,
"text": "\nJAVA / Python / C++\n"
},
{
"code": null,
"e": 16328,
"s": 16313,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16439,
"s": 16328,
"text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n"
},
{
"code": null,
"e": 16454,
"s": 16439,
"text": "\nSchool Guide\n"
},
{
"code": null,
"e": 16475,
"s": 16454,
"text": "\nPython Programming\n"
},
{
"code": null,
"e": 16496,
"s": 16475,
"text": "\nLearn To Make Apps\n"
},
{
"code": null,
"e": 16511,
"s": 16496,
"text": "\nExplore more\n"
},
{
"code": null,
"e": 16816,
"s": 16511,
"text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n"
},
{
"code": null,
"e": 16839,
"s": 16816,
"text": "\nSearching Algorithms\n"
},
{
"code": null,
"e": 16860,
"s": 16839,
"text": "\nSorting Algorithms\n"
},
{
"code": null,
"e": 16879,
"s": 16860,
"text": "\nGraph Algorithms\n"
},
{
"code": null,
"e": 16899,
"s": 16879,
"text": "\nPattern Searching\n"
},
{
"code": null,
"e": 16922,
"s": 16899,
"text": "\nGeometric Algorithms\n"
},
{
"code": null,
"e": 16937,
"s": 16922,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 16958,
"s": 16937,
"text": "\nBitwise Algorithms\n"
},
{
"code": null,
"e": 16982,
"s": 16958,
"text": "\nRandomized Algorithms\n"
},
{
"code": null,
"e": 17002,
"s": 16982,
"text": "\nGreedy Algorithms\n"
},
{
"code": null,
"e": 17024,
"s": 17002,
"text": "\nDynamic Programming\n"
},
{
"code": null,
"e": 17045,
"s": 17024,
"text": "\nDivide and Conquer\n"
},
{
"code": null,
"e": 17060,
"s": 17045,
"text": "\nBacktracking\n"
},
{
"code": null,
"e": 17079,
"s": 17060,
"text": "\nBranch and Bound\n"
},
{
"code": null,
"e": 17096,
"s": 17079,
"text": "\nAll Algorithms\n"
},
{
"code": null,
"e": 17481,
"s": 17096,
"text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n"
},
{
"code": null,
"e": 17503,
"s": 17481,
"text": "\nAsymptotic Analysis\n"
},
{
"code": null,
"e": 17535,
"s": 17503,
"text": "\nWorst, Average and Best Cases\n"
},
{
"code": null,
"e": 17558,
"s": 17535,
"text": "\nAsymptotic Notations\n"
},
{
"code": null,
"e": 17596,
"s": 17558,
"text": "\nLittle o and little omega notations\n"
},
{
"code": null,
"e": 17627,
"s": 17596,
"text": "\nLower and Upper Bound Theory\n"
},
{
"code": null,
"e": 17647,
"s": 17627,
"text": "\nAnalysis of Loops\n"
},
{
"code": null,
"e": 17669,
"s": 17647,
"text": "\nSolving Recurrences\n"
},
{
"code": null,
"e": 17690,
"s": 17669,
"text": "\nAmortized Analysis\n"
},
{
"code": null,
"e": 17728,
"s": 17690,
"text": "\nWhat does 'Space Complexity' mean ?\n"
},
{
"code": null,
"e": 17759,
"s": 17728,
"text": "\nPseudo-polynomial Algorithms\n"
},
{
"code": null,
"e": 17798,
"s": 17759,
"text": "\nPolynomial Time Approximation Scheme\n"
},
{
"code": null,
"e": 17827,
"s": 17798,
"text": "\nA Time Complexity Question\n"
},
{
"code": null,
"e": 18024,
"s": 17827,
"text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n"
},
{
"code": null,
"e": 18033,
"s": 18024,
"text": "\nArrays\n"
},
{
"code": null,
"e": 18047,
"s": 18033,
"text": "\nLinked List\n"
},
{
"code": null,
"e": 18055,
"s": 18047,
"text": "\nStack\n"
},
{
"code": null,
"e": 18063,
"s": 18055,
"text": "\nQueue\n"
},
{
"code": null,
"e": 18077,
"s": 18063,
"text": "\nBinary Tree\n"
},
{
"code": null,
"e": 18098,
"s": 18077,
"text": "\nBinary Search Tree\n"
},
{
"code": null,
"e": 18105,
"s": 18098,
"text": "\nHeap\n"
},
{
"code": null,
"e": 18115,
"s": 18105,
"text": "\nHashing\n"
},
{
"code": null,
"e": 18123,
"s": 18115,
"text": "\nGraph\n"
},
{
"code": null,
"e": 18149,
"s": 18123,
"text": "\nAdvanced Data Structure\n"
},
{
"code": null,
"e": 18158,
"s": 18149,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 18168,
"s": 18158,
"text": "\nStrings\n"
},
{
"code": null,
"e": 18190,
"s": 18168,
"text": "\nAll Data Structures\n"
},
{
"code": null,
"e": 18458,
"s": 18190,
"text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18480,
"s": 18458,
"text": "\nCompany Preparation\n"
},
{
"code": null,
"e": 18493,
"s": 18480,
"text": "\nTop Topics\n"
},
{
"code": null,
"e": 18522,
"s": 18493,
"text": "\nPractice Company Questions\n"
},
{
"code": null,
"e": 18546,
"s": 18522,
"text": "\nInterview Experiences\n"
},
{
"code": null,
"e": 18571,
"s": 18546,
"text": "\nExperienced Interviews\n"
},
{
"code": null,
"e": 18595,
"s": 18571,
"text": "\nInternship Interviews\n"
},
{
"code": null,
"e": 18622,
"s": 18595,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 18640,
"s": 18622,
"text": "\nDesign Patterns\n"
},
{
"code": null,
"e": 18665,
"s": 18640,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 18691,
"s": 18665,
"text": "\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18830,
"s": 18691,
"text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n"
},
{
"code": null,
"e": 18834,
"s": 18830,
"text": "\nC\n"
},
{
"code": null,
"e": 18840,
"s": 18834,
"text": "\nC++\n"
},
{
"code": null,
"e": 18847,
"s": 18840,
"text": "\nJava\n"
},
{
"code": null,
"e": 18856,
"s": 18847,
"text": "\nPython\n"
},
{
"code": null,
"e": 18861,
"s": 18856,
"text": "\nC#\n"
},
{
"code": null,
"e": 18874,
"s": 18861,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 18883,
"s": 18874,
"text": "\njQuery\n"
},
{
"code": null,
"e": 18889,
"s": 18883,
"text": "\nSQL\n"
},
{
"code": null,
"e": 18895,
"s": 18889,
"text": "\nPHP\n"
},
{
"code": null,
"e": 18903,
"s": 18895,
"text": "\nScala\n"
},
{
"code": null,
"e": 18910,
"s": 18903,
"text": "\nPerl\n"
},
{
"code": null,
"e": 18924,
"s": 18910,
"text": "\nGo Language\n"
},
{
"code": null,
"e": 18931,
"s": 18924,
"text": "\nHTML\n"
},
{
"code": null,
"e": 18937,
"s": 18931,
"text": "\nCSS\n"
},
{
"code": null,
"e": 18946,
"s": 18937,
"text": "\nKotlin\n"
},
{
"code": null,
"e": 19024,
"s": 18946,
"text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n"
},
{
"code": null,
"e": 19043,
"s": 19024,
"text": "\nMachine Learning\n"
},
{
"code": null,
"e": 19058,
"s": 19043,
"text": "\nData Science\n"
},
{
"code": null,
"e": 19271,
"s": 19058,
"text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n"
},
{
"code": null,
"e": 19285,
"s": 19271,
"text": "\nMathematics\n"
},
{
"code": null,
"e": 19304,
"s": 19285,
"text": "\nOperating System\n"
},
{
"code": null,
"e": 19311,
"s": 19304,
"text": "\nDBMS\n"
},
{
"code": null,
"e": 19331,
"s": 19311,
"text": "\nComputer Networks\n"
},
{
"code": null,
"e": 19372,
"s": 19331,
"text": "\nComputer Organization and Architecture\n"
},
{
"code": null,
"e": 19396,
"s": 19372,
"text": "\nTheory of Computation\n"
},
{
"code": null,
"e": 19414,
"s": 19396,
"text": "\nCompiler Design\n"
},
{
"code": null,
"e": 19430,
"s": 19414,
"text": "\nDigital Logic\n"
},
{
"code": null,
"e": 19453,
"s": 19430,
"text": "\nSoftware Engineering\n"
},
{
"code": null,
"e": 19670,
"s": 19453,
"text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19700,
"s": 19670,
"text": "\nGATE Computer Science Notes\n"
},
{
"code": null,
"e": 19720,
"s": 19700,
"text": "\nLast Minute Notes\n"
},
{
"code": null,
"e": 19744,
"s": 19720,
"text": "\nGATE CS Solved Papers\n"
},
{
"code": null,
"e": 19788,
"s": 19744,
"text": "\nGATE CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 19806,
"s": 19788,
"text": "\nGATE 2021 Dates\n"
},
{
"code": null,
"e": 19830,
"s": 19806,
"text": "\nGATE CS 2021 Syllabus\n"
},
{
"code": null,
"e": 19861,
"s": 19830,
"text": "\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19981,
"s": 19861,
"text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n"
},
{
"code": null,
"e": 19988,
"s": 19981,
"text": "\nHTML\n"
},
{
"code": null,
"e": 19994,
"s": 19988,
"text": "\nCSS\n"
},
{
"code": null,
"e": 20007,
"s": 19994,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 20019,
"s": 20007,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 20029,
"s": 20019,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 20038,
"s": 20029,
"text": "\nNodeJS\n"
},
{
"code": null,
"e": 20050,
"s": 20038,
"text": "\nBootstrap\n"
},
{
"code": null,
"e": 20059,
"s": 20050,
"text": "\njQuery\n"
},
{
"code": null,
"e": 20065,
"s": 20059,
"text": "\nPHP\n"
},
{
"code": null,
"e": 20160,
"s": 20065,
"text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20187,
"s": 20160,
"text": "\nSoftware Design Patterns\n"
},
{
"code": null,
"e": 20212,
"s": 20187,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20276,
"s": 20212,
"text": "\nSchool Learning\n \n\n\nSchool Programming\n"
},
{
"code": null,
"e": 20297,
"s": 20276,
"text": "\nSchool Programming\n"
},
{
"code": null,
"e": 20433,
"s": 20297,
"text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n"
},
{
"code": null,
"e": 20449,
"s": 20433,
"text": "\nNumber System\n"
},
{
"code": null,
"e": 20459,
"s": 20449,
"text": "\nAlgebra\n"
},
{
"code": null,
"e": 20474,
"s": 20459,
"text": "\nTrigonometry\n"
},
{
"code": null,
"e": 20487,
"s": 20474,
"text": "\nStatistics\n"
},
{
"code": null,
"e": 20501,
"s": 20487,
"text": "\nProbability\n"
},
{
"code": null,
"e": 20512,
"s": 20501,
"text": "\nGeometry\n"
},
{
"code": null,
"e": 20526,
"s": 20512,
"text": "\nMensuration\n"
},
{
"code": null,
"e": 20537,
"s": 20526,
"text": "\nCalculus\n"
},
{
"code": null,
"e": 20668,
"s": 20537,
"text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n"
},
{
"code": null,
"e": 20684,
"s": 20668,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 20700,
"s": 20684,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 20717,
"s": 20700,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 20734,
"s": 20717,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 20751,
"s": 20734,
"text": "\nClass 12 Notes\n"
},
{
"code": null,
"e": 20918,
"s": 20751,
"text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 20943,
"s": 20918,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 20968,
"s": 20943,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 20994,
"s": 20968,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21020,
"s": 20994,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21046,
"s": 21020,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21217,
"s": 21046,
"text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21242,
"s": 21217,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 21267,
"s": 21242,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 21293,
"s": 21267,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21319,
"s": 21293,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21345,
"s": 21319,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21462,
"s": 21345,
"text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n"
},
{
"code": null,
"e": 21478,
"s": 21462,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 21494,
"s": 21478,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 21511,
"s": 21494,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 21528,
"s": 21511,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 21570,
"s": 21528,
"text": "\nCS Exams/PSUs\n \n\n"
},
{
"code": null,
"e": 21715,
"s": 21570,
"text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21759,
"s": 21715,
"text": "\nISRO CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 21783,
"s": 21759,
"text": "\nISRO CS Solved Papers\n"
},
{
"code": null,
"e": 21830,
"s": 21783,
"text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21947,
"s": 21830,
"text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 21975,
"s": 21947,
"text": "\nUGC NET CS Notes Paper II\n"
},
{
"code": null,
"e": 22004,
"s": 21975,
"text": "\nUGC NET CS Notes Paper III\n"
},
{
"code": null,
"e": 22031,
"s": 22004,
"text": "\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 22288,
"s": 22031,
"text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n"
},
{
"code": null,
"e": 22316,
"s": 22288,
"text": "\nCampus Ambassador Program\n"
},
{
"code": null,
"e": 22344,
"s": 22316,
"text": "\nSchool Ambassador Program\n"
},
{
"code": null,
"e": 22354,
"s": 22344,
"text": "\nProject\n"
},
{
"code": null,
"e": 22374,
"s": 22354,
"text": "\nGeek of the Month\n"
},
{
"code": null,
"e": 22401,
"s": 22374,
"text": "\nCampus Geek of the Month\n"
},
{
"code": null,
"e": 22420,
"s": 22401,
"text": "\nPlacement Course\n"
},
{
"code": null,
"e": 22447,
"s": 22420,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 22462,
"s": 22447,
"text": "\nTestimonials\n"
},
{
"code": null,
"e": 22480,
"s": 22462,
"text": "\nStudent Chapter\n"
},
{
"code": null,
"e": 22498,
"s": 22480,
"text": "\nGeek on the Top\n"
},
{
"code": null,
"e": 22511,
"s": 22498,
"text": "\nInternship\n"
},
{
"code": null,
"e": 22521,
"s": 22511,
"text": "\nCareers\n"
},
{
"code": null,
"e": 22679,
"s": 22521,
"text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22703,
"s": 22679,
"text": "\nTop 50 Array Problems\n"
},
{
"code": null,
"e": 22728,
"s": 22703,
"text": "\nTop 50 String Problems\n"
},
{
"code": null,
"e": 22751,
"s": 22728,
"text": "\nTop 50 Tree Problems\n"
},
{
"code": null,
"e": 22775,
"s": 22751,
"text": "\nTop 50 Graph Problems\n"
},
{
"code": null,
"e": 22796,
"s": 22775,
"text": "\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22834,
"s": 22796,
"text": "\nTutorials\n \n\n"
},
{
"code": null,
"e": 22907,
"s": 22834,
"text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n"
},
{
"code": null,
"e": 22924,
"s": 22907,
"text": "\nApply for Jobs\n"
},
{
"code": null,
"e": 22937,
"s": 22924,
"text": "\nPost a Job\n"
},
{
"code": null,
"e": 22950,
"s": 22937,
"text": "\nJOB-A-THON\n"
},
{
"code": null,
"e": 23136,
"s": 22950,
"text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23155,
"s": 23136,
"text": "\nAll DSA Problems\n"
},
{
"code": null,
"e": 23176,
"s": 23155,
"text": "\nProblem of the Day\n"
},
{
"code": null,
"e": 23212,
"s": 23176,
"text": "\nInterview Series: Weekly Contests\n"
},
{
"code": null,
"e": 23248,
"s": 23212,
"text": "\nBi-Wizard Coding: School Contests\n"
},
{
"code": null,
"e": 23270,
"s": 23248,
"text": "\nContests and Events\n"
},
{
"code": null,
"e": 23291,
"s": 23270,
"text": "\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23297,
"s": 23291,
"text": "GBlog"
},
{
"code": null,
"e": 23305,
"s": 23297,
"text": "Puzzles"
},
{
"code": null,
"e": 23318,
"s": 23305,
"text": "What's New ?"
},
{
"code": null,
"e": 23324,
"s": 23318,
"text": "Array"
},
{
"code": null,
"e": 23331,
"s": 23324,
"text": "Matrix"
},
{
"code": null,
"e": 23339,
"s": 23331,
"text": "Strings"
},
{
"code": null,
"e": 23347,
"s": 23339,
"text": "Hashing"
},
{
"code": null,
"e": 23359,
"s": 23347,
"text": "Linked List"
},
{
"code": null,
"e": 23365,
"s": 23359,
"text": "Stack"
},
{
"code": null,
"e": 23371,
"s": 23365,
"text": "Queue"
},
{
"code": null,
"e": 23383,
"s": 23371,
"text": "Binary Tree"
},
{
"code": null,
"e": 23402,
"s": 23383,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 23407,
"s": 23402,
"text": "Heap"
},
{
"code": null,
"e": 23413,
"s": 23407,
"text": "Graph"
},
{
"code": null,
"e": 23423,
"s": 23413,
"text": "Searching"
},
{
"code": null,
"e": 23431,
"s": 23423,
"text": "Sorting"
},
{
"code": null,
"e": 23448,
"s": 23431,
"text": "Divide & Conquer"
},
{
"code": null,
"e": 23461,
"s": 23448,
"text": "Mathematical"
},
{
"code": null,
"e": 23471,
"s": 23461,
"text": "Geometric"
},
{
"code": null,
"e": 23479,
"s": 23471,
"text": "Bitwise"
},
{
"code": null,
"e": 23486,
"s": 23479,
"text": "Greedy"
},
{
"code": null,
"e": 23499,
"s": 23486,
"text": "Backtracking"
},
{
"code": null,
"e": 23516,
"s": 23499,
"text": "Branch and Bound"
},
{
"code": null,
"e": 23536,
"s": 23516,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 23554,
"s": 23536,
"text": "Pattern Searching"
},
{
"code": null,
"e": 23565,
"s": 23554,
"text": "Randomized"
},
{
"code": null,
"e": 23599,
"s": 23565,
"text": "Engineering Mathematics Tutorials"
},
{
"code": null,
"e": 23657,
"s": 23599,
"text": "Mathematics | Introduction to Propositional Logic | Set 1"
},
{
"code": null,
"e": 23715,
"s": 23657,
"text": "Mathematics | Introduction to Propositional Logic | Set 2"
},
{
"code": null,
"e": 23756,
"s": 23715,
"text": "Mathematics | Propositional Equivalences"
},
{
"code": null,
"e": 23805,
"s": 23756,
"text": "Mathematics | Predicates and Quantifiers | Set 1"
},
{
"code": null,
"e": 23854,
"s": 23805,
"text": "Mathematics | Predicates and Quantifiers | Set 2"
},
{
"code": null,
"e": 23904,
"s": 23854,
"text": "Mathematics | Some theorems on Nested Quantifiers"
},
{
"code": null,
"e": 23937,
"s": 23904,
"text": "Mathematics | Rules of Inference"
},
{
"code": null,
"e": 23975,
"s": 23937,
"text": "PDNF and PCNF in Discrete Mathematics"
},
{
"code": null,
"e": 24016,
"s": 23975,
"text": "Mathematics | Introduction of Set theory"
},
{
"code": null,
"e": 24058,
"s": 24016,
"text": "Mathematics | Set Operations (Set theory)"
},
{
"code": null,
"e": 24107,
"s": 24058,
"text": "Inclusion-Exclusion and its various Applications"
},
{
"code": null,
"e": 24150,
"s": 24107,
"text": "Mathematics | Power Set and its Properties"
},
{
"code": null,
"e": 24192,
"s": 24150,
"text": "Mathematics | Partial Orders and Lattices"
},
{
"code": null,
"e": 24226,
"s": 24192,
"text": "Mathematics | Algebraic Structure"
},
{
"code": null,
"e": 24276,
"s": 24226,
"text": "Mathematics | Introduction and types of Relations"
},
{
"code": null,
"e": 24322,
"s": 24276,
"text": "Discrete Mathematics | Representing Relations"
},
{
"code": null,
"e": 24388,
"s": 24322,
"text": "Mathematics | Representations of Matrices and Graphs in Relations"
},
{
"code": null,
"e": 24449,
"s": 24388,
"text": "Mathematics | Closure of Relations and Equivalence Relations"
},
{
"code": null,
"e": 24506,
"s": 24449,
"text": "Number of possible Equivalence Relations on a finite set"
},
{
"code": null,
"e": 24576,
"s": 24506,
"text": "Mathematics | Classes (Injective, surjective, Bijective) of Functions"
},
{
"code": null,
"e": 24625,
"s": 24576,
"text": "Mathematics | Total number of possible functions"
},
{
"code": null,
"e": 24694,
"s": 24625,
"text": "Discrete Maths | Generating Functions-Introduction and Prerequisites"
},
{
"code": null,
"e": 24737,
"s": 24694,
"text": "Mathematics | Generating Functions – Set 2"
},
{
"code": null,
"e": 24783,
"s": 24737,
"text": "Mathematics | Sequence, Series and Summations"
},
{
"code": null,
"e": 24837,
"s": 24783,
"text": "Mathematics | Independent Sets, Covering and Matching"
},
{
"code": null,
"e": 24874,
"s": 24837,
"text": "Mathematics | Introduction to Proofs"
},
{
"code": null,
"e": 24912,
"s": 24874,
"text": "Discrete Mathematics | Hasse Diagrams"
},
{
"code": null,
"e": 24946,
"s": 24912,
"text": "Introduction to Mojette transform"
},
{
"code": null,
"e": 24995,
"s": 24946,
"text": "Mathematics | Rings, Integral domains and Fields"
},
{
"code": null,
"e": 25034,
"s": 24995,
"text": "Mathematics | The Pigeonhole Principle"
},
{
"code": null,
"e": 25069,
"s": 25034,
"text": "Mathematics | Combinatorics Basics"
},
{
"code": null,
"e": 25113,
"s": 25069,
"text": "Mathematics | PnC and Binomial Coefficients"
},
{
"code": null,
"e": 25149,
"s": 25113,
"text": "Mathematics | Generalized PnC Set 1"
},
{
"code": null,
"e": 25185,
"s": 25149,
"text": "Mathematics | Generalized PnC Set 2"
},
{
"code": null,
"e": 25217,
"s": 25185,
"text": "Corollaries of Binomial Theorem"
},
{
"code": null,
"e": 25289,
"s": 25217,
"text": "Number of triangles in a plane if no more than two points are collinear"
},
{
"code": null,
"e": 25350,
"s": 25289,
"text": "Mathematics | Sum of squares of even and odd natural numbers"
},
{
"code": null,
"e": 25394,
"s": 25350,
"text": "Finding nth term of any Polynomial Sequence"
},
{
"code": null,
"e": 25455,
"s": 25394,
"text": "Discrete Mathematics | Types of Recurrence Relations – Set 2"
},
{
"code": null,
"e": 25497,
"s": 25455,
"text": "Mathematics | Graph Theory Basics – Set 1"
},
{
"code": null,
"e": 25539,
"s": 25497,
"text": "Mathematics | Graph Theory Basics – Set 2"
},
{
"code": null,
"e": 25568,
"s": 25539,
"text": "Graph Types and Applications"
},
{
"code": null,
"e": 25610,
"s": 25568,
"text": "Mathematics | Euler and Hamiltonian Paths"
},
{
"code": null,
"e": 25657,
"s": 25610,
"text": "Mathematics | Planar Graphs and Graph Coloring"
},
{
"code": null,
"e": 25707,
"s": 25657,
"text": "Mathematics | Graph Isomorphisms and Connectivity"
},
{
"code": null,
"e": 25745,
"s": 25707,
"text": "Mathematics | Matching (graph theory)"
},
{
"code": null,
"e": 25789,
"s": 25745,
"text": "Betweenness Centrality (Centrality Measure)"
},
{
"code": null,
"e": 25854,
"s": 25789,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
},
{
"code": null,
"e": 25931,
"s": 25854,
"text": "Graph measurements: length, distance, diameter, eccentricity, radius, center"
},
{
"code": null,
"e": 25994,
"s": 25931,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 26028,
"s": 25994,
"text": "Mathematics | Matrix Introduction"
},
{
"code": null,
"e": 26061,
"s": 26028,
"text": "Different Operations on Matrices"
},
{
"code": null,
"e": 26125,
"s": 26061,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
},
{
"code": null,
"e": 26164,
"s": 26125,
"text": "Doolittle Algorithm : LU Decomposition"
},
{
"code": null,
"e": 26205,
"s": 26164,
"text": "Mathematics | System of Linear Equations"
},
{
"code": null,
"e": 26250,
"s": 26205,
"text": "Mathematics | Eigen Values and Eigen Vectors"
},
{
"code": null,
"e": 26276,
"s": 26250,
"text": "Mathematics | Probability"
},
{
"code": null,
"e": 26307,
"s": 26276,
"text": "Mathematics | Random Variables"
},
{
"code": null,
"e": 26359,
"s": 26307,
"text": "Mathematics | Mean, Variance and Standard Deviation"
},
{
"code": null,
"e": 26398,
"s": 26359,
"text": "Mathematics | Law of total probability"
},
{
"code": null,
"e": 26442,
"s": 26398,
"text": "Bayes’s Theorem for Conditional Probability"
},
{
"code": null,
"e": 26511,
"s": 26442,
"text": "Mathematics | Probability Distributions Set 1 (Uniform Distribution)"
},
{
"code": null,
"e": 26584,
"s": 26511,
"text": "Mathematics | Probability Distributions Set 2 (Exponential Distribution)"
},
{
"code": null,
"e": 26652,
"s": 26584,
"text": "Mathematics | Probability Distributions Set 3 (Normal Distribution)"
},
{
"code": null,
"e": 26722,
"s": 26652,
"text": "Mathematics | Probability Distributions Set 4 (Binomial Distribution)"
},
{
"code": null,
"e": 26791,
"s": 26722,
"text": "Mathematics | Probability Distributions Set 5 (Poisson Distribution)"
},
{
"code": null,
"e": 26839,
"s": 26791,
"text": "Mathematics | Hypergeometric Distribution model"
},
{
"code": null,
"e": 26877,
"s": 26839,
"text": "Mathematics | Conditional Probability"
},
{
"code": null,
"e": 26918,
"s": 26877,
"text": "Mathematics | Covariance and Correlation"
},
{
"code": null,
"e": 26973,
"s": 26918,
"text": "Mathematics | Limits, Continuity and Differentiability"
},
{
"code": null,
"e": 27017,
"s": 26973,
"text": "Mathematics | Lagrange’s Mean Value Theorem"
},
{
"code": null,
"e": 27058,
"s": 27017,
"text": "Mathematics | Rolle’s Mean Value Theorem"
},
{
"code": null,
"e": 27086,
"s": 27058,
"text": "Cauchy’s Mean Value Theorem"
},
{
"code": null,
"e": 27121,
"s": 27086,
"text": "Mathematics | Indefinite Integrals"
},
{
"code": null,
"e": 27168,
"s": 27121,
"text": "Mathematics | Problems On Permutations | Set 1"
},
{
"code": null,
"e": 27217,
"s": 27168,
"text": "Problem on permutations and combinations | Set 2"
},
{
"code": null,
"e": 27263,
"s": 27217,
"text": "Mathematics | Graph theory practice questions"
},
{
"code": null,
"e": 27291,
"s": 27263,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 27328,
"s": 27291,
"text": "Propositional and First Order Logic."
},
{
"code": null,
"e": 27349,
"s": 27328,
"text": "Set Theory & Algebra"
},
{
"code": null,
"e": 27363,
"s": 27349,
"text": "Combinatorics"
},
{
"code": null,
"e": 27376,
"s": 27363,
"text": "Graph Theory"
},
{
"code": null,
"e": 27391,
"s": 27376,
"text": "Linear Algebra"
},
{
"code": null,
"e": 27403,
"s": 27391,
"text": "Probability"
},
{
"code": null,
"e": 27434,
"s": 27403,
"text": "Numerical Methods and Calculus"
},
{
"code": null,
"e": 27468,
"s": 27434,
"text": "Engineering Mathematics Tutorials"
},
{
"code": null,
"e": 27526,
"s": 27468,
"text": "Mathematics | Introduction to Propositional Logic | Set 1"
},
{
"code": null,
"e": 27584,
"s": 27526,
"text": "Mathematics | Introduction to Propositional Logic | Set 2"
},
{
"code": null,
"e": 27625,
"s": 27584,
"text": "Mathematics | Propositional Equivalences"
},
{
"code": null,
"e": 27674,
"s": 27625,
"text": "Mathematics | Predicates and Quantifiers | Set 1"
},
{
"code": null,
"e": 27723,
"s": 27674,
"text": "Mathematics | Predicates and Quantifiers | Set 2"
},
{
"code": null,
"e": 27773,
"s": 27723,
"text": "Mathematics | Some theorems on Nested Quantifiers"
},
{
"code": null,
"e": 27806,
"s": 27773,
"text": "Mathematics | Rules of Inference"
},
{
"code": null,
"e": 27844,
"s": 27806,
"text": "PDNF and PCNF in Discrete Mathematics"
},
{
"code": null,
"e": 27885,
"s": 27844,
"text": "Mathematics | Introduction of Set theory"
},
{
"code": null,
"e": 27927,
"s": 27885,
"text": "Mathematics | Set Operations (Set theory)"
},
{
"code": null,
"e": 27976,
"s": 27927,
"text": "Inclusion-Exclusion and its various Applications"
},
{
"code": null,
"e": 28019,
"s": 27976,
"text": "Mathematics | Power Set and its Properties"
},
{
"code": null,
"e": 28061,
"s": 28019,
"text": "Mathematics | Partial Orders and Lattices"
},
{
"code": null,
"e": 28095,
"s": 28061,
"text": "Mathematics | Algebraic Structure"
},
{
"code": null,
"e": 28145,
"s": 28095,
"text": "Mathematics | Introduction and types of Relations"
},
{
"code": null,
"e": 28191,
"s": 28145,
"text": "Discrete Mathematics | Representing Relations"
},
{
"code": null,
"e": 28257,
"s": 28191,
"text": "Mathematics | Representations of Matrices and Graphs in Relations"
},
{
"code": null,
"e": 28318,
"s": 28257,
"text": "Mathematics | Closure of Relations and Equivalence Relations"
},
{
"code": null,
"e": 28375,
"s": 28318,
"text": "Number of possible Equivalence Relations on a finite set"
},
{
"code": null,
"e": 28445,
"s": 28375,
"text": "Mathematics | Classes (Injective, surjective, Bijective) of Functions"
},
{
"code": null,
"e": 28494,
"s": 28445,
"text": "Mathematics | Total number of possible functions"
},
{
"code": null,
"e": 28563,
"s": 28494,
"text": "Discrete Maths | Generating Functions-Introduction and Prerequisites"
},
{
"code": null,
"e": 28606,
"s": 28563,
"text": "Mathematics | Generating Functions – Set 2"
},
{
"code": null,
"e": 28652,
"s": 28606,
"text": "Mathematics | Sequence, Series and Summations"
},
{
"code": null,
"e": 28706,
"s": 28652,
"text": "Mathematics | Independent Sets, Covering and Matching"
},
{
"code": null,
"e": 28743,
"s": 28706,
"text": "Mathematics | Introduction to Proofs"
},
{
"code": null,
"e": 28781,
"s": 28743,
"text": "Discrete Mathematics | Hasse Diagrams"
},
{
"code": null,
"e": 28815,
"s": 28781,
"text": "Introduction to Mojette transform"
},
{
"code": null,
"e": 28864,
"s": 28815,
"text": "Mathematics | Rings, Integral domains and Fields"
},
{
"code": null,
"e": 28903,
"s": 28864,
"text": "Mathematics | The Pigeonhole Principle"
},
{
"code": null,
"e": 28938,
"s": 28903,
"text": "Mathematics | Combinatorics Basics"
},
{
"code": null,
"e": 28982,
"s": 28938,
"text": "Mathematics | PnC and Binomial Coefficients"
},
{
"code": null,
"e": 29018,
"s": 28982,
"text": "Mathematics | Generalized PnC Set 1"
},
{
"code": null,
"e": 29054,
"s": 29018,
"text": "Mathematics | Generalized PnC Set 2"
},
{
"code": null,
"e": 29086,
"s": 29054,
"text": "Corollaries of Binomial Theorem"
},
{
"code": null,
"e": 29158,
"s": 29086,
"text": "Number of triangles in a plane if no more than two points are collinear"
},
{
"code": null,
"e": 29219,
"s": 29158,
"text": "Mathematics | Sum of squares of even and odd natural numbers"
},
{
"code": null,
"e": 29263,
"s": 29219,
"text": "Finding nth term of any Polynomial Sequence"
},
{
"code": null,
"e": 29324,
"s": 29263,
"text": "Discrete Mathematics | Types of Recurrence Relations – Set 2"
},
{
"code": null,
"e": 29366,
"s": 29324,
"text": "Mathematics | Graph Theory Basics – Set 1"
},
{
"code": null,
"e": 29408,
"s": 29366,
"text": "Mathematics | Graph Theory Basics – Set 2"
},
{
"code": null,
"e": 29437,
"s": 29408,
"text": "Graph Types and Applications"
},
{
"code": null,
"e": 29479,
"s": 29437,
"text": "Mathematics | Euler and Hamiltonian Paths"
},
{
"code": null,
"e": 29526,
"s": 29479,
"text": "Mathematics | Planar Graphs and Graph Coloring"
},
{
"code": null,
"e": 29576,
"s": 29526,
"text": "Mathematics | Graph Isomorphisms and Connectivity"
},
{
"code": null,
"e": 29614,
"s": 29576,
"text": "Mathematics | Matching (graph theory)"
},
{
"code": null,
"e": 29658,
"s": 29614,
"text": "Betweenness Centrality (Centrality Measure)"
},
{
"code": null,
"e": 29723,
"s": 29658,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
},
{
"code": null,
"e": 29800,
"s": 29723,
"text": "Graph measurements: length, distance, diameter, eccentricity, radius, center"
},
{
"code": null,
"e": 29863,
"s": 29800,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 29897,
"s": 29863,
"text": "Mathematics | Matrix Introduction"
},
{
"code": null,
"e": 29930,
"s": 29897,
"text": "Different Operations on Matrices"
},
{
"code": null,
"e": 29994,
"s": 29930,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
},
{
"code": null,
"e": 30033,
"s": 29994,
"text": "Doolittle Algorithm : LU Decomposition"
},
{
"code": null,
"e": 30074,
"s": 30033,
"text": "Mathematics | System of Linear Equations"
},
{
"code": null,
"e": 30119,
"s": 30074,
"text": "Mathematics | Eigen Values and Eigen Vectors"
},
{
"code": null,
"e": 30145,
"s": 30119,
"text": "Mathematics | Probability"
},
{
"code": null,
"e": 30176,
"s": 30145,
"text": "Mathematics | Random Variables"
},
{
"code": null,
"e": 30228,
"s": 30176,
"text": "Mathematics | Mean, Variance and Standard Deviation"
},
{
"code": null,
"e": 30267,
"s": 30228,
"text": "Mathematics | Law of total probability"
},
{
"code": null,
"e": 30311,
"s": 30267,
"text": "Bayes’s Theorem for Conditional Probability"
},
{
"code": null,
"e": 30380,
"s": 30311,
"text": "Mathematics | Probability Distributions Set 1 (Uniform Distribution)"
},
{
"code": null,
"e": 30453,
"s": 30380,
"text": "Mathematics | Probability Distributions Set 2 (Exponential Distribution)"
},
{
"code": null,
"e": 30521,
"s": 30453,
"text": "Mathematics | Probability Distributions Set 3 (Normal Distribution)"
},
{
"code": null,
"e": 30591,
"s": 30521,
"text": "Mathematics | Probability Distributions Set 4 (Binomial Distribution)"
},
{
"code": null,
"e": 30660,
"s": 30591,
"text": "Mathematics | Probability Distributions Set 5 (Poisson Distribution)"
},
{
"code": null,
"e": 30708,
"s": 30660,
"text": "Mathematics | Hypergeometric Distribution model"
},
{
"code": null,
"e": 30746,
"s": 30708,
"text": "Mathematics | Conditional Probability"
},
{
"code": null,
"e": 30787,
"s": 30746,
"text": "Mathematics | Covariance and Correlation"
},
{
"code": null,
"e": 30842,
"s": 30787,
"text": "Mathematics | Limits, Continuity and Differentiability"
},
{
"code": null,
"e": 30886,
"s": 30842,
"text": "Mathematics | Lagrange’s Mean Value Theorem"
},
{
"code": null,
"e": 30927,
"s": 30886,
"text": "Mathematics | Rolle’s Mean Value Theorem"
},
{
"code": null,
"e": 30955,
"s": 30927,
"text": "Cauchy’s Mean Value Theorem"
},
{
"code": null,
"e": 30990,
"s": 30955,
"text": "Mathematics | Indefinite Integrals"
},
{
"code": null,
"e": 31037,
"s": 30990,
"text": "Mathematics | Problems On Permutations | Set 1"
},
{
"code": null,
"e": 31086,
"s": 31037,
"text": "Problem on permutations and combinations | Set 2"
},
{
"code": null,
"e": 31132,
"s": 31086,
"text": "Mathematics | Graph theory practice questions"
},
{
"code": null,
"e": 31160,
"s": 31132,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 31197,
"s": 31160,
"text": "Propositional and First Order Logic."
},
{
"code": null,
"e": 31218,
"s": 31197,
"text": "Set Theory & Algebra"
},
{
"code": null,
"e": 31232,
"s": 31218,
"text": "Combinatorics"
},
{
"code": null,
"e": 31245,
"s": 31232,
"text": "Graph Theory"
},
{
"code": null,
"e": 31260,
"s": 31245,
"text": "Linear Algebra"
},
{
"code": null,
"e": 31272,
"s": 31260,
"text": "Probability"
},
{
"code": null,
"e": 31303,
"s": 31272,
"text": "Numerical Methods and Calculus"
},
{
"code": null,
"e": 31327,
"s": 31303,
"text": "Difficulty Level :\nEasy"
},
{
"code": null,
"e": 31696,
"s": 31327,
"text": "Given a few terms of a sequence, we are often asked to find the expression for the nth term of this sequence. While there is a multitude of ways to do this, In this article, we discuss an algorithmic approach which will give the correct answer for any polynomial expression. Note that this method fails for trigonometric, exponential or other transcendental sequences."
},
{
"code": null,
"e": 31775,
"s": 31696,
"text": "We will take a few examples and discuss the method as we solve these examples."
},
{
"code": null,
"e": 31785,
"s": 31775,
"text": "Example 1"
},
{
"code": null,
"e": 31810,
"s": 31785,
"text": "Let us take the sequence"
},
{
"code": null,
"e": 31835,
"s": 31810,
"text": "S = 3, 9, 15, 21, .... \n"
},
{
"code": null,
"e": 31852,
"s": 31835,
"text": "Trivial Solution"
},
{
"code": null,
"e": 32006,
"s": 31852,
"text": "We can easily see that this is an A.P series. The starting term is 3 and the common difference is 6. Hence the nth term of the sequence is 3 + (n-1) * 6."
},
{
"code": null,
"e": 32019,
"s": 32006,
"text": "Our Solution"
},
{
"code": null,
"e": 32076,
"s": 32019,
"text": "Since we know that an nth order polynomial has the form:"
},
{
"code": null,
"e": 32131,
"s": 32076,
"text": "Polynomial = Pn = a0 + a1*x^1 + a2*x^2 + ... + an*x^n\n"
},
{
"code": null,
"e": 32362,
"s": 32131,
"text": "Since we already know a few terms of the sequence, we can substitute these values in the above expression and obtain some equations. Then we need to solve this system of linear equations and obtain the coefficients a0, a1, ... an."
},
{
"code": null,
"e": 32420,
"s": 32362,
"text": "The trick is to somehow know the order of the polynomial."
},
{
"code": null,
"e": 32644,
"s": 32420,
"text": "This is simple enough to do if we remember that the nth order forward difference is constant for an nth order polynomial. Also all higher order forward differences are 0. Let us obtain the forward differences for the series"
},
{
"code": null,
"e": 32689,
"s": 32644,
"text": "3 9 15 21 27 ...\n 6 6 6 6\n"
},
{
"code": null,
"e": 32796,
"s": 32689,
"text": "Since the first forward difference is constant, we conclude that the sequence is a first order polynomial."
},
{
"code": null,
"e": 32996,
"s": 32796,
"text": "1st order polynomial Sn = a0 + a1*n\nFor n = 1, Sn = 3\n3 = a0 + a1 .... (1)\nFor n = 2, Sn = 9 \n9 = a0 + 2*a1 .... (2)\n\nSolving (1) and (2) we get\na1 = 6 and a0 = -3\n\nHence we obtain Sn = -3 + 6*n\n"
},
{
"code": null,
"e": 33183,
"s": 32996,
"text": "Note that we obtain slightly different formulations of the sequence in the above two methods. But both these formulations are correct and can easily be converted from one form to another"
},
{
"code": null,
"e": 33193,
"s": 33183,
"text": "Example 2"
},
{
"code": null,
"e": 33765,
"s": 33193,
"text": "Lets us take the sequence S =\n 9 24 47 78 117 164 219 ...\n 15 23 31 39 47 55 \n 8 8 8 8 8\n\nSince the 2n order forward difference is constant, the Sequence is a 2nd order\npolynomial\n\nS = a0 + a1*n + a2 *n*n\nSubstituting n = 1, 2, 3 and corresponding entries we get\n9 = a0 + a1 + a2 ... (1)\n24 = a0 + 2*a1 + 4*a2 ... (2)\n47 = a0 + 3*a1 + 9*a3 ... (3)\n\nWriting matrices for above equations\nA = 1 1 1 \n 1 2 4\n 1 3 9\nB = 9 24 47\nX = [a0 a1 a2] = inv(A)*B = [ 2 3 4]\nHence a0 = 2, a1 = 3, a2 = 4\nTherefore S = 2 + 3*n + 4 * n * n\n"
},
{
"code": null,
"e": 33775,
"s": 33765,
"text": "Example 3"
},
{
"code": null,
"e": 34398,
"s": 33775,
"text": "S = 28, 168, 516, 1168, 2220 ...\n\nForward Differences\n28 168 516 1168 2220\n 140 348 652 1052\n 208 304 400\n 96 96\n\nThe Sequence is a third order polynomial\nS = a0 + a1*n + a2*n*n + a3*n*n*n\nSubstituting n = 1, 2, 3, 4 and corresponding values\n28 = a0 + a1 + a2 + a3\n168 = a0 + 2*a1 + 4*a2*a2 + 8*a3*a3*a3\n516 = a0 + 3*a1 + 9*a2*a2 + 27*a3*a3*a3\n1168 = a0 + 4*a1 + 16*a2*a2 + 64*a3*a3*a3 \n\nWriting matrices for above equations\nA = 1 1 1 1\n 1 2 4 8\n 1 3 9 27\n 1 4 16 64 \nB = 28, 168, 516, 1168\nX = [a0 a1 a2 a3] = inv(A)*B = [0, 4, 8, 16]\n\nTherefore S = 4*n + 8*n*n + 16*n*n*n\n"
},
{
"code": null,
"e": 34652,
"s": 34398,
"text": "Note: To solve an nth order Sequence we need to solve a system of n equations. These equations can either be solved by hand or by using matrix-based math calculators like MATLAB, Octave etc. A free online version of Octave is available at Octave Online."
},
{
"code": null,
"e": 34659,
"s": 34652,
"text": "series"
},
{
"code": null,
"e": 34683,
"s": 34659,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 34696,
"s": 34683,
"text": "Mathematical"
},
{
"code": null,
"e": 34709,
"s": 34696,
"text": "Mathematical"
},
{
"code": null,
"e": 34716,
"s": 34709,
"text": "series"
},
{
"code": null,
"e": 34814,
"s": 34716,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34836,
"s": 34814,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 34857,
"s": 34836,
"text": "Activation Functions"
},
{
"code": null,
"e": 34880,
"s": 34857,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 34930,
"s": 34880,
"text": "Newton's Divided Difference Interpolation Formula"
},
{
"code": null,
"e": 34953,
"s": 34930,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 34983,
"s": 34953,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35043,
"s": 34983,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35058,
"s": 35043,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35101,
"s": 35058,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Upload Progress Bar in PHP - GeeksforGeeks
|
17 Jul, 2019
XAMPP is a free and open source cross-platform web server solution stack package developed by Apache which allows a web application to be easily tested on the local web server. But when it comes to uploading files to the server using PHP it is a headache. In most of the cases, PHP servers do not allow to upload files bigger than 30 MegaByte (30MB).
Using PHP only we can not create a progress bar interface as PHP would not provide a response until the upload is done. So to create a progress bar interface we have to use JavaScript along with PHP.
Change the limit of file upload size:Edit php.ini file to change the upload file size on ther server. To ensure that file upload works correctly, the post_max_size directive should be a little larger than the upload_max_filesize. For example, the following settings demonstrate how to set a file upload limit to 100 megabytes:
upload_max_filesize = 100M
post_max_size = 101M
Now, What if your hosting provider does not allow you to access the “php.ini” file?In this case, it is suggested to use JavaScript to upload your big file to the server in small blobs. JavaScript will break your local file into multiple files and it will try to upload the files to the server. Here you have to keep in mind that your blob size must not exceed the upload size limit of your PHP hosting.
Steps to run Upload ProgressBar Project:
Download complete project from Github.
Use Winrar to extract the zipped file.
Save the extracted file in XAMPP htdocs folder.
Run XAMPP server.
Now, open browser tab and type localhost/geeks/index.php or localhost/geeks on the address bar. It will display the output.
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
Split a comma delimited string into an array in PHP
How to declare a global variable in PHP?
How to fetch data from localserver database and display on HTML table using PHP ?
Removing Array Element and Re-Indexing in PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Split a comma delimited string into an array in PHP
How to declare a global variable in PHP?
How to fetch data from localserver database and display on HTML table using PHP ?
|
[
{
"code": null,
"e": 26497,
"s": 26469,
"text": "\n17 Jul, 2019"
},
{
"code": null,
"e": 26848,
"s": 26497,
"text": "XAMPP is a free and open source cross-platform web server solution stack package developed by Apache which allows a web application to be easily tested on the local web server. But when it comes to uploading files to the server using PHP it is a headache. In most of the cases, PHP servers do not allow to upload files bigger than 30 MegaByte (30MB)."
},
{
"code": null,
"e": 27048,
"s": 26848,
"text": "Using PHP only we can not create a progress bar interface as PHP would not provide a response until the upload is done. So to create a progress bar interface we have to use JavaScript along with PHP."
},
{
"code": null,
"e": 27375,
"s": 27048,
"text": "Change the limit of file upload size:Edit php.ini file to change the upload file size on ther server. To ensure that file upload works correctly, the post_max_size directive should be a little larger than the upload_max_filesize. For example, the following settings demonstrate how to set a file upload limit to 100 megabytes:"
},
{
"code": null,
"e": 27424,
"s": 27375,
"text": "upload_max_filesize = 100M\npost_max_size = 101M\n"
},
{
"code": null,
"e": 27827,
"s": 27424,
"text": "Now, What if your hosting provider does not allow you to access the “php.ini” file?In this case, it is suggested to use JavaScript to upload your big file to the server in small blobs. JavaScript will break your local file into multiple files and it will try to upload the files to the server. Here you have to keep in mind that your blob size must not exceed the upload size limit of your PHP hosting."
},
{
"code": null,
"e": 27868,
"s": 27827,
"text": "Steps to run Upload ProgressBar Project:"
},
{
"code": null,
"e": 27907,
"s": 27868,
"text": "Download complete project from Github."
},
{
"code": null,
"e": 27946,
"s": 27907,
"text": "Use Winrar to extract the zipped file."
},
{
"code": null,
"e": 27994,
"s": 27946,
"text": "Save the extracted file in XAMPP htdocs folder."
},
{
"code": null,
"e": 28012,
"s": 27994,
"text": "Run XAMPP server."
},
{
"code": null,
"e": 28136,
"s": 28012,
"text": "Now, open browser tab and type localhost/geeks/index.php or localhost/geeks on the address bar. It will display the output."
},
{
"code": null,
"e": 28143,
"s": 28136,
"text": "Picked"
},
{
"code": null,
"e": 28147,
"s": 28143,
"text": "PHP"
},
{
"code": null,
"e": 28160,
"s": 28147,
"text": "PHP Programs"
},
{
"code": null,
"e": 28177,
"s": 28160,
"text": "Web Technologies"
},
{
"code": null,
"e": 28204,
"s": 28177,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28208,
"s": 28204,
"text": "PHP"
},
{
"code": null,
"e": 28306,
"s": 28208,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28346,
"s": 28306,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28398,
"s": 28346,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 28439,
"s": 28398,
"text": "How to declare a global variable in PHP?"
},
{
"code": null,
"e": 28521,
"s": 28439,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 28567,
"s": 28521,
"text": "Removing Array Element and Re-Indexing in PHP"
},
{
"code": null,
"e": 28607,
"s": 28567,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28659,
"s": 28607,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 28711,
"s": 28659,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 28752,
"s": 28711,
"text": "How to declare a global variable in PHP?"
}
] |
Scala Set count() method with example - GeeksforGeeks
|
15 Oct, 2019
The count() method is utilized to count the number of elements in the set.
Method Definition: def count(p: (A) => Boolean): Int
Return Type: It returns the number of elements present in the set.
Example #1:
// Scala program of count()// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating sets val s1 = Set(1, 2, 3, 4, 5) // Applying count method val result = s1.count(z=>true) // Displays output println(result) } }
5
Example #2:
// Scala program of count()// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating sets val s1 = Set() // Applying count method val result = s1.count(z=>true) // Displays output println(result) } }
0
Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
Scala | Traits
Scala ListBuffer
Scala | Case Class and Case Object
Hello World in Scala
Scala | Functions - Basics
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Scala List map() method with example
Comments In Scala
Abstract Classes in Scala
|
[
{
"code": null,
"e": 25301,
"s": 25273,
"text": "\n15 Oct, 2019"
},
{
"code": null,
"e": 25376,
"s": 25301,
"text": "The count() method is utilized to count the number of elements in the set."
},
{
"code": null,
"e": 25429,
"s": 25376,
"text": "Method Definition: def count(p: (A) => Boolean): Int"
},
{
"code": null,
"e": 25496,
"s": 25429,
"text": "Return Type: It returns the number of elements present in the set."
},
{
"code": null,
"e": 25508,
"s": 25496,
"text": "Example #1:"
},
{
"code": "// Scala program of count()// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating sets val s1 = Set(1, 2, 3, 4, 5) // Applying count method val result = s1.count(z=>true) // Displays output println(result) } } ",
"e": 25863,
"s": 25508,
"text": null
},
{
"code": null,
"e": 25866,
"s": 25863,
"text": "5\n"
},
{
"code": null,
"e": 25878,
"s": 25866,
"text": "Example #2:"
},
{
"code": "// Scala program of count()// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating sets val s1 = Set() // Applying count method val result = s1.count(z=>true) // Displays output println(result) } } ",
"e": 26220,
"s": 25878,
"text": null
},
{
"code": null,
"e": 26223,
"s": 26220,
"text": "0\n"
},
{
"code": null,
"e": 26229,
"s": 26223,
"text": "Scala"
},
{
"code": null,
"e": 26246,
"s": 26229,
"text": "scala-collection"
},
{
"code": null,
"e": 26259,
"s": 26246,
"text": "Scala-Method"
},
{
"code": null,
"e": 26269,
"s": 26259,
"text": "Scala-Set"
},
{
"code": null,
"e": 26275,
"s": 26269,
"text": "Scala"
},
{
"code": null,
"e": 26373,
"s": 26275,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26394,
"s": 26373,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 26409,
"s": 26394,
"text": "Scala | Traits"
},
{
"code": null,
"e": 26426,
"s": 26409,
"text": "Scala ListBuffer"
},
{
"code": null,
"e": 26461,
"s": 26426,
"text": "Scala | Case Class and Case Object"
},
{
"code": null,
"e": 26482,
"s": 26461,
"text": "Hello World in Scala"
},
{
"code": null,
"e": 26509,
"s": 26482,
"text": "Scala | Functions - Basics"
},
{
"code": null,
"e": 26575,
"s": 26509,
"text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)"
},
{
"code": null,
"e": 26612,
"s": 26575,
"text": "Scala List map() method with example"
},
{
"code": null,
"e": 26630,
"s": 26612,
"text": "Comments In Scala"
}
] |
What is a clearfix? - GeeksforGeeks
|
29 Oct, 2021
A clearfix is a way for an element to automatically clear or fix its elements so that it does not need to add additional markup. It is generally used in float layouts where elements are floated to be stacked horizontally. If the element is taller than the element containing it then use the overflow property of CSS by setting its value as auto in order to overcome & fix the problem.
Example: From the below image, the logo is not fit into the div element. To fix this problem, there are two ways. The first is by increasing the height of the div block and the second by the use of clearfix CSS property.
We will understand these concepts its implementation through the examples.
Please refer to the CSS Float article to understand the floating concept in CSS.
Example 1: In the code below, the problem is fixed without using the overflow property.
HTML
<!DOCTYPE html><html> <head> <!-- CSS code to show the working of this property --> <style> div { border: 3px solid green; padding: 10px; height: 200px; text-align: justify; } img { float: right; } </style></head> <body> <div> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png" alt="Pineapple" width="200" height="200"> GATE(Graduate Aptitude Test in Engineering) is one the most important and in-demand entrance exam for engineering graduates in our country. M.Tech. in Computer Science is one of the most demanding courses at prestigious institutes like IISCs and IITs. GATE(Graduate Aptitude Test in Engineering) is one of the ways to get into these top institutes. Every year around 10 Lakh candidates apply for GATE exam and very few of them manage to ace the exam with good score. So the competition is clearly very tough and simply preparing without any strategy will make it difficult to land you into IISCs and IITs. </div></body> </html>
Output:
Example 2: In this code, the problem is fixed using the overflow property.
HTML
<!DOCTYPE html><html> <head> <!-- CSS code to show the working of this property --> <style> div { border: 3px solid green; padding: 10px; text-align: justify; } img { float: right; } .gfg { overflow: auto; } </style></head> <body> <div class="gfg"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png" alt="Pineapple" width="200" height="200"> GATE(Graduate Aptitude Test in Engineering) is one the most important and in-demand entrance exam for engineering graduates in our country. M.Tech. in Computer Science is one of the most demanding courses at prestigious institutes like IISCs and IITs. GATE(Graduate Aptitude Test in Engineering) is one of the ways to get into these top institutes. Every year around 10 Lakh candidates apply for GATE exam and very few of them manage to ace the exam with good score. So the competition is clearly very tough and simply preparing without any strategy will make it difficult to land you into IISCs and IITs. </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
bhaskargeeksforgeeks
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 25935,
"s": 25907,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 26320,
"s": 25935,
"text": "A clearfix is a way for an element to automatically clear or fix its elements so that it does not need to add additional markup. It is generally used in float layouts where elements are floated to be stacked horizontally. If the element is taller than the element containing it then use the overflow property of CSS by setting its value as auto in order to overcome & fix the problem."
},
{
"code": null,
"e": 26541,
"s": 26320,
"text": "Example: From the below image, the logo is not fit into the div element. To fix this problem, there are two ways. The first is by increasing the height of the div block and the second by the use of clearfix CSS property."
},
{
"code": null,
"e": 26616,
"s": 26541,
"text": "We will understand these concepts its implementation through the examples."
},
{
"code": null,
"e": 26697,
"s": 26616,
"text": "Please refer to the CSS Float article to understand the floating concept in CSS."
},
{
"code": null,
"e": 26785,
"s": 26697,
"text": "Example 1: In the code below, the problem is fixed without using the overflow property."
},
{
"code": null,
"e": 26790,
"s": 26785,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- CSS code to show the working of this property --> <style> div { border: 3px solid green; padding: 10px; height: 200px; text-align: justify; } img { float: right; } </style></head> <body> <div> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png\" alt=\"Pineapple\" width=\"200\" height=\"200\"> GATE(Graduate Aptitude Test in Engineering) is one the most important and in-demand entrance exam for engineering graduates in our country. M.Tech. in Computer Science is one of the most demanding courses at prestigious institutes like IISCs and IITs. GATE(Graduate Aptitude Test in Engineering) is one of the ways to get into these top institutes. Every year around 10 Lakh candidates apply for GATE exam and very few of them manage to ace the exam with good score. So the competition is clearly very tough and simply preparing without any strategy will make it difficult to land you into IISCs and IITs. </div></body> </html>",
"e": 27959,
"s": 26790,
"text": null
},
{
"code": null,
"e": 27967,
"s": 27959,
"text": "Output:"
},
{
"code": null,
"e": 28042,
"s": 27967,
"text": "Example 2: In this code, the problem is fixed using the overflow property."
},
{
"code": null,
"e": 28047,
"s": 28042,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- CSS code to show the working of this property --> <style> div { border: 3px solid green; padding: 10px; text-align: justify; } img { float: right; } .gfg { overflow: auto; } </style></head> <body> <div class=\"gfg\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png\" alt=\"Pineapple\" width=\"200\" height=\"200\"> GATE(Graduate Aptitude Test in Engineering) is one the most important and in-demand entrance exam for engineering graduates in our country. M.Tech. in Computer Science is one of the most demanding courses at prestigious institutes like IISCs and IITs. GATE(Graduate Aptitude Test in Engineering) is one of the ways to get into these top institutes. Every year around 10 Lakh candidates apply for GATE exam and very few of them manage to ace the exam with good score. So the competition is clearly very tough and simply preparing without any strategy will make it difficult to land you into IISCs and IITs. </div></body> </html>",
"e": 29251,
"s": 28047,
"text": null
},
{
"code": null,
"e": 29259,
"s": 29251,
"text": "Output:"
},
{
"code": null,
"e": 29396,
"s": 29259,
"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": 29417,
"s": 29396,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 29426,
"s": 29417,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29433,
"s": 29426,
"text": "Picked"
},
{
"code": null,
"e": 29437,
"s": 29433,
"text": "CSS"
},
{
"code": null,
"e": 29442,
"s": 29437,
"text": "HTML"
},
{
"code": null,
"e": 29459,
"s": 29442,
"text": "Web Technologies"
},
{
"code": null,
"e": 29464,
"s": 29459,
"text": "HTML"
},
{
"code": null,
"e": 29562,
"s": 29464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29612,
"s": 29562,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29674,
"s": 29612,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29722,
"s": 29674,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29780,
"s": 29722,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29835,
"s": 29780,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29885,
"s": 29835,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29947,
"s": 29885,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29995,
"s": 29947,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30055,
"s": 29995,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Display Hostname and IP address in Python - GeeksforGeeks
|
05 Oct, 2021
There are many ways to find hostname and IP address of a local machine. Here is a simple method to find hostname and IP address using python code. Library used – socket: This module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, MacOS, and probably additional platforms. Method used :
gethostname() : The gethostname function retrieves the standard host name for the local computer.
gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database.
Python3
# Python3 code to display hostname and# IP address # Importing socket libraryimport socket # Function to display hostname and# IP addressdef get_Host_name_IP(): try: host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) print("Hostname : ",host_name) print("IP : ",host_ip) except: print("Unable to get Hostname and IP") # Driver codeget_Host_name_IP() #Function call #This code is contributed by "Sharad_Bhardwaj".
Output:
Hostname : pppContainer
IP : 10.98.162.168
NOTE : Output varies machine to machine.
sagar0719kumar
Computer Networks-IP Addressing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
|
[
{
"code": null,
"e": 26012,
"s": 25984,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 26349,
"s": 26012,
"text": "There are many ways to find hostname and IP address of a local machine. Here is a simple method to find hostname and IP address using python code. Library used – socket: This module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, MacOS, and probably additional platforms. Method used : "
},
{
"code": null,
"e": 26447,
"s": 26349,
"text": "gethostname() : The gethostname function retrieves the standard host name for the local computer."
},
{
"code": null,
"e": 26571,
"s": 26447,
"text": "gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database. "
},
{
"code": null,
"e": 26579,
"s": 26571,
"text": "Python3"
},
{
"code": "# Python3 code to display hostname and# IP address # Importing socket libraryimport socket # Function to display hostname and# IP addressdef get_Host_name_IP(): try: host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) print(\"Hostname : \",host_name) print(\"IP : \",host_ip) except: print(\"Unable to get Hostname and IP\") # Driver codeget_Host_name_IP() #Function call #This code is contributed by \"Sharad_Bhardwaj\".",
"e": 27058,
"s": 26579,
"text": null
},
{
"code": null,
"e": 27067,
"s": 27058,
"text": "Output: "
},
{
"code": null,
"e": 27113,
"s": 27067,
"text": "Hostname : pppContainer\nIP : 10.98.162.168"
},
{
"code": null,
"e": 27155,
"s": 27113,
"text": "NOTE : Output varies machine to machine. "
},
{
"code": null,
"e": 27170,
"s": 27155,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 27202,
"s": 27170,
"text": "Computer Networks-IP Addressing"
},
{
"code": null,
"e": 27209,
"s": 27202,
"text": "Python"
},
{
"code": null,
"e": 27307,
"s": 27209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27325,
"s": 27307,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27357,
"s": 27325,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27379,
"s": 27357,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27421,
"s": 27379,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27451,
"s": 27421,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27477,
"s": 27451,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27506,
"s": 27477,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27550,
"s": 27506,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27587,
"s": 27550,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Time Series Analysis using Facebook Prophet in R Programming - GeeksforGeeks
|
22 Jul, 2020
Time Series Analysis is a way of analysing and learning the behaviour of datasets over a period. Moreover, it helps in learning the behavior of the dataset by plotting the time series object on the graph. In R programming, it can be easily performed by using ts() function that takes the data vector and converts it into time series object as specified in function parameters.
Facebook Prophet is a tool developed by Facebook for forecasting time series objects or data. It helps businesses to learn the behavior of their products by forecasting prices, sales, or weather. Facebook Prophet tool is based on decomposable model i.e., trend, seasonality and holidays that helps in making more accurate predictive models with these constraints. It is much better than the ARIMA model as it helps in tuning and adjusting the input parameters.
where,y(t) refers to the forecastg(t) refers to the trends(t) refers to the seasonalityh(t) refers to the holidays for the forecaste(t) refers to the error term while forecasting
TrendA trend is a shift in development either in increment or decrement direction. Mathematically,where,C indicates the carry capacityk indicates the growthm indicates the offset parameter
where,C indicates the carry capacityk indicates the growthm indicates the offset parameter
SeasonalitySeasonality is a feature of time series object that occurs at a particular time/season and changes the trend.
HolidaysHolidays are a time period that changes a lot to the business. It can make a profit or loss depending upon the business.
In the example below, let us download the dataset AirPassengers and perform the forecasting of the dataset using the Facebook Prophet model. After executing the whole code, the model will show the forecasted values with the trend and seasonality of the business.
Step 1: Installing the required library
# Install the libraryinstall.packages("prophet")
Step 2: Load the required library
# Load the librarylibrary(prophet)
Step 3: Download the dataset AirPassengers from here
# Datasetap <- read.csv("example_air_passengers.csv")
Step 4: Call the prophet function to fit the model
m <- prophet(ap)
Step 5: Make predictions
# Predictionsfuture <- make_future_dataframe(m, periods = 365) # Print predictionscat("\nPredictions:\n")tail(future)
Output:
Predictions:
ds
504 1961-11-26
505 1961-11-27
506 1961-11-28
507 1961-11-29
508 1961-11-30
509 1961-12-01
Step 6: Forecast data using predictions
# Forecastforecast <- predict(m, future)tail(forecast[c('ds', 'yhat', 'yhat_lower', 'yhat_upper')])
ds yhat yhat_lower yhat_upper
504 1961-11-26 497.2056 468.6301 525.7918
505 1961-11-27 496.0703 467.8579 525.6728
506 1961-11-28 493.1698 465.5788 522.9650
507 1961-11-29 496.0497 469.2889 524.6313
508 1961-11-30 492.8452 463.7279 520.4519
509 1961-12-01 493.6417 466.3496 522.9887
Step 7: Plot the forecast
# Output to be present# As PNG filepng(file = "facebookprophetGFG.png") # Plotplot(m, forecast) # Saving the filedev.off()
Output:Above graph shows the forecasted values of AirPassengers where, Black dots refers to the original data, Dark blue line refers to the predicted value(yhat), and Light blue area indicates the yhat_upper and yhat_lower value.
Step 8: Plot the trend, weekly and yearly seasonality
# Output to be present # As PNG filepng(file = "facebookprophettrendGFG.png") # Plotprophet_plot_components(m, forecast) # Saving the filedev.off()
Output:The above graph shows the trend of the dataset that air passengers have been increased over a given period of time. In second graph, it shows seasonality of the dataset over a period of time i.e., yearly and signifies that air passengers were maximum between months from June to August.
data-science
R Machine-Learning
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n22 Jul, 2020"
},
{
"code": null,
"e": 26864,
"s": 26487,
"text": "Time Series Analysis is a way of analysing and learning the behaviour of datasets over a period. Moreover, it helps in learning the behavior of the dataset by plotting the time series object on the graph. In R programming, it can be easily performed by using ts() function that takes the data vector and converts it into time series object as specified in function parameters."
},
{
"code": null,
"e": 27325,
"s": 26864,
"text": "Facebook Prophet is a tool developed by Facebook for forecasting time series objects or data. It helps businesses to learn the behavior of their products by forecasting prices, sales, or weather. Facebook Prophet tool is based on decomposable model i.e., trend, seasonality and holidays that helps in making more accurate predictive models with these constraints. It is much better than the ARIMA model as it helps in tuning and adjusting the input parameters."
},
{
"code": null,
"e": 27504,
"s": 27325,
"text": "where,y(t) refers to the forecastg(t) refers to the trends(t) refers to the seasonalityh(t) refers to the holidays for the forecaste(t) refers to the error term while forecasting"
},
{
"code": null,
"e": 27693,
"s": 27504,
"text": "TrendA trend is a shift in development either in increment or decrement direction. Mathematically,where,C indicates the carry capacityk indicates the growthm indicates the offset parameter"
},
{
"code": null,
"e": 27784,
"s": 27693,
"text": "where,C indicates the carry capacityk indicates the growthm indicates the offset parameter"
},
{
"code": null,
"e": 27905,
"s": 27784,
"text": "SeasonalitySeasonality is a feature of time series object that occurs at a particular time/season and changes the trend."
},
{
"code": null,
"e": 28034,
"s": 27905,
"text": "HolidaysHolidays are a time period that changes a lot to the business. It can make a profit or loss depending upon the business."
},
{
"code": null,
"e": 28297,
"s": 28034,
"text": "In the example below, let us download the dataset AirPassengers and perform the forecasting of the dataset using the Facebook Prophet model. After executing the whole code, the model will show the forecasted values with the trend and seasonality of the business."
},
{
"code": null,
"e": 28337,
"s": 28297,
"text": "Step 1: Installing the required library"
},
{
"code": "# Install the libraryinstall.packages(\"prophet\")",
"e": 28386,
"s": 28337,
"text": null
},
{
"code": null,
"e": 28420,
"s": 28386,
"text": "Step 2: Load the required library"
},
{
"code": "# Load the librarylibrary(prophet)",
"e": 28455,
"s": 28420,
"text": null
},
{
"code": null,
"e": 28508,
"s": 28455,
"text": "Step 3: Download the dataset AirPassengers from here"
},
{
"code": "# Datasetap <- read.csv(\"example_air_passengers.csv\")",
"e": 28562,
"s": 28508,
"text": null
},
{
"code": null,
"e": 28613,
"s": 28562,
"text": "Step 4: Call the prophet function to fit the model"
},
{
"code": "m <- prophet(ap)",
"e": 28630,
"s": 28613,
"text": null
},
{
"code": null,
"e": 28655,
"s": 28630,
"text": "Step 5: Make predictions"
},
{
"code": "# Predictionsfuture <- make_future_dataframe(m, periods = 365) # Print predictionscat(\"\\nPredictions:\\n\")tail(future)",
"e": 28793,
"s": 28655,
"text": null
},
{
"code": null,
"e": 28801,
"s": 28793,
"text": "Output:"
},
{
"code": null,
"e": 28916,
"s": 28801,
"text": "Predictions:\n ds\n504 1961-11-26\n505 1961-11-27\n506 1961-11-28\n507 1961-11-29\n508 1961-11-30\n509 1961-12-01\n"
},
{
"code": null,
"e": 28956,
"s": 28916,
"text": "Step 6: Forecast data using predictions"
},
{
"code": "# Forecastforecast <- predict(m, future)tail(forecast[c('ds', 'yhat', 'yhat_lower', 'yhat_upper')])",
"e": 29060,
"s": 28956,
"text": null
},
{
"code": null,
"e": 29384,
"s": 29060,
"text": " ds yhat yhat_lower yhat_upper\n504 1961-11-26 497.2056 468.6301 525.7918\n505 1961-11-27 496.0703 467.8579 525.6728\n506 1961-11-28 493.1698 465.5788 522.9650\n507 1961-11-29 496.0497 469.2889 524.6313\n508 1961-11-30 492.8452 463.7279 520.4519\n509 1961-12-01 493.6417 466.3496 522.9887\n"
},
{
"code": null,
"e": 29410,
"s": 29384,
"text": "Step 7: Plot the forecast"
},
{
"code": "# Output to be present# As PNG filepng(file = \"facebookprophetGFG.png\") # Plotplot(m, forecast) # Saving the filedev.off()",
"e": 29535,
"s": 29410,
"text": null
},
{
"code": null,
"e": 29765,
"s": 29535,
"text": "Output:Above graph shows the forecasted values of AirPassengers where, Black dots refers to the original data, Dark blue line refers to the predicted value(yhat), and Light blue area indicates the yhat_upper and yhat_lower value."
},
{
"code": null,
"e": 29819,
"s": 29765,
"text": "Step 8: Plot the trend, weekly and yearly seasonality"
},
{
"code": "# Output to be present # As PNG filepng(file = \"facebookprophettrendGFG.png\") # Plotprophet_plot_components(m, forecast) # Saving the filedev.off()",
"e": 29969,
"s": 29819,
"text": null
},
{
"code": null,
"e": 30263,
"s": 29969,
"text": "Output:The above graph shows the trend of the dataset that air passengers have been increased over a given period of time. In second graph, it shows seasonality of the dataset over a period of time i.e., yearly and signifies that air passengers were maximum between months from June to August."
},
{
"code": null,
"e": 30276,
"s": 30263,
"text": "data-science"
},
{
"code": null,
"e": 30295,
"s": 30276,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 30306,
"s": 30295,
"text": "R Language"
},
{
"code": null,
"e": 30404,
"s": 30306,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30456,
"s": 30404,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30491,
"s": 30456,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30529,
"s": 30491,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30587,
"s": 30529,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30630,
"s": 30587,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30679,
"s": 30630,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30716,
"s": 30679,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30742,
"s": 30716,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 30759,
"s": 30742,
"text": "R - if statement"
}
] |
Arrange given numbers to form the biggest number | Set 2 - GeeksforGeeks
|
04 Jun, 2020
Given an array of non-negative numbers(of Integer Range), they are needed to be arranged in some order such that it gives the max number. For example given array is A[1, 34, 3, 98, 9, 76, 45, 4, 12, 121]. if we arrange these numbers in the following order, A[9, 98, 76, 45, 4, 34, 3, 12, 121, 1], then by joining them we get “99876454343121211” as largest number.
Examples:
Input : [1, 34, 3, 98, 9, 76, 45, 4, 12, 121]
Output : 99876454343121211
Input : [12, 121]
Output : 12121
In SET 1, we have discussed an approach to do same. In this set, we will discuss another logic.
1) Find number of digits in the largest number. Let number of digits be n.2) Create extended version of all numbers. In extended version, we have n+1 digits formed by concatenating the number of with itself and truncating extra digits.3) Sort original numbers according to their extended values.4) Concatenating the sorted numbers produces th required result.
Java
Python
// Java program to arrange the numbers to form the// largest numberimport java.math.BigInteger;import java.util.*; public class LargestNumber{ // method that returns largest number form public static String largestNumber(List<Integer> arr) { // finding number of digits in maximum element // present in array int n = Collections.max(arr).toString().length(); ArrayList<ExtendedNum> en = new ArrayList<ExtendedNum>(); for (int i = 0 ; i < arr.size(); i++) en.add(new ExtendedNum(arr.get(i), n)); // sort based on modified value Collections.sort(en, (p1, p2) -> (int)(p2.modifiedValue - p1.modifiedValue)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < en.size(); i++) sb.append(new StringBuilder (Long.toString(en.get(i).originalValue))); // To remove any zeroes at head. BigInteger bi = new BigInteger(sb.toString()); return bi.toString(); } // Driver method public static void main(String[] args) { Integer arr[] = {1, 34, 3, 98, 9, 76, 45, 4, 12, 121}; List<Integer> l = Arrays.asList(arr); System.out.println(largestNumber(l)); }} // A utility class to generate new valueclass ExtendedNum{ int originalValue; long modifiedValue; public ExtendedNum(int originalValue, int n) { this.originalValue = originalValue; String s = Integer.toString(originalValue); StringBuilder sb = new StringBuilder(s); StringBuilder ans = new StringBuilder(); while (ans.length() <= n + 1) ans.append(sb); s = ans.toString().substring(0, n + 1); modifiedValue = Long.parseLong(s); } public String toString() { return "[" + modifiedValue + ", " + originalValue + "]"; }}
# Python program to find largest# number from the given values# function that return largest# possible numberdef largestNumber(array): # extval is a empty list for extended # values and ans for calculating answer extval, ans = [], "" # calculating the length of largest number # from given and add 1 for further operation l = len(str(max(array))) + 1 # iterate given values and # calculating extended values for i in array: temp = str(i) * l # make tuple of extended value and # equivalant original value then # append to list extval.append((temp[:l:], i)) # sort extval in descending order extval.sort(reverse = True) # iterate extended values for i in extval: # concatinate original value equivalant # to extended value into ans variable ans += str(i[1]) if int(ans)==0: return "0" return ans # Driver codea = [1, 34, 3, 98, 9, 76, 45, 4, 12, 121] print(largestNumber(a)) # This code is contributed by Chhekur
99876454343121211
This article is contributed by Kondiparthi Shanmukha Sarath. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Chhekur
Galld
number-digits
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Array of Strings in C++ (5 Different Ways to Create)
Queue | Set 1 (Introduction and Array Implementation)
Find the Missing Number
Subset Sum Problem | DP-25
K'th Smallest/Largest Element in Unsorted Array | Set 1
Find Second largest element in an array
|
[
{
"code": null,
"e": 26761,
"s": 26733,
"text": "\n04 Jun, 2020"
},
{
"code": null,
"e": 27125,
"s": 26761,
"text": "Given an array of non-negative numbers(of Integer Range), they are needed to be arranged in some order such that it gives the max number. For example given array is A[1, 34, 3, 98, 9, 76, 45, 4, 12, 121]. if we arrange these numbers in the following order, A[9, 98, 76, 45, 4, 34, 3, 12, 121, 1], then by joining them we get “99876454343121211” as largest number."
},
{
"code": null,
"e": 27135,
"s": 27125,
"text": "Examples:"
},
{
"code": null,
"e": 27245,
"s": 27135,
"text": "Input : [1, 34, 3, 98, 9, 76, 45, 4, 12, 121]\nOutput : 99876454343121211\n\nInput : [12, 121]\nOutput : 12121\n"
},
{
"code": null,
"e": 27341,
"s": 27245,
"text": "In SET 1, we have discussed an approach to do same. In this set, we will discuss another logic."
},
{
"code": null,
"e": 27701,
"s": 27341,
"text": "1) Find number of digits in the largest number. Let number of digits be n.2) Create extended version of all numbers. In extended version, we have n+1 digits formed by concatenating the number of with itself and truncating extra digits.3) Sort original numbers according to their extended values.4) Concatenating the sorted numbers produces th required result."
},
{
"code": null,
"e": 27706,
"s": 27701,
"text": "Java"
},
{
"code": null,
"e": 27713,
"s": 27706,
"text": "Python"
},
{
"code": "// Java program to arrange the numbers to form the// largest numberimport java.math.BigInteger;import java.util.*; public class LargestNumber{ // method that returns largest number form public static String largestNumber(List<Integer> arr) { // finding number of digits in maximum element // present in array int n = Collections.max(arr).toString().length(); ArrayList<ExtendedNum> en = new ArrayList<ExtendedNum>(); for (int i = 0 ; i < arr.size(); i++) en.add(new ExtendedNum(arr.get(i), n)); // sort based on modified value Collections.sort(en, (p1, p2) -> (int)(p2.modifiedValue - p1.modifiedValue)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < en.size(); i++) sb.append(new StringBuilder (Long.toString(en.get(i).originalValue))); // To remove any zeroes at head. BigInteger bi = new BigInteger(sb.toString()); return bi.toString(); } // Driver method public static void main(String[] args) { Integer arr[] = {1, 34, 3, 98, 9, 76, 45, 4, 12, 121}; List<Integer> l = Arrays.asList(arr); System.out.println(largestNumber(l)); }} // A utility class to generate new valueclass ExtendedNum{ int originalValue; long modifiedValue; public ExtendedNum(int originalValue, int n) { this.originalValue = originalValue; String s = Integer.toString(originalValue); StringBuilder sb = new StringBuilder(s); StringBuilder ans = new StringBuilder(); while (ans.length() <= n + 1) ans.append(sb); s = ans.toString().substring(0, n + 1); modifiedValue = Long.parseLong(s); } public String toString() { return \"[\" + modifiedValue + \", \" + originalValue + \"]\"; }}",
"e": 29673,
"s": 27713,
"text": null
},
{
"code": "# Python program to find largest# number from the given values# function that return largest# possible numberdef largestNumber(array): # extval is a empty list for extended # values and ans for calculating answer extval, ans = [], \"\" # calculating the length of largest number # from given and add 1 for further operation l = len(str(max(array))) + 1 # iterate given values and # calculating extended values for i in array: temp = str(i) * l # make tuple of extended value and # equivalant original value then # append to list extval.append((temp[:l:], i)) # sort extval in descending order extval.sort(reverse = True) # iterate extended values for i in extval: # concatinate original value equivalant # to extended value into ans variable ans += str(i[1]) if int(ans)==0: return \"0\" return ans # Driver codea = [1, 34, 3, 98, 9, 76, 45, 4, 12, 121] print(largestNumber(a)) # This code is contributed by Chhekur",
"e": 30759,
"s": 29673,
"text": null
},
{
"code": null,
"e": 30778,
"s": 30759,
"text": "99876454343121211\n"
},
{
"code": null,
"e": 31094,
"s": 30778,
"text": "This article is contributed by Kondiparthi Shanmukha Sarath. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 31219,
"s": 31094,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31227,
"s": 31219,
"text": "Chhekur"
},
{
"code": null,
"e": 31233,
"s": 31227,
"text": "Galld"
},
{
"code": null,
"e": 31247,
"s": 31233,
"text": "number-digits"
},
{
"code": null,
"e": 31254,
"s": 31247,
"text": "Arrays"
},
{
"code": null,
"e": 31261,
"s": 31254,
"text": "Arrays"
},
{
"code": null,
"e": 31359,
"s": 31261,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31382,
"s": 31359,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 31403,
"s": 31382,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 31448,
"s": 31403,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 31496,
"s": 31448,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 31549,
"s": 31496,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 31603,
"s": 31549,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 31627,
"s": 31603,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 31654,
"s": 31627,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 31710,
"s": 31654,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
Mixture and Alligation | Set 2 - GeeksforGeeks
|
08 Sep, 2021
Question 1: 30 litres of a mixture of milk and water contains 10% of water, the water to be added, to make the water content 25% in the new mixture. Find how many litres water will be added? Solution : Water in the 30 litre of mixture = 30 x 10/100 = 3 litres Milk in the mixture = 30 – 3 = 27 litres Let x litres of water is mixed. Acc. to question (3 + x)/(30 + x) = 25/100 4(3 + x) = 30 + x 12 + 4x = 30 + x 3x = 18 x = 6 Hence, 6 litres of water to be added in the mixture.
Alternate :
Question 2: 25000 students appeared in an exam. 60% of the boys and 40% of the girls cleared the examination. If the total percent of students qualifying is 55%, how many girls appeared in the exam? Solution : By alligation method
4 -> 25000 1 -> 6250 Hence, number of girls passed in the exam is 6250.
Question 3: In what ratio must a shopkeeper mix sugar at Rs 30/kg and Rs 32.5/kg, so that by selling the mixture at Rs 34.1/kg he may gain 10%. Solution : Acc. to question SP of 1 kg of mixture = Rs 34.1 Profit = 10% = 10/100 = 1/10 SP = 1 + 10 = 11 unit 11 units ->34.1 1 unit -> 3.1 10 unit -> 31 We obtain the CP of the mixture Rs 31. To obtain the ratio use alligation method
Hence, the ratio in which he mixed is 3:2
Question 4: Two vessels A and B contain mixture of milk and water in ratios 3:4 and 4:1 respectively. In what ratio should quantities of mixture be taken from A and B to form a mixture in which milk to water is in the ratio 5:2? Solution :Acc. to question
Milk Water total
Mixture A 3x5 : 4x5 -> 7 LCM(7, 5, 7)=35
Mixture B 4x7 : 1x7 -> 5
Final mixture 5x5 : 2x5 -> 7
To make quantity equal of both multiply with 7 and 5 respectively.
Milk Water
Mixture A 15 : 20
Mixture B 28 : 7
Final mixture 25 : 10
To obtain the ratio in which A and B mixed we apply alligation rule
Hence, the required ratio is 3:10.
Question 5: 40 kg of an alloy mixed with 100 kg of alloy B. If alloy A has lead and copper in the ratio 3:2 and alloy B has copper and tin in the ratio 1:3., then the amount of copper in the new alloy is Solution :Alloy A 40 kg contains lead and copper in ratio 3:2 So, 3+2 = 5 5 unit -> 40 1 unit -> 8 2 unit -> 16 Amount of copper in alloy A is 16 kg. Alloy B contains copper and tin in ratio 1:3 So, 1+3 = 4 4 unit -> 100 1 -> 25 Amount of copper in alloy B is 25 kg Hence, amount of copper in the new alloy is 16 + 25 = 41 kg.
rajeev0719singh
Placements
QA - Placements
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 20 Puzzles Commonly Asked During SDE Interviews
Codenation Recruitment Process
Minimum changes required to make all Array elements Prime
Permutation and Combination
Interview Preparation
Permutation and Combination
Problem on Numbers
Probability
Clocks
Problems on Work and Wages
|
[
{
"code": null,
"e": 24903,
"s": 24875,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 25382,
"s": 24903,
"text": "Question 1: 30 litres of a mixture of milk and water contains 10% of water, the water to be added, to make the water content 25% in the new mixture. Find how many litres water will be added? Solution : Water in the 30 litre of mixture = 30 x 10/100 = 3 litres Milk in the mixture = 30 – 3 = 27 litres Let x litres of water is mixed. Acc. to question (3 + x)/(30 + x) = 25/100 4(3 + x) = 30 + x 12 + 4x = 30 + x 3x = 18 x = 6 Hence, 6 litres of water to be added in the mixture. "
},
{
"code": null,
"e": 25396,
"s": 25382,
"text": "Alternate : "
},
{
"code": null,
"e": 25629,
"s": 25396,
"text": "Question 2: 25000 students appeared in an exam. 60% of the boys and 40% of the girls cleared the examination. If the total percent of students qualifying is 55%, how many girls appeared in the exam? Solution : By alligation method "
},
{
"code": null,
"e": 25702,
"s": 25629,
"text": "4 -> 25000 1 -> 6250 Hence, number of girls passed in the exam is 6250. "
},
{
"code": null,
"e": 26084,
"s": 25702,
"text": "Question 3: In what ratio must a shopkeeper mix sugar at Rs 30/kg and Rs 32.5/kg, so that by selling the mixture at Rs 34.1/kg he may gain 10%. Solution : Acc. to question SP of 1 kg of mixture = Rs 34.1 Profit = 10% = 10/100 = 1/10 SP = 1 + 10 = 11 unit 11 units ->34.1 1 unit -> 3.1 10 unit -> 31 We obtain the CP of the mixture Rs 31. To obtain the ratio use alligation method "
},
{
"code": null,
"e": 26127,
"s": 26084,
"text": "Hence, the ratio in which he mixed is 3:2 "
},
{
"code": null,
"e": 26385,
"s": 26127,
"text": "Question 4: Two vessels A and B contain mixture of milk and water in ratios 3:4 and 4:1 respectively. In what ratio should quantities of mixture be taken from A and B to form a mixture in which milk to water is in the ratio 5:2? Solution :Acc. to question "
},
{
"code": null,
"e": 26605,
"s": 26385,
"text": " Milk Water total\nMixture A 3x5 : 4x5 -> 7 LCM(7, 5, 7)=35\nMixture B 4x7 : 1x7 -> 5 \nFinal mixture 5x5 : 2x5 -> 7"
},
{
"code": null,
"e": 26674,
"s": 26605,
"text": "To make quantity equal of both multiply with 7 and 5 respectively. "
},
{
"code": null,
"e": 26835,
"s": 26674,
"text": " Milk Water \nMixture A 15 : 20 \nMixture B 28 : 7 \nFinal mixture 25 : 10 "
},
{
"code": null,
"e": 26905,
"s": 26835,
"text": "To obtain the ratio in which A and B mixed we apply alligation rule "
},
{
"code": null,
"e": 26941,
"s": 26905,
"text": "Hence, the required ratio is 3:10. "
},
{
"code": null,
"e": 27473,
"s": 26941,
"text": "Question 5: 40 kg of an alloy mixed with 100 kg of alloy B. If alloy A has lead and copper in the ratio 3:2 and alloy B has copper and tin in the ratio 1:3., then the amount of copper in the new alloy is Solution :Alloy A 40 kg contains lead and copper in ratio 3:2 So, 3+2 = 5 5 unit -> 40 1 unit -> 8 2 unit -> 16 Amount of copper in alloy A is 16 kg. Alloy B contains copper and tin in ratio 1:3 So, 1+3 = 4 4 unit -> 100 1 -> 25 Amount of copper in alloy B is 25 kg Hence, amount of copper in the new alloy is 16 + 25 = 41 kg. "
},
{
"code": null,
"e": 27489,
"s": 27473,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 27500,
"s": 27489,
"text": "Placements"
},
{
"code": null,
"e": 27516,
"s": 27500,
"text": "QA - Placements"
},
{
"code": null,
"e": 27614,
"s": 27516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27666,
"s": 27614,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 27697,
"s": 27666,
"text": "Codenation Recruitment Process"
},
{
"code": null,
"e": 27755,
"s": 27697,
"text": "Minimum changes required to make all Array elements Prime"
},
{
"code": null,
"e": 27783,
"s": 27755,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 27805,
"s": 27783,
"text": "Interview Preparation"
},
{
"code": null,
"e": 27833,
"s": 27805,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 27852,
"s": 27833,
"text": "Problem on Numbers"
},
{
"code": null,
"e": 27864,
"s": 27852,
"text": "Probability"
},
{
"code": null,
"e": 27871,
"s": 27864,
"text": "Clocks"
}
] |
Creating And Fitting A Regression Model In Julia | by Emmett Boudreau | Towards Data Science
|
Lathe 0.0.9 has just been merged to the Master branch, and with it comes a host of new features that will certainly be exciting to show off. Machine-learning in Julia is now easier than it has ever been before. The only issues currently facing machine-learning in Julia are the lack of a Python-size ecosystem, and the lack of documentation. Fortunately, for Lathe users there are a lot of features and tools at our disposal, and even better:
Lathe has good documentation!
I found another CSV data-set to work with online. To load this CSV into Julia, we will need the first of our three dependencies, CSV.jl. So with that in mind, the first step is to jump into the Pkg REPL, by first entering the Julia REPL, and then pressing ]. From this REPL we can add our three dependencies:
julia> ]pkg> add "Lathe"#Unstablepkg> add "DataFrames"pkg> add "CSV"
Now that we have CSV.jl on our system, we can bring it into Julia with using, and read in our data with the CSV.read() method:
using CSVdf = CSV.read("weatherHistory.csv")
There are a lot of options with this data-set for both continuous, and categorical features, which will first and foremost allow me to show off Lathe.preprocess’s newest method,
One Hot Encode
The first thing I decided to do is separate the data into two data-frames, one that I would use for our model, and the other will be used to show off the one hot encoder. I did this by first doing
show(df, allcols = true)
and then secondly I constructed two new DataFrame types with the corresponding features:
using DataFrameshotdf = DataFrame(:Humidity => df[:Humidity], :Type => df[Symbol("Precip Type")])df = DataFrame(:Humidity => df[:Humidity],:WindSpeed => df[Symbol("Wind Speed (km/h)")])
Just for the sake of this example, I’m going to pretend that I have no idea how to use Lathe in order to show-off the in-code documentation in Lathe. Firstly, of course we’ll need to load Lathe with using:
using Lathe
And then we can use Julia’s ?() method on the package itself:
?(Lathe)|====== Lathe - Easily ML =====|= = = = = v. 0.0.9 = = = = = ||==============================|__Lathe.stats|__Lathe.validate|__Lathe.preprocess|__Lathe.models|__Use ?(Lathe.package) for information![uuid]38d8eb38-e7b1-11e9-0012-376b6c802672[deps]DataFrames.jlRandom.jl
From this, we are greeted with a module tree which displays three modules:
Lathe.stats
Lathe.validate
Lathe.preprocess
Lathe.models
For a one hot encoder, we’re certainly going to be looking into Lathe.preprocess. The doc-string even clearly states that we can use ?(Lathe.package) for more information, so let’s try that!
And now we can see the OneHotEncode() function inside of the module tree, so let’s do the same on it:
?(Lathe.preprocess.OneHotEncode)
From this we get a brief description, parameters, and even usage. It looks like the function takes a data-frame, along with a symbol representing the column we wish to encode. This of course works about how you would anticipate:
Off-hand methods aside, let’s get back into our original data-frame with our two features, Humidity and Wind Speed. Since the data-set had no missing values on this particular column, and I’m not going to be scaling any features, I decided the first thing to do was go ahead and TrainTestSplit:
using Lathe.preprocess: TrainTestSplittrain, test = TrainTestSplit(df)
This will return two new data-frames, train will account for 75 percent of the data, whereas test will account for the remaining 25. We can adjust this by adding a float percentage after df:
train, test = TrainTestSplit(df, .5)
This would split the data evenly.
For me personally, I like to assign all of my data to variables that can easily be changed prior to even thinking about doing a model. Here is how you do that in Julia:
x = :Humidityy = :WindSpeedtrainX = train[x]trainy = train[y]testX = test[x]testy = test[y]
Next up, we just need to import our model, our prediction function, and then we can construct and fit!
using Lathe.models: predict, LinearRegressionmodel = LinearRegression(trainX, trainy)yhat = predict(model, testX)
And here is the result:
That’s really how easy it is! How can you be upset with that? I’m excited for where Lathe will be in the future and how the module could potential effect Julia in general as a whole. As of right now, Lathe is probably the easiest ML package that you could ever use, and I think most of the learning curve stems from using DataFrames.jl, not Lathe. Overall I’m very excited for what is to come of Lathe in the next version, 0.1.0, and beyond!
|
[
{
"code": null,
"e": 614,
"s": 171,
"text": "Lathe 0.0.9 has just been merged to the Master branch, and with it comes a host of new features that will certainly be exciting to show off. Machine-learning in Julia is now easier than it has ever been before. The only issues currently facing machine-learning in Julia are the lack of a Python-size ecosystem, and the lack of documentation. Fortunately, for Lathe users there are a lot of features and tools at our disposal, and even better:"
},
{
"code": null,
"e": 644,
"s": 614,
"text": "Lathe has good documentation!"
},
{
"code": null,
"e": 953,
"s": 644,
"text": "I found another CSV data-set to work with online. To load this CSV into Julia, we will need the first of our three dependencies, CSV.jl. So with that in mind, the first step is to jump into the Pkg REPL, by first entering the Julia REPL, and then pressing ]. From this REPL we can add our three dependencies:"
},
{
"code": null,
"e": 1022,
"s": 953,
"text": "julia> ]pkg> add \"Lathe\"#Unstablepkg> add \"DataFrames\"pkg> add \"CSV\""
},
{
"code": null,
"e": 1149,
"s": 1022,
"text": "Now that we have CSV.jl on our system, we can bring it into Julia with using, and read in our data with the CSV.read() method:"
},
{
"code": null,
"e": 1194,
"s": 1149,
"text": "using CSVdf = CSV.read(\"weatherHistory.csv\")"
},
{
"code": null,
"e": 1372,
"s": 1194,
"text": "There are a lot of options with this data-set for both continuous, and categorical features, which will first and foremost allow me to show off Lathe.preprocess’s newest method,"
},
{
"code": null,
"e": 1387,
"s": 1372,
"text": "One Hot Encode"
},
{
"code": null,
"e": 1584,
"s": 1387,
"text": "The first thing I decided to do is separate the data into two data-frames, one that I would use for our model, and the other will be used to show off the one hot encoder. I did this by first doing"
},
{
"code": null,
"e": 1609,
"s": 1584,
"text": "show(df, allcols = true)"
},
{
"code": null,
"e": 1698,
"s": 1609,
"text": "and then secondly I constructed two new DataFrame types with the corresponding features:"
},
{
"code": null,
"e": 1884,
"s": 1698,
"text": "using DataFrameshotdf = DataFrame(:Humidity => df[:Humidity], :Type => df[Symbol(\"Precip Type\")])df = DataFrame(:Humidity => df[:Humidity],:WindSpeed => df[Symbol(\"Wind Speed (km/h)\")])"
},
{
"code": null,
"e": 2090,
"s": 1884,
"text": "Just for the sake of this example, I’m going to pretend that I have no idea how to use Lathe in order to show-off the in-code documentation in Lathe. Firstly, of course we’ll need to load Lathe with using:"
},
{
"code": null,
"e": 2102,
"s": 2090,
"text": "using Lathe"
},
{
"code": null,
"e": 2164,
"s": 2102,
"text": "And then we can use Julia’s ?() method on the package itself:"
},
{
"code": null,
"e": 2441,
"s": 2164,
"text": "?(Lathe)|====== Lathe - Easily ML =====|= = = = = v. 0.0.9 = = = = = ||==============================|__Lathe.stats|__Lathe.validate|__Lathe.preprocess|__Lathe.models|__Use ?(Lathe.package) for information![uuid]38d8eb38-e7b1-11e9-0012-376b6c802672[deps]DataFrames.jlRandom.jl"
},
{
"code": null,
"e": 2516,
"s": 2441,
"text": "From this, we are greeted with a module tree which displays three modules:"
},
{
"code": null,
"e": 2528,
"s": 2516,
"text": "Lathe.stats"
},
{
"code": null,
"e": 2543,
"s": 2528,
"text": "Lathe.validate"
},
{
"code": null,
"e": 2560,
"s": 2543,
"text": "Lathe.preprocess"
},
{
"code": null,
"e": 2573,
"s": 2560,
"text": "Lathe.models"
},
{
"code": null,
"e": 2764,
"s": 2573,
"text": "For a one hot encoder, we’re certainly going to be looking into Lathe.preprocess. The doc-string even clearly states that we can use ?(Lathe.package) for more information, so let’s try that!"
},
{
"code": null,
"e": 2866,
"s": 2764,
"text": "And now we can see the OneHotEncode() function inside of the module tree, so let’s do the same on it:"
},
{
"code": null,
"e": 2899,
"s": 2866,
"text": "?(Lathe.preprocess.OneHotEncode)"
},
{
"code": null,
"e": 3128,
"s": 2899,
"text": "From this we get a brief description, parameters, and even usage. It looks like the function takes a data-frame, along with a symbol representing the column we wish to encode. This of course works about how you would anticipate:"
},
{
"code": null,
"e": 3423,
"s": 3128,
"text": "Off-hand methods aside, let’s get back into our original data-frame with our two features, Humidity and Wind Speed. Since the data-set had no missing values on this particular column, and I’m not going to be scaling any features, I decided the first thing to do was go ahead and TrainTestSplit:"
},
{
"code": null,
"e": 3494,
"s": 3423,
"text": "using Lathe.preprocess: TrainTestSplittrain, test = TrainTestSplit(df)"
},
{
"code": null,
"e": 3685,
"s": 3494,
"text": "This will return two new data-frames, train will account for 75 percent of the data, whereas test will account for the remaining 25. We can adjust this by adding a float percentage after df:"
},
{
"code": null,
"e": 3722,
"s": 3685,
"text": "train, test = TrainTestSplit(df, .5)"
},
{
"code": null,
"e": 3756,
"s": 3722,
"text": "This would split the data evenly."
},
{
"code": null,
"e": 3925,
"s": 3756,
"text": "For me personally, I like to assign all of my data to variables that can easily be changed prior to even thinking about doing a model. Here is how you do that in Julia:"
},
{
"code": null,
"e": 4017,
"s": 3925,
"text": "x = :Humidityy = :WindSpeedtrainX = train[x]trainy = train[y]testX = test[x]testy = test[y]"
},
{
"code": null,
"e": 4120,
"s": 4017,
"text": "Next up, we just need to import our model, our prediction function, and then we can construct and fit!"
},
{
"code": null,
"e": 4234,
"s": 4120,
"text": "using Lathe.models: predict, LinearRegressionmodel = LinearRegression(trainX, trainy)yhat = predict(model, testX)"
},
{
"code": null,
"e": 4258,
"s": 4234,
"text": "And here is the result:"
}
] |
Bootstrap - Jumbotron
|
This chapter will discuss one more feature that Bootstrap supports, the Jumbotron. As the name suggest this component can optionally increase the size of headings and add a lot of margin for landing page content. To use the Jumbotron −
Create a container <div> with the class of .jumbotron.
Create a container <div> with the class of .jumbotron.
In addition to a larger <h1>, the font-weight is reduced to 200px.
In addition to a larger <h1>, the font-weight is reduced to 200px.
The following example demonstrates this −
<div class = "container">
<div class = "jumbotron">
<h1>Welcome to landing page!</h1>
<p>This is an example for jumbotron.</p>
<p>
<a class = "btn btn-primary btn-lg" role = "button">Learn more</a>
</p>
</div>
</div>
This is an example for jumbotron.
Learn more
To get a jumbotron of full width, and without rounded corners use the .jumbotron class outside all .container classes and instead add a .container within, as shown in the following example −
<div class = "jumbotron">
<div class = "container">
<h1>Welcome to landing page!</h1>
<p>This is an example for jumbotron.</p>
<p>
<a class = "btn btn-primary btn-lg" role = "button">Learn more</a>
</p>
</div>
</div>
This is an example for jumbotron.
Learn more
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3567,
"s": 3331,
"text": "This chapter will discuss one more feature that Bootstrap supports, the Jumbotron. As the name suggest this component can optionally increase the size of headings and add a lot of margin for landing page content. To use the Jumbotron −"
},
{
"code": null,
"e": 3622,
"s": 3567,
"text": "Create a container <div> with the class of .jumbotron."
},
{
"code": null,
"e": 3677,
"s": 3622,
"text": "Create a container <div> with the class of .jumbotron."
},
{
"code": null,
"e": 3744,
"s": 3677,
"text": "In addition to a larger <h1>, the font-weight is reduced to 200px."
},
{
"code": null,
"e": 3811,
"s": 3744,
"text": "In addition to a larger <h1>, the font-weight is reduced to 200px."
},
{
"code": null,
"e": 3853,
"s": 3811,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 4121,
"s": 3853,
"text": "<div class = \"container\">\n\n <div class = \"jumbotron\">\n <h1>Welcome to landing page!</h1>\n <p>This is an example for jumbotron.</p>\n \n <p>\n <a class = \"btn btn-primary btn-lg\" role = \"button\">Learn more</a>\n </p>\n </div>\n \n</div>"
},
{
"code": null,
"e": 4155,
"s": 4121,
"text": "This is an example for jumbotron."
},
{
"code": null,
"e": 4183,
"s": 4155,
"text": "\n Learn more\n"
},
{
"code": null,
"e": 4375,
"s": 4183,
"text": "To get a jumbotron of full width, and without rounded corners use the .jumbotron class outside all .container classes and instead add a .container within, as shown in the following example −"
},
{
"code": null,
"e": 4646,
"s": 4375,
"text": "<div class = \"jumbotron\">\n \n <div class = \"container\">\n <h1>Welcome to landing page!</h1>\n <p>This is an example for jumbotron.</p>\n \n <p>\n <a class = \"btn btn-primary btn-lg\" role = \"button\">Learn more</a>\n </p>\n </div>\n \n</div>"
},
{
"code": null,
"e": 4680,
"s": 4646,
"text": "This is an example for jumbotron."
},
{
"code": null,
"e": 4708,
"s": 4680,
"text": "\n Learn more\n"
},
{
"code": null,
"e": 4741,
"s": 4708,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4755,
"s": 4741,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4790,
"s": 4755,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4807,
"s": 4790,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4844,
"s": 4807,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 4872,
"s": 4844,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4905,
"s": 4872,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4917,
"s": 4905,
"text": " Azaz Patel"
},
{
"code": null,
"e": 4952,
"s": 4917,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4969,
"s": 4952,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 5002,
"s": 4969,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5022,
"s": 5002,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 5029,
"s": 5022,
"text": " Print"
},
{
"code": null,
"e": 5040,
"s": 5029,
"text": " Add Notes"
}
] |
MySQL query to display structure of a table
|
To display structure of a table, following is the syntax −
show create table yourTableName;
Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> EmployeeFirstName varchar(100),
-> EmployeeLastName varchar(100),
-> EmployeeAge int,
-> isMarried tinyint(1),
-> EmployeeAddress varchar(100),
-> EmployeeCountryName varchar(100)
-> );
Query OK, 0 rows affected (0.62 sec)
Here is the query to display structure −
mysql> show create table DemoTable;
This will produce the following output −
+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table
|
+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DemoTable | CREATE TABLE `DemoTable` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`EmployeeFirstName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`EmployeeLastName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`EmployeeAge` int(11) DEFAULT NULL,
`isMarried` tinyint(1) DEFAULT NULL,
`EmployeeAddress` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`EmployeeCountryName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1121,
"s": 1062,
"text": "To display structure of a table, following is the syntax −"
},
{
"code": null,
"e": 1154,
"s": 1121,
"text": "show create table yourTableName;"
},
{
"code": null,
"e": 1184,
"s": 1154,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1519,
"s": 1184,
"text": "mysql> create table DemoTable\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> EmployeeFirstName varchar(100),\n -> EmployeeLastName varchar(100),\n -> EmployeeAge int,\n -> isMarried tinyint(1),\n -> EmployeeAddress varchar(100),\n -> EmployeeCountryName varchar(100)\n -> );\nQuery OK, 0 rows affected (0.62 sec)"
},
{
"code": null,
"e": 1560,
"s": 1519,
"text": "Here is the query to display structure −"
},
{
"code": null,
"e": 1596,
"s": 1560,
"text": "mysql> show create table DemoTable;"
},
{
"code": null,
"e": 1637,
"s": 1596,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3865,
"s": 1637,
"text": "+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Table | Create Table \n|\n+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| DemoTable | CREATE TABLE `DemoTable` (\n `Id` int(11) NOT NULL AUTO_INCREMENT,\n `EmployeeFirstName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n `EmployeeLastName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n `EmployeeAge` int(11) DEFAULT NULL,\n `isMarried` tinyint(1) DEFAULT NULL,\n `EmployeeAddress` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n `EmployeeCountryName` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`Id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |\n+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)"
}
] |
Render 3D meshes with PyTorch3D | Adele Kuzmiakova | Towards Data Science
|
3D understanding plays a critical role in numerous applications ranging from self-driving cars and autonomous robots to virtual reality and augmented reality. Over the past year, PyTorch3D has become an increasingly popular open-source framework for 3D deep learning with Python. Gratefully, the folks behind the PyTorch3D library have done the legwork of implementing several common 3D operators, loss functions, and differentiable rendering API, making PyTorch3D even more accessible and easier to get started (or play) with [1]. Some of the key PyTorch3D components include:
Data structures for storing and manipulating triangle meshes
Efficient operations on triangle meshes
Differentiable mesh rendering API
Rendering is an essential building block in a computer graphics pipeline that converts 3D representations — be they meshes (.obj) or point clouds (.ply) — into 2D images.
In this post, we’ll build background knowledge on how to render a 3D .obj file from various viewpoints to create 2D images. We’ll also build a basic 3D rendering pipeline using PyTorch3D in Python with components shown below.
This post assumes only a basic knowledge of 3D file representation so hopefully it’ll be accessible for everyone :) However, if you’d like to read more about 3D reconstruction, then check out this fabulous, up-to-date resource list [2] or course notes from Stanford CS231A [3] and CS468 [4] classes.
At the end of this article, you will know how to:
Load a 3D mesh using .obj and .mtl files
Create a renderer
Render the mesh
Optional: Use batch properties to render the mesh efficiently from different viewpoints
Just want the code? The entire code is available in this GitHub repository [5].
Ready? Let’s start! 🎉
We start with importing pre-requisite libraries, such as torch or numpy, and a variety of utility functions and structures from pytorch3d library.
Lastly, line 43 imports class Params from utils.py, which loads the important hyperparameters from a configuration file. Generally, it is a good practice to write all your parameters in a single file and load them from this particular file. This allows you to keep track of the hyperparameters that you are testing and review which hyperparameters led to the best performance. In our case, the hyperparameters are stored in params_demo.json :
Don’t worry if some of those hypeparameters don’t make sense; I’ll explain them later in this tutorial!
Loading the hyperparameters is done via:
params = Params(“params_demo.json”)# Access batch size parameterprint(params.elevation)
Once your params object is initialized, you can also update it with another .json file using params.update("your_other_params.json") method.
Okay, so now that we imported libraries and declared parameters, we can load the mesh. 🎉
There are a couple of ways to represent 3D data, such as point clouds, meshes, or voxels [6]. In this tutorial we’ll focus on 3D meshes although the same procedure in PyTorch3D is applicable to point clouds too [7].
Information about a 3D textured mesh is typically stored in the following files:
.obj file, which stores vertices and faces
.mtl file, which stores material properties
.jpg or .png texture image
In this tutorial, we will be working with a 3D capsule object, which is stored in data/capsule folder. The example files were obtained from a public repository hosted here [8]. To visualize the mesh we are working with, we can use Blender:
PyTorch3D contains several functions to load .obj files, such as load_obj or load_objs_as_meshes. We will use the first one and we load the .obj file using the following syntax:
verts, faces, aux = load_obj(filename)
Here, verts is a (V,3)-tensor of vertices, faces.verts_idx is an (F,3)-tensor of indices for each face corner, and aux stores auxiliary information about the mesh, such as uv coordinates, material colors, or textures. We then pass those verts, faces.verts_idx, and aux structures into the Meshes constructor which creates an object named capsule_mesh:
Lastly, line 33checks the number of faces and vertices in capsule mesh. This returns:
We have 5252 vertices and 10200 faces.
which is what we would expect by checking the .obj file structure.
If you’d like to learn more, the official documentation for Meshes object can be found here [9].
This is probably the most important step. Now that we successfully read our capsule mesh, we need to create a renderer using MeshRenderer class. Looking at MeshRenderer documentation [10], we see that it consists of 2 components:
rasterizer
shader
So let’s break down this task into 2 steps and, at the end, we put them together.
Rasterization refers to taking an image representation described in polygons or triangles (.obj file) and converting it into a raster image described in pixels (.png or .jpg file).
Our rasterizer is created by using a class called MeshRasterizer, which also has several subcomponents, such camerasand raster_settingsarguments. Basically, cameras is responsible for transforming 3D coordinates from the world space to the screen space. To initialize the camera, we need 3 important arguments. These are: 1) distance, 2) azimuth angle, and 3) elevation angle. If that sounds like a lot, don’t worry; I’ll go through them step-by-step.
Distance refers to the distance between the camera and the object.
Elevation angle refers to the angle between the vector from the object to the camera and the horizontal plane y=0 (plane xz). Elevation basically tells us from how high we are looking at the object.
Azimuth angle refers to the vector from the object to the camera is projected onto a horizontal plane y = 0. Azimuth angle is the angle between the projected vector and a reference vector at (0, 0, 1) on the reference plane (the horizontal plane). Azimuth angle takes on values on the interval from 0o to 360o. It basically tells us from which side (e.g. left size, right side, front view, back view, etc.) we are looking at the object. See more info here [11], [12].
In our params.json file (Fig 2), we declared that distance is 3, elevation is 0, and azimuth angle is 90, so if we render this mesh, we should be looking at it directly from distance of 3 units.
Regarding raster settings, the most important parameter is the size of the resulting 2D image. The smaller the size, the more pixelated the image will appear.
PyTorch3D offers multiple types of shaders, including SoftPhongShader or HardPhongShader. Here we’ll use a predefined SoftPhongShader and pass in the camera and the device on which to initialize the default parameters.
Last but not least, we combine both the rasterizer and the shader:
This is a very easy step because we only have to call renderer method on our Meshes object. Let’s render our capsule mesh and plot the results:
The rendered result looks pretty much the same as the Blender visualization in Fig 5, which is a good sign! :)
Using batch properties may potentially be useful if you want to render the mesh from multiple viewpoints. Before we dive into the code, it’s worth understanding how the current batching implementation works. The current implementation relies on a single argument, which is the batch size. This batch size then divides both elevation and azimuth angle space into n equal increments. So, if your batch size is 4, then your elevation and azimuth angle spaces are torch.linspace(0, 360, 4) which is tensor([0, 120, 240, 360]). In each batch, the index moves along both elevation and azimuth angle lists and stops once all elements are exhausted. As a result, we only get 4 rendered pictures: a) with both elev. and azimuth = 0, b) with both elev. and azimuth = 120, c) with both elev. and azimuth = 240, and d) with both elev. and azimuth = 360.
This is analogous to the Python map() function where you pass two iterable arguments — you also don’t get the results from all pair-wise combinations of those two parameters. So if you expect to get all pair-wise combinations of elevations and azimuth angles, then something like list comprehension is one way to go.
Alright, alright, alright, back to batch properties... We set the batch size to 4, which represents the number of viewpoints from which we want to render the mesh. We use this batch size to extend our meshes, elevation vectors, and azimuth angle vectors. After images are rendered, the resulting tensor has shape [4, 256, 256, 4].
Congratulations! 🎉 You have now understood the ins and outs of how to render a 3D mesh from a single and multiple viewpoints.
Here’s what we’ve gone through:
We’ve seen the installation of PyTorch3D
We’ve loaded the mesh and textures from .obj and .mtl files
We’ve created a renderer to render the mesh
We’ve utilized PyTorch3D batching features to extend the mesh and render it from multiple viewpoints in a single forward pass
I’ve helped you to explore some basic PyTorch3D properties but please don’t stop here. It’s just the beginning and it’s up to you where this journey will take you!
Like the tutorial and have any comments or suggestions? Anything I may have missed? I’d love to hear your thoughts :) Send me a message or follow me on GitHub!
|
[
{
"code": null,
"e": 750,
"s": 172,
"text": "3D understanding plays a critical role in numerous applications ranging from self-driving cars and autonomous robots to virtual reality and augmented reality. Over the past year, PyTorch3D has become an increasingly popular open-source framework for 3D deep learning with Python. Gratefully, the folks behind the PyTorch3D library have done the legwork of implementing several common 3D operators, loss functions, and differentiable rendering API, making PyTorch3D even more accessible and easier to get started (or play) with [1]. Some of the key PyTorch3D components include:"
},
{
"code": null,
"e": 811,
"s": 750,
"text": "Data structures for storing and manipulating triangle meshes"
},
{
"code": null,
"e": 851,
"s": 811,
"text": "Efficient operations on triangle meshes"
},
{
"code": null,
"e": 885,
"s": 851,
"text": "Differentiable mesh rendering API"
},
{
"code": null,
"e": 1056,
"s": 885,
"text": "Rendering is an essential building block in a computer graphics pipeline that converts 3D representations — be they meshes (.obj) or point clouds (.ply) — into 2D images."
},
{
"code": null,
"e": 1282,
"s": 1056,
"text": "In this post, we’ll build background knowledge on how to render a 3D .obj file from various viewpoints to create 2D images. We’ll also build a basic 3D rendering pipeline using PyTorch3D in Python with components shown below."
},
{
"code": null,
"e": 1582,
"s": 1282,
"text": "This post assumes only a basic knowledge of 3D file representation so hopefully it’ll be accessible for everyone :) However, if you’d like to read more about 3D reconstruction, then check out this fabulous, up-to-date resource list [2] or course notes from Stanford CS231A [3] and CS468 [4] classes."
},
{
"code": null,
"e": 1632,
"s": 1582,
"text": "At the end of this article, you will know how to:"
},
{
"code": null,
"e": 1673,
"s": 1632,
"text": "Load a 3D mesh using .obj and .mtl files"
},
{
"code": null,
"e": 1691,
"s": 1673,
"text": "Create a renderer"
},
{
"code": null,
"e": 1707,
"s": 1691,
"text": "Render the mesh"
},
{
"code": null,
"e": 1795,
"s": 1707,
"text": "Optional: Use batch properties to render the mesh efficiently from different viewpoints"
},
{
"code": null,
"e": 1875,
"s": 1795,
"text": "Just want the code? The entire code is available in this GitHub repository [5]."
},
{
"code": null,
"e": 1897,
"s": 1875,
"text": "Ready? Let’s start! 🎉"
},
{
"code": null,
"e": 2044,
"s": 1897,
"text": "We start with importing pre-requisite libraries, such as torch or numpy, and a variety of utility functions and structures from pytorch3d library."
},
{
"code": null,
"e": 2487,
"s": 2044,
"text": "Lastly, line 43 imports class Params from utils.py, which loads the important hyperparameters from a configuration file. Generally, it is a good practice to write all your parameters in a single file and load them from this particular file. This allows you to keep track of the hyperparameters that you are testing and review which hyperparameters led to the best performance. In our case, the hyperparameters are stored in params_demo.json :"
},
{
"code": null,
"e": 2591,
"s": 2487,
"text": "Don’t worry if some of those hypeparameters don’t make sense; I’ll explain them later in this tutorial!"
},
{
"code": null,
"e": 2632,
"s": 2591,
"text": "Loading the hyperparameters is done via:"
},
{
"code": null,
"e": 2720,
"s": 2632,
"text": "params = Params(“params_demo.json”)# Access batch size parameterprint(params.elevation)"
},
{
"code": null,
"e": 2861,
"s": 2720,
"text": "Once your params object is initialized, you can also update it with another .json file using params.update(\"your_other_params.json\") method."
},
{
"code": null,
"e": 2950,
"s": 2861,
"text": "Okay, so now that we imported libraries and declared parameters, we can load the mesh. 🎉"
},
{
"code": null,
"e": 3166,
"s": 2950,
"text": "There are a couple of ways to represent 3D data, such as point clouds, meshes, or voxels [6]. In this tutorial we’ll focus on 3D meshes although the same procedure in PyTorch3D is applicable to point clouds too [7]."
},
{
"code": null,
"e": 3247,
"s": 3166,
"text": "Information about a 3D textured mesh is typically stored in the following files:"
},
{
"code": null,
"e": 3290,
"s": 3247,
"text": ".obj file, which stores vertices and faces"
},
{
"code": null,
"e": 3334,
"s": 3290,
"text": ".mtl file, which stores material properties"
},
{
"code": null,
"e": 3361,
"s": 3334,
"text": ".jpg or .png texture image"
},
{
"code": null,
"e": 3601,
"s": 3361,
"text": "In this tutorial, we will be working with a 3D capsule object, which is stored in data/capsule folder. The example files were obtained from a public repository hosted here [8]. To visualize the mesh we are working with, we can use Blender:"
},
{
"code": null,
"e": 3779,
"s": 3601,
"text": "PyTorch3D contains several functions to load .obj files, such as load_obj or load_objs_as_meshes. We will use the first one and we load the .obj file using the following syntax:"
},
{
"code": null,
"e": 3818,
"s": 3779,
"text": "verts, faces, aux = load_obj(filename)"
},
{
"code": null,
"e": 4170,
"s": 3818,
"text": "Here, verts is a (V,3)-tensor of vertices, faces.verts_idx is an (F,3)-tensor of indices for each face corner, and aux stores auxiliary information about the mesh, such as uv coordinates, material colors, or textures. We then pass those verts, faces.verts_idx, and aux structures into the Meshes constructor which creates an object named capsule_mesh:"
},
{
"code": null,
"e": 4256,
"s": 4170,
"text": "Lastly, line 33checks the number of faces and vertices in capsule mesh. This returns:"
},
{
"code": null,
"e": 4295,
"s": 4256,
"text": "We have 5252 vertices and 10200 faces."
},
{
"code": null,
"e": 4362,
"s": 4295,
"text": "which is what we would expect by checking the .obj file structure."
},
{
"code": null,
"e": 4459,
"s": 4362,
"text": "If you’d like to learn more, the official documentation for Meshes object can be found here [9]."
},
{
"code": null,
"e": 4689,
"s": 4459,
"text": "This is probably the most important step. Now that we successfully read our capsule mesh, we need to create a renderer using MeshRenderer class. Looking at MeshRenderer documentation [10], we see that it consists of 2 components:"
},
{
"code": null,
"e": 4700,
"s": 4689,
"text": "rasterizer"
},
{
"code": null,
"e": 4707,
"s": 4700,
"text": "shader"
},
{
"code": null,
"e": 4789,
"s": 4707,
"text": "So let’s break down this task into 2 steps and, at the end, we put them together."
},
{
"code": null,
"e": 4970,
"s": 4789,
"text": "Rasterization refers to taking an image representation described in polygons or triangles (.obj file) and converting it into a raster image described in pixels (.png or .jpg file)."
},
{
"code": null,
"e": 5422,
"s": 4970,
"text": "Our rasterizer is created by using a class called MeshRasterizer, which also has several subcomponents, such camerasand raster_settingsarguments. Basically, cameras is responsible for transforming 3D coordinates from the world space to the screen space. To initialize the camera, we need 3 important arguments. These are: 1) distance, 2) azimuth angle, and 3) elevation angle. If that sounds like a lot, don’t worry; I’ll go through them step-by-step."
},
{
"code": null,
"e": 5489,
"s": 5422,
"text": "Distance refers to the distance between the camera and the object."
},
{
"code": null,
"e": 5688,
"s": 5489,
"text": "Elevation angle refers to the angle between the vector from the object to the camera and the horizontal plane y=0 (plane xz). Elevation basically tells us from how high we are looking at the object."
},
{
"code": null,
"e": 6156,
"s": 5688,
"text": "Azimuth angle refers to the vector from the object to the camera is projected onto a horizontal plane y = 0. Azimuth angle is the angle between the projected vector and a reference vector at (0, 0, 1) on the reference plane (the horizontal plane). Azimuth angle takes on values on the interval from 0o to 360o. It basically tells us from which side (e.g. left size, right side, front view, back view, etc.) we are looking at the object. See more info here [11], [12]."
},
{
"code": null,
"e": 6351,
"s": 6156,
"text": "In our params.json file (Fig 2), we declared that distance is 3, elevation is 0, and azimuth angle is 90, so if we render this mesh, we should be looking at it directly from distance of 3 units."
},
{
"code": null,
"e": 6510,
"s": 6351,
"text": "Regarding raster settings, the most important parameter is the size of the resulting 2D image. The smaller the size, the more pixelated the image will appear."
},
{
"code": null,
"e": 6729,
"s": 6510,
"text": "PyTorch3D offers multiple types of shaders, including SoftPhongShader or HardPhongShader. Here we’ll use a predefined SoftPhongShader and pass in the camera and the device on which to initialize the default parameters."
},
{
"code": null,
"e": 6796,
"s": 6729,
"text": "Last but not least, we combine both the rasterizer and the shader:"
},
{
"code": null,
"e": 6940,
"s": 6796,
"text": "This is a very easy step because we only have to call renderer method on our Meshes object. Let’s render our capsule mesh and plot the results:"
},
{
"code": null,
"e": 7051,
"s": 6940,
"text": "The rendered result looks pretty much the same as the Blender visualization in Fig 5, which is a good sign! :)"
},
{
"code": null,
"e": 7893,
"s": 7051,
"text": "Using batch properties may potentially be useful if you want to render the mesh from multiple viewpoints. Before we dive into the code, it’s worth understanding how the current batching implementation works. The current implementation relies on a single argument, which is the batch size. This batch size then divides both elevation and azimuth angle space into n equal increments. So, if your batch size is 4, then your elevation and azimuth angle spaces are torch.linspace(0, 360, 4) which is tensor([0, 120, 240, 360]). In each batch, the index moves along both elevation and azimuth angle lists and stops once all elements are exhausted. As a result, we only get 4 rendered pictures: a) with both elev. and azimuth = 0, b) with both elev. and azimuth = 120, c) with both elev. and azimuth = 240, and d) with both elev. and azimuth = 360."
},
{
"code": null,
"e": 8210,
"s": 7893,
"text": "This is analogous to the Python map() function where you pass two iterable arguments — you also don’t get the results from all pair-wise combinations of those two parameters. So if you expect to get all pair-wise combinations of elevations and azimuth angles, then something like list comprehension is one way to go."
},
{
"code": null,
"e": 8541,
"s": 8210,
"text": "Alright, alright, alright, back to batch properties... We set the batch size to 4, which represents the number of viewpoints from which we want to render the mesh. We use this batch size to extend our meshes, elevation vectors, and azimuth angle vectors. After images are rendered, the resulting tensor has shape [4, 256, 256, 4]."
},
{
"code": null,
"e": 8667,
"s": 8541,
"text": "Congratulations! 🎉 You have now understood the ins and outs of how to render a 3D mesh from a single and multiple viewpoints."
},
{
"code": null,
"e": 8699,
"s": 8667,
"text": "Here’s what we’ve gone through:"
},
{
"code": null,
"e": 8740,
"s": 8699,
"text": "We’ve seen the installation of PyTorch3D"
},
{
"code": null,
"e": 8800,
"s": 8740,
"text": "We’ve loaded the mesh and textures from .obj and .mtl files"
},
{
"code": null,
"e": 8844,
"s": 8800,
"text": "We’ve created a renderer to render the mesh"
},
{
"code": null,
"e": 8970,
"s": 8844,
"text": "We’ve utilized PyTorch3D batching features to extend the mesh and render it from multiple viewpoints in a single forward pass"
},
{
"code": null,
"e": 9134,
"s": 8970,
"text": "I’ve helped you to explore some basic PyTorch3D properties but please don’t stop here. It’s just the beginning and it’s up to you where this journey will take you!"
}
] |
How to extract data from a Matplotlib plot?
|
To extract data from a plot in matplotlib, we can use get_xdata() and get_ydata() methods.
Set the figure size and adjust the padding between and around the subplots.
Create y data points using numpy.
Plot y data points with color=red and linewidth=5.
Print a statment for data extraction.
Use get_xdata() and get_ydata() methods to extract the data from the plot (step 3).
Print x and y data (Step 5).
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
y = np.array([1, 3, 2, 5, 2, 3, 1])
curve, = plt.plot(y, c='red', lw=5)
print("Extracting data from plot....")
xdata = curve.get_xdata()
ydata = curve.get_ydata()
print("X data points for the plot is: ", xdata)
print("Y data points for the plot is: ", ydata)
plt.show()
Extracting data from plot....
X data points for the plot is: [0. 1. 2. 3. 4. 5. 6.]
Y data points for the plot is: [1 3 2 5 2 3 1]
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "To extract data from a plot in matplotlib, we can use get_xdata() and get_ydata() methods."
},
{
"code": null,
"e": 1229,
"s": 1153,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1263,
"s": 1229,
"text": "Create y data points using numpy."
},
{
"code": null,
"e": 1314,
"s": 1263,
"text": "Plot y data points with color=red and linewidth=5."
},
{
"code": null,
"e": 1352,
"s": 1314,
"text": "Print a statment for data extraction."
},
{
"code": null,
"e": 1436,
"s": 1352,
"text": "Use get_xdata() and get_ydata() methods to extract the data from the plot (step 3)."
},
{
"code": null,
"e": 1465,
"s": 1436,
"text": "Print x and y data (Step 5)."
},
{
"code": null,
"e": 1507,
"s": 1465,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1920,
"s": 1507,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ny = np.array([1, 3, 2, 5, 2, 3, 1])\ncurve, = plt.plot(y, c='red', lw=5)\nprint(\"Extracting data from plot....\")\nxdata = curve.get_xdata()\nydata = curve.get_ydata()\nprint(\"X data points for the plot is: \", xdata)\nprint(\"Y data points for the plot is: \", ydata)\nplt.show()"
},
{
"code": null,
"e": 2051,
"s": 1920,
"text": "Extracting data from plot....\nX data points for the plot is: [0. 1. 2. 3. 4. 5. 6.]\nY data points for the plot is: [1 3 2 5 2 3 1]"
}
] |
Implementing DBSCAN algorithm using Sklearn - GeeksforGeeks
|
06 Jun, 2019
Prerequisites: DBSCAN Algorithm
Density Based Spatial Clustering of Applications with Noise(DBCSAN) is a clustering algorithm which was proposed in 1996. In 2014, the algorithm was awarded the ‘Test of Time’ award at the leading Data Mining conference, KDD.
Dataset – Credit Card.
Step 1: Importing the required libraries
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt from sklearn.cluster import DBSCANfrom sklearn.preprocessing import StandardScalerfrom sklearn.preprocessing import normalizefrom sklearn.decomposition import PCA
Step 2: Loading the data
X = pd.read_csv('..input_path/CC_GENERAL.csv') # Dropping the CUST_ID column from the dataX = X.drop('CUST_ID', axis = 1) # Handling the missing valuesX.fillna(method ='ffill', inplace = True) print(X.head())
Step 3: Preprocessing the data
# Scaling the data to bring all the attributes to a comparable levelscaler = StandardScaler()X_scaled = scaler.fit_transform(X) # Normalizing the data so that # the data approximately follows a Gaussian distributionX_normalized = normalize(X_scaled) # Converting the numpy array into a pandas DataFrameX_normalized = pd.DataFrame(X_normalized)
Step 4: Reducing the dimensionality of the data to make it visualizable
pca = PCA(n_components = 2)X_principal = pca.fit_transform(X_normalized)X_principal = pd.DataFrame(X_principal)X_principal.columns = ['P1', 'P2']print(X_principal.head())
Step 5: Building the clustering model
# Numpy array of all the cluster labels assigned to each data pointdb_default = DBSCAN(eps = 0.0375, min_samples = 3).fit(X_principal)labels = db_default.labels_
Step 6: Visualizing the clustering
# Building the label to colour mappingcolours = {}colours[0] = 'r'colours[1] = 'g'colours[2] = 'b'colours[-1] = 'k' # Building the colour vector for each data pointcvec = [colours[label] for label in labels] # For the construction of the legend of the plotr = plt.scatter(X_principal['P1'], X_principal['P2'], color ='r');g = plt.scatter(X_principal['P1'], X_principal['P2'], color ='g');b = plt.scatter(X_principal['P1'], X_principal['P2'], color ='b');k = plt.scatter(X_principal['P1'], X_principal['P2'], color ='k'); # Plotting P1 on the X-Axis and P2 on the Y-Axis # according to the colour vector definedplt.figure(figsize =(9, 9))plt.scatter(X_principal['P1'], X_principal['P2'], c = cvec) # Building the legendplt.legend((r, g, b, k), ('Label 0', 'Label 1', 'Label 2', 'Label -1')) plt.show()
Step 7: Tuning the parameters of the model
db = DBSCAN(eps = 0.0375, min_samples = 50).fit(X_principal)labels1 = db.labels_
Step 8: Visualizing the changes
colours1 = {}colours1[0] = 'r'colours1[1] = 'g'colours1[2] = 'b'colours1[3] = 'c'colours1[4] = 'y'colours1[5] = 'm'colours1[-1] = 'k' cvec = [colours1[label] for label in labels]colors = ['r', 'g', 'b', 'c', 'y', 'm', 'k' ] r = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[0])g = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[1])b = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[2])c = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[3])y = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[4])m = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[5])k = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[6]) plt.figure(figsize =(9, 9))plt.scatter(X_principal['P1'], X_principal['P2'], c = cvec)plt.legend((r, g, b, c, y, m, k), ('Label 0', 'Label 1', 'Label 2', 'Label 3 'Label 4', 'Label 5', 'Label -1'), scatterpoints = 1, loc ='upper left', ncol = 3, fontsize = 8)plt.show()
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Elbow Method for optimal value of k in KMeans
Principal Component Analysis with Python
Python | Lemmatization with NLTK
ML | Logistic Regression using Python
Decision Tree
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24009,
"s": 23981,
"text": "\n06 Jun, 2019"
},
{
"code": null,
"e": 24041,
"s": 24009,
"text": "Prerequisites: DBSCAN Algorithm"
},
{
"code": null,
"e": 24267,
"s": 24041,
"text": "Density Based Spatial Clustering of Applications with Noise(DBCSAN) is a clustering algorithm which was proposed in 1996. In 2014, the algorithm was awarded the ‘Test of Time’ award at the leading Data Mining conference, KDD."
},
{
"code": null,
"e": 24290,
"s": 24267,
"text": "Dataset – Credit Card."
},
{
"code": null,
"e": 24331,
"s": 24290,
"text": "Step 1: Importing the required libraries"
},
{
"code": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt from sklearn.cluster import DBSCANfrom sklearn.preprocessing import StandardScalerfrom sklearn.preprocessing import normalizefrom sklearn.decomposition import PCA",
"e": 24564,
"s": 24331,
"text": null
},
{
"code": null,
"e": 24589,
"s": 24564,
"text": "Step 2: Loading the data"
},
{
"code": "X = pd.read_csv('..input_path/CC_GENERAL.csv') # Dropping the CUST_ID column from the dataX = X.drop('CUST_ID', axis = 1) # Handling the missing valuesX.fillna(method ='ffill', inplace = True) print(X.head())",
"e": 24801,
"s": 24589,
"text": null
},
{
"code": null,
"e": 24832,
"s": 24801,
"text": "Step 3: Preprocessing the data"
},
{
"code": "# Scaling the data to bring all the attributes to a comparable levelscaler = StandardScaler()X_scaled = scaler.fit_transform(X) # Normalizing the data so that # the data approximately follows a Gaussian distributionX_normalized = normalize(X_scaled) # Converting the numpy array into a pandas DataFrameX_normalized = pd.DataFrame(X_normalized)",
"e": 25178,
"s": 24832,
"text": null
},
{
"code": null,
"e": 25250,
"s": 25178,
"text": "Step 4: Reducing the dimensionality of the data to make it visualizable"
},
{
"code": "pca = PCA(n_components = 2)X_principal = pca.fit_transform(X_normalized)X_principal = pd.DataFrame(X_principal)X_principal.columns = ['P1', 'P2']print(X_principal.head())",
"e": 25421,
"s": 25250,
"text": null
},
{
"code": null,
"e": 25459,
"s": 25421,
"text": "Step 5: Building the clustering model"
},
{
"code": "# Numpy array of all the cluster labels assigned to each data pointdb_default = DBSCAN(eps = 0.0375, min_samples = 3).fit(X_principal)labels = db_default.labels_",
"e": 25621,
"s": 25459,
"text": null
},
{
"code": null,
"e": 25656,
"s": 25621,
"text": "Step 6: Visualizing the clustering"
},
{
"code": "# Building the label to colour mappingcolours = {}colours[0] = 'r'colours[1] = 'g'colours[2] = 'b'colours[-1] = 'k' # Building the colour vector for each data pointcvec = [colours[label] for label in labels] # For the construction of the legend of the plotr = plt.scatter(X_principal['P1'], X_principal['P2'], color ='r');g = plt.scatter(X_principal['P1'], X_principal['P2'], color ='g');b = plt.scatter(X_principal['P1'], X_principal['P2'], color ='b');k = plt.scatter(X_principal['P1'], X_principal['P2'], color ='k'); # Plotting P1 on the X-Axis and P2 on the Y-Axis # according to the colour vector definedplt.figure(figsize =(9, 9))plt.scatter(X_principal['P1'], X_principal['P2'], c = cvec) # Building the legendplt.legend((r, g, b, k), ('Label 0', 'Label 1', 'Label 2', 'Label -1')) plt.show()",
"e": 26462,
"s": 25656,
"text": null
},
{
"code": null,
"e": 26505,
"s": 26462,
"text": "Step 7: Tuning the parameters of the model"
},
{
"code": "db = DBSCAN(eps = 0.0375, min_samples = 50).fit(X_principal)labels1 = db.labels_",
"e": 26586,
"s": 26505,
"text": null
},
{
"code": null,
"e": 26618,
"s": 26586,
"text": "Step 8: Visualizing the changes"
},
{
"code": "colours1 = {}colours1[0] = 'r'colours1[1] = 'g'colours1[2] = 'b'colours1[3] = 'c'colours1[4] = 'y'colours1[5] = 'm'colours1[-1] = 'k' cvec = [colours1[label] for label in labels]colors = ['r', 'g', 'b', 'c', 'y', 'm', 'k' ] r = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[0])g = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[1])b = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[2])c = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[3])y = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[4])m = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[5])k = plt.scatter( X_principal['P1'], X_principal['P2'], marker ='o', color = colors[6]) plt.figure(figsize =(9, 9))plt.scatter(X_principal['P1'], X_principal['P2'], c = cvec)plt.legend((r, g, b, c, y, m, k), ('Label 0', 'Label 1', 'Label 2', 'Label 3 'Label 4', 'Label 5', 'Label -1'), scatterpoints = 1, loc ='upper left', ncol = 3, fontsize = 8)plt.show()",
"e": 27828,
"s": 26618,
"text": null
},
{
"code": null,
"e": 27845,
"s": 27828,
"text": "Machine Learning"
},
{
"code": null,
"e": 27852,
"s": 27845,
"text": "Python"
},
{
"code": null,
"e": 27869,
"s": 27852,
"text": "Machine Learning"
},
{
"code": null,
"e": 27967,
"s": 27869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27976,
"s": 27967,
"text": "Comments"
},
{
"code": null,
"e": 27989,
"s": 27976,
"text": "Old Comments"
},
{
"code": null,
"e": 28035,
"s": 27989,
"text": "Elbow Method for optimal value of k in KMeans"
},
{
"code": null,
"e": 28076,
"s": 28035,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 28109,
"s": 28076,
"text": "Python | Lemmatization with NLTK"
},
{
"code": null,
"e": 28147,
"s": 28109,
"text": "ML | Logistic Regression using Python"
},
{
"code": null,
"e": 28161,
"s": 28147,
"text": "Decision Tree"
},
{
"code": null,
"e": 28189,
"s": 28161,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28239,
"s": 28189,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28261,
"s": 28239,
"text": "Python map() function"
}
] |
Python Tweepy – Getting the number of tweets a user has tweeted - GeeksforGeeks
|
18 Jun, 2020
In this article we will see how we can get number of statuses/tweets a user has tweeted/updated. The statuses_count attribute provides us with an integer which denotes the number of statuses the user has posted.
Identifying the date when a user was created in the GUI :
In the above mentioned profile, number of statuses the user has posted : 13.2K (13, 200+)
In order to get the number of statuses a user has posted, we have to do the following :
Identify the user ID or the screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the statuses_count attribute present in it.
Identify the user ID or the screen name of the profile.
Get the User object of the profile using the get_user() method with the user ID or the screen name.
From this object, fetch the statuses_count attribute present in it.
Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058.
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the statuses_count attributestatuses_count = user.statuses_count print("The number of statuses the user has posted are : " + str(statuses_count))
Output :
The number of statuses the user has posted are : 13239
Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG.
# the screen name of the userscreen_name = "PracticeGfG" # fetching the useruser = api.get_user(screen_name) # fetching the statuses_count attributestatuses_count = user.statuses_count print("The number of statuses the user has posted are : " + str(statuses_count))
Output :
The number of statuses the user has posted are : 2265
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
|
[
{
"code": null,
"e": 24101,
"s": 24073,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 24313,
"s": 24101,
"text": "In this article we will see how we can get number of statuses/tweets a user has tweeted/updated. The statuses_count attribute provides us with an integer which denotes the number of statuses the user has posted."
},
{
"code": null,
"e": 24371,
"s": 24313,
"text": "Identifying the date when a user was created in the GUI :"
},
{
"code": null,
"e": 24461,
"s": 24371,
"text": "In the above mentioned profile, number of statuses the user has posted : 13.2K (13, 200+)"
},
{
"code": null,
"e": 24549,
"s": 24461,
"text": "In order to get the number of statuses a user has posted, we have to do the following :"
},
{
"code": null,
"e": 24771,
"s": 24549,
"text": "Identify the user ID or the screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the statuses_count attribute present in it."
},
{
"code": null,
"e": 24827,
"s": 24771,
"text": "Identify the user ID or the screen name of the profile."
},
{
"code": null,
"e": 24927,
"s": 24827,
"text": "Get the User object of the profile using the get_user() method with the user ID or the screen name."
},
{
"code": null,
"e": 24995,
"s": 24927,
"text": "From this object, fetch the statuses_count attribute present in it."
},
{
"code": null,
"e": 25137,
"s": 24995,
"text": "Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058."
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the statuses_count attributestatuses_count = user.statuses_count print(\"The number of statuses the user has posted are : \" + str(statuses_count))",
"e": 25782,
"s": 25137,
"text": null
},
{
"code": null,
"e": 25791,
"s": 25782,
"text": "Output :"
},
{
"code": null,
"e": 25847,
"s": 25791,
"text": "The number of statuses the user has posted are : 13239\n"
},
{
"code": null,
"e": 26000,
"s": 25847,
"text": "Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG."
},
{
"code": "# the screen name of the userscreen_name = \"PracticeGfG\" # fetching the useruser = api.get_user(screen_name) # fetching the statuses_count attributestatuses_count = user.statuses_count print(\"The number of statuses the user has posted are : \" + str(statuses_count))",
"e": 26270,
"s": 26000,
"text": null
},
{
"code": null,
"e": 26279,
"s": 26270,
"text": "Output :"
},
{
"code": null,
"e": 26334,
"s": 26279,
"text": "The number of statuses the user has posted are : 2265\n"
},
{
"code": null,
"e": 26348,
"s": 26334,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 26355,
"s": 26348,
"text": "Python"
},
{
"code": null,
"e": 26453,
"s": 26355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26462,
"s": 26453,
"text": "Comments"
},
{
"code": null,
"e": 26475,
"s": 26462,
"text": "Old Comments"
},
{
"code": null,
"e": 26493,
"s": 26475,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26515,
"s": 26493,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26547,
"s": 26515,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26589,
"s": 26547,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26615,
"s": 26589,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26659,
"s": 26615,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26684,
"s": 26659,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26721,
"s": 26684,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26777,
"s": 26721,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Visualizing marginal effects using ggeffects in R | by Matthieu Renard | Towards Data Science
|
It’s a known dilemma: You know that your variable X1 impacts your variable Y, and you can show it in a regression analysis, but it is hard to show it graphically. The reason is that there is another variable impacting Y, namely X2, and only after the effect of X2 is taken into account does the effect of X1 on Y appear. So you would need a way of showing how X1 impacts Y while taking the effect of X2 into account.
This is where marginal effects come in handy. They enable you to show how a change of the independent variable of interest impacts your dependent variable while taking all other independent variables into account. More specifically, you could use the package ggeffects to visualize the marginal effects of key variables.
The following tutorial will use the salaries dataset available in base R. It contains data on professors' salaries and several other variables that would intuitively influence their salary.
You can load it by simply entering this command.
df=Salaries
We want to answer the key question in this dataset: Does a professor’s sex influence their salary?
Naively, one could try to answer this question by simply running the below regression model:
fit1=lm(salary~sex,df)summary(fit1)
Just looking at the output, it seems that sex influences a professor’s salary. Also, when plotting the impact of sex on salary, the impact seems to be significant.
#install and load ggplotinstall.packages("ggplot2")library(ggplot2)#plot the relationshipggplot(df,aes(y=salary, x=sex))+ stat_summary(fun.y="mean", geom="bar",position="dodge")+ stat_summary(fun.data = mean_se, geom = "errorbar", position="dodge",width=.8)+ labs( x="Sex", y="Salary", title="The Effect of Sex on Salary" )
However, the question is: Is it sex that is driving this difference, or is sex correlated to a more immediate predictor of salary? This question is easy to answer in a regression. One adds more covariates to check if it really is sex driving the difference or something else.
fit2=lm(salary~sex+yrs.since.phd+yrs.service+rank+discipline,df)summary(fit2)
As one can see, the marginal effect of sex now is insignificant, implying that sex isn’t an actual predictor of salary in this dataset, but rather that it is correlated with one of the other variables in the dataset, which can be summarized as indicators of seniority and the academic discipline.
So we know that sex is not a significant predictor of salary. But if we were to plot the relationship between sex and salary — as in the above plot — it would look as if sex were an actual salary predictor. What if we wanted to plot the actual effect of sex on a salary after taking all other covariates into account — i.e., plot the marginal effect? This is where ggeffects comes into play.
So, we install ggeffects and load it, if we haven’t done so already.
install.packages("ggeffects")library(ggeffects)
Then we use the ggpredict function from the ggeffects package and predict the marginal effect for each sex in the dataset. We save the output, a tidy data frame, under the name dummy.
dummy=ggpredict(fit2, terms = "sex")
Then, we use ggplot to plot these marginal effects.
ggplot(dummy, aes(x=x, y=predicted)) + geom_bar(stat = "identity", position = position_dodge()) + geom_errorbar(aes(ymin = conf.low, ymax = conf.high), alpha = .9,position = position_dodge())+ labs( x="Sex", y="Salary", title="The Marginal Effect of Sex on Salary" )+scale_x_continuous(breaks=c(1,2) ,labels = c("Female", "Male"))
We can now plot the actual marginal effect of sex on a salary after controlling for all other predictors.
Found this story interesting? Follow me on Medium to see my other stories!
|
[
{
"code": null,
"e": 588,
"s": 171,
"text": "It’s a known dilemma: You know that your variable X1 impacts your variable Y, and you can show it in a regression analysis, but it is hard to show it graphically. The reason is that there is another variable impacting Y, namely X2, and only after the effect of X2 is taken into account does the effect of X1 on Y appear. So you would need a way of showing how X1 impacts Y while taking the effect of X2 into account."
},
{
"code": null,
"e": 909,
"s": 588,
"text": "This is where marginal effects come in handy. They enable you to show how a change of the independent variable of interest impacts your dependent variable while taking all other independent variables into account. More specifically, you could use the package ggeffects to visualize the marginal effects of key variables."
},
{
"code": null,
"e": 1099,
"s": 909,
"text": "The following tutorial will use the salaries dataset available in base R. It contains data on professors' salaries and several other variables that would intuitively influence their salary."
},
{
"code": null,
"e": 1148,
"s": 1099,
"text": "You can load it by simply entering this command."
},
{
"code": null,
"e": 1160,
"s": 1148,
"text": "df=Salaries"
},
{
"code": null,
"e": 1259,
"s": 1160,
"text": "We want to answer the key question in this dataset: Does a professor’s sex influence their salary?"
},
{
"code": null,
"e": 1352,
"s": 1259,
"text": "Naively, one could try to answer this question by simply running the below regression model:"
},
{
"code": null,
"e": 1388,
"s": 1352,
"text": "fit1=lm(salary~sex,df)summary(fit1)"
},
{
"code": null,
"e": 1552,
"s": 1388,
"text": "Just looking at the output, it seems that sex influences a professor’s salary. Also, when plotting the impact of sex on salary, the impact seems to be significant."
},
{
"code": null,
"e": 1889,
"s": 1552,
"text": "#install and load ggplotinstall.packages(\"ggplot2\")library(ggplot2)#plot the relationshipggplot(df,aes(y=salary, x=sex))+ stat_summary(fun.y=\"mean\", geom=\"bar\",position=\"dodge\")+ stat_summary(fun.data = mean_se, geom = \"errorbar\", position=\"dodge\",width=.8)+ labs( x=\"Sex\", y=\"Salary\", title=\"The Effect of Sex on Salary\" )"
},
{
"code": null,
"e": 2165,
"s": 1889,
"text": "However, the question is: Is it sex that is driving this difference, or is sex correlated to a more immediate predictor of salary? This question is easy to answer in a regression. One adds more covariates to check if it really is sex driving the difference or something else."
},
{
"code": null,
"e": 2243,
"s": 2165,
"text": "fit2=lm(salary~sex+yrs.since.phd+yrs.service+rank+discipline,df)summary(fit2)"
},
{
"code": null,
"e": 2540,
"s": 2243,
"text": "As one can see, the marginal effect of sex now is insignificant, implying that sex isn’t an actual predictor of salary in this dataset, but rather that it is correlated with one of the other variables in the dataset, which can be summarized as indicators of seniority and the academic discipline."
},
{
"code": null,
"e": 2932,
"s": 2540,
"text": "So we know that sex is not a significant predictor of salary. But if we were to plot the relationship between sex and salary — as in the above plot — it would look as if sex were an actual salary predictor. What if we wanted to plot the actual effect of sex on a salary after taking all other covariates into account — i.e., plot the marginal effect? This is where ggeffects comes into play."
},
{
"code": null,
"e": 3001,
"s": 2932,
"text": "So, we install ggeffects and load it, if we haven’t done so already."
},
{
"code": null,
"e": 3049,
"s": 3001,
"text": "install.packages(\"ggeffects\")library(ggeffects)"
},
{
"code": null,
"e": 3233,
"s": 3049,
"text": "Then we use the ggpredict function from the ggeffects package and predict the marginal effect for each sex in the dataset. We save the output, a tidy data frame, under the name dummy."
},
{
"code": null,
"e": 3270,
"s": 3233,
"text": "dummy=ggpredict(fit2, terms = \"sex\")"
},
{
"code": null,
"e": 3322,
"s": 3270,
"text": "Then, we use ggplot to plot these marginal effects."
},
{
"code": null,
"e": 3666,
"s": 3322,
"text": "ggplot(dummy, aes(x=x, y=predicted)) + geom_bar(stat = \"identity\", position = position_dodge()) + geom_errorbar(aes(ymin = conf.low, ymax = conf.high), alpha = .9,position = position_dodge())+ labs( x=\"Sex\", y=\"Salary\", title=\"The Marginal Effect of Sex on Salary\" )+scale_x_continuous(breaks=c(1,2) ,labels = c(\"Female\", \"Male\"))"
},
{
"code": null,
"e": 3772,
"s": 3666,
"text": "We can now plot the actual marginal effect of sex on a salary after controlling for all other predictors."
}
] |
NHibernate - Cascades
|
In this chapter, we will be covering how to use the Cascade feature. If you have a set or a collection of items or a relationship between two classes such as our customer and order and have a foreign key relationship. If we delete the customer by default, NHibernate doesn't do anything to the child objects, so the ones that belong to that customer and we could be orphaning orders.
We could also be violating foreign key constraints, so we can use the notion of cascades.
We could also be violating foreign key constraints, so we can use the notion of cascades.
By default, NHibernate does not cascade operations to child objects.
By default, NHibernate does not cascade operations to child objects.
The reason for this is that you can have relationships such as a customer having a default shipping address and that shipping address is shared with many different customers.
The reason for this is that you can have relationships such as a customer having a default shipping address and that shipping address is shared with many different customers.
So you wouldn't want to cascade that relationship necessarily because other customers are still referring to it.
So you wouldn't want to cascade that relationship necessarily because other customers are still referring to it.
So the whole notion of cascades is to tell NHibernate how to handle its child entities.
So the whole notion of cascades is to tell NHibernate how to handle its child entities.
There are different options for cascading, which are as follows −
none − which is the default and it means no cascading.
none − which is the default and it means no cascading.
all − which is going to cascade saves, updates, and deletes.
all − which is going to cascade saves, updates, and deletes.
save-update − it will cascade, saves and updates.
save-update − it will cascade, saves and updates.
delete − it will cascade deletes.
delete − it will cascade deletes.
all-delete-orphan − it is a special one which is quite frequently used and is the same as All Except, if it finds Delete-orphan rows, it will delete those as well.
all-delete-orphan − it is a special one which is quite frequently used and is the same as All Except, if it finds Delete-orphan rows, it will delete those as well.
You can specify the default in your hbm.xml file, so you can provide a default cascade on that Hibernate mapping element or you can also specify it for specific collections and relationships such as the many-to-one.
Let’s have a look into simple example cascades, let's fix the problem in the program, where we have to manually cascade the save to the orders as shown in the following code.
using(var session = sessionFactory.OpenSession())
using(var tx = session.BeginTransaction()) {
var newCustomer = CreateCustomer();
Console.WriteLine("New Customer:");
Console.WriteLine(newCustomer);
session.Save(newCustomer);
foreach (var order in newCustomer.Orders) {
session.Save(order);
}
id = newCustomer.Id;
tx.Commit();
}
In the above code snippet, you can see that we are manually saving all the orders for the customer. Now let’s remove manual cascade code in which all the orders are saved.
using(var session = sessionFactory.OpenSession())
using(var tx = session.BeginTransaction()) {
var newCustomer = CreateCustomer();
Console.WriteLine("New Customer:");
Console.WriteLine(newCustomer);
session.Save(newCustomer);
id = newCustomer.Id;
tx.Commit();
}
We need to specify the cascade option in customer.hbm.xml.
<?xml version = "1.0" encoding = "utf-8" ?>
<hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" assembly = "NHibernateDemo"
namespace = "NHibernateDemo">
<class name = "Customer">
<id name = "Id">
<generator class = "guid.comb"/>
</id>
<property name = "FirstName"/>
<property name = "LastName"/>
<property name = "AverageRating"/>
<property name = "Points"/>
<property name = "HasGoldStatus"/>
<property name = "MemberSince" type = "UtcDateTime"/>
<property name = "CreditRating" type = "CustomerCreditRatingType"/>
<component name = "Address">
<property name = "Street"/>
<property name = "City"/>
<property name = "Province"/>
<property name = "Country"/>
</component>
<set name = "Orders" table = "`Order`" cascade = "all-delete-orphan">
<key column = "CustomerId"/>
<one-to-many class = "Order"/>
</set>
</class>
</hibernate-mapping>
Now, orders fully belong to the customer. So if the customers were deleted from the database, our application here would want to delete all of those orders, including any that might have been orphaned.
Now, orders fully belong to the customer. So if the customers were deleted from the database, our application here would want to delete all of those orders, including any that might have been orphaned.
It will end up doing a delete. By that, it will say delete from order table, where the customer ID equals the customer that you're deleting.
It will end up doing a delete. By that, it will say delete from order table, where the customer ID equals the customer that you're deleting.
So you can actually cascade these deletes. So with the All, it will do saves, updates, and deletes.
So you can actually cascade these deletes. So with the All, it will do saves, updates, and deletes.
Now when you run this application, you will see the following output.
New Customer:
John Doe (00000000-0000-0000-0000-000000000000)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Unspecified)
CreditRating: Good
AverageRating: 42.42424242
Orders:
Order Id: 00000000-0000-0000-0000-000000000000
Order Id: 00000000-0000-0000-0000-000000000000
Reloaded:
John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133
Order Id: b03858e7-8c36-4555-8878-a5bb00b85134
The orders were ordered by:
John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133
Order Id: b03858e7-8c36-4555-8878-a5bb00b85134
John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133
Order Id: b03858e7-8c36-4555-8878-a5bb00b85134
Press <ENTER> to exit...
As you can see that we have deleted the code from the program that manually cascaded and our application is still working.
So depending on your relationship, you might want to cascade those. Now, let's take a look at a different cascade relationship. Let’s go to the Order.hbm.xml file and we can cascade that many-to-one relationship.
<?xml version = "1.0" encoding = "utf-8" ?>
<hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" assembly = "NHibernateDemo"
namespace = "NHibernateDemo">
<class name = "Order" table = "`Order`">
<id name = "Id">
<generator class = "guid.comb"/>
</id>
<property name = "Ordered"/>
<property name = "Shipped"/>
<component name = "ShipTo">
<property name = "Street"/>
<property name = "City"/>
<property name = "Province"/>
<property name = "Country"/>
</component>
<many-to-one name = "Customer" column = "CustomerId" cascade = "save-update"/>
</class>
</hibernate-mapping>
So if we create a new order and there's a new customer attached to it and we say, save that order, we might want to cascade that. But one thing that we'd probably don't want to do is if an order is deleted to delete the corresponding customer.
So here, we would want to do a save update, so using a save-update, it will cascade any saves or updates to that customer. So, if we get a new customer or if we are changing the customer, it will cascade that. If it is a delete, it won't delete that from the database.
So running our application again, everything still works as expected.
New Customer:
John Doe (00000000-0000-0000-0000-000000000000)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Unspecified)
CreditRating: Good
AverageRating: 42.42424242
Orders:
Id: 00000000-0000-0000-0000-000000000000
Order Id: 00000000-0000-0000-0000-000000000000
Reloaded:
John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133
Order Id: b03858e7-8c36-4555-8878-a5bb00b85134
The orders were ordered by:
John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133
Order Id: b03858e7-8c36-4555-8878-a5bb00b85134
John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)
Points: 100
HasGoldStatus: True
MemberSince: 1/1/2012 12:00:00 AM (Utc)
CreditRating: Good
AverageRating: 42.4242
Orders:
Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133
Order Id: b03858e7-8c36-4555-8878-a5bb00b85134
Press <ENTER> to exit...
Now you should have a look at your application, remember that the default is None and you have to think about your entities and your relationships between them to determine the appropriate cascades for each of your entities as well as each of your relationships in that database.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2717,
"s": 2333,
"text": "In this chapter, we will be covering how to use the Cascade feature. If you have a set or a collection of items or a relationship between two classes such as our customer and order and have a foreign key relationship. If we delete the customer by default, NHibernate doesn't do anything to the child objects, so the ones that belong to that customer and we could be orphaning orders."
},
{
"code": null,
"e": 2807,
"s": 2717,
"text": "We could also be violating foreign key constraints, so we can use the notion of cascades."
},
{
"code": null,
"e": 2897,
"s": 2807,
"text": "We could also be violating foreign key constraints, so we can use the notion of cascades."
},
{
"code": null,
"e": 2966,
"s": 2897,
"text": "By default, NHibernate does not cascade operations to child objects."
},
{
"code": null,
"e": 3035,
"s": 2966,
"text": "By default, NHibernate does not cascade operations to child objects."
},
{
"code": null,
"e": 3210,
"s": 3035,
"text": "The reason for this is that you can have relationships such as a customer having a default shipping address and that shipping address is shared with many different customers."
},
{
"code": null,
"e": 3385,
"s": 3210,
"text": "The reason for this is that you can have relationships such as a customer having a default shipping address and that shipping address is shared with many different customers."
},
{
"code": null,
"e": 3498,
"s": 3385,
"text": "So you wouldn't want to cascade that relationship necessarily because other customers are still referring to it."
},
{
"code": null,
"e": 3611,
"s": 3498,
"text": "So you wouldn't want to cascade that relationship necessarily because other customers are still referring to it."
},
{
"code": null,
"e": 3699,
"s": 3611,
"text": "So the whole notion of cascades is to tell NHibernate how to handle its child entities."
},
{
"code": null,
"e": 3787,
"s": 3699,
"text": "So the whole notion of cascades is to tell NHibernate how to handle its child entities."
},
{
"code": null,
"e": 3853,
"s": 3787,
"text": "There are different options for cascading, which are as follows −"
},
{
"code": null,
"e": 3908,
"s": 3853,
"text": "none − which is the default and it means no cascading."
},
{
"code": null,
"e": 3963,
"s": 3908,
"text": "none − which is the default and it means no cascading."
},
{
"code": null,
"e": 4024,
"s": 3963,
"text": "all − which is going to cascade saves, updates, and deletes."
},
{
"code": null,
"e": 4085,
"s": 4024,
"text": "all − which is going to cascade saves, updates, and deletes."
},
{
"code": null,
"e": 4135,
"s": 4085,
"text": "save-update − it will cascade, saves and updates."
},
{
"code": null,
"e": 4185,
"s": 4135,
"text": "save-update − it will cascade, saves and updates."
},
{
"code": null,
"e": 4219,
"s": 4185,
"text": "delete − it will cascade deletes."
},
{
"code": null,
"e": 4253,
"s": 4219,
"text": "delete − it will cascade deletes."
},
{
"code": null,
"e": 4417,
"s": 4253,
"text": "all-delete-orphan − it is a special one which is quite frequently used and is the same as All Except, if it finds Delete-orphan rows, it will delete those as well."
},
{
"code": null,
"e": 4581,
"s": 4417,
"text": "all-delete-orphan − it is a special one which is quite frequently used and is the same as All Except, if it finds Delete-orphan rows, it will delete those as well."
},
{
"code": null,
"e": 4797,
"s": 4581,
"text": "You can specify the default in your hbm.xml file, so you can provide a default cascade on that Hibernate mapping element or you can also specify it for specific collections and relationships such as the many-to-one."
},
{
"code": null,
"e": 4972,
"s": 4797,
"text": "Let’s have a look into simple example cascades, let's fix the problem in the program, where we have to manually cascade the save to the orders as shown in the following code."
},
{
"code": null,
"e": 5347,
"s": 4972,
"text": "using(var session = sessionFactory.OpenSession()) \n\nusing(var tx = session.BeginTransaction()) { \n var newCustomer = CreateCustomer(); \n Console.WriteLine(\"New Customer:\"); \n Console.WriteLine(newCustomer); \n session.Save(newCustomer); \n\t\n foreach (var order in newCustomer.Orders) { \n session.Save(order); \n } \n\t\n id = newCustomer.Id; \n tx.Commit(); \n}"
},
{
"code": null,
"e": 5519,
"s": 5347,
"text": "In the above code snippet, you can see that we are manually saving all the orders for the customer. Now let’s remove manual cascade code in which all the orders are saved."
},
{
"code": null,
"e": 5809,
"s": 5519,
"text": "using(var session = sessionFactory.OpenSession())\n \nusing(var tx = session.BeginTransaction()) { \n var newCustomer = CreateCustomer(); \n Console.WriteLine(\"New Customer:\"); \n Console.WriteLine(newCustomer);\n\t\n session.Save(newCustomer); \n id = newCustomer.Id; \n tx.Commit(); \n}"
},
{
"code": null,
"e": 5868,
"s": 5809,
"text": "We need to specify the cascade option in customer.hbm.xml."
},
{
"code": null,
"e": 6914,
"s": 5868,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" assembly = \"NHibernateDemo\"\n namespace = \"NHibernateDemo\"> \n\t\n <class name = \"Customer\"> \n \n <id name = \"Id\"> \n <generator class = \"guid.comb\"/> \n </id> \n \n <property name = \"FirstName\"/> \n <property name = \"LastName\"/> \n <property name = \"AverageRating\"/> \n <property name = \"Points\"/> \n <property name = \"HasGoldStatus\"/> \n <property name = \"MemberSince\" type = \"UtcDateTime\"/> \n <property name = \"CreditRating\" type = \"CustomerCreditRatingType\"/>\n \n <component name = \"Address\"> \n <property name = \"Street\"/> \n <property name = \"City\"/> \n <property name = \"Province\"/> \n <property name = \"Country\"/> \n </component>\n \n <set name = \"Orders\" table = \"`Order`\" cascade = \"all-delete-orphan\"> \n <key column = \"CustomerId\"/> \n <one-to-many class = \"Order\"/> \n </set> \n \n </class> \n</hibernate-mapping>"
},
{
"code": null,
"e": 7116,
"s": 6914,
"text": "Now, orders fully belong to the customer. So if the customers were deleted from the database, our application here would want to delete all of those orders, including any that might have been orphaned."
},
{
"code": null,
"e": 7318,
"s": 7116,
"text": "Now, orders fully belong to the customer. So if the customers were deleted from the database, our application here would want to delete all of those orders, including any that might have been orphaned."
},
{
"code": null,
"e": 7459,
"s": 7318,
"text": "It will end up doing a delete. By that, it will say delete from order table, where the customer ID equals the customer that you're deleting."
},
{
"code": null,
"e": 7600,
"s": 7459,
"text": "It will end up doing a delete. By that, it will say delete from order table, where the customer ID equals the customer that you're deleting."
},
{
"code": null,
"e": 7700,
"s": 7600,
"text": "So you can actually cascade these deletes. So with the All, it will do saves, updates, and deletes."
},
{
"code": null,
"e": 7800,
"s": 7700,
"text": "So you can actually cascade these deletes. So with the All, it will do saves, updates, and deletes."
},
{
"code": null,
"e": 7870,
"s": 7800,
"text": "Now when you run this application, you will see the following output."
},
{
"code": null,
"e": 9146,
"s": 7870,
"text": "New Customer:\nJohn Doe (00000000-0000-0000-0000-000000000000)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Unspecified)\n CreditRating: Good\n AverageRating: 42.42424242\n\n Orders:\n Order Id: 00000000-0000-0000-0000-000000000000\n Order Id: 00000000-0000-0000-0000-000000000000\n\nReloaded:\nJohn Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133\n Order Id: b03858e7-8c36-4555-8878-a5bb00b85134\n\nThe orders were ordered by:\nJohn Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133\n Order Id: b03858e7-8c36-4555-8878-a5bb00b85134\n\nJohn Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133\n Order Id: b03858e7-8c36-4555-8878-a5bb00b85134\n\t\t\nPress <ENTER> to exit...\n"
},
{
"code": null,
"e": 9269,
"s": 9146,
"text": "As you can see that we have deleted the code from the program that manually cascaded and our application is still working."
},
{
"code": null,
"e": 9482,
"s": 9269,
"text": "So depending on your relationship, you might want to cascade those. Now, let's take a look at a different cascade relationship. Let’s go to the Order.hbm.xml file and we can cascade that many-to-one relationship."
},
{
"code": null,
"e": 10193,
"s": 9482,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" assembly = \"NHibernateDemo\"\n namespace = \"NHibernateDemo\"> \n \n <class name = \"Order\" table = \"`Order`\"> \n\t\n <id name = \"Id\"> \n <generator class = \"guid.comb\"/> \n </id> \n\n <property name = \"Ordered\"/> \n <property name = \"Shipped\"/> \n \n <component name = \"ShipTo\"> \n <property name = \"Street\"/> \n <property name = \"City\"/> \n <property name = \"Province\"/> \n <property name = \"Country\"/> \n </component> \n \n <many-to-one name = \"Customer\" column = \"CustomerId\" cascade = \"save-update\"/>\n\t\t\n </class> \n</hibernate-mapping>"
},
{
"code": null,
"e": 10437,
"s": 10193,
"text": "So if we create a new order and there's a new customer attached to it and we say, save that order, we might want to cascade that. But one thing that we'd probably don't want to do is if an order is deleted to delete the corresponding customer."
},
{
"code": null,
"e": 10706,
"s": 10437,
"text": "So here, we would want to do a save update, so using a save-update, it will cascade any saves or updates to that customer. So, if we get a new customer or if we are changing the customer, it will cascade that. If it is a delete, it won't delete that from the database."
},
{
"code": null,
"e": 10776,
"s": 10706,
"text": "So running our application again, everything still works as expected."
},
{
"code": null,
"e": 12054,
"s": 10776,
"text": "New Customer:\nJohn Doe (00000000-0000-0000-0000-000000000000)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Unspecified)\n CreditRating: Good\n AverageRating: 42.42424242\n\n Orders:\n Id: 00000000-0000-0000-0000-000000000000\n Order Id: 00000000-0000-0000-0000-000000000000\n\nReloaded:\nJohn Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133\n Order Id: b03858e7-8c36-4555-8878-a5bb00b85134\n\nThe orders were ordered by:\nJohn Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133\n Order Id: b03858e7-8c36-4555-8878-a5bb00b85134\n John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e)\n\t\t\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133\n Order Id: b03858e7-8c36-4555-8878-a5bb00b85134\n\t\t\nPress <ENTER> to exit...\n"
},
{
"code": null,
"e": 12334,
"s": 12054,
"text": "Now you should have a look at your application, remember that the default is None and you have to think about your entities and your relationships between them to determine the appropriate cascades for each of your entities as well as each of your relationships in that database."
},
{
"code": null,
"e": 12341,
"s": 12334,
"text": " Print"
},
{
"code": null,
"e": 12352,
"s": 12341,
"text": " Add Notes"
}
] |
Rat in a Maze | Backtracking-2 - GeeksforGeeks
|
22 Apr, 2022
We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking.
A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move only in two directions: forward and down.
In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves.
Following is an example maze.
Gray blocks are dead ends (value = 0).
Following is a binary matrix representation of the above maze.
{1, 0, 0, 0}
{1, 1, 0, 1}
{0, 1, 0, 0}
{1, 1, 1, 1}
Following is a maze with highlighted solution path.
Following is the solution matrix (output of program) for the above input matrix.
{1, 0, 0, 0}
{1, 1, 0, 0}
{0, 1, 0, 0}
{0, 1, 1, 1}
All entries in solution path are marked as 1.
Backtracking Algorithm: Backtracking is an algorithmic-technique for solving problems recursively by trying to build a solution incrementally. Solving one piece at a time, and removing those solutions that fail to satisfy the constraints of the problem at any point of time (by time, here, is referred to the time elapsed till reaching any level of the search tree) is the process of backtracking.
Approach: Form a recursive function, which will follow a path and check if the path reaches the destination or not. If the path does not reach the destination then backtrack and try other paths.
Algorithm:
Create a solution matrix, initially filled with 0’s.Create a recursive function, which takes initial matrix, output matrix and position of rat (i, j).if the position is out of the matrix or the position is not valid then return.Mark the position output[i][j] as 1 and check if the current position is destination or not. If destination is reached print the output matrix and return.Recursively call for position (i+1, j) and (i, j+1).Unmark position (i, j), i.e output[i][j] = 0.
Create a solution matrix, initially filled with 0’s.
Create a recursive function, which takes initial matrix, output matrix and position of rat (i, j).
if the position is out of the matrix or the position is not valid then return.
Mark the position output[i][j] as 1 and check if the current position is destination or not. If destination is reached print the output matrix and return.
Recursively call for position (i+1, j) and (i, j+1).
Unmark position (i, j), i.e output[i][j] = 0.
C++
C
Java
Python3
C#
Javascript
// C++ program to solve Rat in a Maze problem using// backtracking#include <bits/stdc++.h>using namespace std;// Maze size#define N 4 bool solveMazeUtil(int maze[N][N], int x, int y,int sol[N][N]); // A utility function to print solution matrix sol[N][N]void printSolution(int sol[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout<<" "<<sol[i][j]<<" "; cout<<endl; }} // A utility function to check if x, y is valid index for// N*N mazebool isSafe(int maze[N][N], int x, int y){ // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) return true; return false;} // This function solves the Maze problem using Backtracking.// It mainly uses solveMazeUtil() to solve the problem. It// returns false if no path is possible, otherwise return// true and prints the path in the form of 1s. Please note// that there may be more than one solutions, this function// prints one of the feasible solutions.bool solveMaze(int maze[N][N]){ int sol[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { cout<<"Solution doesn't exist"; return false; } printSolution(sol); return true;} // A recursive utility function to solve Maze problembool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of // solution path. if (sol[x][y] == 1) return false; // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol) == true) return true; // If moving in x direction doesn't give solution // then Move down in y direction if (solveMazeUtil(maze, x, y + 1, sol) == true) return true; // If none of the above movements work then // BACKTRACK: unmark x, y as part of solution path sol[x][y] = 0; return false; } return false;} // driver program to test above functionint main(){ int maze[N][N] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; solveMaze(maze); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C++ program to solve Rat in a Maze problem using// backtracking#include <stdio.h>#include <stdbool.h>// Maze size#define N 4 bool solveMazeUtil(int maze[N][N], int x, int y,int sol[N][N]); // A utility function to print solution matrix sol[N][N]void printSolution(int sol[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", sol[i][j]); printf("\n"); }} // A utility function to check if x, y is valid index for// N*N mazebool isSafe(int maze[N][N], int x, int y){ // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) return true; return false;} // This function solves the Maze problem using Backtracking.// It mainly uses solveMazeUtil() to solve the problem. It// returns false if no path is possible, otherwise return// true and prints the path in the form of 1s. Please note// that there may be more than one solutions, this function// prints one of the feasible solutions.bool solveMaze(int maze[N][N]){ int sol[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { printf("Solution doesn't exist"); return false; } printSolution(sol); return true;} // A recursive utility function to solve Maze problembool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of // solution path. if (sol[x][y] == 1) return false; // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol) == true) return true; // If moving in x direction doesn't give solution // then Move down in y direction if (solveMazeUtil(maze, x, y + 1, sol) == true) return true; // If none of the above movements work then // BACKTRACK: unmark x, y as part of solution path sol[x][y] = 0; return false; } return false;} // driver program to test above functionint main(){ int maze[N][N] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; solveMaze(maze); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
/* Java program to solve Rat in a Maze problem using backtracking */ public class RatMaze { // Size of the maze static int N; /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print( " " + sol[i][j] + " "); System.out.println(); } } /* A utility function to check if x, y is valid index for N*N maze */ boolean isSafe( int maze[][], int x, int y) { // if (x, y outside maze) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1); } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ boolean solveMaze(int maze[][]) { int sol[][] = new int[N][N]; if (solveMazeUtil(maze, 0, 0, sol) == false) { System.out.print("Solution doesn't exist"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of solution path. if (sol[x][y] == 1) return false; // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol)) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol)) return true; /* If moving in y direction doesn't give solution then Move backwards in x direction */ if (solveMazeUtil(maze, x - 1, y, sol)) return true; /* If moving backwards in x direction doesn't give solution then Move upwards in y direction */ if (solveMazeUtil(maze, x, y - 1, sol)) return true; /* If none of the above movements works then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false; } public static void main(String args[]) { RatMaze rat = new RatMaze(); int maze[][] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; N = maze.length; rat.solveMaze(maze); }}// This code is contributed by Abhishek Shankhadhar
# Python3 program to solve Rat in a Maze# problem using backtracking # Maze sizeN = 4 # A utility function to print solution matrix soldef printSolution( sol ): for i in sol: for j in i: print(str(j) + " ", end ="") print("") # A utility function to check if x, y is valid# index for N * N Mazedef isSafe( maze, x, y ): if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: return True return False """ This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasable solutions. """def solveMaze( maze ): # Creating a 4 * 4 2-D list sol = [ [ 0 for j in range(4) ] for i in range(4) ] if solveMazeUtil(maze, 0, 0, sol) == False: print("Solution doesn't exist"); return False printSolution(sol) return True # A recursive utility function to solve Maze problemdef solveMazeUtil(maze, x, y, sol): # if (x, y is goal) return True if x == N - 1 and y == N - 1 and maze[x][y]== 1: sol[x][y] = 1 return True # Check if maze[x][y] is valid if isSafe(maze, x, y) == True: # Check if the current block is already part of solution path. if sol[x][y] == 1: return False # mark x, y as part of solution path sol[x][y] = 1 # Move forward in x direction if solveMazeUtil(maze, x + 1, y, sol) == True: return True # If moving in x direction doesn't give solution # then Move down in y direction if solveMazeUtil(maze, x, y + 1, sol) == True: return True # If moving in y direction doesn't give solution then # Move back in x direction if solveMazeUtil(maze, x - 1, y, sol) == True: return True # If moving in backwards in x direction doesn't give solution # then Move upwards in y direction if solveMazeUtil(maze, x, y - 1, sol) == True: return True # If none of the above movements work then # BACKTRACK: unmark x, y as part of solution path sol[x][y] = 0 return False # Driver program to test above functionif __name__ == "__main__": # Initialising the maze maze = [ [1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1] ] solveMaze(maze) # This code is contributed by Shiv Shankar
// C# program to solve Rat in a Maze// problem using backtrackingusing System; class RatMaze{ // Size of the mazestatic int N; // A utility function to print// solution matrix sol[N,N]void printSolution(int [,]sol){ for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) Console.Write(" " + sol[i, j] + " "); Console.WriteLine(); }} // A utility function to check if x, y// is valid index for N*N mazebool isSafe(int [,]maze, int x, int y){ // If (x, y outside maze) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x, y] == 1);} // This function solves the Maze problem using// Backtracking. It mainly uses solveMazeUtil()// to solve the problem. It returns false if no// path is possible, otherwise return true and// prints the path in the form of 1s. Please note// that there may be more than one solutions, this// function prints one of the feasible solutions.bool solveMaze(int [,]maze){ int [,]sol = new int[N, N]; if (solveMazeUtil(maze, 0, 0, sol) == false) { Console.Write("Solution doesn't exist"); return false; } printSolution(sol); return true;} // A recursive utility function to solve Maze// problembool solveMazeUtil(int [,]maze, int x, int y, int [,]sol){ // If (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x, y] == 1) { sol[x, y] = 1; return true; } // Check if maze[x,y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of solution path. if (sol[x, y] == 1) return false; // Mark x, y as part of solution path sol[x, y] = 1; // Move forward in x direction if (solveMazeUtil(maze, x + 1, y, sol)) return true; // If moving in x direction doesn't give // solution then Move down in y direction if (solveMazeUtil(maze, x, y + 1, sol)) return true; // If moving in y direction doesm't give // solution then Move backward in x direction if (solveMazeUtil(maze, x - 1, y, sol)) return true; // If moving in backwards in x direction doesn't give // solution then Move upwards in y direction if (solveMazeUtil(maze, x, y - 1, sol)) return true; // If none of the above movements works then // BACKTRACK: unmark x, y as part of solution // path sol[x, y] = 0; return false; } return false;} // Driver Codepublic static void Main(String []args){ RatMaze rat = new RatMaze(); int [,]maze = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; N = maze.GetLength(0); rat.solveMaze(maze);}} // This code is contributed by gauravrajput1
<script>/* Javascript program to solve Rat in a Maze problem using backtracking */ // Size of the mazelet N; /* A utility function to print solution matrix sol[N][N] */function printSolution(sol){ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write( " " + sol[i][j] + " "); document.write("<br>"); }} /* A utility function to check if x, y is valid index for N*N maze */function isSafe(maze,x,y){ // if (x, y outside maze) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1);} /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/function solveMaze(maze){ let sol = new Array(N); for(let i=0;i<N;i++) { sol[i]=new Array(N); for(let j=0;j<N;j++) { sol[i][j]=0; } } if (solveMazeUtil(maze, 0, 0, sol) == false) { document.write("Solution doesn't exist"); return false; } printSolution(sol); return true;}/* A recursive utility function to solve Maze problem */function solveMazeUtil(maze,x,y,sol){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of solution path. if (sol[x][y] == 1) return false; // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol)) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol)) return true; /* If moving in y direction doesn't give solution then Move backwards in x direction */ if (solveMazeUtil(maze, x - 1, y, sol)) return true; /* If moving backwards in x direction doesn't give solution then Move upwards in y direction */ if (solveMazeUtil(maze, x, y - 1, sol)) return true; /* If none of the above movements works then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false;} let maze=[[ 1, 0, 0, 0 ], [ 1, 1, 0, 1 ], [ 0, 1, 0, 0 ], [ 1, 1, 1, 1 ] ];N = maze.length;solveMaze(maze); // This code is contributed by avanitrachhadiya2155</script>
Output: The 1 values show the path for rat
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1
Complexity Analysis:
Time Complexity: O(2^(n^2)). The recursion can run upper-bound 2^(n^2) times.
Space Complexity: O(n^2). Output matrix is required so an extra space of size n*n is needed.
Below is an extended version of this problem. Count number of ways to reach destination in a MazePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Kakashi11
Debomit Dey
andrew1234
GauravRajput1
khushboogoyal499
sumitu0812
avanitrachhadiya2155
sweetyty
rajatjain0807
Amazon
Drishti-Soft
Expedia
Flipkart
Grofers
MakeMyTrip
Numerify
Paytm
Visa
Yatra.com
Zycus
Backtracking
Matrix
Paytm
Flipkart
Amazon
MakeMyTrip
Visa
Yatra.com
Drishti-Soft
Zycus
Expedia
Grofers
Matrix
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Backtracking | Introduction
Print all paths from a given source to a destination
Printing all solutions in N-Queen Problem
Backtracking to find all subsets
Program to find largest element in an array
Print a given matrix in spiral form
Find the number of islands | Set 1 (Using DFS)
Program to multiply two matrices
Inplace rotate square matrix by 90 degrees | Set 1
|
[
{
"code": null,
"e": 34205,
"s": 34177,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 34367,
"s": 34205,
"text": "We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking."
},
{
"code": null,
"e": 34667,
"s": 34367,
"text": "A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move only in two directions: forward and down. "
},
{
"code": null,
"e": 35004,
"s": 34667,
"text": "In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves."
},
{
"code": null,
"e": 35036,
"s": 35004,
"text": "Following is an example maze. "
},
{
"code": null,
"e": 35076,
"s": 35036,
"text": " Gray blocks are dead ends (value = 0)."
},
{
"code": null,
"e": 35140,
"s": 35076,
"text": "Following is a binary matrix representation of the above maze. "
},
{
"code": null,
"e": 35192,
"s": 35140,
"text": "{1, 0, 0, 0}\n{1, 1, 0, 1}\n{0, 1, 0, 0}\n{1, 1, 1, 1}"
},
{
"code": null,
"e": 35244,
"s": 35192,
"text": "Following is a maze with highlighted solution path."
},
{
"code": null,
"e": 35326,
"s": 35244,
"text": "Following is the solution matrix (output of program) for the above input matrix. "
},
{
"code": null,
"e": 35424,
"s": 35326,
"text": "{1, 0, 0, 0}\n{1, 1, 0, 0}\n{0, 1, 0, 0}\n{0, 1, 1, 1}\nAll entries in solution path are marked as 1."
},
{
"code": null,
"e": 35822,
"s": 35424,
"text": "Backtracking Algorithm: Backtracking is an algorithmic-technique for solving problems recursively by trying to build a solution incrementally. Solving one piece at a time, and removing those solutions that fail to satisfy the constraints of the problem at any point of time (by time, here, is referred to the time elapsed till reaching any level of the search tree) is the process of backtracking."
},
{
"code": null,
"e": 36018,
"s": 35822,
"text": "Approach: Form a recursive function, which will follow a path and check if the path reaches the destination or not. If the path does not reach the destination then backtrack and try other paths. "
},
{
"code": null,
"e": 36031,
"s": 36018,
"text": "Algorithm: "
},
{
"code": null,
"e": 36511,
"s": 36031,
"text": "Create a solution matrix, initially filled with 0’s.Create a recursive function, which takes initial matrix, output matrix and position of rat (i, j).if the position is out of the matrix or the position is not valid then return.Mark the position output[i][j] as 1 and check if the current position is destination or not. If destination is reached print the output matrix and return.Recursively call for position (i+1, j) and (i, j+1).Unmark position (i, j), i.e output[i][j] = 0."
},
{
"code": null,
"e": 36564,
"s": 36511,
"text": "Create a solution matrix, initially filled with 0’s."
},
{
"code": null,
"e": 36663,
"s": 36564,
"text": "Create a recursive function, which takes initial matrix, output matrix and position of rat (i, j)."
},
{
"code": null,
"e": 36742,
"s": 36663,
"text": "if the position is out of the matrix or the position is not valid then return."
},
{
"code": null,
"e": 36897,
"s": 36742,
"text": "Mark the position output[i][j] as 1 and check if the current position is destination or not. If destination is reached print the output matrix and return."
},
{
"code": null,
"e": 36950,
"s": 36897,
"text": "Recursively call for position (i+1, j) and (i, j+1)."
},
{
"code": null,
"e": 36996,
"s": 36950,
"text": "Unmark position (i, j), i.e output[i][j] = 0."
},
{
"code": null,
"e": 37000,
"s": 36996,
"text": "C++"
},
{
"code": null,
"e": 37002,
"s": 37000,
"text": "C"
},
{
"code": null,
"e": 37007,
"s": 37002,
"text": "Java"
},
{
"code": null,
"e": 37015,
"s": 37007,
"text": "Python3"
},
{
"code": null,
"e": 37018,
"s": 37015,
"text": "C#"
},
{
"code": null,
"e": 37029,
"s": 37018,
"text": "Javascript"
},
{
"code": "// C++ program to solve Rat in a Maze problem using// backtracking#include <bits/stdc++.h>using namespace std;// Maze size#define N 4 bool solveMazeUtil(int maze[N][N], int x, int y,int sol[N][N]); // A utility function to print solution matrix sol[N][N]void printSolution(int sol[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout<<\" \"<<sol[i][j]<<\" \"; cout<<endl; }} // A utility function to check if x, y is valid index for// N*N mazebool isSafe(int maze[N][N], int x, int y){ // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) return true; return false;} // This function solves the Maze problem using Backtracking.// It mainly uses solveMazeUtil() to solve the problem. It// returns false if no path is possible, otherwise return// true and prints the path in the form of 1s. Please note// that there may be more than one solutions, this function// prints one of the feasible solutions.bool solveMaze(int maze[N][N]){ int sol[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { cout<<\"Solution doesn't exist\"; return false; } printSolution(sol); return true;} // A recursive utility function to solve Maze problembool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of // solution path. if (sol[x][y] == 1) return false; // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol) == true) return true; // If moving in x direction doesn't give solution // then Move down in y direction if (solveMazeUtil(maze, x, y + 1, sol) == true) return true; // If none of the above movements work then // BACKTRACK: unmark x, y as part of solution path sol[x][y] = 0; return false; } return false;} // driver program to test above functionint main(){ int maze[N][N] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; solveMaze(maze); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 39670,
"s": 37029,
"text": null
},
{
"code": "// C++ program to solve Rat in a Maze problem using// backtracking#include <stdio.h>#include <stdbool.h>// Maze size#define N 4 bool solveMazeUtil(int maze[N][N], int x, int y,int sol[N][N]); // A utility function to print solution matrix sol[N][N]void printSolution(int sol[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(\" %d \", sol[i][j]); printf(\"\\n\"); }} // A utility function to check if x, y is valid index for// N*N mazebool isSafe(int maze[N][N], int x, int y){ // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) return true; return false;} // This function solves the Maze problem using Backtracking.// It mainly uses solveMazeUtil() to solve the problem. It// returns false if no path is possible, otherwise return// true and prints the path in the form of 1s. Please note// that there may be more than one solutions, this function// prints one of the feasible solutions.bool solveMaze(int maze[N][N]){ int sol[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { printf(\"Solution doesn't exist\"); return false; } printSolution(sol); return true;} // A recursive utility function to solve Maze problembool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of // solution path. if (sol[x][y] == 1) return false; // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol) == true) return true; // If moving in x direction doesn't give solution // then Move down in y direction if (solveMazeUtil(maze, x, y + 1, sol) == true) return true; // If none of the above movements work then // BACKTRACK: unmark x, y as part of solution path sol[x][y] = 0; return false; } return false;} // driver program to test above functionint main(){ int maze[N][N] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; solveMaze(maze); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 42309,
"s": 39670,
"text": null
},
{
"code": "/* Java program to solve Rat in a Maze problem using backtracking */ public class RatMaze { // Size of the maze static int N; /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print( \" \" + sol[i][j] + \" \"); System.out.println(); } } /* A utility function to check if x, y is valid index for N*N maze */ boolean isSafe( int maze[][], int x, int y) { // if (x, y outside maze) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1); } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ boolean solveMaze(int maze[][]) { int sol[][] = new int[N][N]; if (solveMazeUtil(maze, 0, 0, sol) == false) { System.out.print(\"Solution doesn't exist\"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of solution path. if (sol[x][y] == 1) return false; // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol)) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol)) return true; /* If moving in y direction doesn't give solution then Move backwards in x direction */ if (solveMazeUtil(maze, x - 1, y, sol)) return true; /* If moving backwards in x direction doesn't give solution then Move upwards in y direction */ if (solveMazeUtil(maze, x, y - 1, sol)) return true; /* If none of the above movements works then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false; } public static void main(String args[]) { RatMaze rat = new RatMaze(); int maze[][] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; N = maze.length; rat.solveMaze(maze); }}// This code is contributed by Abhishek Shankhadhar",
"e": 45565,
"s": 42309,
"text": null
},
{
"code": "# Python3 program to solve Rat in a Maze# problem using backtracking # Maze sizeN = 4 # A utility function to print solution matrix soldef printSolution( sol ): for i in sol: for j in i: print(str(j) + \" \", end =\"\") print(\"\") # A utility function to check if x, y is valid# index for N * N Mazedef isSafe( maze, x, y ): if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: return True return False \"\"\" This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasable solutions. \"\"\"def solveMaze( maze ): # Creating a 4 * 4 2-D list sol = [ [ 0 for j in range(4) ] for i in range(4) ] if solveMazeUtil(maze, 0, 0, sol) == False: print(\"Solution doesn't exist\"); return False printSolution(sol) return True # A recursive utility function to solve Maze problemdef solveMazeUtil(maze, x, y, sol): # if (x, y is goal) return True if x == N - 1 and y == N - 1 and maze[x][y]== 1: sol[x][y] = 1 return True # Check if maze[x][y] is valid if isSafe(maze, x, y) == True: # Check if the current block is already part of solution path. if sol[x][y] == 1: return False # mark x, y as part of solution path sol[x][y] = 1 # Move forward in x direction if solveMazeUtil(maze, x + 1, y, sol) == True: return True # If moving in x direction doesn't give solution # then Move down in y direction if solveMazeUtil(maze, x, y + 1, sol) == True: return True # If moving in y direction doesn't give solution then # Move back in x direction if solveMazeUtil(maze, x - 1, y, sol) == True: return True # If moving in backwards in x direction doesn't give solution # then Move upwards in y direction if solveMazeUtil(maze, x, y - 1, sol) == True: return True # If none of the above movements work then # BACKTRACK: unmark x, y as part of solution path sol[x][y] = 0 return False # Driver program to test above functionif __name__ == \"__main__\": # Initialising the maze maze = [ [1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1] ] solveMaze(maze) # This code is contributed by Shiv Shankar",
"e": 48261,
"s": 45565,
"text": null
},
{
"code": "// C# program to solve Rat in a Maze// problem using backtrackingusing System; class RatMaze{ // Size of the mazestatic int N; // A utility function to print// solution matrix sol[N,N]void printSolution(int [,]sol){ for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) Console.Write(\" \" + sol[i, j] + \" \"); Console.WriteLine(); }} // A utility function to check if x, y// is valid index for N*N mazebool isSafe(int [,]maze, int x, int y){ // If (x, y outside maze) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x, y] == 1);} // This function solves the Maze problem using// Backtracking. It mainly uses solveMazeUtil()// to solve the problem. It returns false if no// path is possible, otherwise return true and// prints the path in the form of 1s. Please note// that there may be more than one solutions, this// function prints one of the feasible solutions.bool solveMaze(int [,]maze){ int [,]sol = new int[N, N]; if (solveMazeUtil(maze, 0, 0, sol) == false) { Console.Write(\"Solution doesn't exist\"); return false; } printSolution(sol); return true;} // A recursive utility function to solve Maze// problembool solveMazeUtil(int [,]maze, int x, int y, int [,]sol){ // If (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x, y] == 1) { sol[x, y] = 1; return true; } // Check if maze[x,y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of solution path. if (sol[x, y] == 1) return false; // Mark x, y as part of solution path sol[x, y] = 1; // Move forward in x direction if (solveMazeUtil(maze, x + 1, y, sol)) return true; // If moving in x direction doesn't give // solution then Move down in y direction if (solveMazeUtil(maze, x, y + 1, sol)) return true; // If moving in y direction doesm't give // solution then Move backward in x direction if (solveMazeUtil(maze, x - 1, y, sol)) return true; // If moving in backwards in x direction doesn't give // solution then Move upwards in y direction if (solveMazeUtil(maze, x, y - 1, sol)) return true; // If none of the above movements works then // BACKTRACK: unmark x, y as part of solution // path sol[x, y] = 0; return false; } return false;} // Driver Codepublic static void Main(String []args){ RatMaze rat = new RatMaze(); int [,]maze = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; N = maze.GetLength(0); rat.solveMaze(maze);}} // This code is contributed by gauravrajput1",
"e": 51173,
"s": 48261,
"text": null
},
{
"code": "<script>/* Javascript program to solve Rat in a Maze problem using backtracking */ // Size of the mazelet N; /* A utility function to print solution matrix sol[N][N] */function printSolution(sol){ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write( \" \" + sol[i][j] + \" \"); document.write(\"<br>\"); }} /* A utility function to check if x, y is valid index for N*N maze */function isSafe(maze,x,y){ // if (x, y outside maze) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1);} /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/function solveMaze(maze){ let sol = new Array(N); for(let i=0;i<N;i++) { sol[i]=new Array(N); for(let j=0;j<N;j++) { sol[i][j]=0; } } if (solveMazeUtil(maze, 0, 0, sol) == false) { document.write(\"Solution doesn't exist\"); return false; } printSolution(sol); return true;}/* A recursive utility function to solve Maze problem */function solveMazeUtil(maze,x,y,sol){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // Check if the current block is already part of solution path. if (sol[x][y] == 1) return false; // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol)) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol)) return true; /* If moving in y direction doesn't give solution then Move backwards in x direction */ if (solveMazeUtil(maze, x - 1, y, sol)) return true; /* If moving backwards in x direction doesn't give solution then Move upwards in y direction */ if (solveMazeUtil(maze, x, y - 1, sol)) return true; /* If none of the above movements works then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false;} let maze=[[ 1, 0, 0, 0 ], [ 1, 1, 0, 1 ], [ 0, 1, 0, 0 ], [ 1, 1, 1, 1 ] ];N = maze.length;solveMaze(maze); // This code is contributed by avanitrachhadiya2155</script>",
"e": 54257,
"s": 51173,
"text": null
},
{
"code": null,
"e": 54301,
"s": 54257,
"text": "Output: The 1 values show the path for rat "
},
{
"code": null,
"e": 54352,
"s": 54301,
"text": " 1 0 0 0 \n 1 1 0 0 \n 0 1 0 0 \n 0 1 1 1"
},
{
"code": null,
"e": 54374,
"s": 54352,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 54452,
"s": 54374,
"text": "Time Complexity: O(2^(n^2)). The recursion can run upper-bound 2^(n^2) times."
},
{
"code": null,
"e": 54545,
"s": 54452,
"text": "Space Complexity: O(n^2). Output matrix is required so an extra space of size n*n is needed."
},
{
"code": null,
"e": 54767,
"s": 54545,
"text": "Below is an extended version of this problem. Count number of ways to reach destination in a MazePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 54777,
"s": 54767,
"text": "Kakashi11"
},
{
"code": null,
"e": 54789,
"s": 54777,
"text": "Debomit Dey"
},
{
"code": null,
"e": 54800,
"s": 54789,
"text": "andrew1234"
},
{
"code": null,
"e": 54814,
"s": 54800,
"text": "GauravRajput1"
},
{
"code": null,
"e": 54831,
"s": 54814,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 54842,
"s": 54831,
"text": "sumitu0812"
},
{
"code": null,
"e": 54863,
"s": 54842,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 54872,
"s": 54863,
"text": "sweetyty"
},
{
"code": null,
"e": 54886,
"s": 54872,
"text": "rajatjain0807"
},
{
"code": null,
"e": 54893,
"s": 54886,
"text": "Amazon"
},
{
"code": null,
"e": 54906,
"s": 54893,
"text": "Drishti-Soft"
},
{
"code": null,
"e": 54914,
"s": 54906,
"text": "Expedia"
},
{
"code": null,
"e": 54923,
"s": 54914,
"text": "Flipkart"
},
{
"code": null,
"e": 54931,
"s": 54923,
"text": "Grofers"
},
{
"code": null,
"e": 54942,
"s": 54931,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 54951,
"s": 54942,
"text": "Numerify"
},
{
"code": null,
"e": 54957,
"s": 54951,
"text": "Paytm"
},
{
"code": null,
"e": 54962,
"s": 54957,
"text": "Visa"
},
{
"code": null,
"e": 54972,
"s": 54962,
"text": "Yatra.com"
},
{
"code": null,
"e": 54978,
"s": 54972,
"text": "Zycus"
},
{
"code": null,
"e": 54991,
"s": 54978,
"text": "Backtracking"
},
{
"code": null,
"e": 54998,
"s": 54991,
"text": "Matrix"
},
{
"code": null,
"e": 55004,
"s": 54998,
"text": "Paytm"
},
{
"code": null,
"e": 55013,
"s": 55004,
"text": "Flipkart"
},
{
"code": null,
"e": 55020,
"s": 55013,
"text": "Amazon"
},
{
"code": null,
"e": 55031,
"s": 55020,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 55036,
"s": 55031,
"text": "Visa"
},
{
"code": null,
"e": 55046,
"s": 55036,
"text": "Yatra.com"
},
{
"code": null,
"e": 55059,
"s": 55046,
"text": "Drishti-Soft"
},
{
"code": null,
"e": 55065,
"s": 55059,
"text": "Zycus"
},
{
"code": null,
"e": 55073,
"s": 55065,
"text": "Expedia"
},
{
"code": null,
"e": 55081,
"s": 55073,
"text": "Grofers"
},
{
"code": null,
"e": 55088,
"s": 55081,
"text": "Matrix"
},
{
"code": null,
"e": 55101,
"s": 55088,
"text": "Backtracking"
},
{
"code": null,
"e": 55199,
"s": 55101,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 55208,
"s": 55199,
"text": "Comments"
},
{
"code": null,
"e": 55221,
"s": 55208,
"text": "Old Comments"
},
{
"code": null,
"e": 55306,
"s": 55221,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 55334,
"s": 55306,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 55387,
"s": 55334,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 55429,
"s": 55387,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 55462,
"s": 55429,
"text": "Backtracking to find all subsets"
},
{
"code": null,
"e": 55506,
"s": 55462,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 55542,
"s": 55506,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 55589,
"s": 55542,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 55622,
"s": 55589,
"text": "Program to multiply two matrices"
}
] |
Python - Create Nested Dictionary using given List - GeeksforGeeks
|
29 Aug, 2020
Given a list and dictionary, map each element of list with each item of dictionary, forming nested dictionary as value.
Input : test_dict = {‘Gfg’ : 4, ‘best’ : 9}, test_list = [8, 2]Output : {8: {‘Gfg’: 4}, 2: {‘best’: 9}}Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4} and so on.
Input : test_dict = {‘Gfg’ : 4}, test_list = [8]Output : {8: {‘Gfg’: 4}}Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4}.
Method #1 : Using loop + zip()
This is one of the ways in which this task can be performed. In this, we combine both the lists using zip() and loop is used to do iteration of zipped keys and dictionary construction.
Python3
# Python3 code to demonstrate working of # Nested Dictionary with List# Using loop + zip() # initializing dictionary and listtest_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9} test_list = [8, 3, 2] # printing original dictionary and listprint("The original dictionary is : " + str(test_dict))print("The original list is : " + str(test_list)) # using zip() and loop to perform # combining and assignment respectively.res = {}for key, ele in zip(test_list, test_dict.items()): res[key] = dict([ele]) # printing result print("The mapped dictionary : " + str(res))
The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}
The original list is : [8, 3, 2]
The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}
Method #2 : Using dictionary comprehension + zip()
This is yet another way in which this task can be performed. In this, we perform similar task as above method, but in one liner using dictionary comprehension
Python3
# Python3 code to demonstrate working of # Nested Dictionary with List# Using dictionary comprehension + zip() # initializing dictionary and listtest_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9} test_list = [8, 3, 2] # printing original dictionary and listprint("The original dictionary is : " + str(test_dict))print("The original list is : " + str(test_list)) # zip() and dictionary comprehension mapped in one liner to solveres = {idx: {key : test_dict[key]} for idx, key in zip(test_list, test_dict)} # printing result print("The mapped dictionary : " + str(res))
The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}
The original list is : [8, 3, 2]
The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 25767,
"s": 25647,
"text": "Given a list and dictionary, map each element of list with each item of dictionary, forming nested dictionary as value."
},
{
"code": null,
"e": 25958,
"s": 25767,
"text": "Input : test_dict = {‘Gfg’ : 4, ‘best’ : 9}, test_list = [8, 2]Output : {8: {‘Gfg’: 4}, 2: {‘best’: 9}}Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4} and so on."
},
{
"code": null,
"e": 26108,
"s": 25958,
"text": "Input : test_dict = {‘Gfg’ : 4}, test_list = [8]Output : {8: {‘Gfg’: 4}}Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4}."
},
{
"code": null,
"e": 26140,
"s": 26108,
"text": "Method #1 : Using loop + zip() "
},
{
"code": null,
"e": 26325,
"s": 26140,
"text": "This is one of the ways in which this task can be performed. In this, we combine both the lists using zip() and loop is used to do iteration of zipped keys and dictionary construction."
},
{
"code": null,
"e": 26333,
"s": 26325,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Nested Dictionary with List# Using loop + zip() # initializing dictionary and listtest_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9} test_list = [8, 3, 2] # printing original dictionary and listprint(\"The original dictionary is : \" + str(test_dict))print(\"The original list is : \" + str(test_list)) # using zip() and loop to perform # combining and assignment respectively.res = {}for key, ele in zip(test_list, test_dict.items()): res[key] = dict([ele]) # printing result print(\"The mapped dictionary : \" + str(res)) ",
"e": 26905,
"s": 26333,
"text": null
},
{
"code": null,
"e": 27069,
"s": 26905,
"text": "The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}\nThe original list is : [8, 3, 2]\nThe mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}\n"
},
{
"code": null,
"e": 27120,
"s": 27069,
"text": "Method #2 : Using dictionary comprehension + zip()"
},
{
"code": null,
"e": 27279,
"s": 27120,
"text": "This is yet another way in which this task can be performed. In this, we perform similar task as above method, but in one liner using dictionary comprehension"
},
{
"code": null,
"e": 27287,
"s": 27279,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Nested Dictionary with List# Using dictionary comprehension + zip() # initializing dictionary and listtest_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9} test_list = [8, 3, 2] # printing original dictionary and listprint(\"The original dictionary is : \" + str(test_dict))print(\"The original list is : \" + str(test_list)) # zip() and dictionary comprehension mapped in one liner to solveres = {idx: {key : test_dict[key]} for idx, key in zip(test_list, test_dict)} # printing result print(\"The mapped dictionary : \" + str(res)) ",
"e": 27863,
"s": 27287,
"text": null
},
{
"code": null,
"e": 28027,
"s": 27863,
"text": "The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}\nThe original list is : [8, 3, 2]\nThe mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}\n"
},
{
"code": null,
"e": 28054,
"s": 28027,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 28075,
"s": 28054,
"text": "Python list-programs"
},
{
"code": null,
"e": 28082,
"s": 28075,
"text": "Python"
},
{
"code": null,
"e": 28098,
"s": 28082,
"text": "Python Programs"
},
{
"code": null,
"e": 28196,
"s": 28098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28228,
"s": 28196,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28270,
"s": 28228,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28312,
"s": 28270,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28368,
"s": 28312,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28395,
"s": 28368,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28417,
"s": 28395,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28456,
"s": 28417,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28502,
"s": 28456,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28540,
"s": 28502,
"text": "Python | Convert a list to dictionary"
}
] |
Console.SetCursorPosition() Method in C# - GeeksforGeeks
|
14 Mar, 2019
Console.SetCursorPosition(Int32, Int32) Method is used to set the position of cursor. Basically, it specifies where the next write operation will begin in the console window. The window origin changes automatically to make the cursor visible if the specified cursor position is outside the area that is currently visible in the console window.
Syntax: public static void SetCursorposition(int left, int top);
Parameters:left: It is the column position of the cursor. Columns are numbered from left to right starting at 0.top: It is the row position of the cursor. Rows are numbered from top to bottom starting at 0.
Exceptions:
ArgumentOutOfRangeException: If the left or top is less than 0 or left >= BufferWidth or top >= BufferHeight.
SecurityException: If the user doesn’t have the permission to perform this action.
Example:
// C# Program to illustrate // Console.CursorPosition() methodusing System; class GFG { // Main Method public static void Main() { // setting the window size Console.SetWindowSize(40, 40); // setting buffer size of console Console.SetBufferSize(80, 80); // using the method Console.SetCursorPosition(20, 20); Console.WriteLine("Hello GFG!"); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } }
Output:
When Console.SetCursorPosition() method is not used:
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.console.setcursorposition?view=netframework-4.7.2
CSharp-Console-Class
CSharp-method
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Class and Object
Extension Method in C#
C# | Delegates
C# | Data Types
HashSet in C# with Examples
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
Partial Classes in C#
Top 50 C# Interview Questions & Answers
How to find the length of an Array in C#
C# | How to insert an element in an Array?
|
[
{
"code": null,
"e": 24494,
"s": 24466,
"text": "\n14 Mar, 2019"
},
{
"code": null,
"e": 24838,
"s": 24494,
"text": "Console.SetCursorPosition(Int32, Int32) Method is used to set the position of cursor. Basically, it specifies where the next write operation will begin in the console window. The window origin changes automatically to make the cursor visible if the specified cursor position is outside the area that is currently visible in the console window."
},
{
"code": null,
"e": 24903,
"s": 24838,
"text": "Syntax: public static void SetCursorposition(int left, int top);"
},
{
"code": null,
"e": 25110,
"s": 24903,
"text": "Parameters:left: It is the column position of the cursor. Columns are numbered from left to right starting at 0.top: It is the row position of the cursor. Rows are numbered from top to bottom starting at 0."
},
{
"code": null,
"e": 25122,
"s": 25110,
"text": "Exceptions:"
},
{
"code": null,
"e": 25232,
"s": 25122,
"text": "ArgumentOutOfRangeException: If the left or top is less than 0 or left >= BufferWidth or top >= BufferHeight."
},
{
"code": null,
"e": 25315,
"s": 25232,
"text": "SecurityException: If the user doesn’t have the permission to perform this action."
},
{
"code": null,
"e": 25324,
"s": 25315,
"text": "Example:"
},
{
"code": "// C# Program to illustrate // Console.CursorPosition() methodusing System; class GFG { // Main Method public static void Main() { // setting the window size Console.SetWindowSize(40, 40); // setting buffer size of console Console.SetBufferSize(80, 80); // using the method Console.SetCursorPosition(20, 20); Console.WriteLine(\"Hello GFG!\"); Console.Write(\"Press any key to continue . . . \"); Console.ReadKey(true); } } ",
"e": 25831,
"s": 25324,
"text": null
},
{
"code": null,
"e": 25839,
"s": 25831,
"text": "Output:"
},
{
"code": null,
"e": 25892,
"s": 25839,
"text": "When Console.SetCursorPosition() method is not used:"
},
{
"code": null,
"e": 25903,
"s": 25892,
"text": "Reference:"
},
{
"code": null,
"e": 26004,
"s": 25903,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.console.setcursorposition?view=netframework-4.7.2"
},
{
"code": null,
"e": 26025,
"s": 26004,
"text": "CSharp-Console-Class"
},
{
"code": null,
"e": 26039,
"s": 26025,
"text": "CSharp-method"
},
{
"code": null,
"e": 26046,
"s": 26039,
"text": "Picked"
},
{
"code": null,
"e": 26049,
"s": 26046,
"text": "C#"
},
{
"code": null,
"e": 26147,
"s": 26049,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26156,
"s": 26147,
"text": "Comments"
},
{
"code": null,
"e": 26169,
"s": 26156,
"text": "Old Comments"
},
{
"code": null,
"e": 26191,
"s": 26169,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 26214,
"s": 26191,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26229,
"s": 26214,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26245,
"s": 26229,
"text": "C# | Data Types"
},
{
"code": null,
"e": 26273,
"s": 26245,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26360,
"s": 26273,
"text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework"
},
{
"code": null,
"e": 26382,
"s": 26360,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 26422,
"s": 26382,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26463,
"s": 26422,
"text": "How to find the length of an Array in C#"
}
] |
C Program for Round Robin scheduling
|
We are given with the n processes with their corresponding burst time and time quantum and the task is to find the average waiting time and average turnaround time and display the result.
What is Round Robin Scheduling?
Round robin is a CPU scheduling algorithm that is designed especially for time sharing systems. It is more like a FCFS scheduling algorithm with one change that in Round Robin processes are bounded with a quantum time size. A small unit of time is known as Time Quantum or Time Slice. Time quantum can range from 10 to 100 milliseconds. CPU treat ready queue as a circular queue for executing the processes with given time slice. It follows preemptive approach because fixed time are allocated to processes. The only disadvantage of it is overhead of context switching.
What we need to calculate?
Completion Time is the time required by the process to complete its execution
Turnaround Time is the time interval between the submission of a process and its completion.
Turnaround Time = completion of a process – submission of a process
Waiting Time is the difference between turnaround time and burst time
Waiting Time = turnaround time – burst time
We are given with 3 processes P1, P2 and P3 with their corresponding burst time as 24, 3 and 3
Since the time quantum is of 4 milliseconds, process P1 gets the first 4 milliseconds but it requires another 20 millisecond to complete its execution but CPU will preempt it after the first time quantum and CPU will be allocated to the next process P2. As shown in the table, Process P2 requires only 3 milliseconds to complete its execution so CPU will be allocated for time quantum of 3 milliseconds only instead of 4 milliseconds.
Using the Gantt chart, Average waiting time is calculated as given below −
Average waiting time = 17/3 = 5.66 milliseconds
Start
Step 1-> In function int turnarroundtime(int processes[], int n, int bt[], int wt[], int tat[])
Loop For i = 0 and i < n and i++
Set tat[i] = bt[i] + wt[i]
return 1
Step 2-> In function int waitingtime(int processes[], int n, int bt[], int wt[], int quantum)
Declare rem_bt[n]
Loop For i = 0 and i < n and i++
Set rem_bt[i] = bt[i]
Set t = 0
Loop While (1)
Set done = true
Loop For i = 0 and i < n and i++
If rem_bt[i] > 0 then,
Set done = false
If rem_bt[i] > quantum then,
Set t = t + quantum
Set rem_bt[i] = rem_bt[i] - quantum
Else
Set t = t + rem_bt[i]
Set wt[i] = t - bt[i]
Set rem_bt[i] = 0
If done == true then,
Break
Step 3->In function int findavgTime(int processes[], int n, int bt[], int quantum)
Declare and initialize wt[n], tat[n], total_wt = 0, total_tat = 0
Call function waitingtime(processes, n, bt, wt, quantum)
Call function turnarroundtime(processes, n, bt, wt, tat)
Print "Processes Burst Time Waiting Time turnaround time "
Loop For i=0 and i<n and i++
Set total_wt = total_wt + wt[i]
Set total_tat = total_tat + tat[i]
Print the value i+1, bt[i], wt[i], tat[i]
Print "Average waiting time = total_wt / n
Print "Average turnaround time =total_tat / n
Step 4-> In function int main()
Delcare and initialize processes[] = { 1, 2, 3}
Declare and initialize n = sizeof processes / sizeof processes[0]
Declare and initialize burst_time[] = {8, 6, 12}
Set quantum = 2
Call function findavgTime(processes, n, burst_time, quantum)
Live Demo
#include <stdio.h>
// Function to calculate turn around time
int turnarroundtime(int processes[], int n,
int bt[], int wt[], int tat[]) {
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
return 1;
}
// Function to find the waiting time for all
// processes
int waitingtime(int processes[], int n,
int bt[], int wt[], int quantum) {
// Make a copy of burst times bt[] to store remaining
// burst times.
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];
int t = 0; // Current time
// Keep traversing processes in round robin manner
// until all of them are not done.
while (1) {
bool done = true;
// Traverse all processes one by one repeatedly
for (int i = 0 ; i < n; i++) {
// If burst time of a process is greater than 0
// then only need to process further
if (rem_bt[i] > 0) {
done = false; // There is a pending process
if (rem_bt[i] > quantum) {
// Increase the value of t i.e. shows
// how much time a process has been processed
t += quantum;
// Decrease the burst_time of current process
// by quantum
rem_bt[i] -= quantum;
}
// If burst time is smaller than or equal to
// quantum. Last cycle for this process
else {
// Increase the value of t i.e. shows
// how much time a process has been processed
t = t + rem_bt[i];
// Waiting time is current time minus time
// used by this process
wt[i] = t - bt[i];
// As the process gets fully executed
// make its remaining burst time = 0
rem_bt[i] = 0;
}
}
}
// If all processes are done
if (done == true)
break;
}
return 1;
}
// Function to calculate average time
int findavgTime(int processes[], int n, int bt[],
int quantum) {
int wt[n], tat[n], total_wt = 0, total_tat = 0;
// Function to find waiting time of all processes
waitingtime(processes, n, bt, wt, quantum);
// Function to find turn around time for all processes
turnarroundtime(processes, n, bt, wt, tat);
// Display processes along with all details
printf("Processes Burst Time Waiting Time turnaround time\n");
// Calculate total waiting time and total turn
// around time
for (int i=0; i<n; i++) {
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
printf("\t%d\t\t\t%d\t\t\t%d\t\t\t%d\n",i+1, bt[i], wt[i], tat[i]);
}
printf("Average waiting time = %f", (float)total_wt / (float)n);
printf("\nAverage turnaround time = %f\n", (float)total_tat / (float)n);
return 1;
}
// main function
int main() {
// process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];
// Burst time of all processes
int burst_time[] = {8, 6, 12};
// Time quantum
int quantum = 2;
findavgTime(processes, n, burst_time, quantum);
return 0;
}
|
[
{
"code": null,
"e": 1250,
"s": 1062,
"text": "We are given with the n processes with their corresponding burst time and time quantum and the task is to find the average waiting time and average turnaround time and display the result."
},
{
"code": null,
"e": 1282,
"s": 1250,
"text": "What is Round Robin Scheduling?"
},
{
"code": null,
"e": 1852,
"s": 1282,
"text": "Round robin is a CPU scheduling algorithm that is designed especially for time sharing systems. It is more like a FCFS scheduling algorithm with one change that in Round Robin processes are bounded with a quantum time size. A small unit of time is known as Time Quantum or Time Slice. Time quantum can range from 10 to 100 milliseconds. CPU treat ready queue as a circular queue for executing the processes with given time slice. It follows preemptive approach because fixed time are allocated to processes. The only disadvantage of it is overhead of context switching."
},
{
"code": null,
"e": 1879,
"s": 1852,
"text": "What we need to calculate?"
},
{
"code": null,
"e": 1957,
"s": 1879,
"text": "Completion Time is the time required by the process to complete its execution"
},
{
"code": null,
"e": 2050,
"s": 1957,
"text": "Turnaround Time is the time interval between the submission of a process and its completion."
},
{
"code": null,
"e": 2118,
"s": 2050,
"text": "Turnaround Time = completion of a process – submission of a process"
},
{
"code": null,
"e": 2188,
"s": 2118,
"text": "Waiting Time is the difference between turnaround time and burst time"
},
{
"code": null,
"e": 2232,
"s": 2188,
"text": "Waiting Time = turnaround time – burst time"
},
{
"code": null,
"e": 2327,
"s": 2232,
"text": "We are given with 3 processes P1, P2 and P3 with their corresponding burst time as 24, 3 and 3"
},
{
"code": null,
"e": 2762,
"s": 2327,
"text": "Since the time quantum is of 4 milliseconds, process P1 gets the first 4 milliseconds but it requires another 20 millisecond to complete its execution but CPU will preempt it after the first time quantum and CPU will be allocated to the next process P2. As shown in the table, Process P2 requires only 3 milliseconds to complete its execution so CPU will be allocated for time quantum of 3 milliseconds only instead of 4 milliseconds."
},
{
"code": null,
"e": 2837,
"s": 2762,
"text": "Using the Gantt chart, Average waiting time is calculated as given below −"
},
{
"code": null,
"e": 2885,
"s": 2837,
"text": "Average waiting time = 17/3 = 5.66 milliseconds"
},
{
"code": null,
"e": 4503,
"s": 2885,
"text": "Start\nStep 1-> In function int turnarroundtime(int processes[], int n, int bt[], int wt[], int tat[])\n Loop For i = 0 and i < n and i++\n Set tat[i] = bt[i] + wt[i]\n return 1\nStep 2-> In function int waitingtime(int processes[], int n, int bt[], int wt[], int quantum)\nDeclare rem_bt[n]\n Loop For i = 0 and i < n and i++\n Set rem_bt[i] = bt[i]\n Set t = 0\n Loop While (1)\n Set done = true\n Loop For i = 0 and i < n and i++\n If rem_bt[i] > 0 then,\n Set done = false\n If rem_bt[i] > quantum then,\n Set t = t + quantum\n Set rem_bt[i] = rem_bt[i] - quantum\n Else\n Set t = t + rem_bt[i]\n Set wt[i] = t - bt[i]\n Set rem_bt[i] = 0\n If done == true then,\n Break\nStep 3->In function int findavgTime(int processes[], int n, int bt[], int quantum)\n Declare and initialize wt[n], tat[n], total_wt = 0, total_tat = 0\n Call function waitingtime(processes, n, bt, wt, quantum)\n Call function turnarroundtime(processes, n, bt, wt, tat)\n Print \"Processes Burst Time Waiting Time turnaround time \"\n Loop For i=0 and i<n and i++\n Set total_wt = total_wt + wt[i]\n Set total_tat = total_tat + tat[i]\n Print the value i+1, bt[i], wt[i], tat[i]\n Print \"Average waiting time = total_wt / n\n Print \"Average turnaround time =total_tat / n\nStep 4-> In function int main()\n Delcare and initialize processes[] = { 1, 2, 3}\n Declare and initialize n = sizeof processes / sizeof processes[0]\n Declare and initialize burst_time[] = {8, 6, 12}\n Set quantum = 2\n Call function findavgTime(processes, n, burst_time, quantum)"
},
{
"code": null,
"e": 4514,
"s": 4503,
"text": " Live Demo"
},
{
"code": null,
"e": 7692,
"s": 4514,
"text": "#include <stdio.h>\n// Function to calculate turn around time\nint turnarroundtime(int processes[], int n,\nint bt[], int wt[], int tat[]) {\n // calculating turnaround time by adding\n // bt[i] + wt[i]\n for (int i = 0; i < n ; i++)\n tat[i] = bt[i] + wt[i];\n return 1;\n}\n// Function to find the waiting time for all\n// processes\nint waitingtime(int processes[], int n,\nint bt[], int wt[], int quantum) {\n // Make a copy of burst times bt[] to store remaining\n // burst times.\n int rem_bt[n];\n for (int i = 0 ; i < n ; i++)\n rem_bt[i] = bt[i];\n int t = 0; // Current time\n // Keep traversing processes in round robin manner\n // until all of them are not done.\n while (1) {\n bool done = true;\n // Traverse all processes one by one repeatedly\n for (int i = 0 ; i < n; i++) {\n // If burst time of a process is greater than 0\n // then only need to process further\n if (rem_bt[i] > 0) {\n done = false; // There is a pending process\n if (rem_bt[i] > quantum) {\n // Increase the value of t i.e. shows\n // how much time a process has been processed\n t += quantum;\n // Decrease the burst_time of current process\n // by quantum\n rem_bt[i] -= quantum;\n }\n // If burst time is smaller than or equal to\n // quantum. Last cycle for this process\n else {\n // Increase the value of t i.e. shows\n // how much time a process has been processed\n t = t + rem_bt[i];\n // Waiting time is current time minus time\n // used by this process\n wt[i] = t - bt[i];\n // As the process gets fully executed\n // make its remaining burst time = 0\n rem_bt[i] = 0;\n }\n }\n }\n // If all processes are done\n if (done == true)\n break;\n }\n return 1;\n}\n// Function to calculate average time\nint findavgTime(int processes[], int n, int bt[],\nint quantum) {\n int wt[n], tat[n], total_wt = 0, total_tat = 0;\n // Function to find waiting time of all processes\n waitingtime(processes, n, bt, wt, quantum);\n // Function to find turn around time for all processes\n turnarroundtime(processes, n, bt, wt, tat);\n // Display processes along with all details\n printf(\"Processes Burst Time Waiting Time turnaround time\\n\");\n // Calculate total waiting time and total turn\n // around time\n for (int i=0; i<n; i++) {\n total_wt = total_wt + wt[i];\n total_tat = total_tat + tat[i];\n printf(\"\\t%d\\t\\t\\t%d\\t\\t\\t%d\\t\\t\\t%d\\n\",i+1, bt[i], wt[i], tat[i]);\n }\n printf(\"Average waiting time = %f\", (float)total_wt / (float)n);\n printf(\"\\nAverage turnaround time = %f\\n\", (float)total_tat / (float)n);\n return 1;\n}\n// main function\nint main() {\n // process id's\n int processes[] = { 1, 2, 3};\n int n = sizeof processes / sizeof processes[0];\n // Burst time of all processes\n int burst_time[] = {8, 6, 12};\n // Time quantum\n int quantum = 2;\n findavgTime(processes, n, burst_time, quantum);\n return 0;\n}"
}
] |
Amazon Interview Experience for FTE | On-Campus 2020(Virtual) - GeeksforGeeks
|
27 Nov, 2020
Online Coding Round: 2 Coding questions based on tree and graph.
Round – 1 (60 Minutes):
In a range of m and n print all the numbers having consecutive difference 1 between digits. (3 Approach)Arrival and Departure of the train is given, you have to calculate the minimum number of Stations(2 Approach)
In a range of m and n print all the numbers having consecutive difference 1 between digits. (3 Approach)
Arrival and Departure of the train is given, you have to calculate the minimum number of Stations(2 Approach)
Round – 2 (60 Minutes):
Given an array of candidates of a marathon, such that for every a[i], a[i] comes before i+1.(2 Approach)If a[i]= -1, that means a[i] is the winner. Output the array with the ranking of candidatesMinimum number of Steps Knight will require reaching x,y position in infinite size Chess Board(2 Approach)
Given an array of candidates of a marathon, such that for every a[i], a[i] comes before i+1.(2 Approach)If a[i]= -1, that means a[i] is the winner. Output the array with the ranking of candidates
Given an array of candidates of a marathon, such that for every a[i], a[i] comes before i+1.(2 Approach)
If a[i]= -1, that means a[i] is the winner.
Output the array with the ranking of candidates
Minimum number of Steps Knight will require reaching x,y position in infinite size Chess Board(2 Approach)
Minimum number of Steps Knight will require reaching x,y position in infinite size Chess Board(2 Approach)
Round 3 – (1 hr 45 Minutes):
Tell me About YourselfGiven a String having 0 and 1. Have to convert that string such that all 0 comes first and all 1 comes after 0 in a minimum number of flips Ex. 00001000110111 output->2Symmetric Tree(2 Approach) kth largest element in running stream.(2 Approach)Sorting(merge, Heap)Heap sort ImplementationThrashingDeadlockPolymorphismRun-Time Polymorphism vs Compile Time Polymorphism (Example)Inheritance vs Composition (Example)TCP vs UDPSQL vs NO SQLReason for Deadlock to occurWhat happens when you type www.facebook.com
Tell me About Yourself
Tell me About Yourself
Given a String having 0 and 1. Have to convert that string such that all 0 comes first and all 1 comes after 0 in a minimum number of flips Ex. 00001000110111 output->2
Given a String having 0 and 1. Have to convert that string such that all 0 comes first and all 1 comes after 0 in a minimum number of flips
Ex.
00001000110111 output->2
Symmetric Tree(2 Approach)
Symmetric Tree(2 Approach)
kth largest element in running stream.(2 Approach)
kth largest element in running stream.(2 Approach)
Sorting(merge, Heap)
Sorting(merge, Heap)
Heap sort Implementation
Heap sort Implementation
Thrashing
Thrashing
Deadlock
Deadlock
Polymorphism
Polymorphism
Run-Time Polymorphism vs Compile Time Polymorphism (Example)
Run-Time Polymorphism vs Compile Time Polymorphism (Example)
Inheritance vs Composition (Example)
Inheritance vs Composition (Example)
TCP vs UDP
TCP vs UDP
SQL vs NO SQL
SQL vs NO SQL
Reason for Deadlock to occur
Reason for Deadlock to occur
What happens when you type www.facebook.com
What happens when you type www.facebook.com
They took only 1 student and I can’t make it.
Amazon
Marketing
On-Campus
Interview Experiences
Amazon
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Zoho Interview | Set 3 (Off-Campus)
Difference between ANN, CNN and RNN
Amazon Interview Experience
Amazon Interview Experience for SDE-1
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience (Off-Campus) 2022
Infosys Interview Experience for DSE 2022
Amazon Interview Experience for SDE-1 (On-Campus)
|
[
{
"code": null,
"e": 26811,
"s": 26783,
"text": "\n27 Nov, 2020"
},
{
"code": null,
"e": 26876,
"s": 26811,
"text": "Online Coding Round: 2 Coding questions based on tree and graph."
},
{
"code": null,
"e": 26900,
"s": 26876,
"text": "Round – 1 (60 Minutes):"
},
{
"code": null,
"e": 27114,
"s": 26900,
"text": "In a range of m and n print all the numbers having consecutive difference 1 between digits. (3 Approach)Arrival and Departure of the train is given, you have to calculate the minimum number of Stations(2 Approach)"
},
{
"code": null,
"e": 27219,
"s": 27114,
"text": "In a range of m and n print all the numbers having consecutive difference 1 between digits. (3 Approach)"
},
{
"code": null,
"e": 27329,
"s": 27219,
"text": "Arrival and Departure of the train is given, you have to calculate the minimum number of Stations(2 Approach)"
},
{
"code": null,
"e": 27353,
"s": 27329,
"text": "Round – 2 (60 Minutes):"
},
{
"code": null,
"e": 27655,
"s": 27353,
"text": "Given an array of candidates of a marathon, such that for every a[i], a[i] comes before i+1.(2 Approach)If a[i]= -1, that means a[i] is the winner. Output the array with the ranking of candidatesMinimum number of Steps Knight will require reaching x,y position in infinite size Chess Board(2 Approach)"
},
{
"code": null,
"e": 27851,
"s": 27655,
"text": "Given an array of candidates of a marathon, such that for every a[i], a[i] comes before i+1.(2 Approach)If a[i]= -1, that means a[i] is the winner. Output the array with the ranking of candidates"
},
{
"code": null,
"e": 27956,
"s": 27851,
"text": "Given an array of candidates of a marathon, such that for every a[i], a[i] comes before i+1.(2 Approach)"
},
{
"code": null,
"e": 28001,
"s": 27956,
"text": "If a[i]= -1, that means a[i] is the winner. "
},
{
"code": null,
"e": 28049,
"s": 28001,
"text": "Output the array with the ranking of candidates"
},
{
"code": null,
"e": 28156,
"s": 28049,
"text": "Minimum number of Steps Knight will require reaching x,y position in infinite size Chess Board(2 Approach)"
},
{
"code": null,
"e": 28263,
"s": 28156,
"text": "Minimum number of Steps Knight will require reaching x,y position in infinite size Chess Board(2 Approach)"
},
{
"code": null,
"e": 28292,
"s": 28263,
"text": "Round 3 – (1 hr 45 Minutes):"
},
{
"code": null,
"e": 28823,
"s": 28292,
"text": "Tell me About YourselfGiven a String having 0 and 1. Have to convert that string such that all 0 comes first and all 1 comes after 0 in a minimum number of flips Ex. 00001000110111 output->2Symmetric Tree(2 Approach) kth largest element in running stream.(2 Approach)Sorting(merge, Heap)Heap sort ImplementationThrashingDeadlockPolymorphismRun-Time Polymorphism vs Compile Time Polymorphism (Example)Inheritance vs Composition (Example)TCP vs UDPSQL vs NO SQLReason for Deadlock to occurWhat happens when you type www.facebook.com"
},
{
"code": null,
"e": 28846,
"s": 28823,
"text": "Tell me About Yourself"
},
{
"code": null,
"e": 28869,
"s": 28846,
"text": "Tell me About Yourself"
},
{
"code": null,
"e": 29038,
"s": 28869,
"text": "Given a String having 0 and 1. Have to convert that string such that all 0 comes first and all 1 comes after 0 in a minimum number of flips Ex. 00001000110111 output->2"
},
{
"code": null,
"e": 29178,
"s": 29038,
"text": "Given a String having 0 and 1. Have to convert that string such that all 0 comes first and all 1 comes after 0 in a minimum number of flips"
},
{
"code": null,
"e": 29184,
"s": 29178,
"text": " Ex. "
},
{
"code": null,
"e": 29209,
"s": 29184,
"text": "00001000110111 output->2"
},
{
"code": null,
"e": 29236,
"s": 29209,
"text": "Symmetric Tree(2 Approach)"
},
{
"code": null,
"e": 29263,
"s": 29236,
"text": "Symmetric Tree(2 Approach)"
},
{
"code": null,
"e": 29315,
"s": 29263,
"text": " kth largest element in running stream.(2 Approach)"
},
{
"code": null,
"e": 29367,
"s": 29315,
"text": " kth largest element in running stream.(2 Approach)"
},
{
"code": null,
"e": 29388,
"s": 29367,
"text": "Sorting(merge, Heap)"
},
{
"code": null,
"e": 29409,
"s": 29388,
"text": "Sorting(merge, Heap)"
},
{
"code": null,
"e": 29434,
"s": 29409,
"text": "Heap sort Implementation"
},
{
"code": null,
"e": 29459,
"s": 29434,
"text": "Heap sort Implementation"
},
{
"code": null,
"e": 29469,
"s": 29459,
"text": "Thrashing"
},
{
"code": null,
"e": 29479,
"s": 29469,
"text": "Thrashing"
},
{
"code": null,
"e": 29488,
"s": 29479,
"text": "Deadlock"
},
{
"code": null,
"e": 29497,
"s": 29488,
"text": "Deadlock"
},
{
"code": null,
"e": 29510,
"s": 29497,
"text": "Polymorphism"
},
{
"code": null,
"e": 29523,
"s": 29510,
"text": "Polymorphism"
},
{
"code": null,
"e": 29584,
"s": 29523,
"text": "Run-Time Polymorphism vs Compile Time Polymorphism (Example)"
},
{
"code": null,
"e": 29645,
"s": 29584,
"text": "Run-Time Polymorphism vs Compile Time Polymorphism (Example)"
},
{
"code": null,
"e": 29682,
"s": 29645,
"text": "Inheritance vs Composition (Example)"
},
{
"code": null,
"e": 29719,
"s": 29682,
"text": "Inheritance vs Composition (Example)"
},
{
"code": null,
"e": 29730,
"s": 29719,
"text": "TCP vs UDP"
},
{
"code": null,
"e": 29741,
"s": 29730,
"text": "TCP vs UDP"
},
{
"code": null,
"e": 29755,
"s": 29741,
"text": "SQL vs NO SQL"
},
{
"code": null,
"e": 29769,
"s": 29755,
"text": "SQL vs NO SQL"
},
{
"code": null,
"e": 29798,
"s": 29769,
"text": "Reason for Deadlock to occur"
},
{
"code": null,
"e": 29827,
"s": 29798,
"text": "Reason for Deadlock to occur"
},
{
"code": null,
"e": 29871,
"s": 29827,
"text": "What happens when you type www.facebook.com"
},
{
"code": null,
"e": 29915,
"s": 29871,
"text": "What happens when you type www.facebook.com"
},
{
"code": null,
"e": 29961,
"s": 29915,
"text": "They took only 1 student and I can’t make it."
},
{
"code": null,
"e": 29968,
"s": 29961,
"text": "Amazon"
},
{
"code": null,
"e": 29978,
"s": 29968,
"text": "Marketing"
},
{
"code": null,
"e": 29988,
"s": 29978,
"text": "On-Campus"
},
{
"code": null,
"e": 30010,
"s": 29988,
"text": "Interview Experiences"
},
{
"code": null,
"e": 30017,
"s": 30010,
"text": "Amazon"
},
{
"code": null,
"e": 30115,
"s": 30017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30166,
"s": 30115,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 30208,
"s": 30166,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 30244,
"s": 30208,
"text": "Zoho Interview | Set 3 (Off-Campus)"
},
{
"code": null,
"e": 30280,
"s": 30244,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 30308,
"s": 30280,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 30346,
"s": 30308,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30418,
"s": 30346,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
},
{
"code": null,
"e": 30464,
"s": 30418,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 30506,
"s": 30464,
"text": "Infosys Interview Experience for DSE 2022"
}
] |
LinkedList add() Method in Java With Examples - GeeksforGeeks
|
15 Nov, 2021
LinkedList is a class implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. As we all know that class contains various methods so do here we will be discussing and implementing add() method to grasp a better understanding of how elements are added in a LinkedList.
For that refer to the below flowchart to get a better understanding of any methods. Note that it is very important to go through flowcharts in programming . Here two cases arises that is default addition of elements and custom addition of elements. Here we will be covering both of them as follows:
Case 1: Default addition by adding at last of List
This method appends the specified element to the end of this list. This function accepts a single parameter element as shown in the above syntax
Syntax:
boolean add(Object element)
Parameters: The element specified by this parameter is appended to the end of the list.
Return Value: Boolean true after execution.
Example:
Java
// Java Program to Illustrate add() Method// of LinkedList class// Where we are Adding at Last of List // Importing required classesimport java.io.*;import java.util.LinkedList; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty LinkedList LinkedList list = new LinkedList(); // Adding elements in the list // using add() method list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Printing the elements of current LinkedList System.out.println("The list is:" + list); // Adding new elements to the end // Note: Default addition happens from last list.add("Last"); list.add("Element"); // Printing elements of updated LinkedList System.out.println("The new List is:" + list); }}
Output:
The list is:[Geeks, for, Geeks, 10, 20]
The new List is:[Geeks, for, Geeks, 10, 20, Last, Element]
Case 2: Adding at the specified index
This method inserts an element at a specified index in the list. It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).
Syntax:
void add(int index, Object element)
Parameters: This method accepts two parameters as described below.
index: The index at which the specified element is to be inserted.
element: The element which is needed to be inserted.
Return Value: Boolean true after execution.
Example:
Java
// Java Program to Illustrate add() Method// of LinkedList class// Adding at a Specified Index // Importing required classes import java.util.LinkedList;import java.io.*; // Main class class GFG { // Main driver method public static void main(String[] args) { // Creating an empty LinkedList of string type LinkedList<String> ll = new LinkedList(); // Adding elements to LinkedList // using add() method ll.add("Geeks"); ll.add("For"); ll.add("Geeks"); // Printing the current elements of LinkedList System.out.println(ll); // Adding element at a particular index // by passing as an argument ll.add(2, "Java"); // Printing the updated elements of LinkedList // after insertion at specified index System.out.println(ll); }}
Output:
[Geeks, For, Geeks]
[Geeks, For, Java, Geeks]
solankimayank
Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 25772,
"s": 25744,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 26197,
"s": 25772,
"text": "LinkedList is a class implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. As we all know that class contains various methods so do here we will be discussing and implementing add() method to grasp a better understanding of how elements are added in a LinkedList. "
},
{
"code": null,
"e": 26496,
"s": 26197,
"text": "For that refer to the below flowchart to get a better understanding of any methods. Note that it is very important to go through flowcharts in programming . Here two cases arises that is default addition of elements and custom addition of elements. Here we will be covering both of them as follows:"
},
{
"code": null,
"e": 26550,
"s": 26496,
"text": "Case 1: Default addition by adding at last of List "
},
{
"code": null,
"e": 26695,
"s": 26550,
"text": "This method appends the specified element to the end of this list. This function accepts a single parameter element as shown in the above syntax"
},
{
"code": null,
"e": 26704,
"s": 26695,
"text": "Syntax: "
},
{
"code": null,
"e": 26732,
"s": 26704,
"text": "boolean add(Object element)"
},
{
"code": null,
"e": 26821,
"s": 26732,
"text": "Parameters: The element specified by this parameter is appended to the end of the list. "
},
{
"code": null,
"e": 26865,
"s": 26821,
"text": "Return Value: Boolean true after execution."
},
{
"code": null,
"e": 26874,
"s": 26865,
"text": "Example:"
},
{
"code": null,
"e": 26879,
"s": 26874,
"text": "Java"
},
{
"code": "// Java Program to Illustrate add() Method// of LinkedList class// Where we are Adding at Last of List // Importing required classesimport java.io.*;import java.util.LinkedList; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty LinkedList LinkedList list = new LinkedList(); // Adding elements in the list // using add() method list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Printing the elements of current LinkedList System.out.println(\"The list is:\" + list); // Adding new elements to the end // Note: Default addition happens from last list.add(\"Last\"); list.add(\"Element\"); // Printing elements of updated LinkedList System.out.println(\"The new List is:\" + list); }}",
"e": 27805,
"s": 26879,
"text": null
},
{
"code": null,
"e": 27814,
"s": 27805,
"text": "Output: "
},
{
"code": null,
"e": 27913,
"s": 27814,
"text": "The list is:[Geeks, for, Geeks, 10, 20]\nThe new List is:[Geeks, for, Geeks, 10, 20, Last, Element]"
},
{
"code": null,
"e": 27952,
"s": 27913,
"text": "Case 2: Adding at the specified index "
},
{
"code": null,
"e": 28149,
"s": 27952,
"text": "This method inserts an element at a specified index in the list. It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices)."
},
{
"code": null,
"e": 28158,
"s": 28149,
"text": "Syntax: "
},
{
"code": null,
"e": 28194,
"s": 28158,
"text": "void add(int index, Object element)"
},
{
"code": null,
"e": 28262,
"s": 28194,
"text": "Parameters: This method accepts two parameters as described below. "
},
{
"code": null,
"e": 28329,
"s": 28262,
"text": "index: The index at which the specified element is to be inserted."
},
{
"code": null,
"e": 28382,
"s": 28329,
"text": "element: The element which is needed to be inserted."
},
{
"code": null,
"e": 28426,
"s": 28382,
"text": "Return Value: Boolean true after execution."
},
{
"code": null,
"e": 28435,
"s": 28426,
"text": "Example:"
},
{
"code": null,
"e": 28440,
"s": 28435,
"text": "Java"
},
{
"code": "// Java Program to Illustrate add() Method// of LinkedList class// Adding at a Specified Index // Importing required classes import java.util.LinkedList;import java.io.*; // Main class class GFG { // Main driver method public static void main(String[] args) { // Creating an empty LinkedList of string type LinkedList<String> ll = new LinkedList(); // Adding elements to LinkedList // using add() method ll.add(\"Geeks\"); ll.add(\"For\"); ll.add(\"Geeks\"); // Printing the current elements of LinkedList System.out.println(ll); // Adding element at a particular index // by passing as an argument ll.add(2, \"Java\"); // Printing the updated elements of LinkedList // after insertion at specified index System.out.println(ll); }}",
"e": 29293,
"s": 28440,
"text": null
},
{
"code": null,
"e": 29301,
"s": 29293,
"text": "Output:"
},
{
"code": null,
"e": 29347,
"s": 29301,
"text": "[Geeks, For, Geeks]\n[Geeks, For, Java, Geeks]"
},
{
"code": null,
"e": 29361,
"s": 29347,
"text": "solankimayank"
},
{
"code": null,
"e": 29381,
"s": 29361,
"text": "Java - util package"
},
{
"code": null,
"e": 29398,
"s": 29381,
"text": "Java-Collections"
},
{
"code": null,
"e": 29413,
"s": 29398,
"text": "Java-Functions"
},
{
"code": null,
"e": 29429,
"s": 29413,
"text": "java-LinkedList"
},
{
"code": null,
"e": 29434,
"s": 29429,
"text": "Java"
},
{
"code": null,
"e": 29439,
"s": 29434,
"text": "Java"
},
{
"code": null,
"e": 29456,
"s": 29439,
"text": "Java-Collections"
},
{
"code": null,
"e": 29554,
"s": 29456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29605,
"s": 29554,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29620,
"s": 29605,
"text": "Stream In Java"
},
{
"code": null,
"e": 29650,
"s": 29620,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29669,
"s": 29650,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29700,
"s": 29669,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29732,
"s": 29700,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29752,
"s": 29732,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29776,
"s": 29752,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29808,
"s": 29776,
"text": "Multidimensional Arrays in Java"
}
] |
Material UI Button Component - GeeksforGeeks
|
14 Apr, 2021
Material-UI is a user interface library that provides predefined and customizable React components for faster and easy web development, these Material-UI components are based on top of Material Design by Google. In this article let’s discuss the Typography component in the Material-UI library.
Buttons are one of the ways in which user communicates in the application. Material UI provides a customizable <Button/> component that can be used for several purposes through its props.
Syntax:
<Button> This ia a Button </Button>
Installing React App:
Step1: Create a React app using the following command.npx create-react-app button-example
Step1: Create a React app using the following command.
npx create-react-app button-example
Step 2: Now get into the project directorycd button-example
Step 2: Now get into the project directory
cd button-example
Installing Material-UI: Installing Material-UI’s source files via npm/yarn, and they take care of injecting the CSS needed.
npm install @material-ui/core
OR
yarn add @material-ui/core
Importing AppBar and Toolbar:
import Button from '@material-ui/core/Button';
Contained Buttons: Contained buttons use elevation and fill to give high-emphasis to the users. They are of several types
Default
Primary
Secondary
Link
Disabled
Props list:
children: It is the content of the button.
classes: It is to override or extend the styles applied to the component.
size: It is used to customize the size of the button.
disableElevation: It is the boolean value to determine the elevation for the button.
fullWidth: It is the boolean value that determines whether it covers the entire width of the container or not.
disabled: It is the Boolean value to enable or disable the button.
disableElevation: It is the boolean value to enable or disable the button’s elevated appearance.
disableFocusRipple: It is the boolean value to enable or disable the keyboard focus ripple effect.
startIcon: Element before the children.
endIcon: Element after the children.
href: Its URL to link to when the button is clicked.
color: It is the color of the component.
disableRipple: It is the boolean value to disable or enable the ripple effect.
Example:
App.js
import React from 'react';import { makeStyles } from '@material-ui/core/styles';import Button from '@material-ui/core/Button';import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme) => ({ root: { textAlign: "center", marginTop: "50px" }, btns:{ '& > *': { margin: theme.spacing(1), }, marginTop: "40px" }})); export default function SimpleContainer() { const classes = useStyles(); return ( <div className={classes.root}> <Typography variant="h4" component="h4"> Welcome to GFG </Typography> <div className={classes.btns}> <Button variant="contained">Default</Button> <Button variant="contained" color="primary"> Primary </Button> <Button variant="contained" color="secondary"> Secondary </Button> <Button variant="contained" disabled> Disabled </Button> <Button variant="contained" color="primary" href="#contained-buttons"> Link </Button> </div> </div> );}
Output:
Text Buttons: Text Buttons are more emphasized on the content of the button rather than the appearance of the button.
Example:
App.js
import React from 'react';import { makeStyles } from '@material-ui/core/styles';import Button from '@material-ui/core/Button';import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme) => ({ root: { textAlign: "center", marginTop: "50px" }, btns:{ '& > *': { margin: theme.spacing(1), }, marginTop: "40px" }})); export default function SimpleContainer() { const classes = useStyles(); return ( <div className={classes.root}> <Typography variant="h4" component="h4"> Welcome to GFG </Typography> <div className={classes.btns}> <Button>Default</Button> <Button color="primary">Primary</Button> <Button color="secondary">Secondary</Button> <Button disabled>Disabled</Button> <Button href="#text-buttons" color="primary"> Link </Button> </div> </div> );}
Output:
Outlined Buttons: They are text buttons wrapped with a border
Example:
App.js
import React from 'react';import { makeStyles } from '@material-ui/core/styles';import Button from '@material-ui/core/Button';import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme) => ({ root: { textAlign: "center", marginTop: "50px" }, btns:{ '& > *': { margin: theme.spacing(1), }, marginTop: "40px" }})); export default function SimpleContainer() { const classes = useStyles(); return ( <div className={classes.root}> <Typography variant="h4" component="h4"> Welcome to GFG </Typography> <div className={classes.btns}> <Button variant="outlined">Default</Button> <Button variant="outlined" color="primary"> Primary </Button> <Button variant="outlined" color="secondary"> Secondary </Button> <Button variant="outlined" disabled> Disabled </Button> <Button variant="outlined" color="primary" href="#outlined-buttons"> Link </Button> </div> </div> );}
Output:
Reference: https://material-ui.com/api/button/
Material-UI
Picked
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
How to navigate on path by button click in react router ?
How to create a table in ReactJS ?
ReactJS useNavigate() Hook
Axios in React: A Guide for Beginners
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24708,
"s": 24680,
"text": "\n14 Apr, 2021"
},
{
"code": null,
"e": 25003,
"s": 24708,
"text": "Material-UI is a user interface library that provides predefined and customizable React components for faster and easy web development, these Material-UI components are based on top of Material Design by Google. In this article let’s discuss the Typography component in the Material-UI library."
},
{
"code": null,
"e": 25191,
"s": 25003,
"text": "Buttons are one of the ways in which user communicates in the application. Material UI provides a customizable <Button/> component that can be used for several purposes through its props."
},
{
"code": null,
"e": 25199,
"s": 25191,
"text": "Syntax:"
},
{
"code": null,
"e": 25236,
"s": 25199,
"text": "<Button> This ia a Button </Button> "
},
{
"code": null,
"e": 25258,
"s": 25236,
"text": "Installing React App:"
},
{
"code": null,
"e": 25348,
"s": 25258,
"text": "Step1: Create a React app using the following command.npx create-react-app button-example"
},
{
"code": null,
"e": 25403,
"s": 25348,
"text": "Step1: Create a React app using the following command."
},
{
"code": null,
"e": 25439,
"s": 25403,
"text": "npx create-react-app button-example"
},
{
"code": null,
"e": 25499,
"s": 25439,
"text": "Step 2: Now get into the project directorycd button-example"
},
{
"code": null,
"e": 25542,
"s": 25499,
"text": "Step 2: Now get into the project directory"
},
{
"code": null,
"e": 25560,
"s": 25542,
"text": "cd button-example"
},
{
"code": null,
"e": 25684,
"s": 25560,
"text": "Installing Material-UI: Installing Material-UI’s source files via npm/yarn, and they take care of injecting the CSS needed."
},
{
"code": null,
"e": 25744,
"s": 25684,
"text": "npm install @material-ui/core\nOR\nyarn add @material-ui/core"
},
{
"code": null,
"e": 25774,
"s": 25744,
"text": "Importing AppBar and Toolbar:"
},
{
"code": null,
"e": 25821,
"s": 25774,
"text": "import Button from '@material-ui/core/Button';"
},
{
"code": null,
"e": 25943,
"s": 25821,
"text": "Contained Buttons: Contained buttons use elevation and fill to give high-emphasis to the users. They are of several types"
},
{
"code": null,
"e": 25951,
"s": 25943,
"text": "Default"
},
{
"code": null,
"e": 25959,
"s": 25951,
"text": "Primary"
},
{
"code": null,
"e": 25969,
"s": 25959,
"text": "Secondary"
},
{
"code": null,
"e": 25974,
"s": 25969,
"text": "Link"
},
{
"code": null,
"e": 25983,
"s": 25974,
"text": "Disabled"
},
{
"code": null,
"e": 25995,
"s": 25983,
"text": "Props list:"
},
{
"code": null,
"e": 26038,
"s": 25995,
"text": "children: It is the content of the button."
},
{
"code": null,
"e": 26112,
"s": 26038,
"text": "classes: It is to override or extend the styles applied to the component."
},
{
"code": null,
"e": 26166,
"s": 26112,
"text": "size: It is used to customize the size of the button."
},
{
"code": null,
"e": 26251,
"s": 26166,
"text": "disableElevation: It is the boolean value to determine the elevation for the button."
},
{
"code": null,
"e": 26362,
"s": 26251,
"text": "fullWidth: It is the boolean value that determines whether it covers the entire width of the container or not."
},
{
"code": null,
"e": 26429,
"s": 26362,
"text": "disabled: It is the Boolean value to enable or disable the button."
},
{
"code": null,
"e": 26527,
"s": 26429,
"text": "disableElevation: It is the boolean value to enable or disable the button’s elevated appearance."
},
{
"code": null,
"e": 26626,
"s": 26527,
"text": "disableFocusRipple: It is the boolean value to enable or disable the keyboard focus ripple effect."
},
{
"code": null,
"e": 26666,
"s": 26626,
"text": "startIcon: Element before the children."
},
{
"code": null,
"e": 26703,
"s": 26666,
"text": "endIcon: Element after the children."
},
{
"code": null,
"e": 26756,
"s": 26703,
"text": "href: Its URL to link to when the button is clicked."
},
{
"code": null,
"e": 26797,
"s": 26756,
"text": "color: It is the color of the component."
},
{
"code": null,
"e": 26876,
"s": 26797,
"text": "disableRipple: It is the boolean value to disable or enable the ripple effect."
},
{
"code": null,
"e": 26885,
"s": 26876,
"text": "Example:"
},
{
"code": null,
"e": 26892,
"s": 26885,
"text": "App.js"
},
{
"code": "import React from 'react';import { makeStyles } from '@material-ui/core/styles';import Button from '@material-ui/core/Button';import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme) => ({ root: { textAlign: \"center\", marginTop: \"50px\" }, btns:{ '& > *': { margin: theme.spacing(1), }, marginTop: \"40px\" }})); export default function SimpleContainer() { const classes = useStyles(); return ( <div className={classes.root}> <Typography variant=\"h4\" component=\"h4\"> Welcome to GFG </Typography> <div className={classes.btns}> <Button variant=\"contained\">Default</Button> <Button variant=\"contained\" color=\"primary\"> Primary </Button> <Button variant=\"contained\" color=\"secondary\"> Secondary </Button> <Button variant=\"contained\" disabled> Disabled </Button> <Button variant=\"contained\" color=\"primary\" href=\"#contained-buttons\"> Link </Button> </div> </div> );}",
"e": 27972,
"s": 26892,
"text": null
},
{
"code": null,
"e": 27980,
"s": 27972,
"text": "Output:"
},
{
"code": null,
"e": 28098,
"s": 27980,
"text": "Text Buttons: Text Buttons are more emphasized on the content of the button rather than the appearance of the button."
},
{
"code": null,
"e": 28107,
"s": 28098,
"text": "Example:"
},
{
"code": null,
"e": 28114,
"s": 28107,
"text": "App.js"
},
{
"code": "import React from 'react';import { makeStyles } from '@material-ui/core/styles';import Button from '@material-ui/core/Button';import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme) => ({ root: { textAlign: \"center\", marginTop: \"50px\" }, btns:{ '& > *': { margin: theme.spacing(1), }, marginTop: \"40px\" }})); export default function SimpleContainer() { const classes = useStyles(); return ( <div className={classes.root}> <Typography variant=\"h4\" component=\"h4\"> Welcome to GFG </Typography> <div className={classes.btns}> <Button>Default</Button> <Button color=\"primary\">Primary</Button> <Button color=\"secondary\">Secondary</Button> <Button disabled>Disabled</Button> <Button href=\"#text-buttons\" color=\"primary\"> Link </Button> </div> </div> );}",
"e": 29027,
"s": 28114,
"text": null
},
{
"code": null,
"e": 29035,
"s": 29027,
"text": "Output:"
},
{
"code": null,
"e": 29097,
"s": 29035,
"text": "Outlined Buttons: They are text buttons wrapped with a border"
},
{
"code": null,
"e": 29106,
"s": 29097,
"text": "Example:"
},
{
"code": null,
"e": 29113,
"s": 29106,
"text": "App.js"
},
{
"code": "import React from 'react';import { makeStyles } from '@material-ui/core/styles';import Button from '@material-ui/core/Button';import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme) => ({ root: { textAlign: \"center\", marginTop: \"50px\" }, btns:{ '& > *': { margin: theme.spacing(1), }, marginTop: \"40px\" }})); export default function SimpleContainer() { const classes = useStyles(); return ( <div className={classes.root}> <Typography variant=\"h4\" component=\"h4\"> Welcome to GFG </Typography> <div className={classes.btns}> <Button variant=\"outlined\">Default</Button> <Button variant=\"outlined\" color=\"primary\"> Primary </Button> <Button variant=\"outlined\" color=\"secondary\"> Secondary </Button> <Button variant=\"outlined\" disabled> Disabled </Button> <Button variant=\"outlined\" color=\"primary\" href=\"#outlined-buttons\"> Link </Button> </div> </div> );}",
"e": 30191,
"s": 29113,
"text": null
},
{
"code": null,
"e": 30199,
"s": 30191,
"text": "Output:"
},
{
"code": null,
"e": 30246,
"s": 30199,
"text": "Reference: https://material-ui.com/api/button/"
},
{
"code": null,
"e": 30258,
"s": 30246,
"text": "Material-UI"
},
{
"code": null,
"e": 30265,
"s": 30258,
"text": "Picked"
},
{
"code": null,
"e": 30273,
"s": 30265,
"text": "ReactJS"
},
{
"code": null,
"e": 30290,
"s": 30273,
"text": "Web Technologies"
},
{
"code": null,
"e": 30388,
"s": 30290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30397,
"s": 30388,
"text": "Comments"
},
{
"code": null,
"e": 30410,
"s": 30397,
"text": "Old Comments"
},
{
"code": null,
"e": 30452,
"s": 30410,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 30510,
"s": 30452,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 30545,
"s": 30510,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 30572,
"s": 30545,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 30610,
"s": 30572,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 30652,
"s": 30610,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30685,
"s": 30652,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30747,
"s": 30685,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30797,
"s": 30747,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to install Tkinter in Python?
|
Tkinter is a standard library in Python which is used for GUI application. Tkinter has various controls which are used to build a GUI-based application.
To install Tkinter, we need Python pre-installed. Tkinter actually comes along when we install Python. While installing Python, we need to check the td/tk and IDLE checkbox. This will install the tkinter and we need not install it separately.
However, if we missed installing Tkinter while installing Python, we can do it later using the pip command.
Type the following commands in command propmt to check is python and pip is installed on your system.
python --version
If python is successfully installed, the version of python installed on your system will be displayed.
pip -V
The version of pip will be displayed, if it is successfully installed on your system.
Tkinter can be installed using pip. The following command is run in the command prompt to install Tkinter.
pip install tk
This command will start downloading and installing packages related to the Tkinter library. Once done, the message of successful installation will be displayed.
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "Tkinter is a standard library in Python which is used for GUI application. Tkinter has various controls which are used to build a GUI-based application."
},
{
"code": null,
"e": 1458,
"s": 1215,
"text": "To install Tkinter, we need Python pre-installed. Tkinter actually comes along when we install Python. While installing Python, we need to check the td/tk and IDLE checkbox. This will install the tkinter and we need not install it separately."
},
{
"code": null,
"e": 1566,
"s": 1458,
"text": "However, if we missed installing Tkinter while installing Python, we can do it later using the pip command."
},
{
"code": null,
"e": 1668,
"s": 1566,
"text": "Type the following commands in command propmt to check is python and pip is installed on your system."
},
{
"code": null,
"e": 1685,
"s": 1668,
"text": "python --version"
},
{
"code": null,
"e": 1788,
"s": 1685,
"text": "If python is successfully installed, the version of python installed on your system will be displayed."
},
{
"code": null,
"e": 1795,
"s": 1788,
"text": "pip -V"
},
{
"code": null,
"e": 1881,
"s": 1795,
"text": "The version of pip will be displayed, if it is successfully installed on your system."
},
{
"code": null,
"e": 1988,
"s": 1881,
"text": "Tkinter can be installed using pip. The following command is run in the command prompt to install Tkinter."
},
{
"code": null,
"e": 2003,
"s": 1988,
"text": "pip install tk"
},
{
"code": null,
"e": 2164,
"s": 2003,
"text": "This command will start downloading and installing packages related to the Tkinter library. Once done, the message of successful installation will be displayed."
}
] |
K-Means Clustering of University Data | by Chris Woodard | Towards Data Science
|
Hello everybody! For this project, I want to introduce K-means clustering, one of the most common clustering algorithms in machine learning. Along the way, we’ll do some exploratory data analysis to understand more about a dataset about universities.
For those of you who may be new to machine learning, clustering is an example of an unsupervised learning model, when we feed uncategorized training data into a model and have our model attempt to categorize that data in some way according to its features.
The alternative is a supervised learning model, where we assign labels to our training data in advance indicating which category each data point belongs to, and the model attempts to predict which category a new data point belongs to.
I worked in education in China for almost 4 years, and my work involved using data analytics to estimate students’ likelihood of admission to universities on their school list given their profile. Just for fun, I’ll create a model in Python using K-means clustering to cluster universities into two groups: private and public. In reality, a student who does at least cursory research on a university website can find out in under a minute whether a school is private or public, but we’ll see if a model can correctly categorize schools based on features that may seem very relevant (out-of-state tuition, graduation rate) and others that might not seem relevant at all (percentage of alumni who donate).
NOTE: we actually have the labels for this data set, but we will NOT use them for the K-means clustering algorithm, since that is an unsupervised learning algorithm. At the end, I’ll compare K-means to a supervised learning algorithm to compare the performance of the two models.
Here are the features in this dataset — feel free to glance at them and think about how well or poorly they might predict a school being public or private:
Apps: Number of applications received
Accept: Number of applications accepted
Enroll: Number of new students enrolled
Top10perc: % of new students from top 10% of their high school class
Top25perc: % of new students from top 25% of their high school class
F.Undergrad: Number of full-time undergraduates
P.Undergrad: Number of part-time undergraduates
Outstate: Out-of-state tuition
Room.Board: Room and board costs
Books: Estimated book costs
Personal: Estimated personal spending
PhD: % of faculty with PhDs
Terminal: % of faculty with a terminal degree (PhD/JD/MD/MBA/etc)
S.F.Ratio: Student/faculty ratio
perc.alumni: % alumni who donate
Expend: Instructional expenditure per student
Grad.Rate: Graduation rate
A good way to start any analysis is to use Pandas.DataFrame.describe() to get some basic statistics about your data.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snscolleges = pd.read_csv(‘College_Data’,index_col=0)colleges.describe()
Purely by looking at the max value of some of these columns, a few things stand out:
It’s common knowledge that top private schools can charge up to $60k/year, but the max out-of-state tuition here is only $21,700, so we can assume this tuition is listed on a per semester basis rather than per year.There’s a school that has above 100% of faculty with PhDs! This seems fishy, but it can probably be explained by a handful of over-achieving faculty who may have a dual PhD that has been double counted.In the same vein, we’ve also got a school with a graduation rate of 118%! We’ll explore this anomaly later...
It’s common knowledge that top private schools can charge up to $60k/year, but the max out-of-state tuition here is only $21,700, so we can assume this tuition is listed on a per semester basis rather than per year.
There’s a school that has above 100% of faculty with PhDs! This seems fishy, but it can probably be explained by a handful of over-achieving faculty who may have a dual PhD that has been double counted.
In the same vein, we’ve also got a school with a graduation rate of 118%! We’ll explore this anomaly later...
Feel free to poke around the mean, median, and other statistics to see what sticks out to you! That’s what makes it exploratory data analysis.
Let’s figure out which college had the highest number of applicants.
colleges.loc[colleges[‘Apps’]==np.max(colleges[‘Apps’])]
Turns out Rutgers has the highest number of applicants and acceptances, but not the highest number of enrollments. Another major bragging point for high schools and universities alike is their student-faculty ratio: the lower the better.
colleges.loc[colleges[‘S.F.Ratio’]==np.min(colleges[‘S.F.Ratio’])]
The winner here is University of Charleston, with a very low ratio of 2.5, which is practically as intimate a teaching environment as homeschooling or private tutoring. Considering that the 25th percentile of the student-faculty ratio is 11.5, U of C is a major outlier.
Now let’s talk money: which university has the highest alumni donation rate?
colleges.loc[colleges[‘perc.alumni’]==np.max(colleges[‘perc.alumni’])]
Hardly surprising that Williams takes the prize as it’s a small liberal arts college (~2000 students total) that caters to largely wealthy families with a strong network. Calling .describe() earlier told us that the median donation percentage was a measly 21%, hence the abundance of on-campus job opportunities as student callers.
Now here’s the juicy stuff: let’s see who’s really getting their dollar’s worth from their university education by looking at the ratio of a school’s expenditure on each student to out-of-state tuition.
colleges[‘expense ratio’] = colleges[‘Expend’]/(colleges[‘Outstate’])colleges.describe()[‘expense ratio’]
WOAH! The fact that the mean is less than 1 tells me that the average school is losing money on its students when considering tuition as the only source of income. In fact, ~69% of universities are investing more money in their students than they’re charging, which does not bode well for the future of most universities. The school with the highest ratio is probably some Ivy League school, right?
colleges.loc[colleges[‘expense ratio’]==np.max(colleges[‘expense ratio’])]
WRONG! The best “Bang for Your Buck” award goes to...*drum roll*...University of Alabama at Birmingham with an expense ratio of 3.68! However, a more cynical way of looking at it is if UAB’s spending nearly 4x the out-of-state tuition on every student, then it might not be in business much longer...so if you’re in the HS class of 2021, get in while they’re still afloat, but hold tight to your wallet because those student callers will be working overtime to snag your donation dollars!
For anyone who was wondering, the biggest thief (the college with the lowest expense ratio) is Lindenwood College with a ratio of 0.378. Yikes!
It’s time to create some data visualizations!
Let’s investigate how tuition varies with the number of students and by whether a school is public or private. I suspect that tuition is higher for private schools because they don’t receive government funding like public schools. The number of full-time students could push the needle either way, as more students means more staff and more buildings, but it’s possible that a university could benefit from economies of scale for construction projects for such a large number of students.
plt.figure(figsize=(8,6))sns.scatterplot(data=colleges,x='Outstate',y='F.Undergrad',hue='Private')
Hmmm...very interesting how the school’s undergrad population is almost completely uncorrelated with tuition, which begs the question: where is that money going? Let’s zoom in on out-of-state tuition and take a look at graduation rate as well.
sns.set_style('darkgrid')g = sns.FacetGrid(colleges,hue='Private',palette='coolwarm',height=6,aspect=1.5)g = g.map(plt.hist,'Outstate',bins=20,alpha=0.7)plt.legend(labels=['Private','Public'])
grid = sns.FacetGrid(colleges,hue='Private',palette='coolwarm',height=6,aspect=1.5)grid = grid.map(plt.hist,'Grad.Rate',bins=20,alpha=0.7)plt.legend(labels=['Private','Public'])
As expected, out-of-state tuition is higher for private schools, and so is graduation rate — perhaps because if a student is investing that much money into their education, their parents are thinking, “You better finish...or else!”
Now back to that school with a graduation rate of higher than 100%...turns out the culprit is Cazenovia College. Maybe this school pulled a fast one and counted double majors as having graduated twice? In reality, this makes no sense, so I’m going to change this graduation rate to 100%.
Now on to the moment you’ve all been waiting for: K-means clustering!
First we’ll import KMeans from Scikit-learn, the most popular package for machine learning in Python. The way K-means works is the following:
Pick the number of clusters. Whether you choose 2 or 4 or 10 is dictated by the domain of the specific problem. In this case, we’re sorting into public and private schools, so we will choose the number of clusters to be 2. If you were analyzing genetic variations in a population and knew beforehand there were 7 known variants, then you would choose 7.Randomly assign each data point to a category.Take the centroid of the data points in each category. For those of you who think a centroid is some cool-sounding type of asteroid, it’s multivariable calculus-speak for “the average of all the data in each cluster.” You already understand this intuitively for 1-D data: the average price of grocery items gets you a single number like $52. If you calculate the average price AND average quantity of grocery items (2 dimensions), you’ll get two numbers like $52 and 2 items. In this dataset, we have 18 features, so each centroid corresponds to a 18-D set of coordinates. And no, we’re not going to try and visualize this.Re-assign each data point to the category corresponding to the nearest centroid.Repeat Steps 3 and 4 until there are no more changes in category.
Pick the number of clusters. Whether you choose 2 or 4 or 10 is dictated by the domain of the specific problem. In this case, we’re sorting into public and private schools, so we will choose the number of clusters to be 2. If you were analyzing genetic variations in a population and knew beforehand there were 7 known variants, then you would choose 7.
Randomly assign each data point to a category.
Take the centroid of the data points in each category. For those of you who think a centroid is some cool-sounding type of asteroid, it’s multivariable calculus-speak for “the average of all the data in each cluster.” You already understand this intuitively for 1-D data: the average price of grocery items gets you a single number like $52. If you calculate the average price AND average quantity of grocery items (2 dimensions), you’ll get two numbers like $52 and 2 items. In this dataset, we have 18 features, so each centroid corresponds to a 18-D set of coordinates. And no, we’re not going to try and visualize this.
Re-assign each data point to the category corresponding to the nearest centroid.
Repeat Steps 3 and 4 until there are no more changes in category.
Here’s a great image to help illustrate:
Coding a K-means model in Python is very simple, as shown below, and the clusters that are generated by the model can be referenced with km.labels_ (don’t forget the underscore at the end!).
from sklearn.cluster import KMeanskm = KMeans(n_clusters=2)km.fit(colleges.drop(‘Private’,axis=1))
There is no perfect way to evaluate clustering if you don’t have the labels. However, in this case, the colleges data set told us whether each school was public or private, so we can cross-validate our K-means model with these labels to compare the performance of supervised and unsupervised models in general.
Two quick ways to evaluate the performance of a machine learning model is to look at a confusion matrix and a classification report.
def convertToCluster(cluster): if cluster=='Yes': return 1 else: return 0colleges['Cluster'] = colleges['Private'].apply(convertToCluster)from sklearn.metrics import classification_report,confusion_matrixprint(confusion_matrix(colleges['Cluster'],km.labels_))print(classification_report(colleges['Cluster'],km.labels_))
If you’re used to supervised learning algorithms, you may look at these results and think, “22% accuracy?! This model is garbage! What are unsupervised models good for anyway?” But remember the definition of unsupervised: the model is aiming to make sense out of the mess of 18 features that we’ve given it, with no labels. This is not an easy task, so let’s give credit to K-means where credit is due.
Let’s actually compare the results we just got to that of a supervised learning model to evaluate their performance (or at the very least, set our expectations to the proper low level for unsupervised learning 😉). Let’s just go for a classic logistic regression.
from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionunis = collegesX = unis.drop('Cluster',axis=1)y = unis['Cluster']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)logmodel = LogisticRegression()logmodel.fit(X_train,y_train)preds = logmodel.predict(X_test)print("Using K means clustering (unsupervised):\n")print(confusion_matrix(colleges['Cluster'],km.labels_))print(classification_report(colleges['Cluster'],km.labels_))print("Using logistic regression (supervised):\n")print(confusion_matrix(y_test,preds))print(classification_report(y_test,preds))
Behold the power of labeling, folks. Using a simple logistic regression, a supervised learning model, the accuracy shot up from 22% to 91%, which probably could be improved upon with another model choice.
Hopefully you can begin to see how K Means is useful for making sense out of messy data! Feel free to explore other areas using Exploratory Data Analysis and see what you find!
|
[
{
"code": null,
"e": 422,
"s": 171,
"text": "Hello everybody! For this project, I want to introduce K-means clustering, one of the most common clustering algorithms in machine learning. Along the way, we’ll do some exploratory data analysis to understand more about a dataset about universities."
},
{
"code": null,
"e": 679,
"s": 422,
"text": "For those of you who may be new to machine learning, clustering is an example of an unsupervised learning model, when we feed uncategorized training data into a model and have our model attempt to categorize that data in some way according to its features."
},
{
"code": null,
"e": 914,
"s": 679,
"text": "The alternative is a supervised learning model, where we assign labels to our training data in advance indicating which category each data point belongs to, and the model attempts to predict which category a new data point belongs to."
},
{
"code": null,
"e": 1618,
"s": 914,
"text": "I worked in education in China for almost 4 years, and my work involved using data analytics to estimate students’ likelihood of admission to universities on their school list given their profile. Just for fun, I’ll create a model in Python using K-means clustering to cluster universities into two groups: private and public. In reality, a student who does at least cursory research on a university website can find out in under a minute whether a school is private or public, but we’ll see if a model can correctly categorize schools based on features that may seem very relevant (out-of-state tuition, graduation rate) and others that might not seem relevant at all (percentage of alumni who donate)."
},
{
"code": null,
"e": 1898,
"s": 1618,
"text": "NOTE: we actually have the labels for this data set, but we will NOT use them for the K-means clustering algorithm, since that is an unsupervised learning algorithm. At the end, I’ll compare K-means to a supervised learning algorithm to compare the performance of the two models."
},
{
"code": null,
"e": 2054,
"s": 1898,
"text": "Here are the features in this dataset — feel free to glance at them and think about how well or poorly they might predict a school being public or private:"
},
{
"code": null,
"e": 2092,
"s": 2054,
"text": "Apps: Number of applications received"
},
{
"code": null,
"e": 2132,
"s": 2092,
"text": "Accept: Number of applications accepted"
},
{
"code": null,
"e": 2172,
"s": 2132,
"text": "Enroll: Number of new students enrolled"
},
{
"code": null,
"e": 2241,
"s": 2172,
"text": "Top10perc: % of new students from top 10% of their high school class"
},
{
"code": null,
"e": 2310,
"s": 2241,
"text": "Top25perc: % of new students from top 25% of their high school class"
},
{
"code": null,
"e": 2358,
"s": 2310,
"text": "F.Undergrad: Number of full-time undergraduates"
},
{
"code": null,
"e": 2406,
"s": 2358,
"text": "P.Undergrad: Number of part-time undergraduates"
},
{
"code": null,
"e": 2437,
"s": 2406,
"text": "Outstate: Out-of-state tuition"
},
{
"code": null,
"e": 2470,
"s": 2437,
"text": "Room.Board: Room and board costs"
},
{
"code": null,
"e": 2498,
"s": 2470,
"text": "Books: Estimated book costs"
},
{
"code": null,
"e": 2536,
"s": 2498,
"text": "Personal: Estimated personal spending"
},
{
"code": null,
"e": 2564,
"s": 2536,
"text": "PhD: % of faculty with PhDs"
},
{
"code": null,
"e": 2630,
"s": 2564,
"text": "Terminal: % of faculty with a terminal degree (PhD/JD/MD/MBA/etc)"
},
{
"code": null,
"e": 2663,
"s": 2630,
"text": "S.F.Ratio: Student/faculty ratio"
},
{
"code": null,
"e": 2696,
"s": 2663,
"text": "perc.alumni: % alumni who donate"
},
{
"code": null,
"e": 2742,
"s": 2696,
"text": "Expend: Instructional expenditure per student"
},
{
"code": null,
"e": 2769,
"s": 2742,
"text": "Grad.Rate: Graduation rate"
},
{
"code": null,
"e": 2886,
"s": 2769,
"text": "A good way to start any analysis is to use Pandas.DataFrame.describe() to get some basic statistics about your data."
},
{
"code": null,
"e": 3045,
"s": 2886,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snscolleges = pd.read_csv(‘College_Data’,index_col=0)colleges.describe()"
},
{
"code": null,
"e": 3130,
"s": 3045,
"text": "Purely by looking at the max value of some of these columns, a few things stand out:"
},
{
"code": null,
"e": 3657,
"s": 3130,
"text": "It’s common knowledge that top private schools can charge up to $60k/year, but the max out-of-state tuition here is only $21,700, so we can assume this tuition is listed on a per semester basis rather than per year.There’s a school that has above 100% of faculty with PhDs! This seems fishy, but it can probably be explained by a handful of over-achieving faculty who may have a dual PhD that has been double counted.In the same vein, we’ve also got a school with a graduation rate of 118%! We’ll explore this anomaly later..."
},
{
"code": null,
"e": 3873,
"s": 3657,
"text": "It’s common knowledge that top private schools can charge up to $60k/year, but the max out-of-state tuition here is only $21,700, so we can assume this tuition is listed on a per semester basis rather than per year."
},
{
"code": null,
"e": 4076,
"s": 3873,
"text": "There’s a school that has above 100% of faculty with PhDs! This seems fishy, but it can probably be explained by a handful of over-achieving faculty who may have a dual PhD that has been double counted."
},
{
"code": null,
"e": 4186,
"s": 4076,
"text": "In the same vein, we’ve also got a school with a graduation rate of 118%! We’ll explore this anomaly later..."
},
{
"code": null,
"e": 4329,
"s": 4186,
"text": "Feel free to poke around the mean, median, and other statistics to see what sticks out to you! That’s what makes it exploratory data analysis."
},
{
"code": null,
"e": 4398,
"s": 4329,
"text": "Let’s figure out which college had the highest number of applicants."
},
{
"code": null,
"e": 4455,
"s": 4398,
"text": "colleges.loc[colleges[‘Apps’]==np.max(colleges[‘Apps’])]"
},
{
"code": null,
"e": 4693,
"s": 4455,
"text": "Turns out Rutgers has the highest number of applicants and acceptances, but not the highest number of enrollments. Another major bragging point for high schools and universities alike is their student-faculty ratio: the lower the better."
},
{
"code": null,
"e": 4760,
"s": 4693,
"text": "colleges.loc[colleges[‘S.F.Ratio’]==np.min(colleges[‘S.F.Ratio’])]"
},
{
"code": null,
"e": 5031,
"s": 4760,
"text": "The winner here is University of Charleston, with a very low ratio of 2.5, which is practically as intimate a teaching environment as homeschooling or private tutoring. Considering that the 25th percentile of the student-faculty ratio is 11.5, U of C is a major outlier."
},
{
"code": null,
"e": 5108,
"s": 5031,
"text": "Now let’s talk money: which university has the highest alumni donation rate?"
},
{
"code": null,
"e": 5179,
"s": 5108,
"text": "colleges.loc[colleges[‘perc.alumni’]==np.max(colleges[‘perc.alumni’])]"
},
{
"code": null,
"e": 5511,
"s": 5179,
"text": "Hardly surprising that Williams takes the prize as it’s a small liberal arts college (~2000 students total) that caters to largely wealthy families with a strong network. Calling .describe() earlier told us that the median donation percentage was a measly 21%, hence the abundance of on-campus job opportunities as student callers."
},
{
"code": null,
"e": 5714,
"s": 5511,
"text": "Now here’s the juicy stuff: let’s see who’s really getting their dollar’s worth from their university education by looking at the ratio of a school’s expenditure on each student to out-of-state tuition."
},
{
"code": null,
"e": 5820,
"s": 5714,
"text": "colleges[‘expense ratio’] = colleges[‘Expend’]/(colleges[‘Outstate’])colleges.describe()[‘expense ratio’]"
},
{
"code": null,
"e": 6219,
"s": 5820,
"text": "WOAH! The fact that the mean is less than 1 tells me that the average school is losing money on its students when considering tuition as the only source of income. In fact, ~69% of universities are investing more money in their students than they’re charging, which does not bode well for the future of most universities. The school with the highest ratio is probably some Ivy League school, right?"
},
{
"code": null,
"e": 6294,
"s": 6219,
"text": "colleges.loc[colleges[‘expense ratio’]==np.max(colleges[‘expense ratio’])]"
},
{
"code": null,
"e": 6783,
"s": 6294,
"text": "WRONG! The best “Bang for Your Buck” award goes to...*drum roll*...University of Alabama at Birmingham with an expense ratio of 3.68! However, a more cynical way of looking at it is if UAB’s spending nearly 4x the out-of-state tuition on every student, then it might not be in business much longer...so if you’re in the HS class of 2021, get in while they’re still afloat, but hold tight to your wallet because those student callers will be working overtime to snag your donation dollars!"
},
{
"code": null,
"e": 6927,
"s": 6783,
"text": "For anyone who was wondering, the biggest thief (the college with the lowest expense ratio) is Lindenwood College with a ratio of 0.378. Yikes!"
},
{
"code": null,
"e": 6973,
"s": 6927,
"text": "It’s time to create some data visualizations!"
},
{
"code": null,
"e": 7462,
"s": 6973,
"text": "Let’s investigate how tuition varies with the number of students and by whether a school is public or private. I suspect that tuition is higher for private schools because they don’t receive government funding like public schools. The number of full-time students could push the needle either way, as more students means more staff and more buildings, but it’s possible that a university could benefit from economies of scale for construction projects for such a large number of students."
},
{
"code": null,
"e": 7561,
"s": 7462,
"text": "plt.figure(figsize=(8,6))sns.scatterplot(data=colleges,x='Outstate',y='F.Undergrad',hue='Private')"
},
{
"code": null,
"e": 7805,
"s": 7561,
"text": "Hmmm...very interesting how the school’s undergrad population is almost completely uncorrelated with tuition, which begs the question: where is that money going? Let’s zoom in on out-of-state tuition and take a look at graduation rate as well."
},
{
"code": null,
"e": 7998,
"s": 7805,
"text": "sns.set_style('darkgrid')g = sns.FacetGrid(colleges,hue='Private',palette='coolwarm',height=6,aspect=1.5)g = g.map(plt.hist,'Outstate',bins=20,alpha=0.7)plt.legend(labels=['Private','Public'])"
},
{
"code": null,
"e": 8176,
"s": 7998,
"text": "grid = sns.FacetGrid(colleges,hue='Private',palette='coolwarm',height=6,aspect=1.5)grid = grid.map(plt.hist,'Grad.Rate',bins=20,alpha=0.7)plt.legend(labels=['Private','Public'])"
},
{
"code": null,
"e": 8408,
"s": 8176,
"text": "As expected, out-of-state tuition is higher for private schools, and so is graduation rate — perhaps because if a student is investing that much money into their education, their parents are thinking, “You better finish...or else!”"
},
{
"code": null,
"e": 8696,
"s": 8408,
"text": "Now back to that school with a graduation rate of higher than 100%...turns out the culprit is Cazenovia College. Maybe this school pulled a fast one and counted double majors as having graduated twice? In reality, this makes no sense, so I’m going to change this graduation rate to 100%."
},
{
"code": null,
"e": 8766,
"s": 8696,
"text": "Now on to the moment you’ve all been waiting for: K-means clustering!"
},
{
"code": null,
"e": 8908,
"s": 8766,
"text": "First we’ll import KMeans from Scikit-learn, the most popular package for machine learning in Python. The way K-means works is the following:"
},
{
"code": null,
"e": 10076,
"s": 8908,
"text": "Pick the number of clusters. Whether you choose 2 or 4 or 10 is dictated by the domain of the specific problem. In this case, we’re sorting into public and private schools, so we will choose the number of clusters to be 2. If you were analyzing genetic variations in a population and knew beforehand there were 7 known variants, then you would choose 7.Randomly assign each data point to a category.Take the centroid of the data points in each category. For those of you who think a centroid is some cool-sounding type of asteroid, it’s multivariable calculus-speak for “the average of all the data in each cluster.” You already understand this intuitively for 1-D data: the average price of grocery items gets you a single number like $52. If you calculate the average price AND average quantity of grocery items (2 dimensions), you’ll get two numbers like $52 and 2 items. In this dataset, we have 18 features, so each centroid corresponds to a 18-D set of coordinates. And no, we’re not going to try and visualize this.Re-assign each data point to the category corresponding to the nearest centroid.Repeat Steps 3 and 4 until there are no more changes in category."
},
{
"code": null,
"e": 10430,
"s": 10076,
"text": "Pick the number of clusters. Whether you choose 2 or 4 or 10 is dictated by the domain of the specific problem. In this case, we’re sorting into public and private schools, so we will choose the number of clusters to be 2. If you were analyzing genetic variations in a population and knew beforehand there were 7 known variants, then you would choose 7."
},
{
"code": null,
"e": 10477,
"s": 10430,
"text": "Randomly assign each data point to a category."
},
{
"code": null,
"e": 11101,
"s": 10477,
"text": "Take the centroid of the data points in each category. For those of you who think a centroid is some cool-sounding type of asteroid, it’s multivariable calculus-speak for “the average of all the data in each cluster.” You already understand this intuitively for 1-D data: the average price of grocery items gets you a single number like $52. If you calculate the average price AND average quantity of grocery items (2 dimensions), you’ll get two numbers like $52 and 2 items. In this dataset, we have 18 features, so each centroid corresponds to a 18-D set of coordinates. And no, we’re not going to try and visualize this."
},
{
"code": null,
"e": 11182,
"s": 11101,
"text": "Re-assign each data point to the category corresponding to the nearest centroid."
},
{
"code": null,
"e": 11248,
"s": 11182,
"text": "Repeat Steps 3 and 4 until there are no more changes in category."
},
{
"code": null,
"e": 11289,
"s": 11248,
"text": "Here’s a great image to help illustrate:"
},
{
"code": null,
"e": 11480,
"s": 11289,
"text": "Coding a K-means model in Python is very simple, as shown below, and the clusters that are generated by the model can be referenced with km.labels_ (don’t forget the underscore at the end!)."
},
{
"code": null,
"e": 11579,
"s": 11480,
"text": "from sklearn.cluster import KMeanskm = KMeans(n_clusters=2)km.fit(colleges.drop(‘Private’,axis=1))"
},
{
"code": null,
"e": 11890,
"s": 11579,
"text": "There is no perfect way to evaluate clustering if you don’t have the labels. However, in this case, the colleges data set told us whether each school was public or private, so we can cross-validate our K-means model with these labels to compare the performance of supervised and unsupervised models in general."
},
{
"code": null,
"e": 12023,
"s": 11890,
"text": "Two quick ways to evaluate the performance of a machine learning model is to look at a confusion matrix and a classification report."
},
{
"code": null,
"e": 12363,
"s": 12023,
"text": "def convertToCluster(cluster): if cluster=='Yes': return 1 else: return 0colleges['Cluster'] = colleges['Private'].apply(convertToCluster)from sklearn.metrics import classification_report,confusion_matrixprint(confusion_matrix(colleges['Cluster'],km.labels_))print(classification_report(colleges['Cluster'],km.labels_))"
},
{
"code": null,
"e": 12766,
"s": 12363,
"text": "If you’re used to supervised learning algorithms, you may look at these results and think, “22% accuracy?! This model is garbage! What are unsupervised models good for anyway?” But remember the definition of unsupervised: the model is aiming to make sense out of the mess of 18 features that we’ve given it, with no labels. This is not an easy task, so let’s give credit to K-means where credit is due."
},
{
"code": null,
"e": 13029,
"s": 12766,
"text": "Let’s actually compare the results we just got to that of a supervised learning model to evaluate their performance (or at the very least, set our expectations to the proper low level for unsupervised learning 😉). Let’s just go for a classic logistic regression."
},
{
"code": null,
"e": 13657,
"s": 13029,
"text": "from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionunis = collegesX = unis.drop('Cluster',axis=1)y = unis['Cluster']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)logmodel = LogisticRegression()logmodel.fit(X_train,y_train)preds = logmodel.predict(X_test)print(\"Using K means clustering (unsupervised):\\n\")print(confusion_matrix(colleges['Cluster'],km.labels_))print(classification_report(colleges['Cluster'],km.labels_))print(\"Using logistic regression (supervised):\\n\")print(confusion_matrix(y_test,preds))print(classification_report(y_test,preds))"
},
{
"code": null,
"e": 13862,
"s": 13657,
"text": "Behold the power of labeling, folks. Using a simple logistic regression, a supervised learning model, the accuracy shot up from 22% to 91%, which probably could be improved upon with another model choice."
}
] |
TypeScript - Arrays
|
The use of variables to store values poses the following limitations −
Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values.
Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values.
Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration.
Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration.
TypeScript introduces the concept of arrays to tackle the same. An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user defined type.
Here is a list of the features of an array −
An array declaration allocates sequential memory blocks.
An array declaration allocates sequential memory blocks.
Arrays are static. This means that an array once initialized cannot be resized.
Arrays are static. This means that an array once initialized cannot be resized.
Each memory block represents an array element.
Each memory block represents an array element.
Array elements are identified by a unique integer called as the subscript / index of the element.
Array elements are identified by a unique integer called as the subscript / index of the element.
Like variables, arrays too, should be declared before they are used. Use the var keyword to declare an array.
Like variables, arrays too, should be declared before they are used. Use the var keyword to declare an array.
Array initialization refers to populating the array elements.
Array initialization refers to populating the array elements.
Array element values can be updated or modified but cannot be deleted.
Array element values can be updated or modified but cannot be deleted.
To declare an initialize an array in Typescript use the following syntax −
var array_name[:datatype]; //declaration
array_name = [val1,val2,valn..] //initialization
An array declaration without the data type is deemed to be of the type any. The type of such an array is inferred from the data type of the array’s first element during initialization.
For example, a declaration like − var numlist:number[] = [2,4,6,8] will create an array as given below −
The array pointer refers to the first element by default.
Arrays may be declared and initialized in a single statement. The syntax for the same is −
var array_name[:data type] = [val1,val2...valn]
Note − The pair of [] is called the dimension of the array.
The array name followed by the subscript is used refer to an array element. Its syntax is as follows −
array_name[subscript] = value
var alphas:string[];
alphas = ["1","2","3","4"]
console.log(alphas[0]);
console.log(alphas[1]);
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var alphas;
alphas = ["1", "2", "3", "4"];
console.log(alphas[0]);
console.log(alphas[1]);
The output of the above code is as follows −
1
2
var nums:number[] = [1,2,3,3]
console.log(nums[0]);
console.log(nums[1]);
console.log(nums[2]);
console.log(nums[3]);
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var nums = [1, 2, 3, 3];
console.log(nums[0]);
console.log(nums[1]);
console.log(nums[2]);
console.log(nums[3]);
Its output is as follows −
1
2
3
3
An array can also be created using the Array object. The Array constructor can be passed.
A numeric value that represents the size of the array or
A numeric value that represents the size of the array or
A list of comma separated values.
A list of comma separated values.
The following example shows how to create an array using this method.
var arr_names:number[] = new Array(4)
for(var i = 0;i<arr_names.length;i++) {
arr_names[i] = i * 2
console.log(arr_names[i])
}
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var arr_names = new Array(4);
for (var i = 0; i < arr_names.length; i++) {
arr_names[i] = i * 2;
console.log(arr_names[i]);
}
Its output is as follows −
0
2
4
6
var names:string[] = new Array("Mary","Tom","Jack","Jill")
for(var i = 0;i<names.length;i++) {
console.log(names[i])
}
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var names = new Array("Mary", "Tom", "Jack", "Jill");
for (var i = 0; i < names.length; i++) {
console.log(names[i]);
}
Its output is as follows −
Mary
Tom
Jack
Jill
A list of the methods of the Array object along with their description is given below.
Returns a new array comprised of this array joined with other array(s) and/or value(s).
Returns true if every element in this array satisfies the provided testing function.
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
Calls a function for each element in the array.
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
Joins all elements of an array into a string.
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
Creates a new array with the results of calling a provided function on every element in this array.
Removes the last element from an array and returns that element.
Adds one or more elements to the end of an array and returns the new length of the array.
Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
Removes the first element from an array and returns that element.
Extracts a section of an array and returns a new array.
Returns true if at least one element in this array satisfies the provided testing function.
Sorts the elements of an array.
Adds and/or removes elements from an array.
Returns a string representing the array and its elements.
Adds one or more elements to the front of an array and returns the new length of the array.
Refers to breaking up the structure of an entity. TypeScript supports destructuring when used in the context of an array.
var arr:number[] = [12,13]
var[x,y] = arr
console.log(x)
console.log(y)
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var arr = [12, 13];
var x = arr[0], y = arr[1];
console.log(x);
console.log(y);
Its output is as follows −
12
13
One can use the for...in loop to traverse through an array.
var j:any;
var nums:number[] = [1001,1002,1003,1004]
for(j in nums) {
console.log(nums[j])
}
The loop performs an index based array traversal.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var j;
var nums = [1001, 1002, 1003, 1004];
for (j in nums) {
console.log(nums[j]);
}
The output of the above code is given below −
1001
1002
1003
1004
TypeScript supports the following concepts in arrays −
TypeScript supports multidimensional arrays. The simplest form of the multidimensional array is the twodimensional array.
You can pass to the function a pointer to an array by specifying the array's name without an index.
Allows a function to return an array
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2119,
"s": 2048,
"text": "The use of variables to store values poses the following limitations −"
},
{
"code": null,
"e": 2413,
"s": 2119,
"text": "Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values."
},
{
"code": null,
"e": 2707,
"s": 2413,
"text": "Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values."
},
{
"code": null,
"e": 2859,
"s": 2707,
"text": "Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration."
},
{
"code": null,
"e": 3011,
"s": 2859,
"text": "Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration."
},
{
"code": null,
"e": 3220,
"s": 3011,
"text": "TypeScript introduces the concept of arrays to tackle the same. An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user defined type."
},
{
"code": null,
"e": 3265,
"s": 3220,
"text": "Here is a list of the features of an array −"
},
{
"code": null,
"e": 3322,
"s": 3265,
"text": "An array declaration allocates sequential memory blocks."
},
{
"code": null,
"e": 3379,
"s": 3322,
"text": "An array declaration allocates sequential memory blocks."
},
{
"code": null,
"e": 3459,
"s": 3379,
"text": "Arrays are static. This means that an array once initialized cannot be resized."
},
{
"code": null,
"e": 3539,
"s": 3459,
"text": "Arrays are static. This means that an array once initialized cannot be resized."
},
{
"code": null,
"e": 3586,
"s": 3539,
"text": "Each memory block represents an array element."
},
{
"code": null,
"e": 3633,
"s": 3586,
"text": "Each memory block represents an array element."
},
{
"code": null,
"e": 3731,
"s": 3633,
"text": "Array elements are identified by a unique integer called as the subscript / index of the element."
},
{
"code": null,
"e": 3829,
"s": 3731,
"text": "Array elements are identified by a unique integer called as the subscript / index of the element."
},
{
"code": null,
"e": 3939,
"s": 3829,
"text": "Like variables, arrays too, should be declared before they are used. Use the var keyword to declare an array."
},
{
"code": null,
"e": 4049,
"s": 3939,
"text": "Like variables, arrays too, should be declared before they are used. Use the var keyword to declare an array."
},
{
"code": null,
"e": 4111,
"s": 4049,
"text": "Array initialization refers to populating the array elements."
},
{
"code": null,
"e": 4173,
"s": 4111,
"text": "Array initialization refers to populating the array elements."
},
{
"code": null,
"e": 4244,
"s": 4173,
"text": "Array element values can be updated or modified but cannot be deleted."
},
{
"code": null,
"e": 4315,
"s": 4244,
"text": "Array element values can be updated or modified but cannot be deleted."
},
{
"code": null,
"e": 4390,
"s": 4315,
"text": "To declare an initialize an array in Typescript use the following syntax −"
},
{
"code": null,
"e": 4491,
"s": 4390,
"text": "var array_name[:datatype]; //declaration \narray_name = [val1,val2,valn..] //initialization\n"
},
{
"code": null,
"e": 4676,
"s": 4491,
"text": "An array declaration without the data type is deemed to be of the type any. The type of such an array is inferred from the data type of the array’s first element during initialization."
},
{
"code": null,
"e": 4781,
"s": 4676,
"text": "For example, a declaration like − var numlist:number[] = [2,4,6,8] will create an array as given below −"
},
{
"code": null,
"e": 4839,
"s": 4781,
"text": "The array pointer refers to the first element by default."
},
{
"code": null,
"e": 4930,
"s": 4839,
"text": "Arrays may be declared and initialized in a single statement. The syntax for the same is −"
},
{
"code": null,
"e": 4979,
"s": 4930,
"text": "var array_name[:data type] = [val1,val2...valn]\n"
},
{
"code": null,
"e": 5039,
"s": 4979,
"text": "Note − The pair of [] is called the dimension of the array."
},
{
"code": null,
"e": 5142,
"s": 5039,
"text": "The array name followed by the subscript is used refer to an array element. Its syntax is as follows −"
},
{
"code": null,
"e": 5173,
"s": 5142,
"text": "array_name[subscript] = value\n"
},
{
"code": null,
"e": 5273,
"s": 5173,
"text": "var alphas:string[]; \nalphas = [\"1\",\"2\",\"3\",\"4\"] \nconsole.log(alphas[0]); \nconsole.log(alphas[1]);\n"
},
{
"code": null,
"e": 5332,
"s": 5273,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 5457,
"s": 5332,
"text": "//Generated by typescript 1.8.10\nvar alphas;\nalphas = [\"1\", \"2\", \"3\", \"4\"];\nconsole.log(alphas[0]);\nconsole.log(alphas[1]);\n"
},
{
"code": null,
"e": 5502,
"s": 5457,
"text": "The output of the above code is as follows −"
},
{
"code": null,
"e": 5509,
"s": 5502,
"text": "1 \n2 \n"
},
{
"code": null,
"e": 5632,
"s": 5509,
"text": "var nums:number[] = [1,2,3,3] \nconsole.log(nums[0]); \nconsole.log(nums[1]); \nconsole.log(nums[2]); \nconsole.log(nums[3]);\n"
},
{
"code": null,
"e": 5691,
"s": 5632,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 5838,
"s": 5691,
"text": "//Generated by typescript 1.8.10\nvar nums = [1, 2, 3, 3];\nconsole.log(nums[0]);\nconsole.log(nums[1]);\nconsole.log(nums[2]);\nconsole.log(nums[3]);\n"
},
{
"code": null,
"e": 5865,
"s": 5838,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5878,
"s": 5865,
"text": "1 \n2 \n3 \n3 \n"
},
{
"code": null,
"e": 5968,
"s": 5878,
"text": "An array can also be created using the Array object. The Array constructor can be passed."
},
{
"code": null,
"e": 6025,
"s": 5968,
"text": "A numeric value that represents the size of the array or"
},
{
"code": null,
"e": 6082,
"s": 6025,
"text": "A numeric value that represents the size of the array or"
},
{
"code": null,
"e": 6116,
"s": 6082,
"text": "A list of comma separated values."
},
{
"code": null,
"e": 6150,
"s": 6116,
"text": "A list of comma separated values."
},
{
"code": null,
"e": 6220,
"s": 6150,
"text": "The following example shows how to create an array using this method."
},
{
"code": null,
"e": 6360,
"s": 6220,
"text": "var arr_names:number[] = new Array(4) \n\nfor(var i = 0;i<arr_names.length;i++) { \n arr_names[i] = i * 2 \n console.log(arr_names[i]) \n}\n"
},
{
"code": null,
"e": 6418,
"s": 6360,
"text": "On compiling, it will generate following JavaScript code."
},
{
"code": null,
"e": 6585,
"s": 6418,
"text": "//Generated by typescript 1.8.10\nvar arr_names = new Array(4);\n\nfor (var i = 0; i < arr_names.length; i++) {\n arr_names[i] = i * 2;\n console.log(arr_names[i]);\n}\n"
},
{
"code": null,
"e": 6612,
"s": 6585,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6625,
"s": 6612,
"text": "0 \n2 \n4 \n6 \n"
},
{
"code": null,
"e": 6752,
"s": 6625,
"text": "var names:string[] = new Array(\"Mary\",\"Tom\",\"Jack\",\"Jill\") \n\nfor(var i = 0;i<names.length;i++) { \n console.log(names[i]) \n}\n"
},
{
"code": null,
"e": 6811,
"s": 6752,
"text": "On compiling, it will generate following JavaScript code −"
},
{
"code": null,
"e": 6968,
"s": 6811,
"text": "//Generated by typescript 1.8.10\nvar names = new Array(\"Mary\", \"Tom\", \"Jack\", \"Jill\");\nfor (var i = 0; i < names.length; i++) {\n console.log(names[i]);\n}\n"
},
{
"code": null,
"e": 6995,
"s": 6968,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 7018,
"s": 6995,
"text": "Mary \nTom \nJack \nJill\n"
},
{
"code": null,
"e": 7105,
"s": 7018,
"text": "A list of the methods of the Array object along with their description is given below."
},
{
"code": null,
"e": 7193,
"s": 7105,
"text": "Returns a new array comprised of this array joined with other array(s) and/or value(s)."
},
{
"code": null,
"e": 7278,
"s": 7193,
"text": "Returns true if every element in this array satisfies the provided testing function."
},
{
"code": null,
"e": 7393,
"s": 7278,
"text": "Creates a new array with all of the elements of this array for which the provided filtering function returns true."
},
{
"code": null,
"e": 7441,
"s": 7393,
"text": "Calls a function for each element in the array."
},
{
"code": null,
"e": 7558,
"s": 7441,
"text": "Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found."
},
{
"code": null,
"e": 7604,
"s": 7558,
"text": "Joins all elements of an array into a string."
},
{
"code": null,
"e": 7723,
"s": 7604,
"text": "Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found."
},
{
"code": null,
"e": 7823,
"s": 7723,
"text": "Creates a new array with the results of calling a provided function on every element in this array."
},
{
"code": null,
"e": 7888,
"s": 7823,
"text": "Removes the last element from an array and returns that element."
},
{
"code": null,
"e": 7978,
"s": 7888,
"text": "Adds one or more elements to the end of an array and returns the new length of the array."
},
{
"code": null,
"e": 8098,
"s": 7978,
"text": "Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value."
},
{
"code": null,
"e": 8218,
"s": 8098,
"text": "Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value."
},
{
"code": null,
"e": 8328,
"s": 8218,
"text": "Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first."
},
{
"code": null,
"e": 8394,
"s": 8328,
"text": "Removes the first element from an array and returns that element."
},
{
"code": null,
"e": 8450,
"s": 8394,
"text": "Extracts a section of an array and returns a new array."
},
{
"code": null,
"e": 8542,
"s": 8450,
"text": "Returns true if at least one element in this array satisfies the provided testing function."
},
{
"code": null,
"e": 8574,
"s": 8542,
"text": "Sorts the elements of an array."
},
{
"code": null,
"e": 8618,
"s": 8574,
"text": "Adds and/or removes elements from an array."
},
{
"code": null,
"e": 8676,
"s": 8618,
"text": "Returns a string representing the array and its elements."
},
{
"code": null,
"e": 8768,
"s": 8676,
"text": "Adds one or more elements to the front of an array and returns the new length of the array."
},
{
"code": null,
"e": 8890,
"s": 8768,
"text": "Refers to breaking up the structure of an entity. TypeScript supports destructuring when used in the context of an array."
},
{
"code": null,
"e": 8966,
"s": 8890,
"text": "var arr:number[] = [12,13] \nvar[x,y] = arr \nconsole.log(x) \nconsole.log(y)\n"
},
{
"code": null,
"e": 9024,
"s": 8966,
"text": "On compiling, it will generate following JavaScript code."
},
{
"code": null,
"e": 9138,
"s": 9024,
"text": "//Generated by typescript 1.8.10\nvar arr = [12, 13];\nvar x = arr[0], y = arr[1];\nconsole.log(x);\nconsole.log(y);\n"
},
{
"code": null,
"e": 9165,
"s": 9138,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 9173,
"s": 9165,
"text": "12 \n13\n"
},
{
"code": null,
"e": 9233,
"s": 9173,
"text": "One can use the for...in loop to traverse through an array."
},
{
"code": null,
"e": 9336,
"s": 9233,
"text": "var j:any; \nvar nums:number[] = [1001,1002,1003,1004] \n\nfor(j in nums) { \n console.log(nums[j]) \n} \n"
},
{
"code": null,
"e": 9386,
"s": 9336,
"text": "The loop performs an index based array traversal."
},
{
"code": null,
"e": 9444,
"s": 9386,
"text": "On compiling, it will generate following JavaScript code."
},
{
"code": null,
"e": 9568,
"s": 9444,
"text": "//Generated by typescript 1.8.10\nvar j;\nvar nums = [1001, 1002, 1003, 1004];\n\nfor (j in nums) {\n console.log(nums[j]);\n}\n"
},
{
"code": null,
"e": 9614,
"s": 9568,
"text": "The output of the above code is given below −"
},
{
"code": null,
"e": 9638,
"s": 9614,
"text": "1001 \n1002 \n1003 \n1004\n"
},
{
"code": null,
"e": 9693,
"s": 9638,
"text": "TypeScript supports the following concepts in arrays −"
},
{
"code": null,
"e": 9815,
"s": 9693,
"text": "TypeScript supports multidimensional arrays. The simplest form of the multidimensional array is the twodimensional array."
},
{
"code": null,
"e": 9915,
"s": 9815,
"text": "You can pass to the function a pointer to an array by specifying the array's name without an index."
},
{
"code": null,
"e": 9952,
"s": 9915,
"text": "Allows a function to return an array"
},
{
"code": null,
"e": 9985,
"s": 9952,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9999,
"s": 9985,
"text": " Antonio Papa"
},
{
"code": null,
"e": 10032,
"s": 9999,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 10046,
"s": 10032,
"text": " Haider Malik"
},
{
"code": null,
"e": 10081,
"s": 10046,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10101,
"s": 10081,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 10134,
"s": 10101,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10148,
"s": 10134,
"text": " Sean Bradley"
},
{
"code": null,
"e": 10183,
"s": 10148,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10199,
"s": 10183,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 10232,
"s": 10199,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 10252,
"s": 10232,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 10259,
"s": 10252,
"text": " Print"
},
{
"code": null,
"e": 10270,
"s": 10259,
"text": " Add Notes"
}
] |
Everything to know about lists in Python | Nouman | Towards Data Science
|
Lists in Python, or arrays in other programming languages, are basically a compound data structure that can hold basically a list of items. This article serves as a beginner-friendly way to start with lists in Python. We are going to cover a lot about lists in this article so let’s get started!!
Here’s a list of topics we will discuss on lists (pun intended xD):
Intro to Lists
Common Methods on Lists
Lists Iteration
Using Lists as Stacks
Using Lists as Queues
Conclusion
This is part of my 30-Day Article Writing Challenge. Feel free to check out the articles on my pledge post:
nouman10.medium.com
Python has a lot of data structures that can be used to store a list of items but the list is one of the most versatile ones. It is written as a comma-separated list of values wrapped between square brackets.
array = [1, 2, 3, 4, 5, 6, 7]array
Lists in python can be indexed (0-indexed, negative indexing is allowed) and sliced like follows:
array = [1, 2, 3, 4, 5, 6, 7]print(array[0])print(array[-1])print(array[2:5])
Lists also allow concatenation like follows (but doesn’t modify the original list like this unless you store the value in that variable):
array = [1, 2, 3, 4, 5, 6, 7]print(array + [8, 9, 10, 11])
Lists are mutable i.e, it is possible to change their content like follows:
array = [1, 2, 4, 4, 5, 6, 7] # 4 instead of 3 on index 2array[2] = 3print(array)
We can also assign values to slices of lists too (this may or may not change their length as well):
array = [1, 2, 3, 4, 5, 6, 7]array[2:5] = [5, 4, 3]print(array)array[2:5] = []print(array)
Lists can contain different types of objects as well and even lists within lists! (nested lists)
array_1 = [1, 2, 3, 'a', 'b', 'c']array_2 = [4, 5, 6, 7]combined = [array_1, array_2]print(combined)
That’s all for an intro to lists. Let’s look at some of the common methods used on lists
Here we will look into some of the common methods applied on lists in python and at the end, we will see a demo for all these together:
Note: list , list_1 , list_2 all represent some kind of arbitrary lists.
As the name suggests, it returns the length of a list.
Syntax: len(list)
It allows us to add any item to the end of the list.
Syntax: list.append(item)
It appends all the items from one list to the other.
Syntax: list_1.extend(list_2)
It inserts the given item on the mentioned index
Syntax: list.insert(index, item)
It removes the first occurrence of the given item from the list. In case the item is not present, it raises a ValueError
Syntax: list.remove(item)
It removes the item from the given index and returns that item. In case of no given index, it removes the last item from the list and returns that.
Syntax: list.pop() or list.pop(index)
As the name suggests, it clears the list (empties it)
Syntax: list.clear()
It searches the list for a given item and returns the index of its first occurrence in the list and -1 if it is not present in the list. It also has optional parameters, start, and end, which limit the search space inside the list
Syntax: list.index(item)
Returns the number of times the given item appears in the list
Syntax: list.count(item)
Sorts the list in place i.e modifies the original list
Syntax: list.sort()
Reverses the list in place
Syntax: list.reverse()
Returns a shallow copy of the list
Syntax: list.copy()
List iteration is a topic on its own which I have covered in length in a previous article of mine:
towardsdatascience.com
Stacks perform operations on the basis of the LIFO (Last In, first-out) algorithm. Lists can act as stacks quite easily by using their built-in methods. To append any element to the end of the list, we can use list.append(item) and to retrieve any element from that list, we can use list.pop() without any index, which will remove and return the last (appended) element in the list.
Queues perform operations on the basis of the FIFO (First In, first-out) algorithm. We can use lists for this purpose by using their methods, pop and insert with indices but that’s not efficient because while the append and pop from the end of lists are quite fast, pop and insert at the start of the list is not that efficient as all the elements have to be shifted by one index.
Luckily, Python has a built-in collections.deque that implements fast appends and pops from both ends.
To conclude:
We started with a basic introduction to lists in Python
Then we looked into some built-in methods for lists
Finally, we looked into how lists can be used as stacks and queues.
If you feel that above content was useful for you, do share it and feel free to support me ->
|
[
{
"code": null,
"e": 469,
"s": 172,
"text": "Lists in Python, or arrays in other programming languages, are basically a compound data structure that can hold basically a list of items. This article serves as a beginner-friendly way to start with lists in Python. We are going to cover a lot about lists in this article so let’s get started!!"
},
{
"code": null,
"e": 537,
"s": 469,
"text": "Here’s a list of topics we will discuss on lists (pun intended xD):"
},
{
"code": null,
"e": 552,
"s": 537,
"text": "Intro to Lists"
},
{
"code": null,
"e": 576,
"s": 552,
"text": "Common Methods on Lists"
},
{
"code": null,
"e": 592,
"s": 576,
"text": "Lists Iteration"
},
{
"code": null,
"e": 614,
"s": 592,
"text": "Using Lists as Stacks"
},
{
"code": null,
"e": 636,
"s": 614,
"text": "Using Lists as Queues"
},
{
"code": null,
"e": 647,
"s": 636,
"text": "Conclusion"
},
{
"code": null,
"e": 755,
"s": 647,
"text": "This is part of my 30-Day Article Writing Challenge. Feel free to check out the articles on my pledge post:"
},
{
"code": null,
"e": 775,
"s": 755,
"text": "nouman10.medium.com"
},
{
"code": null,
"e": 984,
"s": 775,
"text": "Python has a lot of data structures that can be used to store a list of items but the list is one of the most versatile ones. It is written as a comma-separated list of values wrapped between square brackets."
},
{
"code": null,
"e": 1019,
"s": 984,
"text": "array = [1, 2, 3, 4, 5, 6, 7]array"
},
{
"code": null,
"e": 1117,
"s": 1019,
"text": "Lists in python can be indexed (0-indexed, negative indexing is allowed) and sliced like follows:"
},
{
"code": null,
"e": 1195,
"s": 1117,
"text": "array = [1, 2, 3, 4, 5, 6, 7]print(array[0])print(array[-1])print(array[2:5])"
},
{
"code": null,
"e": 1333,
"s": 1195,
"text": "Lists also allow concatenation like follows (but doesn’t modify the original list like this unless you store the value in that variable):"
},
{
"code": null,
"e": 1392,
"s": 1333,
"text": "array = [1, 2, 3, 4, 5, 6, 7]print(array + [8, 9, 10, 11])"
},
{
"code": null,
"e": 1468,
"s": 1392,
"text": "Lists are mutable i.e, it is possible to change their content like follows:"
},
{
"code": null,
"e": 1550,
"s": 1468,
"text": "array = [1, 2, 4, 4, 5, 6, 7] # 4 instead of 3 on index 2array[2] = 3print(array)"
},
{
"code": null,
"e": 1650,
"s": 1550,
"text": "We can also assign values to slices of lists too (this may or may not change their length as well):"
},
{
"code": null,
"e": 1741,
"s": 1650,
"text": "array = [1, 2, 3, 4, 5, 6, 7]array[2:5] = [5, 4, 3]print(array)array[2:5] = []print(array)"
},
{
"code": null,
"e": 1838,
"s": 1741,
"text": "Lists can contain different types of objects as well and even lists within lists! (nested lists)"
},
{
"code": null,
"e": 1939,
"s": 1838,
"text": "array_1 = [1, 2, 3, 'a', 'b', 'c']array_2 = [4, 5, 6, 7]combined = [array_1, array_2]print(combined)"
},
{
"code": null,
"e": 2028,
"s": 1939,
"text": "That’s all for an intro to lists. Let’s look at some of the common methods used on lists"
},
{
"code": null,
"e": 2164,
"s": 2028,
"text": "Here we will look into some of the common methods applied on lists in python and at the end, we will see a demo for all these together:"
},
{
"code": null,
"e": 2237,
"s": 2164,
"text": "Note: list , list_1 , list_2 all represent some kind of arbitrary lists."
},
{
"code": null,
"e": 2292,
"s": 2237,
"text": "As the name suggests, it returns the length of a list."
},
{
"code": null,
"e": 2310,
"s": 2292,
"text": "Syntax: len(list)"
},
{
"code": null,
"e": 2363,
"s": 2310,
"text": "It allows us to add any item to the end of the list."
},
{
"code": null,
"e": 2389,
"s": 2363,
"text": "Syntax: list.append(item)"
},
{
"code": null,
"e": 2442,
"s": 2389,
"text": "It appends all the items from one list to the other."
},
{
"code": null,
"e": 2472,
"s": 2442,
"text": "Syntax: list_1.extend(list_2)"
},
{
"code": null,
"e": 2521,
"s": 2472,
"text": "It inserts the given item on the mentioned index"
},
{
"code": null,
"e": 2554,
"s": 2521,
"text": "Syntax: list.insert(index, item)"
},
{
"code": null,
"e": 2675,
"s": 2554,
"text": "It removes the first occurrence of the given item from the list. In case the item is not present, it raises a ValueError"
},
{
"code": null,
"e": 2701,
"s": 2675,
"text": "Syntax: list.remove(item)"
},
{
"code": null,
"e": 2849,
"s": 2701,
"text": "It removes the item from the given index and returns that item. In case of no given index, it removes the last item from the list and returns that."
},
{
"code": null,
"e": 2887,
"s": 2849,
"text": "Syntax: list.pop() or list.pop(index)"
},
{
"code": null,
"e": 2941,
"s": 2887,
"text": "As the name suggests, it clears the list (empties it)"
},
{
"code": null,
"e": 2962,
"s": 2941,
"text": "Syntax: list.clear()"
},
{
"code": null,
"e": 3193,
"s": 2962,
"text": "It searches the list for a given item and returns the index of its first occurrence in the list and -1 if it is not present in the list. It also has optional parameters, start, and end, which limit the search space inside the list"
},
{
"code": null,
"e": 3218,
"s": 3193,
"text": "Syntax: list.index(item)"
},
{
"code": null,
"e": 3281,
"s": 3218,
"text": "Returns the number of times the given item appears in the list"
},
{
"code": null,
"e": 3306,
"s": 3281,
"text": "Syntax: list.count(item)"
},
{
"code": null,
"e": 3361,
"s": 3306,
"text": "Sorts the list in place i.e modifies the original list"
},
{
"code": null,
"e": 3381,
"s": 3361,
"text": "Syntax: list.sort()"
},
{
"code": null,
"e": 3408,
"s": 3381,
"text": "Reverses the list in place"
},
{
"code": null,
"e": 3431,
"s": 3408,
"text": "Syntax: list.reverse()"
},
{
"code": null,
"e": 3466,
"s": 3431,
"text": "Returns a shallow copy of the list"
},
{
"code": null,
"e": 3486,
"s": 3466,
"text": "Syntax: list.copy()"
},
{
"code": null,
"e": 3585,
"s": 3486,
"text": "List iteration is a topic on its own which I have covered in length in a previous article of mine:"
},
{
"code": null,
"e": 3608,
"s": 3585,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3991,
"s": 3608,
"text": "Stacks perform operations on the basis of the LIFO (Last In, first-out) algorithm. Lists can act as stacks quite easily by using their built-in methods. To append any element to the end of the list, we can use list.append(item) and to retrieve any element from that list, we can use list.pop() without any index, which will remove and return the last (appended) element in the list."
},
{
"code": null,
"e": 4372,
"s": 3991,
"text": "Queues perform operations on the basis of the FIFO (First In, first-out) algorithm. We can use lists for this purpose by using their methods, pop and insert with indices but that’s not efficient because while the append and pop from the end of lists are quite fast, pop and insert at the start of the list is not that efficient as all the elements have to be shifted by one index."
},
{
"code": null,
"e": 4475,
"s": 4372,
"text": "Luckily, Python has a built-in collections.deque that implements fast appends and pops from both ends."
},
{
"code": null,
"e": 4488,
"s": 4475,
"text": "To conclude:"
},
{
"code": null,
"e": 4544,
"s": 4488,
"text": "We started with a basic introduction to lists in Python"
},
{
"code": null,
"e": 4596,
"s": 4544,
"text": "Then we looked into some built-in methods for lists"
},
{
"code": null,
"e": 4664,
"s": 4596,
"text": "Finally, we looked into how lists can be used as stacks and queues."
}
] |
Python Pandas - Format Timedelta as ISO 8601
|
To format Timedelta as ISO 8601, use the timedelta.isoformat() method. At first, import the required libraries −
import pandas as pd
Create a Timedelta object
timedelta = pd.Timedelta('4 days 11 hours 38 min 20 s 35 ms 55 ns')
Display the Timedelta
print("Timedelta...\n", timedelta)
Format as ISO 8601
timedelta.isoformat()
Following is the code
import pandas as pd
# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# create a Timedelta object
timedelta = pd.Timedelta('4 days 11 hours 38 min 20 s 35 ms 55 ns')
# display the Timedelta
print("Timedelta...\n", timedelta)
# format as ISO 8601
res = timedelta.isoformat()
# display the Timedelta as ISO 8601
print("\nFormat Timedelta as ISO 8601...\n", res)
This will produce the following code
Timedelta...
4 days 11:38:20.035000055
Format Timedelta as ISO 8601...
P4DT11H38M20.035000055S
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "To format Timedelta as ISO 8601, use the timedelta.isoformat() method. At first, import the required libraries −"
},
{
"code": null,
"e": 1195,
"s": 1175,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1221,
"s": 1195,
"text": "Create a Timedelta object"
},
{
"code": null,
"e": 1289,
"s": 1221,
"text": "timedelta = pd.Timedelta('4 days 11 hours 38 min 20 s 35 ms 55 ns')"
},
{
"code": null,
"e": 1311,
"s": 1289,
"text": "Display the Timedelta"
},
{
"code": null,
"e": 1346,
"s": 1311,
"text": "print(\"Timedelta...\\n\", timedelta)"
},
{
"code": null,
"e": 1365,
"s": 1346,
"text": "Format as ISO 8601"
},
{
"code": null,
"e": 1388,
"s": 1365,
"text": "timedelta.isoformat()\n"
},
{
"code": null,
"e": 1410,
"s": 1388,
"text": "Following is the code"
},
{
"code": null,
"e": 1819,
"s": 1410,
"text": "import pandas as pd\n\n# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s\n# create a Timedelta object\ntimedelta = pd.Timedelta('4 days 11 hours 38 min 20 s 35 ms 55 ns')\n\n# display the Timedelta\nprint(\"Timedelta...\\n\", timedelta)\n\n# format as ISO 8601\nres = timedelta.isoformat()\n\n# display the Timedelta as ISO 8601\nprint(\"\\nFormat Timedelta as ISO 8601...\\n\", res)"
},
{
"code": null,
"e": 1856,
"s": 1819,
"text": "This will produce the following code"
},
{
"code": null,
"e": 1952,
"s": 1856,
"text": "Timedelta...\n4 days 11:38:20.035000055\n\nFormat Timedelta as ISO 8601...\nP4DT11H38M20.035000055S"
}
] |
Formatted output in Java - GeeksforGeeks
|
10 Feb, 2022
Sometimes in Competitive programming, it is essential to print the output in a given specified format. Most users are familiar with printf function in C. Let us discuss how we can format the output in Java.
There are different ways in which we can format output in Java. Some of them are given below.
Using System.out.printf()
Using DecimalFormat class
Using SimpleDateFormat class (for formatting Dates)
This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments.
Java
// Java program to demonstrate working of printf() class JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( "Printing simple integer: x = %d\n", x); // this will print it upto 2 decimal places System.out.printf( "Formatted with precision: PI = %.2f\n", Math.PI); float n = 5.2f; // automatically appends zero to the rightmost part // of decimal System.out.printf( "Formatted to specific width: n = %.4f\n", n); n = 2324435.3f; // here number is formatted from right margin and // occupies a width of 20 characters System.out.printf( "Formatted to right margin: n = %20.4f\n", n); }}
Printing simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500
Note: System.out.format() is equivalent to printf() and can also be used.
DecimalFormat is used to format decimal numbers.
Java
// Java program to demonstrate working of DecimalFormatimport java.text.DecimalFormat; class JavaFormatter2 { public static void main(String args[]) { double num = 123.4567; // prints only numeric part of a floating number DecimalFormat ft = new DecimalFormat("####"); System.out.println("Without fraction part: num = " + ft.format(num)); // this will print it upto 2 decimal places ft = new DecimalFormat("#.##"); System.out.println( "Formatted to Give precision: num = " + ft.format(num)); // automatically appends zero to the rightmost part // of decimal instead of #,we use digit 0 ft = new DecimalFormat("#.000000"); System.out.println( "appended zeroes to right: num = " + ft.format(num)); // automatically appends zero to the leftmost of // decimal number instead of #,we use digit 0 ft = new DecimalFormat("00000.00"); System.out.println( "formatting Numeric part : num = " + ft.format(num)); // formatting money in dollars double income = 23456.789; ft = new DecimalFormat("$###,###.##"); System.out.println("your Formatted Dream Income : " + ft.format(income)); }}
Without fraction part: num = 123
Formatted to Give precision: num = 123.46
appended zeroes to right: num = 123.456700
formatting Numeric part : num = 00123.46
your Formatted Dream Income : $23,456.79
This class is present in java.text package.
Java
// Java program to demonstrate working of SimpleDateFormat import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date; class Formatter3 { public static void main(String args[]) throws ParseException { // Formatting as per given pattern in the argument SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy"); String str = ft.format(new Date()); System.out.println("Formatted Date : " + str); // parsing a given String str = "02/18/1995"; ft = new SimpleDateFormat("MM/dd/yyyy"); Date date = ft.parse(str); // this will print the date as per parsed string System.out.println("Parsed Date : " + date); }}
Formatted Date : 24-01-2022
Parsed Date : Sat Feb 18 00:00:00 UTC 1995
This article is contributed by Pankaj Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mayur_jain
agrawalaryan017
anikaseth98
nishkarshgandhi
Competitive Programming
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Use of FLAG in programming
Setting up Sublime Text for C++ Competitive Programming Environment
Breadth First Traversal ( BFS ) on a 2D array
Container with Most Water
Searching in a map using std::map functions in C++
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 24369,
"s": 24341,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 24576,
"s": 24369,
"text": "Sometimes in Competitive programming, it is essential to print the output in a given specified format. Most users are familiar with printf function in C. Let us discuss how we can format the output in Java."
},
{
"code": null,
"e": 24670,
"s": 24576,
"text": "There are different ways in which we can format output in Java. Some of them are given below."
},
{
"code": null,
"e": 24696,
"s": 24670,
"text": "Using System.out.printf()"
},
{
"code": null,
"e": 24722,
"s": 24696,
"text": "Using DecimalFormat class"
},
{
"code": null,
"e": 24774,
"s": 24722,
"text": "Using SimpleDateFormat class (for formatting Dates)"
},
{
"code": null,
"e": 24964,
"s": 24774,
"text": "This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments."
},
{
"code": null,
"e": 24969,
"s": 24964,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of printf() class JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf( \"Printing simple integer: x = %d\\n\", x); // this will print it upto 2 decimal places System.out.printf( \"Formatted with precision: PI = %.2f\\n\", Math.PI); float n = 5.2f; // automatically appends zero to the rightmost part // of decimal System.out.printf( \"Formatted to specific width: n = %.4f\\n\", n); n = 2324435.3f; // here number is formatted from right margin and // occupies a width of 20 characters System.out.printf( \"Formatted to right margin: n = %20.4f\\n\", n); }}",
"e": 25744,
"s": 24969,
"text": null
},
{
"code": null,
"e": 25905,
"s": 25744,
"text": "Printing simple integer: x = 100\nFormatted with precision: PI = 3.14\nFormatted to specific width: n = 5.2000\nFormatted to right margin: n = 2324435.2500"
},
{
"code": null,
"e": 25979,
"s": 25905,
"text": "Note: System.out.format() is equivalent to printf() and can also be used."
},
{
"code": null,
"e": 26028,
"s": 25979,
"text": "DecimalFormat is used to format decimal numbers."
},
{
"code": null,
"e": 26033,
"s": 26028,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of DecimalFormatimport java.text.DecimalFormat; class JavaFormatter2 { public static void main(String args[]) { double num = 123.4567; // prints only numeric part of a floating number DecimalFormat ft = new DecimalFormat(\"####\"); System.out.println(\"Without fraction part: num = \" + ft.format(num)); // this will print it upto 2 decimal places ft = new DecimalFormat(\"#.##\"); System.out.println( \"Formatted to Give precision: num = \" + ft.format(num)); // automatically appends zero to the rightmost part // of decimal instead of #,we use digit 0 ft = new DecimalFormat(\"#.000000\"); System.out.println( \"appended zeroes to right: num = \" + ft.format(num)); // automatically appends zero to the leftmost of // decimal number instead of #,we use digit 0 ft = new DecimalFormat(\"00000.00\"); System.out.println( \"formatting Numeric part : num = \" + ft.format(num)); // formatting money in dollars double income = 23456.789; ft = new DecimalFormat(\"$###,###.##\"); System.out.println(\"your Formatted Dream Income : \" + ft.format(income)); }}",
"e": 27373,
"s": 26033,
"text": null
},
{
"code": null,
"e": 27573,
"s": 27373,
"text": "Without fraction part: num = 123\nFormatted to Give precision: num = 123.46\nappended zeroes to right: num = 123.456700\nformatting Numeric part : num = 00123.46\nyour Formatted Dream Income : $23,456.79"
},
{
"code": null,
"e": 27618,
"s": 27573,
"text": "This class is present in java.text package. "
},
{
"code": null,
"e": 27623,
"s": 27618,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of SimpleDateFormat import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date; class Formatter3 { public static void main(String args[]) throws ParseException { // Formatting as per given pattern in the argument SimpleDateFormat ft = new SimpleDateFormat(\"dd-MM-yyyy\"); String str = ft.format(new Date()); System.out.println(\"Formatted Date : \" + str); // parsing a given String str = \"02/18/1995\"; ft = new SimpleDateFormat(\"MM/dd/yyyy\"); Date date = ft.parse(str); // this will print the date as per parsed string System.out.println(\"Parsed Date : \" + date); }}",
"e": 28355,
"s": 27623,
"text": null
},
{
"code": null,
"e": 28426,
"s": 28355,
"text": "Formatted Date : 24-01-2022\nParsed Date : Sat Feb 18 00:00:00 UTC 1995"
},
{
"code": null,
"e": 28847,
"s": 28426,
"text": "This article is contributed by Pankaj Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28858,
"s": 28847,
"text": "Mayur_jain"
},
{
"code": null,
"e": 28874,
"s": 28858,
"text": "agrawalaryan017"
},
{
"code": null,
"e": 28886,
"s": 28874,
"text": "anikaseth98"
},
{
"code": null,
"e": 28902,
"s": 28886,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 28926,
"s": 28902,
"text": "Competitive Programming"
},
{
"code": null,
"e": 28931,
"s": 28926,
"text": "Java"
},
{
"code": null,
"e": 28936,
"s": 28931,
"text": "Java"
},
{
"code": null,
"e": 29034,
"s": 28936,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29043,
"s": 29034,
"text": "Comments"
},
{
"code": null,
"e": 29056,
"s": 29043,
"text": "Old Comments"
},
{
"code": null,
"e": 29083,
"s": 29056,
"text": "Use of FLAG in programming"
},
{
"code": null,
"e": 29151,
"s": 29083,
"text": "Setting up Sublime Text for C++ Competitive Programming Environment"
},
{
"code": null,
"e": 29197,
"s": 29151,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 29223,
"s": 29197,
"text": "Container with Most Water"
},
{
"code": null,
"e": 29274,
"s": 29223,
"text": "Searching in a map using std::map functions in C++"
},
{
"code": null,
"e": 29289,
"s": 29274,
"text": "Arrays in Java"
},
{
"code": null,
"e": 29333,
"s": 29289,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 29355,
"s": 29333,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 29380,
"s": 29355,
"text": "Reverse a string in Java"
}
] |
Redis - Connection Echo Command
|
Redis ECHO command is used to print the given string.
String reply.
Following is the basic syntax of Redis ECHO command.
redis 127.0.0.1:6379> ECHO SAMPLE_STRING
redis 127.0.0.1:6379> ECHO "Hello World"
"Hello World"
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2099,
"s": 2045,
"text": "Redis ECHO command is used to print the given string."
},
{
"code": null,
"e": 2113,
"s": 2099,
"text": "String reply."
},
{
"code": null,
"e": 2166,
"s": 2113,
"text": "Following is the basic syntax of Redis ECHO command."
},
{
"code": null,
"e": 2208,
"s": 2166,
"text": "redis 127.0.0.1:6379> ECHO SAMPLE_STRING\n"
},
{
"code": null,
"e": 2266,
"s": 2208,
"text": "redis 127.0.0.1:6379> ECHO \"Hello World\" \n\"Hello World\" \n"
},
{
"code": null,
"e": 2298,
"s": 2266,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2318,
"s": 2298,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2325,
"s": 2318,
"text": " Print"
},
{
"code": null,
"e": 2336,
"s": 2325,
"text": " Add Notes"
}
] |
How to get screen dimensions in pixels on Android App using Kotlin?
|
This example demonstrates how to get screen dimensions in pixels on the Android App 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.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tvHeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tvWidth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tvHeight"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.WindowManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var tvHeight: TextView
lateinit var tvWidth: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
tvHeight = findViewById(R.id.tvHeight)
tvWidth = findViewById(R.id.tvWidth)
val displayMetrics = DisplayMetrics()
val windowsManager = applicationContext.getSystemService(WINDOW_SERVICE) as WindowManager
windowsManager.defaultDisplay.getMetrics(displayMetrics)
val deviceWidth = displayMetrics.widthPixels
val deviceHeight = displayMetrics.heightPixels
tvWidth.text = "Width in Pixels: $deviceWidth"
tvHeight.text = "Height in Pixels: $deviceHeight"
}
}
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="com.example.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>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
Click here to download the project code.
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "This example demonstrates how to get screen dimensions in pixels on the Android App using Kotlin."
},
{
"code": null,
"e": 1289,
"s": 1160,
"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": 1354,
"s": 1289,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2727,
"s": 1354,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/tvHeight\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/tvWidth\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/tvHeight\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"10dp\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2782,
"s": 2727,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3746,
"s": 2782,
"text": "import android.os.Bundle\nimport android.util.DisplayMetrics\nimport android.view.WindowManager\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var tvHeight: TextView\n lateinit var tvWidth: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n tvHeight = findViewById(R.id.tvHeight)\n tvWidth = findViewById(R.id.tvWidth)\n val displayMetrics = DisplayMetrics()\n val windowsManager = applicationContext.getSystemService(WINDOW_SERVICE) as WindowManager\n windowsManager.defaultDisplay.getMetrics(displayMetrics)\n val deviceWidth = displayMetrics.widthPixels\n val deviceHeight = displayMetrics.heightPixels\n tvWidth.text = \"Width in Pixels: $deviceWidth\"\n tvHeight.text = \"Height in Pixels: $deviceHeight\"\n }\n}"
},
{
"code": null,
"e": 3801,
"s": 3746,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4472,
"s": 3801,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.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>\n</manifest>"
},
{
"code": null,
"e": 4822,
"s": 4472,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
},
{
"code": null,
"e": 4863,
"s": 4822,
"text": "Click here to download the project code."
}
] |
Write a MySQL statements for rollback commit and save points
|
Theory of Computation
Like other databases, MySQL also provides facility for rollback commit and save points. In this article, we will explain these in details with examples.
The MySQL ROLLBACK command is used to restore the database to the last committed state. Like, suppose we deleted some records from MySQL database and later realised that we have deleted necessary record, then we can easily rollback this by using ROLLBACK command. This is effective only when the session has not expired and we have not committed the statement.
ROLLBACK [To SAVEPOINT_NAME];
Here, SAVEPOINT_NAME is the name given to save point that we rollback.
The MySQL COMMIT command is used to save the transaction permanently. As without session expires, we can rollback any changes made by INSERT, UPDATE or DELETE command. As they are not permanent, so with the help of COMMIT command we can make any changes permanently.
COMMIT;
The COMMIT statement is written after the MySQL statement, that we want to be permanent in the database. It returns 'Commit complete.' on successfully committed.
The MySQL SAVEPOINTS command is used to save the transaction temporarily, so that we can ROLLBACK this to that point when required.
SAVEPOINT SAVEPOINT_NAME;
Here, SAVEPOINT_NAME is the name given to save point.
Here, we have created an item_order table -
mysql> CREATE TABLE item_order(item_id INT, name CHAR (20), INDEX (item_id));
Next, do a transaction with AUTOCOMMIT turned on -
mysql> START TRANSACTION;
Query OK, 0 rows affected (0.07 sec)
Next, insert data in 'item_order' -
mysql> INSERT INTO item_order VALUES (101, 'Milk');
Query OK, 1 row affected (0.04 sec)
Next, commit this statement, if you want to insert this permanently -
mysql> COMMIT;
Query OK, 0 rows affected (0.00 sec)
Let's make the autocommit off -
mysql> SET autocommit=0;
And, check the ROLLBACK functionality -
mysql> INSERT INTO item_order VALUES (102, 'Biscuit');
Query OK, 1 row affected (0.00 sec)
mysql>INSERT INTO item_order VALUES (103, 'Cake');
Query OK, 1 row affected (0.00 sec)
Let's delete one row and call the ROLLBACK statement-
mysql> SAVEPOINT C;
Query OK, 0 rows affected (0.00 sec)
mysql> DELETE FROM item_order WHERE name = 'Biscuit';
Query OK, 1 row affected (0.04 sec)
ROLLBACK TO C;
After ROLLBACK statement call, the records in the database are shown as -
mysql> SELECT * FROM item_order;
+---------+------+
| item_id | name |
+---------+------+
| 101 | Milk |
| 103 | Cake |
|
[
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 265,
"s": 112,
"text": "Like other databases, MySQL also provides facility for rollback commit and save points. In this article, we will explain these in details with examples."
},
{
"code": null,
"e": 626,
"s": 265,
"text": "The MySQL ROLLBACK command is used to restore the database to the last committed state. Like, suppose we deleted some records from MySQL database and later realised that we have deleted necessary record, then we can easily rollback this by using ROLLBACK command. This is effective only when the session has not expired and we have not committed the statement."
},
{
"code": null,
"e": 656,
"s": 626,
"text": "ROLLBACK [To SAVEPOINT_NAME];"
},
{
"code": null,
"e": 727,
"s": 656,
"text": "Here, SAVEPOINT_NAME is the name given to save point that we rollback."
},
{
"code": null,
"e": 994,
"s": 727,
"text": "The MySQL COMMIT command is used to save the transaction permanently. As without session expires, we can rollback any changes made by INSERT, UPDATE or DELETE command. As they are not permanent, so with the help of COMMIT command we can make any changes permanently."
},
{
"code": null,
"e": 1002,
"s": 994,
"text": "COMMIT;"
},
{
"code": null,
"e": 1164,
"s": 1002,
"text": "The COMMIT statement is written after the MySQL statement, that we want to be permanent in the database. It returns 'Commit complete.' on successfully committed."
},
{
"code": null,
"e": 1296,
"s": 1164,
"text": "The MySQL SAVEPOINTS command is used to save the transaction temporarily, so that we can ROLLBACK this to that point when required."
},
{
"code": null,
"e": 1322,
"s": 1296,
"text": "SAVEPOINT SAVEPOINT_NAME;"
},
{
"code": null,
"e": 1376,
"s": 1322,
"text": "Here, SAVEPOINT_NAME is the name given to save point."
},
{
"code": null,
"e": 1420,
"s": 1376,
"text": "Here, we have created an item_order table -"
},
{
"code": null,
"e": 1498,
"s": 1420,
"text": "mysql> CREATE TABLE item_order(item_id INT, name CHAR (20), INDEX (item_id));"
},
{
"code": null,
"e": 1549,
"s": 1498,
"text": "Next, do a transaction with AUTOCOMMIT turned on -"
},
{
"code": null,
"e": 1612,
"s": 1549,
"text": "mysql> START TRANSACTION;\nQuery OK, 0 rows affected (0.07 sec)"
},
{
"code": null,
"e": 1648,
"s": 1612,
"text": "Next, insert data in 'item_order' -"
},
{
"code": null,
"e": 1736,
"s": 1648,
"text": "mysql> INSERT INTO item_order VALUES (101, 'Milk');\nQuery OK, 1 row affected (0.04 sec)"
},
{
"code": null,
"e": 1806,
"s": 1736,
"text": "Next, commit this statement, if you want to insert this permanently -"
},
{
"code": null,
"e": 1858,
"s": 1806,
"text": "mysql> COMMIT;\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1890,
"s": 1858,
"text": "Let's make the autocommit off -"
},
{
"code": null,
"e": 1915,
"s": 1890,
"text": "mysql> SET autocommit=0;"
},
{
"code": null,
"e": 1955,
"s": 1915,
"text": "And, check the ROLLBACK functionality -"
},
{
"code": null,
"e": 2133,
"s": 1955,
"text": "mysql> INSERT INTO item_order VALUES (102, 'Biscuit');\nQuery OK, 1 row affected (0.00 sec)\nmysql>INSERT INTO item_order VALUES (103, 'Cake');\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 2187,
"s": 2133,
"text": "Let's delete one row and call the ROLLBACK statement-"
},
{
"code": null,
"e": 2334,
"s": 2187,
"text": "mysql> SAVEPOINT C;\nQuery OK, 0 rows affected (0.00 sec)\nmysql> DELETE FROM item_order WHERE name = 'Biscuit';\nQuery OK, 1 row affected (0.04 sec)"
},
{
"code": null,
"e": 2349,
"s": 2334,
"text": "ROLLBACK TO C;"
},
{
"code": null,
"e": 2423,
"s": 2349,
"text": "After ROLLBACK statement call, the records in the database are shown as -"
}
] |
RESTful Web Services - Statelessness
|
As per the REST architecture, a RESTful Web Service should not keep a client state on the server. This restriction is called Statelessness. It is the responsibility of the client to pass its context to the server and then the server can store this context to process the client's further request. For example, session maintained by server is identified by session identifier passed by the client.
RESTful Web Services should adhere to this restriction. We have seen this in the RESTful Web Services - Methods chapter, that the web service methods are not storing any information from the client they are invoked from.
Consider the following URL −
https://localhost:8080/UserManagement/rest/UserService/users/1
If you hit the above url using your browser or using a java based client or using Postman, result will always be the User XML whose Id is 1 because the server does not store any information about the client.
<user>
<id>1</id>
<name>mahesh</name>
<profession>1</profession>
</user>
Following are the benefits of statelessness in RESTful Web Services −
Web services can treat each method request independently.
Web services can treat each method request independently.
Web services need not maintain the client's previous interactions. It simplifies the application design.
Web services need not maintain the client's previous interactions. It simplifies the application design.
As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols.
As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols.
Following are the disadvantages of statelessness in RESTful Web Services −
Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of.
Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of.
71 Lectures
10 hours
Chaand Sheikh
27 Lectures
2 hours
Vinod Kumar Kayartaya
517 Lectures
57 hours
Chaand Sheikh
35 Lectures
3.5 hours
Antonio Papa
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2252,
"s": 1855,
"text": "As per the REST architecture, a RESTful Web Service should not keep a client state on the server. This restriction is called Statelessness. It is the responsibility of the client to pass its context to the server and then the server can store this context to process the client's further request. For example, session maintained by server is identified by session identifier passed by the client."
},
{
"code": null,
"e": 2473,
"s": 2252,
"text": "RESTful Web Services should adhere to this restriction. We have seen this in the RESTful Web Services - Methods chapter, that the web service methods are not storing any information from the client they are invoked from."
},
{
"code": null,
"e": 2502,
"s": 2473,
"text": "Consider the following URL −"
},
{
"code": null,
"e": 2565,
"s": 2502,
"text": "https://localhost:8080/UserManagement/rest/UserService/users/1"
},
{
"code": null,
"e": 2773,
"s": 2565,
"text": "If you hit the above url using your browser or using a java based client or using Postman, result will always be the User XML whose Id is 1 because the server does not store any information about the client."
},
{
"code": null,
"e": 2859,
"s": 2773,
"text": "<user> \n <id>1</id> \n <name>mahesh</name> \n <profession>1</profession> \n</user>"
},
{
"code": null,
"e": 2929,
"s": 2859,
"text": "Following are the benefits of statelessness in RESTful Web Services −"
},
{
"code": null,
"e": 2987,
"s": 2929,
"text": "Web services can treat each method request independently."
},
{
"code": null,
"e": 3045,
"s": 2987,
"text": "Web services can treat each method request independently."
},
{
"code": null,
"e": 3150,
"s": 3045,
"text": "Web services need not maintain the client's previous interactions. It simplifies the application design."
},
{
"code": null,
"e": 3255,
"s": 3150,
"text": "Web services need not maintain the client's previous interactions. It simplifies the application design."
},
{
"code": null,
"e": 3361,
"s": 3255,
"text": "As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols."
},
{
"code": null,
"e": 3467,
"s": 3361,
"text": "As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols."
},
{
"code": null,
"e": 3542,
"s": 3467,
"text": "Following are the disadvantages of statelessness in RESTful Web Services −"
},
{
"code": null,
"e": 3703,
"s": 3542,
"text": "Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of."
},
{
"code": null,
"e": 3864,
"s": 3703,
"text": "Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of."
},
{
"code": null,
"e": 3898,
"s": 3864,
"text": "\n 71 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3913,
"s": 3898,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3946,
"s": 3913,
"text": "\n 27 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3969,
"s": 3946,
"text": " Vinod Kumar Kayartaya"
},
{
"code": null,
"e": 4004,
"s": 3969,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 4019,
"s": 4004,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 4054,
"s": 4019,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4068,
"s": 4054,
"text": " Antonio Papa"
},
{
"code": null,
"e": 4075,
"s": 4068,
"text": " Print"
},
{
"code": null,
"e": 4086,
"s": 4075,
"text": " Add Notes"
}
] |
qmgr - Unix, Linux Command
|
qmgr [generic Postfix daemon options]
Mail addressed to the local double-bounce address is
logged and discarded. This stops potential loops caused by
undeliverable bounce notifications.
RFC 3463 (Enhanced status codes)
RFC 3464 (Delivery status notifications)
Depending on the setting of the notify_classes parameter,
the postmaster is notified of bounces and of other trouble.
The text below provides only a parameter summary. See
postconf(5) for more details including examples.
In the text below, transport is the first field in a
master.cf entry.
/var/spool/postfix/incoming, incoming queue
/var/spool/postfix/active, active queue
/var/spool/postfix/deferred, deferred queue
/var/spool/postfix/bounce, non-delivery status
/var/spool/postfix/defer, non-delivery status
/var/spool/postfix/trace, delivery status
trivial-rewrite(8), address routing
bounce(8), delivery status reports
postconf(5), configuration parameters
master(5), generic daemon options
master(8), process manager
syslogd(8), system logging
SCHEDULER_README, scheduling algorithm
QSHAPE_README, Postfix queue analysis
Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA
Scheduler enhancements:
Patrik Rak
Modra 6
155 00, Prague, Czech Republic
Scheduler enhancements:
Patrik Rak
Modra 6
155 00, Prague, Czech Republic
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10616,
"s": 10577,
"text": "qmgr [generic Postfix daemon options]\n"
},
{
"code": null,
"e": 10767,
"s": 10616,
"text": "\nMail addressed to the local double-bounce address is\nlogged and discarded. This stops potential loops caused by\nundeliverable bounce notifications.\n"
},
{
"code": null,
"e": 10850,
"s": 10775,
"text": "RFC 3463 (Enhanced status codes)\nRFC 3464 (Delivery status notifications)\n"
},
{
"code": null,
"e": 10972,
"s": 10852,
"text": "\nDepending on the setting of the notify_classes parameter,\nthe postmaster is notified of bounces and of other trouble.\n"
},
{
"code": null,
"e": 11079,
"s": 10974,
"text": "\nThe text below provides only a parameter summary. See\npostconf(5) for more details including examples.\n"
},
{
"code": null,
"e": 11151,
"s": 11079,
"text": "\nIn the text below, transport is the first field in a\nmaster.cf entry.\n"
},
{
"code": null,
"e": 11429,
"s": 11165,
"text": "/var/spool/postfix/incoming, incoming queue\n/var/spool/postfix/active, active queue\n/var/spool/postfix/deferred, deferred queue\n/var/spool/postfix/bounce, non-delivery status\n/var/spool/postfix/defer, non-delivery status\n/var/spool/postfix/trace, delivery status\n"
},
{
"code": null,
"e": 11627,
"s": 11429,
"text": "trivial-rewrite(8), address routing\nbounce(8), delivery status reports\npostconf(5), configuration parameters\nmaster(5), generic daemon options\nmaster(8), process manager\nsyslogd(8), system logging\n"
},
{
"code": null,
"e": 11707,
"s": 11629,
"text": "SCHEDULER_README, scheduling algorithm\nQSHAPE_README, Postfix queue analysis\n"
},
{
"code": null,
"e": 11869,
"s": 11709,
"text": "Wietse Venema\nIBM T.J. Watson Research\nP.O. Box 704\nYorktown Heights, NY 10598, USA\n\nScheduler enhancements:\nPatrik Rak\nModra 6\n155 00, Prague, Czech Republic\n"
},
{
"code": null,
"e": 11945,
"s": 11869,
"text": "\nScheduler enhancements:\nPatrik Rak\nModra 6\n155 00, Prague, Czech Republic\n"
},
{
"code": null,
"e": 11962,
"s": 11945,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 11997,
"s": 11962,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12025,
"s": 11997,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12059,
"s": 12025,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12076,
"s": 12059,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12109,
"s": 12076,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12120,
"s": 12109,
"text": " Pradeep D"
},
{
"code": null,
"e": 12155,
"s": 12120,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12171,
"s": 12155,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12204,
"s": 12171,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12216,
"s": 12204,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12248,
"s": 12216,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12256,
"s": 12248,
"text": " Uplatz"
},
{
"code": null,
"e": 12263,
"s": 12256,
"text": " Print"
},
{
"code": null,
"e": 12274,
"s": 12263,
"text": " Add Notes"
}
] |
HTML Form action Attribute
|
The HTML form action attribute defines where to send the form data when a form is submitted in an HTML document.
Following is the syntax −
<form action=”URL”></form>
Let us see an example of HTML Form action Attribute −
Live Demo
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
text-align: center;
}
input {
width: 315px;
display: block;
margin: 1rem auto;
border: 2px solid #fff;
padding: 8px;
background: transparent;
border-radius: 20px;
outline: none;
}
::placeholder {
color: #000;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 20px;
width: 330px;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem auto;
}
</style>
<body>
<h1>HTML Form action Attribute Demo</h1>
<form action="/action_page.php" method="get">
<input type="text" name="firstname" placeholder="Enter First Name">
<input type="text" name="lastname" placeholder="Enter Last Name">
<input type="submit" value="SUBMIT" class="btn">
</form>
</body>
</html>
Enter the form details and then submit the form using “SUBMIT” button to observe how action attribute works.
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "The HTML form action attribute defines where to send the form data when a form is submitted in an HTML document."
},
{
"code": null,
"e": 1201,
"s": 1175,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1228,
"s": 1201,
"text": "<form action=”URL”></form>"
},
{
"code": null,
"e": 1282,
"s": 1228,
"text": "Let us see an example of HTML Form action Attribute −"
},
{
"code": null,
"e": 1293,
"s": 1282,
"text": " Live Demo"
},
{
"code": null,
"e": 2287,
"s": 1293,
"text": "<!DOCTYPE html>\n<html>\n<style>\n body {\n color: #000;\n height: 100vh;\n background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;\n text-align: center;\n }\n input {\n width: 315px;\n display: block;\n margin: 1rem auto;\n border: 2px solid #fff;\n padding: 8px;\n background: transparent;\n border-radius: 20px;\n outline: none;\n }\n ::placeholder {\n color: #000;\n }\n .btn {\n background: #db133a;\n border: none;\n height: 2rem;\n border-radius: 20px;\n width: 330px;\n display: block;\n color: #fff;\n outline: none;\n cursor: pointer;\n margin: 1rem auto;\n }\n</style>\n<body>\n<h1>HTML Form action Attribute Demo</h1>\n<form action=\"/action_page.php\" method=\"get\">\n<input type=\"text\" name=\"firstname\" placeholder=\"Enter First Name\">\n<input type=\"text\" name=\"lastname\" placeholder=\"Enter Last Name\">\n<input type=\"submit\" value=\"SUBMIT\" class=\"btn\">\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 2396,
"s": 2287,
"text": "Enter the form details and then submit the form using “SUBMIT” button to observe how action attribute works."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.