title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Implementing SGD From Scratch. Custom Implementation of Stochastic... | by Jasmeet Singh | Towards Data Science
|
Before implementing Stochastic Gradient Descent let’s talk about what a Gradient Descent is.
Gradient Descent Algorithm is an iterative algorithm used to solve the optimization problem. In almost every Machine Learning and Deep Learning models Gradient Descent is actively used to improve the learning of our algorithm.
After reading this blog you’ll get to know how a Gradient Descent Algorithm actually works. At the end of this blog, we’ll compare our custom SGD implementation with SKlearn’s SGD implementation.
Pick an initial random point x0.x1 = x0 - r [(df/dx) of x0]x2 = x1- r [(df/dx) of x1]Similarly, we find for x0, x1, x2 ............. x[k-1]
Pick an initial random point x0.
x1 = x0 - r [(df/dx) of x0]
x2 = x1- r [(df/dx) of x1]
Similarly, we find for x0, x1, x2 ............. x[k-1]
Here r is the learning rate and df/dx is the gradient function to minimize our loss.
In Mini-Batch SGD the parameters are updated after computing the gradient of error with respect to a subset of the training set.
Let us take the Boston Housing Dataset from Kaggle as an example.
First, we will import all the necessary libraries.
import warningswarnings.filterwarnings("ignore")from sklearn.datasets import load_bostonfrom random import seedfrom random import randrangefrom csv import readerfrom math import sqrtfrom sklearn import preprocessingimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom prettytable import PrettyTablefrom sklearn.linear_model import SGDRegressorfrom sklearn import preprocessingfrom sklearn.metrics import mean_squared_errorfrom sklearn.model_selection import train_test_split
Now, we will load our dataset. Here, X contains the dataset we have and Y contains the label that we need to predict.
X = load_boston().dataY = load_boston().target
Remember to split your data before scaling to avoid the data leakage problem.
# split the data set into train and testX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=0)
Use Standard Scalar function to standardize your dataset. Here, we only fit the train data because we don’t want our model to see this data before, so as to avoid overfitting.
scaler = preprocessing.StandardScaler()X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test)
Creating the DataFrame using pandas.
X_train = pd.DataFrame(data = X_train, columns=load_boston().feature_names)X_train['Price'] = list(y_train) X_test = pd.DataFrame(data = X_test, columns=load_boston().feature_names)X_test['Price'] = list(y_test)
Let’s see how our X_train looks like.
X_train.head()
Below is the loss function for our Linear Model that we need to minimize.
Now, we calculate the gradients for our loss function L w.r.t Weights(W) and Intercept (b). Following is the equations for calculating the gradients,
After calculating the gradients we keep changing our weights and intercept value with each iteration.
Finally, we’ll implement our SGD function.
def sgd_regressor(X, y, learning_rate=0.2, n_epochs=1000, k=40): w = np.random.randn(1,13) # Randomly initializing weights b = np.random.randn(1,1) # Random intercept value epoch=1 while epoch <= n_epochs: temp = X.sample(k) X_tr = temp.iloc[:,0:13].values y_tr = temp.iloc[:,-1].values Lw = w Lb = b loss = 0 y_pred = [] sq_loss = [] for i in range(k): Lw = (-2/k * X_tr[i]) * (y_tr[i] - np.dot(X_tr[i],w.T) - b) Lb = (-2/k) * (y_tr[i] - np.dot(X_tr[i],w.T) - b) w = w - learning_rate * Lw b = b - learning_rate * Lb y_predicted = np.dot(X_tr[i],w.T) y_pred.append(y_predicted) loss = mean_squared_error(y_pred, y_tr) print("Epoch: %d, Loss: %.3f" %(epoch, loss)) epoch+=1 learning_rate = learning_rate/1.02 return w,b
We’ve kept our learning rate = 0.2, epochs = 1000 and batch size = 40. We can change the parameters accordingly to minimize our MSE.
We keep decreasing our learning rate by dividing it by 1.02, you can choose whatever value you want.
I’ve chosen MSE as my error metric, we can also choose RMSE.
Now, we create a predict function and compute our predicted values.
def predict(x,w,b): y_pred=[] for i in range(len(x)): temp_ = x X_test = temp_.iloc[:,0:13].values y = np.asscalar(np.dot(w,X_test[i])+b) y_pred.append(y) return np.array(y_pred)w,b = sgd_regressor(X_train,y_train)y_pred_customsgd = predict(X_test,w,b)
from matplotlib.pyplot import figureplt.figure(figsize=(25,6))plt.plot(y_test, label='Actual')plt.plot(y_pred_customsgd, label='Predicted')plt.legend(prop={'size': 16})plt.show()print('Mean Squared Error :',mean_squared_error(y_test, y_pred_customsgd))
As we can see we got our MSE as 26.8 which is pretty decent.
from sklearn.linear_model import SGDRegressorclf = SGDRegressor(max_iter=1000, tol=1e-3)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)
import matplotlib.pyplot as pltfrom matplotlib.pyplot import figureplt.figure(figsize=(25,6))plt.plot(y_test, label='Actual')plt.plot(y_pred, label='Predicted')plt.legend(prop={'size': 16})plt.show()print('Mean Squared Error :',mean_squared_error(y_test, y_pred))
SKlearn’s SGD implementation works much better than our custom implementation.
import matplotlib.pyplot as pltfrom matplotlib.pyplot import figureplt.figure(figsize=(25,6))plt.plot(y_pred, label='SGD')plt.plot(y_pred_customsgd, label='Custom SGD')plt.legend(prop={'size': 16})plt.show()print('Mean Squared Error of Custom SGD :',mean_squared_error(y_test, y_pred_customsgd))print("Mean Squared Error of SKlearn's SGD :",mean_squared_error(y_test, y_pred))
Well, our custom SGD did a pretty decent job compared to SKlearn’s and we could always do some hyper-parameter tuning to improve our custom model.
Implementing algorithms from scratch takes lot of time but if we use libraries then it still remains black box for us. Let me know in the comment section what you think about this.
Thank you for reading the blog, hope you got some insights on how a SGD actually works.
|
[
{
"code": null,
"e": 265,
"s": 172,
"text": "Before implementing Stochastic Gradient Descent let’s talk about what a Gradient Descent is."
},
{
"code": null,
"e": 492,
"s": 265,
"text": "Gradient Descent Algorithm is an iterative algorithm used to solve the optimization problem. In almost every Machine Learning and Deep Learning models Gradient Descent is actively used to improve the learning of our algorithm."
},
{
"code": null,
"e": 688,
"s": 492,
"text": "After reading this blog you’ll get to know how a Gradient Descent Algorithm actually works. At the end of this blog, we’ll compare our custom SGD implementation with SKlearn’s SGD implementation."
},
{
"code": null,
"e": 828,
"s": 688,
"text": "Pick an initial random point x0.x1 = x0 - r [(df/dx) of x0]x2 = x1- r [(df/dx) of x1]Similarly, we find for x0, x1, x2 ............. x[k-1]"
},
{
"code": null,
"e": 861,
"s": 828,
"text": "Pick an initial random point x0."
},
{
"code": null,
"e": 889,
"s": 861,
"text": "x1 = x0 - r [(df/dx) of x0]"
},
{
"code": null,
"e": 916,
"s": 889,
"text": "x2 = x1- r [(df/dx) of x1]"
},
{
"code": null,
"e": 971,
"s": 916,
"text": "Similarly, we find for x0, x1, x2 ............. x[k-1]"
},
{
"code": null,
"e": 1056,
"s": 971,
"text": "Here r is the learning rate and df/dx is the gradient function to minimize our loss."
},
{
"code": null,
"e": 1185,
"s": 1056,
"text": "In Mini-Batch SGD the parameters are updated after computing the gradient of error with respect to a subset of the training set."
},
{
"code": null,
"e": 1251,
"s": 1185,
"text": "Let us take the Boston Housing Dataset from Kaggle as an example."
},
{
"code": null,
"e": 1302,
"s": 1251,
"text": "First, we will import all the necessary libraries."
},
{
"code": null,
"e": 1797,
"s": 1302,
"text": "import warningswarnings.filterwarnings(\"ignore\")from sklearn.datasets import load_bostonfrom random import seedfrom random import randrangefrom csv import readerfrom math import sqrtfrom sklearn import preprocessingimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom prettytable import PrettyTablefrom sklearn.linear_model import SGDRegressorfrom sklearn import preprocessingfrom sklearn.metrics import mean_squared_errorfrom sklearn.model_selection import train_test_split"
},
{
"code": null,
"e": 1915,
"s": 1797,
"text": "Now, we will load our dataset. Here, X contains the dataset we have and Y contains the label that we need to predict."
},
{
"code": null,
"e": 1962,
"s": 1915,
"text": "X = load_boston().dataY = load_boston().target"
},
{
"code": null,
"e": 2040,
"s": 1962,
"text": "Remember to split your data before scaling to avoid the data leakage problem."
},
{
"code": null,
"e": 2169,
"s": 2040,
"text": "# split the data set into train and testX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=0)"
},
{
"code": null,
"e": 2345,
"s": 2169,
"text": "Use Standard Scalar function to standardize your dataset. Here, we only fit the train data because we don’t want our model to see this data before, so as to avoid overfitting."
},
{
"code": null,
"e": 2457,
"s": 2345,
"text": "scaler = preprocessing.StandardScaler()X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test)"
},
{
"code": null,
"e": 2494,
"s": 2457,
"text": "Creating the DataFrame using pandas."
},
{
"code": null,
"e": 2707,
"s": 2494,
"text": "X_train = pd.DataFrame(data = X_train, columns=load_boston().feature_names)X_train['Price'] = list(y_train) X_test = pd.DataFrame(data = X_test, columns=load_boston().feature_names)X_test['Price'] = list(y_test)"
},
{
"code": null,
"e": 2745,
"s": 2707,
"text": "Let’s see how our X_train looks like."
},
{
"code": null,
"e": 2760,
"s": 2745,
"text": "X_train.head()"
},
{
"code": null,
"e": 2834,
"s": 2760,
"text": "Below is the loss function for our Linear Model that we need to minimize."
},
{
"code": null,
"e": 2984,
"s": 2834,
"text": "Now, we calculate the gradients for our loss function L w.r.t Weights(W) and Intercept (b). Following is the equations for calculating the gradients,"
},
{
"code": null,
"e": 3086,
"s": 2984,
"text": "After calculating the gradients we keep changing our weights and intercept value with each iteration."
},
{
"code": null,
"e": 3129,
"s": 3086,
"text": "Finally, we’ll implement our SGD function."
},
{
"code": null,
"e": 4134,
"s": 3129,
"text": "def sgd_regressor(X, y, learning_rate=0.2, n_epochs=1000, k=40): w = np.random.randn(1,13) # Randomly initializing weights b = np.random.randn(1,1) # Random intercept value epoch=1 while epoch <= n_epochs: temp = X.sample(k) X_tr = temp.iloc[:,0:13].values y_tr = temp.iloc[:,-1].values Lw = w Lb = b loss = 0 y_pred = [] sq_loss = [] for i in range(k): Lw = (-2/k * X_tr[i]) * (y_tr[i] - np.dot(X_tr[i],w.T) - b) Lb = (-2/k) * (y_tr[i] - np.dot(X_tr[i],w.T) - b) w = w - learning_rate * Lw b = b - learning_rate * Lb y_predicted = np.dot(X_tr[i],w.T) y_pred.append(y_predicted) loss = mean_squared_error(y_pred, y_tr) print(\"Epoch: %d, Loss: %.3f\" %(epoch, loss)) epoch+=1 learning_rate = learning_rate/1.02 return w,b"
},
{
"code": null,
"e": 4267,
"s": 4134,
"text": "We’ve kept our learning rate = 0.2, epochs = 1000 and batch size = 40. We can change the parameters accordingly to minimize our MSE."
},
{
"code": null,
"e": 4368,
"s": 4267,
"text": "We keep decreasing our learning rate by dividing it by 1.02, you can choose whatever value you want."
},
{
"code": null,
"e": 4429,
"s": 4368,
"text": "I’ve chosen MSE as my error metric, we can also choose RMSE."
},
{
"code": null,
"e": 4497,
"s": 4429,
"text": "Now, we create a predict function and compute our predicted values."
},
{
"code": null,
"e": 4787,
"s": 4497,
"text": "def predict(x,w,b): y_pred=[] for i in range(len(x)): temp_ = x X_test = temp_.iloc[:,0:13].values y = np.asscalar(np.dot(w,X_test[i])+b) y_pred.append(y) return np.array(y_pred)w,b = sgd_regressor(X_train,y_train)y_pred_customsgd = predict(X_test,w,b)"
},
{
"code": null,
"e": 5040,
"s": 4787,
"text": "from matplotlib.pyplot import figureplt.figure(figsize=(25,6))plt.plot(y_test, label='Actual')plt.plot(y_pred_customsgd, label='Predicted')plt.legend(prop={'size': 16})plt.show()print('Mean Squared Error :',mean_squared_error(y_test, y_pred_customsgd))"
},
{
"code": null,
"e": 5101,
"s": 5040,
"text": "As we can see we got our MSE as 26.8 which is pretty decent."
},
{
"code": null,
"e": 5243,
"s": 5101,
"text": "from sklearn.linear_model import SGDRegressorclf = SGDRegressor(max_iter=1000, tol=1e-3)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)"
},
{
"code": null,
"e": 5507,
"s": 5243,
"text": "import matplotlib.pyplot as pltfrom matplotlib.pyplot import figureplt.figure(figsize=(25,6))plt.plot(y_test, label='Actual')plt.plot(y_pred, label='Predicted')plt.legend(prop={'size': 16})plt.show()print('Mean Squared Error :',mean_squared_error(y_test, y_pred))"
},
{
"code": null,
"e": 5586,
"s": 5507,
"text": "SKlearn’s SGD implementation works much better than our custom implementation."
},
{
"code": null,
"e": 5963,
"s": 5586,
"text": "import matplotlib.pyplot as pltfrom matplotlib.pyplot import figureplt.figure(figsize=(25,6))plt.plot(y_pred, label='SGD')plt.plot(y_pred_customsgd, label='Custom SGD')plt.legend(prop={'size': 16})plt.show()print('Mean Squared Error of Custom SGD :',mean_squared_error(y_test, y_pred_customsgd))print(\"Mean Squared Error of SKlearn's SGD :\",mean_squared_error(y_test, y_pred))"
},
{
"code": null,
"e": 6110,
"s": 5963,
"text": "Well, our custom SGD did a pretty decent job compared to SKlearn’s and we could always do some hyper-parameter tuning to improve our custom model."
},
{
"code": null,
"e": 6291,
"s": 6110,
"text": "Implementing algorithms from scratch takes lot of time but if we use libraries then it still remains black box for us. Let me know in the comment section what you think about this."
}
] |
HashTable forEach() method in Java with Examples - GeeksforGeeks
|
01 Oct, 2019
The forEach(BiConsumer) method of Hashtable class perform the BiConsumer operation on each entry of hashtable until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until all elements have been processed by the method or an exception occurs. Exceptions thrown by the Operation are passed to the caller.
Syntax:
public void
forEach(BiConsumer<? super K, ? super V> action)
Parameters: This method takes a parameter name BiConsumer which represents the action to be performed for each element.
Returns: This method returns nothing.
Exception: This method throws:
NullPointerException: if the specified action is null.
Below programs illustrate the forEach(BiConsumer) method:
Program 1:
// Java program to demonstrate// forEach(BiConsumer) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a table and add some values Map<String, Integer> table = new Hashtable<>(); table.put("Pen", 10); table.put("Book", 500); table.put("Clothes", 400); table.put("Mobile", 5000); table.put("Booklet", 2500); // add 100 in each value using forEach() table.forEach((k, v) -> { v = v + 100; table.replace(k, v); }); // print new mapping using forEcah() table.forEach( (k, v) -> System.out.println("Key : " + k + ", Value : " + v)); }}
Key : Booklet, Value : 2600
Key : Clothes, Value : 500
Key : Mobile, Value : 5100
Key : Pen, Value : 110
Key : Book, Value : 600
Program 2: To Show NullPointerException
// Java program to demonstrate// forEach(BiConsumer) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a table and add some values Map<Integer, String> table = new Hashtable<>(); table.put(1, "100RS"); table.put(2, "500RS"); table.put(3, "1000RS"); try { // add 100 in each value using forEach() table.forEach((k, v) -> { v = v + 100; table.put(null, v); }); } catch (Exception e) { System.out.println("Exception: " + e); } }}
Exception: java.lang.NullPointerException
References: https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html#forEach-java.util.function.BiConsumer-
nidhi_biet
java-basics
Java-Functions
Java-HashTable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 23544,
"s": 23516,
"text": "\n01 Oct, 2019"
},
{
"code": null,
"e": 24025,
"s": 23544,
"text": "The forEach(BiConsumer) method of Hashtable class perform the BiConsumer operation on each entry of hashtable until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until all elements have been processed by the method or an exception occurs. Exceptions thrown by the Operation are passed to the caller."
},
{
"code": null,
"e": 24033,
"s": 24025,
"text": "Syntax:"
},
{
"code": null,
"e": 24099,
"s": 24033,
"text": "public void \n forEach(BiConsumer<? super K, ? super V> action)"
},
{
"code": null,
"e": 24219,
"s": 24099,
"text": "Parameters: This method takes a parameter name BiConsumer which represents the action to be performed for each element."
},
{
"code": null,
"e": 24257,
"s": 24219,
"text": "Returns: This method returns nothing."
},
{
"code": null,
"e": 24288,
"s": 24257,
"text": "Exception: This method throws:"
},
{
"code": null,
"e": 24343,
"s": 24288,
"text": "NullPointerException: if the specified action is null."
},
{
"code": null,
"e": 24401,
"s": 24343,
"text": "Below programs illustrate the forEach(BiConsumer) method:"
},
{
"code": null,
"e": 24412,
"s": 24401,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// forEach(BiConsumer) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a table and add some values Map<String, Integer> table = new Hashtable<>(); table.put(\"Pen\", 10); table.put(\"Book\", 500); table.put(\"Clothes\", 400); table.put(\"Mobile\", 5000); table.put(\"Booklet\", 2500); // add 100 in each value using forEach() table.forEach((k, v) -> { v = v + 100; table.replace(k, v); }); // print new mapping using forEcah() table.forEach( (k, v) -> System.out.println(\"Key : \" + k + \", Value : \" + v)); }}",
"e": 25160,
"s": 24412,
"text": null
},
{
"code": null,
"e": 25290,
"s": 25160,
"text": "Key : Booklet, Value : 2600\nKey : Clothes, Value : 500\nKey : Mobile, Value : 5100\nKey : Pen, Value : 110\nKey : Book, Value : 600\n"
},
{
"code": null,
"e": 25330,
"s": 25290,
"text": "Program 2: To Show NullPointerException"
},
{
"code": "// Java program to demonstrate// forEach(BiConsumer) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a table and add some values Map<Integer, String> table = new Hashtable<>(); table.put(1, \"100RS\"); table.put(2, \"500RS\"); table.put(3, \"1000RS\"); try { // add 100 in each value using forEach() table.forEach((k, v) -> { v = v + 100; table.put(null, v); }); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 25996,
"s": 25330,
"text": null
},
{
"code": null,
"e": 26039,
"s": 25996,
"text": "Exception: java.lang.NullPointerException\n"
},
{
"code": null,
"e": 26157,
"s": 26039,
"text": "References: https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html#forEach-java.util.function.BiConsumer-"
},
{
"code": null,
"e": 26168,
"s": 26157,
"text": "nidhi_biet"
},
{
"code": null,
"e": 26180,
"s": 26168,
"text": "java-basics"
},
{
"code": null,
"e": 26195,
"s": 26180,
"text": "Java-Functions"
},
{
"code": null,
"e": 26210,
"s": 26195,
"text": "Java-HashTable"
},
{
"code": null,
"e": 26215,
"s": 26210,
"text": "Java"
},
{
"code": null,
"e": 26220,
"s": 26215,
"text": "Java"
},
{
"code": null,
"e": 26318,
"s": 26220,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26333,
"s": 26318,
"text": "Arrays in Java"
},
{
"code": null,
"e": 26377,
"s": 26333,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 26399,
"s": 26377,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 26435,
"s": 26399,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 26460,
"s": 26435,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 26492,
"s": 26460,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26543,
"s": 26492,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26573,
"s": 26543,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26592,
"s": 26573,
"text": "Interfaces in Java"
}
] |
D3.js transform.translate() Function - GeeksforGeeks
|
15 Oct, 2020
The transform.translate() function in D3.js library is used to get the transformation whose translation tx1 and ty1 is equal to tx0 + tk x and ty0 + tk y, where tx0 and ty0 is the transform’s translation and tk is the transform’s scale.
Syntax:
transform.translate(x, y)
Parameters: This function accepts the following parameter as mentioned above and described below.
x, y: These parameters are the translation point argument.
Return value: This function returns the transformed zoom behaviour.
Below programs demonstrates the transform.translate() function of D3.js library.
Example 1:
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title> D3.js | transform.translate() Function </title> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"> </script> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | transform.translate() Function</h3> <svg height="200px" width="400px"> <g id="GFG" transform= "translate(25,25) scale(0.25)"> </g> </svg> <script> var svg = d3.select("#GFG"); svg.append("rect").attr({ "x": 0, "y": 0, "height": 100, "width": 100, "fill": "yellow" }) svg.append("rect").attr({ "x": 100, "y": 100, "height": 100, "width": 100, "fill": "orange" }) svg.append("rect").attr({ "x": 0, "y": 100, "height": 100, "width": 100, "fill": "red" }) svg.append("rect").attr({ "x": 100, "y": 0, "height": 100, "width": 100, "fill": "purple" }) var zoom = d3.behavior.zoom() .on("zoom", function () { var val_1 = d3.event.translate; var val_scale = d3.event.scale; svg.attr("transform", "translate(" + val_1[0] + "," + val_1[1] + ") scale(" + val_scale + ")") }) .scaleExtent([1, 10]) .scale(1).translate([0, 0]) d3.select("svg").call(zoom) d3.selectAll("rect").on("mousedown", function () { var scale = Math.random() * 3; var translate = [Math.random() * 10, Math.random() * 10] zoom.scale(scale); zoom.translate(translate); // New transition var T = svg.transition().duration(500) zoom.event(T); }) </script> </center></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title> D3.js | transform.translate() Function </title> <script src="https://d3js.org/d3.v4.min.js"> </script> <style> circle { opacity: 0.7; fill: green; } </style> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | transform.translate() Function</h3> <svg></svg> <script> var transform = d3.zoomIdentity .translate(100, 0).scale(1); var zoom = d3.zoom().on("zoom", handleZoom); var svg = d3.select("svg") .attr('width', 400) .attr('height', 200) .style("background", "orange") .call(zoom) .call(zoom.transform, transform); var zoomable = svg .append("g") .attr("class", "zoomable") .attr("transform", transform); var circles = zoomable.append('circle') .attr("id", "circles") .attr("cx", 100) .attr("cy", 100) .attr('r', 30); function handleZoom() { if (zoomable) { zoomable.attr("transform", d3.event.transform); } }; </script> </center></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 25537,
"s": 25300,
"text": "The transform.translate() function in D3.js library is used to get the transformation whose translation tx1 and ty1 is equal to tx0 + tk x and ty0 + tk y, where tx0 and ty0 is the transform’s translation and tk is the transform’s scale."
},
{
"code": null,
"e": 25545,
"s": 25537,
"text": "Syntax:"
},
{
"code": null,
"e": 25571,
"s": 25545,
"text": "transform.translate(x, y)"
},
{
"code": null,
"e": 25669,
"s": 25571,
"text": "Parameters: This function accepts the following parameter as mentioned above and described below."
},
{
"code": null,
"e": 25728,
"s": 25669,
"text": "x, y: These parameters are the translation point argument."
},
{
"code": null,
"e": 25796,
"s": 25728,
"text": "Return value: This function returns the transformed zoom behaviour."
},
{
"code": null,
"e": 25877,
"s": 25796,
"text": "Below programs demonstrates the transform.translate() function of D3.js library."
},
{
"code": null,
"e": 25888,
"s": 25877,
"text": "Example 1:"
},
{
"code": null,
"e": 25893,
"s": 25888,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title> D3.js | transform.translate() Function </title> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js\"> </script> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | transform.translate() Function</h3> <svg height=\"200px\" width=\"400px\"> <g id=\"GFG\" transform= \"translate(25,25) scale(0.25)\"> </g> </svg> <script> var svg = d3.select(\"#GFG\"); svg.append(\"rect\").attr({ \"x\": 0, \"y\": 0, \"height\": 100, \"width\": 100, \"fill\": \"yellow\" }) svg.append(\"rect\").attr({ \"x\": 100, \"y\": 100, \"height\": 100, \"width\": 100, \"fill\": \"orange\" }) svg.append(\"rect\").attr({ \"x\": 0, \"y\": 100, \"height\": 100, \"width\": 100, \"fill\": \"red\" }) svg.append(\"rect\").attr({ \"x\": 100, \"y\": 0, \"height\": 100, \"width\": 100, \"fill\": \"purple\" }) var zoom = d3.behavior.zoom() .on(\"zoom\", function () { var val_1 = d3.event.translate; var val_scale = d3.event.scale; svg.attr(\"transform\", \"translate(\" + val_1[0] + \",\" + val_1[1] + \") scale(\" + val_scale + \")\") }) .scaleExtent([1, 10]) .scale(1).translate([0, 0]) d3.select(\"svg\").call(zoom) d3.selectAll(\"rect\").on(\"mousedown\", function () { var scale = Math.random() * 3; var translate = [Math.random() * 10, Math.random() * 10] zoom.scale(scale); zoom.translate(translate); // New transition var T = svg.transition().duration(500) zoom.event(T); }) </script> </center></body> </html>",
"e": 28131,
"s": 25893,
"text": null
},
{
"code": null,
"e": 28139,
"s": 28131,
"text": "Output:"
},
{
"code": null,
"e": 28150,
"s": 28139,
"text": "Example 2:"
},
{
"code": null,
"e": 28155,
"s": 28150,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title> D3.js | transform.translate() Function </title> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> circle { opacity: 0.7; fill: green; } </style> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | transform.translate() Function</h3> <svg></svg> <script> var transform = d3.zoomIdentity .translate(100, 0).scale(1); var zoom = d3.zoom().on(\"zoom\", handleZoom); var svg = d3.select(\"svg\") .attr('width', 400) .attr('height', 200) .style(\"background\", \"orange\") .call(zoom) .call(zoom.transform, transform); var zoomable = svg .append(\"g\") .attr(\"class\", \"zoomable\") .attr(\"transform\", transform); var circles = zoomable.append('circle') .attr(\"id\", \"circles\") .attr(\"cx\", 100) .attr(\"cy\", 100) .attr('r', 30); function handleZoom() { if (zoomable) { zoomable.attr(\"transform\", d3.event.transform); } }; </script> </center></body> </html>",
"e": 29593,
"s": 28155,
"text": null
},
{
"code": null,
"e": 29601,
"s": 29593,
"text": "Output:"
},
{
"code": null,
"e": 29607,
"s": 29601,
"text": "D3.js"
},
{
"code": null,
"e": 29618,
"s": 29607,
"text": "JavaScript"
},
{
"code": null,
"e": 29635,
"s": 29618,
"text": "Web Technologies"
},
{
"code": null,
"e": 29733,
"s": 29635,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29794,
"s": 29733,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29835,
"s": 29794,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29889,
"s": 29835,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29929,
"s": 29889,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29977,
"s": 29929,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 30019,
"s": 29977,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30052,
"s": 30019,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30102,
"s": 30052,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 30164,
"s": 30102,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Apache CXF with WSDL First
|
The CXF-POJO application that you have developed results in a very tight coupling between the client and the server. Giving a direct access to the service interface can also pose severe security threats. Thus, decoupling between the client and the server is usually desired, which is achieved by using WSDL (Web Services Description Language).
We write the web service interface in a WSDL document which is XML-based. We will use a tool to map this WSDL to Apache CXF interfaces which are then implemented and used by our client and server applications. For providing decoupling, starting with a WSDL is a preferred way. For this, you need to first learn a new language - WSDL. Writing WSDL needs a careful approach and it would be better if you can gain some understanding on this before you start working on it.
In this lesson, we will start by defining a web service interface in a WSDL document. We will learn how to use CXF to create both server and client applications starting with WSDL. We will keep the application simple to maintain focus on the use of CXF. After the server application is created we will publish it to a desired URL using a built-in CXF class.
First, let us describe the WSDL that we are going to use.
The webservice that we are going to implement will have one single webmethod called greetings that accepts a string parameter holding the user name and returns a string message to the caller after appending a greetings message to the user name. The complete wsdl is shown below −
//Hello.wsdl
<?xml version = "1.0" encoding = "UTF-8"?>
<wsdl:definitions xmlns:soap = "http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns = "http://helloworld.tutorialspoint.com/"
xmlns:wsdl = "http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
name = "HelloWorld"
targetNamespace = "http://helloworld.tutorialspoint.com/">
<wsdl:types>
<xsd:schema attributeFormDefault = "unqualified"
elementFormDefault = "qualified"
targetNamespace = "http://helloworld.tutorialspoint.com/">
<xsd:element name = "greetings" type = "tns:greetings"/>
<xsd:complexType name = "greetings">
<xsd:sequence>
<xsd:element minOccurs = "0" name = "arg0" type = "xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name = "greetingsResponse"
type = "tns:greetingsResponse"/>
<xsd:complexType name = "greetingsResponse">
<xsd:sequence>
<xsd:element minOccurs = "0" name = "return" type = "xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
</wsdl:types>
<wsdl:message name = "greetings">
<wsdl:part element = "tns:greetings" name = "parameters"> </wsdl:part>
</wsdl:message>
<wsdl:message name = "greetingsResponse">
<wsdl:part element = "tns:greetingsResponse" name = "parameters"> </wsdl:part>
</wsdl:message>
<wsdl:portType name = "HelloWorldPortType">
<wsdl:operation name = "greetings">
<wsdl:input message = "tns:greetings" name = "greetings"> </wsdl:input>
<wsdl:output message = "tns:greetingsResponse" name = "greetingsResponse">
</wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name = "HelloWorldSoapBinding" type = "tns:HelloWorldPortType">
<soap:binding style = "document"
transport = "http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name = "greetings">
<soap:operation soapAction = "" style = "document"/>
<wsdl:input name = "greetings"></wsdl:input>
<wsdl:output name = "greetingsResponse">
<soap:body use = "literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name = "HelloWorldService">
<wsdl:port binding = "tns:HelloWorldSoapBinding" name = "HelloWorldPort">
<soap:address location = "http://localhost:9090/HelloServerPort"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
Note that writing a syntactically correct wsdl has always been a challenge to the developers; there are many tools and online editors are available for creating a wsdl. These editors ask for the names of messages that you want to implement along with the parameters that you wish to pass in a message and the type of return message that you want your client application to receive. If you know wsdl syntax, you may hand code the entire document or use one of the editors to create your own.
In the above wsdl, we have defined a single message called greetings. The message is delivered to the service called HelloWorldService that is running at http://localhost:9090/HelloServerPort.
With this, we will now proceed to server development. Before developing the server, we need to generate Apache CXF interface to our web service. This is to be done from the given wsdl. To do this, you use a tool called wsdl2java.
As we will be using maven to build the project, you will need to add the following plugin to the pom.xml file.
<plugins>
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<wsdlOptions>
<wsdlOption>
<wsdl>src/main/resources/hello.wsdl</wsdl>
<faultSerialVersionUID> 1 </faultSerialVersionUID>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
Note that we specify the location of the wsdl file as src/main/resources/Hello.wsdl. You will have to make sure that you create an appropriate directory structure for your project and add the earlier shown hello.wsdl file to the specified folder.
The wsdl2java plugin will compile this wsdl and create Apache CXF classes in a pre-defined folder. The full project structure is shown here for your ready reference.
Now, you are ready to create a server using the wsdl2java generated classes. The classes that wsdl2java has created is shown in the figure below −
In the list of generated classes, you must have noticed one of them is a Apache CXF interface - this is HelloWorldPortType.java. Examine this file in your code editor. The file contents are shown here for your ready reference −
//HelloWorldPortType.java
package com.tutorialspoint.helloworld;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by Apache CXF 3.3.0
* 2019-02-11T12:05:55.220+05:30
* Generated source version: 3.3.0
*
*/
@WebService(targetNamespace = "http://helloworld.tutorialspoint.com/",
name = "HelloWorldPortType")
@XmlSeeAlso({ObjectFactory.class})
public interface HelloWorldPortType {
@WebMethod
@RequestWrapper(localName = "greetings", targetNamespace =
"http://helloworld.tutorialspoint.com/", className =
"com.tutorialspoint.helloworld.Greetings")
@ResponseWrapper(localName = "greetingsResponse", targetNamespace =
"http://helloworld.tutorialspoint.com/", className =
"com.tutorialspoint.helloworld.GreetingsResponse")
@WebResult(name = "return", targetNamespace =
"http://helloworld.tutorialspoint.com/")
public java.lang.String greetings(
@WebParam(name = "arg0", targetNamespace =
"http://helloworld.tutorialspoint.com/")
java.lang.String arg0
);
}
Note that the interface contains a method called greetings. This was a message type in our wsdl. The wsdl2java tool has added this method to the generated interface. Now, you can understand that whatever messages you write in your wsdl, a corresponding method would be generated in the interface.
Now, your task would be to implement all these methods corresponding to the various messages that you have defined in your wsdl. Note that in the earlier example of Apache CXF-First, we started out with a Apache CXF interface for our web service. In this case, the Apache CXF interface is created from wsdl.
The implementation of service interface is trivial. The full implementation is shown in the listing below −
//HelloWorldImpl.java
package com.tutorialspoint.helloworld;
public class HelloWorldImpl implements HelloWorldPortType {
@Override
public String greetings(String name) {
return ("hi " + name);
}
}
The code implements the sole interface method called greetings. The method takes one parameter of string type, prepends a "hi" message to it and returns the resultant string to the caller.
Next, we will write the server application.
Developing server application is once again trivial. Here, we will use the CXF supplied Endpoint class to publish our service. This is done in the following two lines of code −
HelloWorldPortType implementor = new HelloWorldImpl();
Endpoint.publish("http://localhost:9090/HelloServerPort",
implementor,
new LoggingFeature());
First, we create an object of our service implementor class - HelloWorldImpl. Then, we pass this reference as a second parameter to the publish method. The first parameter is the address to which the service is published - the clients would use this URL to access the service. The entire source for the server application is given here −
//Server.java
package com.tutorialspoint.helloworld;
import javax.xml.ws.Endpoint;
import org.apache.cxf.ext.logging.LoggingFeature;
public class Server {
public static void main(String[] args) throws Exception {
HelloWorldPortType implementor = new HelloWorldImpl();
Endpoint.publish("http://localhost:9090/HelloServerPort",
implementor,
new LoggingFeature());
System.out.println("Server ready...");
Thread.sleep(5 * 60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
}
To build this server class you will need to add a build profile in your pom.xml. This is shown below −
<profile>
<id>server</id>
<build>
<defaultGoal>test</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>
com.tutorialspoint.helloworld.Server
</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
</profile>
Note that the fully qualified name of the Server class is specified in the configuration. Also, the dependency tag specifies that we will be using the embedded jetty web server to deploy our server application.
Finally, to deploy the server application, you will need to make one more modification in pom.xml to setup your application as a web application. The code that you need to add into your pom.xml is given below −
<defaultGoal>install</defaultGoal>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
<webResources>
<resource>
<directory>src/main/resources</directory>
<targetPath>WEB-INF</targetPath>
<includes>
<include>*.wsdl</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</pluginManagement>
Before you deploy the application, you need to add two more files to your project. These are shown in the screenshot below −
These files are CXF standard files which define the mapping for CXFServlet. The code within the web.xml file is shown here for your quick reference −
//cxf-servlet.xml
<web-app xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>cxf</display-name>
<servlet>
<description>Apache CXF Endpoint</description>
<display-name>cxf</display-name>
<servlet-name>cxf</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
In the cxf-servlet.xml you declare the properties for your service's endpoint. This is shown in the code snippet below −
<beans ...>
<jaxws:endpoint xmlns:helloworld = "http://tutorialspoint.com/"
id="helloHTTP"
address = "http://localhost:9090/HelloServerPort"
serviceName = "helloworld:HelloServiceService"
endpointName = "helloworld:HelloServicePort">
</jaxws:endpoint>
</beans>
Here we define the id for our service endpoint, the address on which the service will be available, the service name and the endpoint name. Now, you understand how your service gets routed and processed by a CXF servlet.
The pom.xml includes a few more dependencies. Rather than describing all the dependencies, we have included the final version of pom.xml below −
<?xml version="1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>cxf-wsdl</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<defaultGoal>install</defaultGoal>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
<webResources>
<resource>
<directory>src/main/resources</directory>
<targetPath>WEB-INF</targetPath>
<includes>
<include>*.wsdl</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<wsdlOptions>
<wsdlOption>
<wsdl>src/main/resources/Hello.wsdl</wsdl>
<faultSerialVersionUID>1</faultSerialVersionUID>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>server</id>
<build>
<defaultGoal>test</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>
com.tutorialspoint.helloworld.Server
</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
</profile>
<profile>
<id>client</id>
<build>
<defaultGoal>test</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>
com.tutorialspoint.helloworld.Client
</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-management</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-features-metrics</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.cxf.xjc-utils</groupId>
<artifactId>cxf-xjc-runtime</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-features-logging</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta2</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
</project>
Note that it also includes a profile for building client that we will be learning soon in the later sections.
Now, you are ready to run the web app. In the command window, run the build script using the following command.
mvn clean install
This will generate the appropriate Apache CXF classes from your wsdl, compile your Apache CXF classes, deploy the server on the embedded jetty server and run your application.
You will see the following message on the console −
INFO: Setting the server's publish address to be
http://localhost:9090/HelloServerPort
Server ready...
As before, you can test the server by opening the server URL in your browser.
As we did not specify any operation, only a fault message is returned to the browser by our application. Now, try adding the ?wsdl to your URL and you will see the following output −
So our server application is running as expected. You may use the SOAP Client such as Postman described earlier to further test your service.
The next part of this tutorial is to write a client that uses our service.
Writing the client in a CXF application is as important as writing a server. Here is the complete code for the client that essentially consists of only three lines, the rest of the lines just print the service information to the user.
//Client.java
package com.tutorialspoint.helloworld;
public class Client {
public static void main(String[] args) throws Exception {
//Create the service client with its default wsdlurl
HelloWorldService helloServiceService = new HelloWorldService();
System.out.println("service: " +
helloServiceService.getServiceName());
System.out.println("wsdl location: " +
helloServiceService.getWSDLDocumentLocation());
HelloWorldPortType helloService =
helloServiceService.getHelloWorldPort();
System.out.println(helloService.greetings
(System.getProperty("user.name")));
}
}
Here, we simply create an instance of our service HelloWorldService, get its port by calling getHelloWorldPort method, and then pass our greetings message to it. Run the client and you will see the following output −
service: {http://helloworld.tutorialspoint.com/}HelloWorldService
wsdl location: file:/Users/drsarang/Desktop/tutorialpoint/cxf-
wsdl/src/main/resources/Hello.wsdl
hi drsarang
So far you have learned how to use CXF with Apache CXF-First and WSDL-First architectures. In the Apache CXF-First approach, you used a POJO with ServerFactoryBean class from CXF libraries to create a server. To create a client you used ClientProxyFactoryBean class from CXF library. In the WSDL-First approach, you used Endpoint class to publish the service at the desired URL and a specified implementor. You can now extend these techniques to integrate different protocols and transports.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2107,
"s": 1763,
"text": "The CXF-POJO application that you have developed results in a very tight coupling between the client and the server. Giving a direct access to the service interface can also pose severe security threats. Thus, decoupling between the client and the server is usually desired, which is achieved by using WSDL (Web Services Description Language)."
},
{
"code": null,
"e": 2577,
"s": 2107,
"text": "We write the web service interface in a WSDL document which is XML-based. We will use a tool to map this WSDL to Apache CXF interfaces which are then implemented and used by our client and server applications. For providing decoupling, starting with a WSDL is a preferred way. For this, you need to first learn a new language - WSDL. Writing WSDL needs a careful approach and it would be better if you can gain some understanding on this before you start working on it."
},
{
"code": null,
"e": 2935,
"s": 2577,
"text": "In this lesson, we will start by defining a web service interface in a WSDL document. We will learn how to use CXF to create both server and client applications starting with WSDL. We will keep the application simple to maintain focus on the use of CXF. After the server application is created we will publish it to a desired URL using a built-in CXF class."
},
{
"code": null,
"e": 2993,
"s": 2935,
"text": "First, let us describe the WSDL that we are going to use."
},
{
"code": null,
"e": 3273,
"s": 2993,
"text": "The webservice that we are going to implement will have one single webmethod called greetings that accepts a string parameter holding the user name and returns a string message to the caller after appending a greetings message to the user name. The complete wsdl is shown below −"
},
{
"code": null,
"e": 5806,
"s": 3273,
"text": "//Hello.wsdl\n<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<wsdl:definitions xmlns:soap = \"http://schemas.xmlsoap.org/wsdl/soap/\"\n xmlns:tns = \"http://helloworld.tutorialspoint.com/\"\n xmlns:wsdl = \"http://schemas.xmlsoap.org/wsdl/\"\n xmlns:xsd = \"http://www.w3.org/2001/XMLSchema\"\n name = \"HelloWorld\"\n targetNamespace = \"http://helloworld.tutorialspoint.com/\">\n <wsdl:types>\n <xsd:schema attributeFormDefault = \"unqualified\"\n elementFormDefault = \"qualified\"\n targetNamespace = \"http://helloworld.tutorialspoint.com/\">\n <xsd:element name = \"greetings\" type = \"tns:greetings\"/>\n <xsd:complexType name = \"greetings\">\n <xsd:sequence>\n <xsd:element minOccurs = \"0\" name = \"arg0\" type = \"xsd:string\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name = \"greetingsResponse\"\n type = \"tns:greetingsResponse\"/>\n <xsd:complexType name = \"greetingsResponse\">\n <xsd:sequence>\n <xsd:element minOccurs = \"0\" name = \"return\" type = \"xsd:string\"/>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:schema>\n </wsdl:types>\n <wsdl:message name = \"greetings\">\n <wsdl:part element = \"tns:greetings\" name = \"parameters\"> </wsdl:part>\n </wsdl:message>\n <wsdl:message name = \"greetingsResponse\">\n <wsdl:part element = \"tns:greetingsResponse\" name = \"parameters\"> </wsdl:part>\n </wsdl:message>\n <wsdl:portType name = \"HelloWorldPortType\">\n <wsdl:operation name = \"greetings\">\n <wsdl:input message = \"tns:greetings\" name = \"greetings\"> </wsdl:input>\n <wsdl:output message = \"tns:greetingsResponse\" name = \"greetingsResponse\">\n </wsdl:output>\n </wsdl:operation>\n </wsdl:portType>\n <wsdl:binding name = \"HelloWorldSoapBinding\" type = \"tns:HelloWorldPortType\">\n <soap:binding style = \"document\"\n transport = \"http://schemas.xmlsoap.org/soap/http\"/>\n <wsdl:operation name = \"greetings\">\n <soap:operation soapAction = \"\" style = \"document\"/>\n <wsdl:input name = \"greetings\"></wsdl:input>\n <wsdl:output name = \"greetingsResponse\">\n <soap:body use = \"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n </wsdl:binding>\n <wsdl:service name = \"HelloWorldService\">\n <wsdl:port binding = \"tns:HelloWorldSoapBinding\" name = \"HelloWorldPort\">\n <soap:address location = \"http://localhost:9090/HelloServerPort\"/>\n </wsdl:port>\n </wsdl:service>\n</wsdl:definitions>"
},
{
"code": null,
"e": 6297,
"s": 5806,
"text": "Note that writing a syntactically correct wsdl has always been a challenge to the developers; there are many tools and online editors are available for creating a wsdl. These editors ask for the names of messages that you want to implement along with the parameters that you wish to pass in a message and the type of return message that you want your client application to receive. If you know wsdl syntax, you may hand code the entire document or use one of the editors to create your own."
},
{
"code": null,
"e": 6490,
"s": 6297,
"text": "In the above wsdl, we have defined a single message called greetings. The message is delivered to the service called HelloWorldService that is running at http://localhost:9090/HelloServerPort."
},
{
"code": null,
"e": 6720,
"s": 6490,
"text": "With this, we will now proceed to server development. Before developing the server, we need to generate Apache CXF interface to our web service. This is to be done from the given wsdl. To do this, you use a tool called wsdl2java."
},
{
"code": null,
"e": 6831,
"s": 6720,
"text": "As we will be using maven to build the project, you will need to add the following plugin to the pom.xml file."
},
{
"code": null,
"e": 7556,
"s": 6831,
"text": "<plugins>\n <plugin>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-codegen-plugin</artifactId>\n <version>3.3.0</version>\n <executions>\n <execution>\n <id>generate-sources</id>\n <phase>generate-sources</phase>\n <configuration>\n <wsdlOptions>\n <wsdlOption>\n <wsdl>src/main/resources/hello.wsdl</wsdl>\n <faultSerialVersionUID> 1 </faultSerialVersionUID>\n </wsdlOption>\n </wsdlOptions>\n </configuration>\n <goals>\n <goal>wsdl2java</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n</plugins>"
},
{
"code": null,
"e": 7803,
"s": 7556,
"text": "Note that we specify the location of the wsdl file as src/main/resources/Hello.wsdl. You will have to make sure that you create an appropriate directory structure for your project and add the earlier shown hello.wsdl file to the specified folder."
},
{
"code": null,
"e": 7969,
"s": 7803,
"text": "The wsdl2java plugin will compile this wsdl and create Apache CXF classes in a pre-defined folder. The full project structure is shown here for your ready reference."
},
{
"code": null,
"e": 8116,
"s": 7969,
"text": "Now, you are ready to create a server using the wsdl2java generated classes. The classes that wsdl2java has created is shown in the figure below −"
},
{
"code": null,
"e": 8344,
"s": 8116,
"text": "In the list of generated classes, you must have noticed one of them is a Apache CXF interface - this is HelloWorldPortType.java. Examine this file in your code editor. The file contents are shown here for your ready reference −"
},
{
"code": null,
"e": 9584,
"s": 8344,
"text": "//HelloWorldPortType.java\npackage com.tutorialspoint.helloworld;\nimport javax.jws.WebMethod;\nimport javax.jws.WebParam;\nimport javax.jws.WebResult;\nimport javax.jws.WebService;\nimport javax.xml.bind.annotation.XmlSeeAlso;\nimport javax.xml.ws.RequestWrapper;\nimport javax.xml.ws.ResponseWrapper;\n/**\n* This class was generated by Apache CXF 3.3.0\n* 2019-02-11T12:05:55.220+05:30\n* Generated source version: 3.3.0\n*\n*/\n\n@WebService(targetNamespace = \"http://helloworld.tutorialspoint.com/\",\n name = \"HelloWorldPortType\")\n@XmlSeeAlso({ObjectFactory.class})\npublic interface HelloWorldPortType {\n @WebMethod\n @RequestWrapper(localName = \"greetings\", targetNamespace =\n \"http://helloworld.tutorialspoint.com/\", className =\n \"com.tutorialspoint.helloworld.Greetings\")\n @ResponseWrapper(localName = \"greetingsResponse\", targetNamespace =\n \"http://helloworld.tutorialspoint.com/\", className =\n \"com.tutorialspoint.helloworld.GreetingsResponse\")\n @WebResult(name = \"return\", targetNamespace =\n \"http://helloworld.tutorialspoint.com/\")\n public java.lang.String greetings(\n @WebParam(name = \"arg0\", targetNamespace =\n \"http://helloworld.tutorialspoint.com/\")\n java.lang.String arg0\n );\n}"
},
{
"code": null,
"e": 9881,
"s": 9584,
"text": "Note that the interface contains a method called greetings. This was a message type in our wsdl. The wsdl2java tool has added this method to the generated interface. Now, you can understand that whatever messages you write in your wsdl, a corresponding method would be generated in the interface."
},
{
"code": null,
"e": 10189,
"s": 9881,
"text": "Now, your task would be to implement all these methods corresponding to the various messages that you have defined in your wsdl. Note that in the earlier example of Apache CXF-First, we started out with a Apache CXF interface for our web service. In this case, the Apache CXF interface is created from wsdl."
},
{
"code": null,
"e": 10297,
"s": 10189,
"text": "The implementation of service interface is trivial. The full implementation is shown in the listing below −"
},
{
"code": null,
"e": 10509,
"s": 10297,
"text": "//HelloWorldImpl.java\npackage com.tutorialspoint.helloworld;\npublic class HelloWorldImpl implements HelloWorldPortType {\n @Override\n public String greetings(String name) {\n return (\"hi \" + name);\n }\n}"
},
{
"code": null,
"e": 10698,
"s": 10509,
"text": "The code implements the sole interface method called greetings. The method takes one parameter of string type, prepends a \"hi\" message to it and returns the resultant string to the caller."
},
{
"code": null,
"e": 10742,
"s": 10698,
"text": "Next, we will write the server application."
},
{
"code": null,
"e": 10919,
"s": 10742,
"text": "Developing server application is once again trivial. Here, we will use the CXF supplied Endpoint class to publish our service. This is done in the following two lines of code −"
},
{
"code": null,
"e": 11083,
"s": 10919,
"text": "HelloWorldPortType implementor = new HelloWorldImpl();\n Endpoint.publish(\"http://localhost:9090/HelloServerPort\",\n implementor,\n new LoggingFeature());"
},
{
"code": null,
"e": 11421,
"s": 11083,
"text": "First, we create an object of our service implementor class - HelloWorldImpl. Then, we pass this reference as a second parameter to the publish method. The first parameter is the address to which the service is published - the clients would use this URL to access the service. The entire source for the server application is given here −"
},
{
"code": null,
"e": 11969,
"s": 11421,
"text": "//Server.java\npackage com.tutorialspoint.helloworld;\nimport javax.xml.ws.Endpoint;\nimport org.apache.cxf.ext.logging.LoggingFeature;\npublic class Server {\n public static void main(String[] args) throws Exception {\n HelloWorldPortType implementor = new HelloWorldImpl();\n Endpoint.publish(\"http://localhost:9090/HelloServerPort\",\n implementor,\n new LoggingFeature());\n System.out.println(\"Server ready...\");\n Thread.sleep(5 * 60 * 1000);\n System.out.println(\"Server exiting\");\n System.exit(0);\n }\n}"
},
{
"code": null,
"e": 12072,
"s": 11969,
"text": "To build this server class you will need to add a build profile in your pom.xml. This is shown below −"
},
{
"code": null,
"e": 13033,
"s": 12072,
"text": "<profile>\n <id>server</id>\n <build>\n <defaultGoal>test</defaultGoal>\n <plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>exec-maven-plugin</artifactId>\n <version>1.6.0</version>\n <executions>\n <execution>\n <phase>test</phase>\n <goals>\n <goal>java</goal>\n </goals>\n <configuration>\n <mainClass>\n com.tutorialspoint.helloworld.Server\n </mainClass>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n <dependencies>\n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-transports-http-jetty</artifactId>\n <version>3.3.0</version>\n </dependency>\n </dependencies>\n</profile>"
},
{
"code": null,
"e": 13244,
"s": 13033,
"text": "Note that the fully qualified name of the Server class is specified in the configuration. Also, the dependency tag specifies that we will be using the embedded jetty web server to deploy our server application."
},
{
"code": null,
"e": 13455,
"s": 13244,
"text": "Finally, to deploy the server application, you will need to make one more modification in pom.xml to setup your application as a web application. The code that you need to add into your pom.xml is given below −"
},
{
"code": null,
"e": 14109,
"s": 13455,
"text": "<defaultGoal>install</defaultGoal>\n<pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-war-plugin</artifactId>\n <version>3.2.2</version>\n <configuration>\n <webXml>src/main/webapp/WEB-INF/web.xml</webXml>\n <webResources>\n <resource>\n <directory>src/main/resources</directory>\n <targetPath>WEB-INF</targetPath>\n <includes>\n <include>*.wsdl</include>\n </includes>\n </resource>\n </webResources>\n </configuration>\n </plugin>\n </plugins>\n</pluginManagement>"
},
{
"code": null,
"e": 14234,
"s": 14109,
"text": "Before you deploy the application, you need to add two more files to your project. These are shown in the screenshot below −"
},
{
"code": null,
"e": 14384,
"s": 14234,
"text": "These files are CXF standard files which define the mapping for CXFServlet. The code within the web.xml file is shown here for your quick reference −"
},
{
"code": null,
"e": 15200,
"s": 14384,
"text": "//cxf-servlet.xml\n<web-app xmlns = \"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" version=\"2.5\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\">\n <display-name>cxf</display-name>\n <servlet>\n <description>Apache CXF Endpoint</description>\n <display-name>cxf</display-name>\n <servlet-name>cxf</servlet-name>\n <servlet-class>\n org.apache.cxf.transport.servlet.CXFServlet\n </servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n <servlet-mapping>\n <servlet-name>cxf</servlet-name>\n <url-pattern>/services/*</url-pattern>\n </servlet-mapping>\n <session-config>\n <session-timeout>60</session-timeout>\n </session-config>\n</web-app>"
},
{
"code": null,
"e": 15321,
"s": 15200,
"text": "In the cxf-servlet.xml you declare the properties for your service's endpoint. This is shown in the code snippet below −"
},
{
"code": null,
"e": 15612,
"s": 15321,
"text": "<beans ...>\n <jaxws:endpoint xmlns:helloworld = \"http://tutorialspoint.com/\"\n id=\"helloHTTP\"\n address = \"http://localhost:9090/HelloServerPort\"\n serviceName = \"helloworld:HelloServiceService\"\n endpointName = \"helloworld:HelloServicePort\">\n </jaxws:endpoint>\n</beans>"
},
{
"code": null,
"e": 15833,
"s": 15612,
"text": "Here we define the id for our service endpoint, the address on which the service will be available, the service name and the endpoint name. Now, you understand how your service gets routed and processed by a CXF servlet."
},
{
"code": null,
"e": 15978,
"s": 15833,
"text": "The pom.xml includes a few more dependencies. Rather than describing all the dependencies, we have included the final version of pom.xml below −"
},
{
"code": null,
"e": 21993,
"s": 15978,
"text": "<?xml version=\"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>cxf-wsdl</artifactId>\n <version>1.0</version>\n <packaging>jar</packaging>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <maven.compiler.source>1.8</maven.compiler.source>\n <maven.compiler.target>1.8</maven.compiler.target>\n </properties>\n <build>\n <defaultGoal>install</defaultGoal>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-war-plugin</artifactId>\n <version>3.2.2</version>\n <configuration>\n <webXml>src/main/webapp/WEB-INF/web.xml</webXml>\n <webResources>\n <resource>\n <directory>src/main/resources</directory>\n <targetPath>WEB-INF</targetPath>\n <includes>\n <include>*.wsdl</include>\n </includes>\n </resource>\n </webResources>\n </configuration>\n </plugin>\n </plugins>\n </pluginManagement>\n <plugins>\n <plugin>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-codegen-plugin</artifactId>\n <version>3.3.0</version>\n <executions>\n <execution>\n <id>generate-sources</id>\n <phase>generate-sources</phase>\n <configuration>\n <wsdlOptions>\n <wsdlOption>\n <wsdl>src/main/resources/Hello.wsdl</wsdl>\n <faultSerialVersionUID>1</faultSerialVersionUID>\n </wsdlOption>\n </wsdlOptions>\n </configuration>\n <goals>\n <goal>wsdl2java</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n <profiles>\n <profile>\n <id>server</id>\n <build>\n <defaultGoal>test</defaultGoal>\n <plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>exec-maven-plugin</artifactId>\n <version>1.6.0</version>\n <executions>\n <execution>\n <phase>test</phase>\n <goals>\n <goal>java</goal>\n </goals>\n <configuration>\n <mainClass>\n com.tutorialspoint.helloworld.Server\n </mainClass>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n <dependencies>\n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-transports-http-jetty</artifactId>\n <version>3.3.0</version>\n </dependency>\n </dependencies>\n </profile>\n <profile>\n <id>client</id>\n <build>\n <defaultGoal>test</defaultGoal>\n <plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>exec-maven-plugin</artifactId>\n <executions>\n <execution>\n <phase>test</phase>\n <goals>\n <goal>java</goal>\n </goals>\n <configuration>\n <mainClass>\n com.tutorialspoint.helloworld.Client\n </mainClass>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n </profile>\n </profiles>\n <dependencies>\n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-frontend-jaxws</artifactId>\n <version>3.3.0</version>\n </dependency>\n \n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-transports-http</artifactId>\n <version>3.3.0</version>\n </dependency>\n \n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-management</artifactId>\n <version>3.3.0</version>\n </dependency>\n \n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-features-metrics</artifactId>\n <version>3.3.0</version>\n </dependency>\n \n <dependency>\n <groupId>org.apache.cxf.xjc-utils</groupId>\n <artifactId>cxf-xjc-runtime</artifactId>\n <version>3.3.0</version>\n </dependency>\n \n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-features-logging</artifactId>\n <version>3.3.0</version>\n </dependency>\n \n <dependency>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>exec-maven-plugin</artifactId>\n <version>1.6.0</version>\n </dependency>\n \n <dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-api</artifactId>\n <version>1.8.0-beta2</version>\n </dependency>\n \n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-transports-http-jetty</artifactId>\n <version>3.3.0</version>\n </dependency>\n </dependencies>\n</project>"
},
{
"code": null,
"e": 22103,
"s": 21993,
"text": "Note that it also includes a profile for building client that we will be learning soon in the later sections."
},
{
"code": null,
"e": 22215,
"s": 22103,
"text": "Now, you are ready to run the web app. In the command window, run the build script using the following command."
},
{
"code": null,
"e": 22234,
"s": 22215,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 22410,
"s": 22234,
"text": "This will generate the appropriate Apache CXF classes from your wsdl, compile your Apache CXF classes, deploy the server on the embedded jetty server and run your application."
},
{
"code": null,
"e": 22462,
"s": 22410,
"text": "You will see the following message on the console −"
},
{
"code": null,
"e": 22567,
"s": 22462,
"text": "INFO: Setting the server's publish address to be \nhttp://localhost:9090/HelloServerPort\nServer ready...\n"
},
{
"code": null,
"e": 22645,
"s": 22567,
"text": "As before, you can test the server by opening the server URL in your browser."
},
{
"code": null,
"e": 22828,
"s": 22645,
"text": "As we did not specify any operation, only a fault message is returned to the browser by our application. Now, try adding the ?wsdl to your URL and you will see the following output −"
},
{
"code": null,
"e": 22970,
"s": 22828,
"text": "So our server application is running as expected. You may use the SOAP Client such as Postman described earlier to further test your service."
},
{
"code": null,
"e": 23045,
"s": 22970,
"text": "The next part of this tutorial is to write a client that uses our service."
},
{
"code": null,
"e": 23280,
"s": 23045,
"text": "Writing the client in a CXF application is as important as writing a server. Here is the complete code for the client that essentially consists of only three lines, the rest of the lines just print the service information to the user."
},
{
"code": null,
"e": 23922,
"s": 23280,
"text": "//Client.java\npackage com.tutorialspoint.helloworld;\npublic class Client {\n public static void main(String[] args) throws Exception {\n //Create the service client with its default wsdlurl\n HelloWorldService helloServiceService = new HelloWorldService();\n System.out.println(\"service: \" +\n helloServiceService.getServiceName());\n System.out.println(\"wsdl location: \" +\n helloServiceService.getWSDLDocumentLocation());\n HelloWorldPortType helloService =\n helloServiceService.getHelloWorldPort();\n System.out.println(helloService.greetings\n (System.getProperty(\"user.name\")));\n }\n}"
},
{
"code": null,
"e": 24139,
"s": 23922,
"text": "Here, we simply create an instance of our service HelloWorldService, get its port by calling getHelloWorldPort method, and then pass our greetings message to it. Run the client and you will see the following output −"
},
{
"code": null,
"e": 24316,
"s": 24139,
"text": "service: {http://helloworld.tutorialspoint.com/}HelloWorldService\nwsdl location: file:/Users/drsarang/Desktop/tutorialpoint/cxf-\nwsdl/src/main/resources/Hello.wsdl\nhi drsarang\n"
},
{
"code": null,
"e": 24808,
"s": 24316,
"text": "So far you have learned how to use CXF with Apache CXF-First and WSDL-First architectures. In the Apache CXF-First approach, you used a POJO with ServerFactoryBean class from CXF libraries to create a server. To create a client you used ClientProxyFactoryBean class from CXF library. In the WSDL-First approach, you used Endpoint class to publish the service at the desired URL and a specified implementor. You can now extend these techniques to integrate different protocols and transports."
},
{
"code": null,
"e": 24843,
"s": 24808,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 24862,
"s": 24843,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 24897,
"s": 24862,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 24918,
"s": 24897,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 24951,
"s": 24918,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 24964,
"s": 24951,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 24999,
"s": 24964,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 25017,
"s": 24999,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 25050,
"s": 25017,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 25068,
"s": 25050,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 25101,
"s": 25068,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 25119,
"s": 25101,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 25126,
"s": 25119,
"text": " Print"
},
{
"code": null,
"e": 25137,
"s": 25126,
"text": " Add Notes"
}
] |
Common elements in all rows of a given matrix - GeeksforGeeks
|
08 Apr, 2022
Given an m x n matrix, find all common elements present in all rows in O(mn) time and one traversal of matrix.Example:
Input:
mat[4][5] = {{1, 2, 1, 4, 8},
{3, 7, 8, 5, 1},
{8, 7, 7, 3, 1},
{8, 1, 2, 7, 9},
};
Output:
1 8 or 8 1
8 and 1 are present in all rows.
A simple solution is to consider every element and check if it is present in all rows. If present, then print it. A better solution is to sort all rows in the matrix and use similar approach as discussed here. Sorting will take O(mnlogn) time and finding common elements will take O(mn) time. So overall time complexity of this solution is O(mnlogn)Can we do better than O(mnlogn)? The idea is to use maps. We initially insert all elements of the first row in an map. For every other element in remaining rows, we check if it is present in the map. If it is present in the map and is not duplicated in current row, we increment count of the element in map by 1, else we ignore the element. If the currently traversed row is the last row, we print the element if it has appeared m-1 times before. Below is the implementation of the idea:
C++
Java
Python3
C#
Javascript
// A Program to prints common element in all// rows of matrix#include <bits/stdc++.h>using namespace std; // Specify number of rows and columns#define M 4#define N 5 // prints common element in all rows of matrixvoid printCommonElements(int mat[M][N]){ unordered_map<int, int> mp; // initialize 1st row elements with value 1 for (int j = 0; j < N; j++) mp[mat[0][j]] = 1; // traverse the matrix for (int i = 1; i < M; i++) { for (int j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp[mat[i][j]] == i) { // we increment count of the element // in map by 1 mp[mat[i][j]] = i + 1; // If this is last row if (i==M-1 && mp[mat[i][j]]==M) cout << mat[i][j] << " "; } } }} // driver program to test above functionint main(){ int mat[M][N] = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; printCommonElements(mat); return 0;}
// Java Program to prints common element in all// rows of matriximport java.util.*; class GFG{ // Specify number of rows and columnsstatic int M = 4;static int N =5; // prints common element in all rows of matrixstatic void printCommonElements(int mat[][]){ Map<Integer,Integer> mp = new HashMap<>(); // initialize 1st row elements with value 1 for (int j = 0; j < N; j++) mp.put(mat[0][j],1); // traverse the matrix for (int i = 1; i < M; i++) { for (int j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp.get(mat[i][j]) != null && mp.get(mat[i][j]) == i) { // we increment count of the element // in map by 1 mp.put(mat[i][j], i + 1); // If this is last row if (i == M - 1) System.out.print(mat[i][j] + " "); } } }} // Driver codepublic static void main(String[] args){ int mat[][] = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; printCommonElements(mat);}} // This code contributed by Rajput-Ji
# A Program to prints common element# in all rows of matrix # Specify number of rows and columnsM = 4N = 5 # prints common element in all# rows of matrixdef printCommonElements(mat): mp = dict() # initialize 1st row elements # with value 1 for j in range(N): mp[mat[0][j]] = 1 # traverse the matrix for i in range(1, M): for j in range(N): # If element is present in the # map and is not duplicated in # current row. if (mat[i][j] in mp.keys() and mp[mat[i][j]] == i): # we increment count of the # element in map by 1 mp[mat[i][j]] = i + 1 # If this is last row if i == M - 1: print(mat[i][j], end = " ") # Driver Codemat = [[1, 2, 1, 4, 8], [3, 7, 8, 5, 1], [8, 7, 7, 3, 1], [8, 1, 2, 7, 9]] printCommonElements(mat) # This code is contributed# by mohit kumar 29
// C# Program to print common element in all// rows of matrix to another.using System;using System.Collections.Generic; class GFG{ // Specify number of rows and columnsstatic int M = 4;static int N = 5; // prints common element in all rows of matrixstatic void printCommonElements(int [,]mat){ Dictionary<int, int> mp = new Dictionary<int, int>(); // initialize 1st row elements with value 1 for (int j = 0; j < N; j++) { if(!mp.ContainsKey(mat[0, j])) mp.Add(mat[0, j], 1); } // traverse the matrix for (int i = 1; i < M; i++) { for (int j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp.ContainsKey(mat[i, j])&& (mp[mat[i, j]] != 0 && mp[mat[i, j]] == i)) { // we increment count of the element // in map by 1 if(mp.ContainsKey(mat[i, j])) { var v = mp[mat[i, j]]; mp.Remove(mat[i, j]); mp.Add(mat[i, j], i + 1); } else mp.Add(mat[i, j], i + 1); // If this is last row if (i == M - 1) Console.Write(mat[i, j] + " "); } } }} // Driver codepublic static void Main(String[] args){ int [,]mat = {{1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}}; printCommonElements(mat);}} // This code is contributed by 29AjayKumar
<script>// Javascript Program to prints common element in all// rows of matrix // Specify number of rows and columns let M = 4; let N =5; // prints common element in all rows of matrix function printCommonElements(mat) { let mp = new Map(); // initialize 1st row elements with value 1 for (let j = 0; j < N; j++) mp.set(mat[0][j],1); // traverse the matrix for (let i = 1; i < M; i++) { for (let j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp.get(mat[i][j]) != null && mp.get(mat[i][j]) == i) { // we increment count of the element // in map by 1 mp.set(mat[i][j], i + 1); // If this is last row if (i == M - 1) document.write(mat[i][j] + " "); } } } } // Driver code let mat = [[1, 2, 1, 4, 8], [3, 7, 8, 5, 1], [8, 7, 7, 3, 1], [8, 1, 2, 7, 9]] printCommonElements(mat) // This code is contributed by unknown2108</script>
Output:
8 1
The time complexity of this solution is O(m * n) and we are doing only one traversal of the matrix.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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.
mohit kumar 29
Rajput-Ji
29AjayKumar
srivastavaharshit848
unknown2108
simmytarika5
Hash
Matrix
Hash
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Most frequent element in an array
Double Hashing
Quadratic Probing in Hashing
Sorting a Map by value in C++ STL
C++ program for hashing with chaining
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Print a given matrix in spiral form
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
|
[
{
"code": null,
"e": 25422,
"s": 25394,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 25542,
"s": 25422,
"text": "Given an m x n matrix, find all common elements present in all rows in O(mn) time and one traversal of matrix.Example: "
},
{
"code": null,
"e": 25738,
"s": 25542,
"text": "Input:\nmat[4][5] = {{1, 2, 1, 4, 8},\n {3, 7, 8, 5, 1},\n {8, 7, 7, 3, 1},\n {8, 1, 2, 7, 9},\n };\n\nOutput: \n1 8 or 8 1\n8 and 1 are present in all rows."
},
{
"code": null,
"e": 26575,
"s": 25738,
"text": "A simple solution is to consider every element and check if it is present in all rows. If present, then print it. A better solution is to sort all rows in the matrix and use similar approach as discussed here. Sorting will take O(mnlogn) time and finding common elements will take O(mn) time. So overall time complexity of this solution is O(mnlogn)Can we do better than O(mnlogn)? The idea is to use maps. We initially insert all elements of the first row in an map. For every other element in remaining rows, we check if it is present in the map. If it is present in the map and is not duplicated in current row, we increment count of the element in map by 1, else we ignore the element. If the currently traversed row is the last row, we print the element if it has appeared m-1 times before. Below is the implementation of the idea:"
},
{
"code": null,
"e": 26579,
"s": 26575,
"text": "C++"
},
{
"code": null,
"e": 26584,
"s": 26579,
"text": "Java"
},
{
"code": null,
"e": 26592,
"s": 26584,
"text": "Python3"
},
{
"code": null,
"e": 26595,
"s": 26592,
"text": "C#"
},
{
"code": null,
"e": 26606,
"s": 26595,
"text": "Javascript"
},
{
"code": "// A Program to prints common element in all// rows of matrix#include <bits/stdc++.h>using namespace std; // Specify number of rows and columns#define M 4#define N 5 // prints common element in all rows of matrixvoid printCommonElements(int mat[M][N]){ unordered_map<int, int> mp; // initialize 1st row elements with value 1 for (int j = 0; j < N; j++) mp[mat[0][j]] = 1; // traverse the matrix for (int i = 1; i < M; i++) { for (int j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp[mat[i][j]] == i) { // we increment count of the element // in map by 1 mp[mat[i][j]] = i + 1; // If this is last row if (i==M-1 && mp[mat[i][j]]==M) cout << mat[i][j] << \" \"; } } }} // driver program to test above functionint main(){ int mat[M][N] = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; printCommonElements(mat); return 0;}",
"e": 27747,
"s": 26606,
"text": null
},
{
"code": "// Java Program to prints common element in all// rows of matriximport java.util.*; class GFG{ // Specify number of rows and columnsstatic int M = 4;static int N =5; // prints common element in all rows of matrixstatic void printCommonElements(int mat[][]){ Map<Integer,Integer> mp = new HashMap<>(); // initialize 1st row elements with value 1 for (int j = 0; j < N; j++) mp.put(mat[0][j],1); // traverse the matrix for (int i = 1; i < M; i++) { for (int j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp.get(mat[i][j]) != null && mp.get(mat[i][j]) == i) { // we increment count of the element // in map by 1 mp.put(mat[i][j], i + 1); // If this is last row if (i == M - 1) System.out.print(mat[i][j] + \" \"); } } }} // Driver codepublic static void main(String[] args){ int mat[][] = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; printCommonElements(mat);}} // This code contributed by Rajput-Ji",
"e": 28981,
"s": 27747,
"text": null
},
{
"code": "# A Program to prints common element# in all rows of matrix # Specify number of rows and columnsM = 4N = 5 # prints common element in all# rows of matrixdef printCommonElements(mat): mp = dict() # initialize 1st row elements # with value 1 for j in range(N): mp[mat[0][j]] = 1 # traverse the matrix for i in range(1, M): for j in range(N): # If element is present in the # map and is not duplicated in # current row. if (mat[i][j] in mp.keys() and mp[mat[i][j]] == i): # we increment count of the # element in map by 1 mp[mat[i][j]] = i + 1 # If this is last row if i == M - 1: print(mat[i][j], end = \" \") # Driver Codemat = [[1, 2, 1, 4, 8], [3, 7, 8, 5, 1], [8, 7, 7, 3, 1], [8, 1, 2, 7, 9]] printCommonElements(mat) # This code is contributed# by mohit kumar 29",
"e": 30017,
"s": 28981,
"text": null
},
{
"code": "// C# Program to print common element in all// rows of matrix to another.using System;using System.Collections.Generic; class GFG{ // Specify number of rows and columnsstatic int M = 4;static int N = 5; // prints common element in all rows of matrixstatic void printCommonElements(int [,]mat){ Dictionary<int, int> mp = new Dictionary<int, int>(); // initialize 1st row elements with value 1 for (int j = 0; j < N; j++) { if(!mp.ContainsKey(mat[0, j])) mp.Add(mat[0, j], 1); } // traverse the matrix for (int i = 1; i < M; i++) { for (int j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp.ContainsKey(mat[i, j])&& (mp[mat[i, j]] != 0 && mp[mat[i, j]] == i)) { // we increment count of the element // in map by 1 if(mp.ContainsKey(mat[i, j])) { var v = mp[mat[i, j]]; mp.Remove(mat[i, j]); mp.Add(mat[i, j], i + 1); } else mp.Add(mat[i, j], i + 1); // If this is last row if (i == M - 1) Console.Write(mat[i, j] + \" \"); } } }} // Driver codepublic static void Main(String[] args){ int [,]mat = {{1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}}; printCommonElements(mat);}} // This code is contributed by 29AjayKumar",
"e": 31641,
"s": 30017,
"text": null
},
{
"code": "<script>// Javascript Program to prints common element in all// rows of matrix // Specify number of rows and columns let M = 4; let N =5; // prints common element in all rows of matrix function printCommonElements(mat) { let mp = new Map(); // initialize 1st row elements with value 1 for (let j = 0; j < N; j++) mp.set(mat[0][j],1); // traverse the matrix for (let i = 1; i < M; i++) { for (let j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp.get(mat[i][j]) != null && mp.get(mat[i][j]) == i) { // we increment count of the element // in map by 1 mp.set(mat[i][j], i + 1); // If this is last row if (i == M - 1) document.write(mat[i][j] + \" \"); } } } } // Driver code let mat = [[1, 2, 1, 4, 8], [3, 7, 8, 5, 1], [8, 7, 7, 3, 1], [8, 1, 2, 7, 9]] printCommonElements(mat) // This code is contributed by unknown2108</script>",
"e": 32817,
"s": 31641,
"text": null
},
{
"code": null,
"e": 32826,
"s": 32817,
"text": "Output: "
},
{
"code": null,
"e": 32830,
"s": 32826,
"text": "8 1"
},
{
"code": null,
"e": 33319,
"s": 32830,
"text": "The time complexity of this solution is O(m * n) and we are doing only one traversal of the matrix.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 33334,
"s": 33319,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33344,
"s": 33334,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 33356,
"s": 33344,
"text": "29AjayKumar"
},
{
"code": null,
"e": 33377,
"s": 33356,
"text": "srivastavaharshit848"
},
{
"code": null,
"e": 33389,
"s": 33377,
"text": "unknown2108"
},
{
"code": null,
"e": 33402,
"s": 33389,
"text": "simmytarika5"
},
{
"code": null,
"e": 33407,
"s": 33402,
"text": "Hash"
},
{
"code": null,
"e": 33414,
"s": 33407,
"text": "Matrix"
},
{
"code": null,
"e": 33419,
"s": 33414,
"text": "Hash"
},
{
"code": null,
"e": 33426,
"s": 33419,
"text": "Matrix"
},
{
"code": null,
"e": 33524,
"s": 33426,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33533,
"s": 33524,
"text": "Comments"
},
{
"code": null,
"e": 33546,
"s": 33533,
"text": "Old Comments"
},
{
"code": null,
"e": 33580,
"s": 33546,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 33595,
"s": 33580,
"text": "Double Hashing"
},
{
"code": null,
"e": 33624,
"s": 33595,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 33658,
"s": 33624,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 33696,
"s": 33658,
"text": "C++ program for hashing with chaining"
},
{
"code": null,
"e": 33731,
"s": 33696,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 33775,
"s": 33731,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 33806,
"s": 33775,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 33842,
"s": 33806,
"text": "Print a given matrix in spiral form"
}
] |
How to Remove repetitive characters from words of the given Pandas DataFrame using Regex? - GeeksforGeeks
|
29 Oct, 2021
Prerequisite: Regular Expression in Python
In this article, we will see how to remove continuously repeating characters from the words of the given column of the given Pandas Dataframe using Regex.
Here, we are actually looking for continuously occurring repetitively coming characters for that we have created a pattern that contains this regular expression (\w)\1+ here \w is for character, 1+ is for the characters that come more than once.
We are passing our pattern in the re.sub() function of re library.
Syntax: re.sub(pattern, repl, string, count=0, flags=0)
The ‘sub’ in the function stands for SubString, a certain regular expression pattern is searched in the given string(3rd parameter), and upon finding the substring pattern is replaced by repl(2nd parameter), count checks and maintains the number of times this occurs.
Now, Let’s create a Dataframe:
Python3
# importing required librariesimport pandas as pdimport re # creating Dataframe with column# as name and common_commentsdf = pd.DataFrame( { 'name' : ['Akash', 'Ayush', 'Diksha', 'Priyanka', 'Radhika'], 'common_comments' : ['hey buddy meet me today ', 'sorry bro i cant meet', 'hey akash i love geeksforgeeks', 'twiiter is the best way to comment', 'geeksforgeeks is good for learners'] }, columns = ['name', 'common_comments'])# printing Dataframedf
Output:
Now, Remove continuously repetitive characters from words of the Dataframe common_comments column.
Python3
# define a function to remove# continuously repeating character# from the worddef conti_rep_char(str1): tchr = str1.group(0) if len(tchr) > 1: return tchr[0:1] # define a function to check# whether unique character# is present or notdef check_unique_char(rep, sent_text): # regular expression for # repetition of characters convert = re.sub(r'(\w)\1+', rep, sent_text) # returning the converted word return convert df['modified_common_comments'] = df['common_comments'].apply( lambda x : check_unique_char(conti_rep_char, x))# show Dataframedf
Output:
akshaysingh98088
sooda367
prachisoda1234
Python pandas-dataFrame
Python Regex-programs
Python-pandas
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 24335,
"s": 24292,
"text": "Prerequisite: Regular Expression in Python"
},
{
"code": null,
"e": 24490,
"s": 24335,
"text": "In this article, we will see how to remove continuously repeating characters from the words of the given column of the given Pandas Dataframe using Regex."
},
{
"code": null,
"e": 24737,
"s": 24490,
"text": "Here, we are actually looking for continuously occurring repetitively coming characters for that we have created a pattern that contains this regular expression (\\w)\\1+ here \\w is for character, 1+ is for the characters that come more than once. "
},
{
"code": null,
"e": 24805,
"s": 24737,
"text": "We are passing our pattern in the re.sub() function of re library. "
},
{
"code": null,
"e": 24861,
"s": 24805,
"text": "Syntax: re.sub(pattern, repl, string, count=0, flags=0)"
},
{
"code": null,
"e": 25130,
"s": 24861,
"text": "The ‘sub’ in the function stands for SubString, a certain regular expression pattern is searched in the given string(3rd parameter), and upon finding the substring pattern is replaced by repl(2nd parameter), count checks and maintains the number of times this occurs. "
},
{
"code": null,
"e": 25161,
"s": 25130,
"text": "Now, Let’s create a Dataframe:"
},
{
"code": null,
"e": 25169,
"s": 25161,
"text": "Python3"
},
{
"code": "# importing required librariesimport pandas as pdimport re # creating Dataframe with column# as name and common_commentsdf = pd.DataFrame( { 'name' : ['Akash', 'Ayush', 'Diksha', 'Priyanka', 'Radhika'], 'common_comments' : ['hey buddy meet me today ', 'sorry bro i cant meet', 'hey akash i love geeksforgeeks', 'twiiter is the best way to comment', 'geeksforgeeks is good for learners'] }, columns = ['name', 'common_comments'])# printing Dataframedf",
"e": 25750,
"s": 25169,
"text": null
},
{
"code": null,
"e": 25761,
"s": 25753,
"text": "Output:"
},
{
"code": null,
"e": 25865,
"s": 25765,
"text": "Now, Remove continuously repetitive characters from words of the Dataframe common_comments column. "
},
{
"code": null,
"e": 25875,
"s": 25867,
"text": "Python3"
},
{
"code": "# define a function to remove# continuously repeating character# from the worddef conti_rep_char(str1): tchr = str1.group(0) if len(tchr) > 1: return tchr[0:1] # define a function to check# whether unique character# is present or notdef check_unique_char(rep, sent_text): # regular expression for # repetition of characters convert = re.sub(r'(\\w)\\1+', rep, sent_text) # returning the converted word return convert df['modified_common_comments'] = df['common_comments'].apply( lambda x : check_unique_char(conti_rep_char, x))# show Dataframedf",
"e": 26592,
"s": 25875,
"text": null
},
{
"code": null,
"e": 26603,
"s": 26595,
"text": "Output:"
},
{
"code": null,
"e": 26624,
"s": 26607,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 26633,
"s": 26624,
"text": "sooda367"
},
{
"code": null,
"e": 26648,
"s": 26633,
"text": "prachisoda1234"
},
{
"code": null,
"e": 26672,
"s": 26648,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26694,
"s": 26672,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 26708,
"s": 26694,
"text": "Python-pandas"
},
{
"code": null,
"e": 26721,
"s": 26708,
"text": "python-regex"
},
{
"code": null,
"e": 26728,
"s": 26721,
"text": "Python"
},
{
"code": null,
"e": 26826,
"s": 26728,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26858,
"s": 26826,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26914,
"s": 26858,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26956,
"s": 26914,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26998,
"s": 26956,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27020,
"s": 26998,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27051,
"s": 27020,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27090,
"s": 27051,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27145,
"s": 27090,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27174,
"s": 27145,
"text": "Create a directory in Python"
}
] |
Conditionals in Rust - GeeksforGeeks
|
03 Mar, 2021
Conditional Statements are the decision-making statements based on given conditions. Conditional statements are common in programming languages and rust has them and unlike many of them, the boolean condition doesn’t need to be surrounded by parentheses but is better to use, and each condition is followed by a block. Some things to keep in mind while using conditional statements.
Always compare similar data types.
The conditional statement always returns a boolean value.
Conditional statements supported by Rust are
if statement
else if statement
else statement
Syntax:
fn main() {
if condition1 {
// executed if condition1 true
statement;
}
else if condition2 {
// executed if condition2 is true
statement;
}
else{
// executed if both condition1 and condition2 are false
statement;
}
}
If statement is the first basic condition that needs to be checked, In other words, you provide a condition and then state, “If this condition is met, run this block of code. If the condition is not met, do not run this block of code.”
Example:
A sample code is below which checks whether the given number is greater than 10 or not. Here the below approach is used:
Provide an integer input.
The given input is checked whether is greater than 10
If true “greater than 10” is printed as output
If false the program is exited.
Rust
use std::io; fn main() { println!("enter a number:"); let mut strn = String::new(); io::stdin() .read_line(&mut strn) .expect("failed to read input."); let n: i32 = strn.trim().parse().expect("invalid input"); if n>10 { println!("Greater than 10"); }}
Output:
An if statement will be executed when the given condition is true, Else statement is executed when the given condition fails.
Example 1: A simple program to check the string input is equal to “gfg”.
Rust
fn main() { let strn = "Geeksforgeeks"; let fixed_string = "gfg"; if fixed_string==strn { println!("Same"); }else{ println!("Not Same"); }}
Output:
Not Same
Example 2: Program to check whether the given number is greater than 10 or not.
Rust
fn main() { let n = 7; if n>10 { println!("Greater than 10"); }else{ println!("Smaller than 10"); }}
Output:
Smaller than 10
Else if statement is used to check another condition after the if condition before the else condition. A program can have as many else if statements but can only have one if and one else statements.
Example: The below program checks whether the value is smaller or equals to or greater than 10.
Rust
fn main() { let n = 10; if n>10 { println!("Greater than 10"); }else if n==10 { println!("Equal to 10"); }else { println!("Smaller than 10"); }}
Output:
Equal to 10
rust-control-flow
Rust
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rust - For and Range
Rust - Casting
Rust - Creating a Library
Rust - Generic Function
Rust - Box Smart Pointer
Rust - Comments
Rust - Concept of Structures
Rust - Concept of Smart Pointers
Rust - While Loop
Scalar Datatypes in Rust
|
[
{
"code": null,
"e": 23630,
"s": 23602,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 24013,
"s": 23630,
"text": "Conditional Statements are the decision-making statements based on given conditions. Conditional statements are common in programming languages and rust has them and unlike many of them, the boolean condition doesn’t need to be surrounded by parentheses but is better to use, and each condition is followed by a block. Some things to keep in mind while using conditional statements."
},
{
"code": null,
"e": 24048,
"s": 24013,
"text": "Always compare similar data types."
},
{
"code": null,
"e": 24106,
"s": 24048,
"text": "The conditional statement always returns a boolean value."
},
{
"code": null,
"e": 24151,
"s": 24106,
"text": "Conditional statements supported by Rust are"
},
{
"code": null,
"e": 24164,
"s": 24151,
"text": "if statement"
},
{
"code": null,
"e": 24182,
"s": 24164,
"text": "else if statement"
},
{
"code": null,
"e": 24197,
"s": 24182,
"text": "else statement"
},
{
"code": null,
"e": 24205,
"s": 24197,
"text": "Syntax:"
},
{
"code": null,
"e": 24464,
"s": 24205,
"text": "fn main() {\n if condition1 {\n // executed if condition1 true\n statement;\n }\n else if condition2 {\n // executed if condition2 is true\n statement;\n }\n else{\n // executed if both condition1 and condition2 are false\n statement;\n }\n}"
},
{
"code": null,
"e": 24700,
"s": 24464,
"text": "If statement is the first basic condition that needs to be checked, In other words, you provide a condition and then state, “If this condition is met, run this block of code. If the condition is not met, do not run this block of code.”"
},
{
"code": null,
"e": 24709,
"s": 24700,
"text": "Example:"
},
{
"code": null,
"e": 24830,
"s": 24709,
"text": "A sample code is below which checks whether the given number is greater than 10 or not. Here the below approach is used:"
},
{
"code": null,
"e": 24856,
"s": 24830,
"text": "Provide an integer input."
},
{
"code": null,
"e": 24910,
"s": 24856,
"text": "The given input is checked whether is greater than 10"
},
{
"code": null,
"e": 24957,
"s": 24910,
"text": "If true “greater than 10” is printed as output"
},
{
"code": null,
"e": 24989,
"s": 24957,
"text": "If false the program is exited."
},
{
"code": null,
"e": 24994,
"s": 24989,
"text": "Rust"
},
{
"code": "use std::io; fn main() { println!(\"enter a number:\"); let mut strn = String::new(); io::stdin() .read_line(&mut strn) .expect(\"failed to read input.\"); let n: i32 = strn.trim().parse().expect(\"invalid input\"); if n>10 { println!(\"Greater than 10\"); }}",
"e": 25288,
"s": 24994,
"text": null
},
{
"code": null,
"e": 25296,
"s": 25288,
"text": "Output:"
},
{
"code": null,
"e": 25423,
"s": 25296,
"text": "An if statement will be executed when the given condition is true, Else statement is executed when the given condition fails. "
},
{
"code": null,
"e": 25497,
"s": 25423,
"text": "Example 1: A simple program to check the string input is equal to “gfg”. "
},
{
"code": null,
"e": 25502,
"s": 25497,
"text": "Rust"
},
{
"code": "fn main() { let strn = \"Geeksforgeeks\"; let fixed_string = \"gfg\"; if fixed_string==strn { println!(\"Same\"); }else{ println!(\"Not Same\"); }}",
"e": 25678,
"s": 25502,
"text": null
},
{
"code": null,
"e": 25686,
"s": 25678,
"text": "Output:"
},
{
"code": null,
"e": 25695,
"s": 25686,
"text": "Not Same"
},
{
"code": null,
"e": 25775,
"s": 25695,
"text": "Example 2: Program to check whether the given number is greater than 10 or not."
},
{
"code": null,
"e": 25780,
"s": 25775,
"text": "Rust"
},
{
"code": "fn main() { let n = 7; if n>10 { println!(\"Greater than 10\"); }else{ println!(\"Smaller than 10\"); }}",
"e": 25912,
"s": 25780,
"text": null
},
{
"code": null,
"e": 25920,
"s": 25912,
"text": "Output:"
},
{
"code": null,
"e": 25936,
"s": 25920,
"text": "Smaller than 10"
},
{
"code": null,
"e": 26136,
"s": 25936,
"text": "Else if statement is used to check another condition after the if condition before the else condition. A program can have as many else if statements but can only have one if and one else statements. "
},
{
"code": null,
"e": 26233,
"s": 26136,
"text": "Example: The below program checks whether the value is smaller or equals to or greater than 10. "
},
{
"code": null,
"e": 26238,
"s": 26233,
"text": "Rust"
},
{
"code": "fn main() { let n = 10; if n>10 { println!(\"Greater than 10\"); }else if n==10 { println!(\"Equal to 10\"); }else { println!(\"Smaller than 10\"); }}",
"e": 26423,
"s": 26238,
"text": null
},
{
"code": null,
"e": 26431,
"s": 26423,
"text": "Output:"
},
{
"code": null,
"e": 26443,
"s": 26431,
"text": "Equal to 10"
},
{
"code": null,
"e": 26461,
"s": 26443,
"text": "rust-control-flow"
},
{
"code": null,
"e": 26466,
"s": 26461,
"text": "Rust"
},
{
"code": null,
"e": 26564,
"s": 26466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26585,
"s": 26564,
"text": "Rust - For and Range"
},
{
"code": null,
"e": 26600,
"s": 26585,
"text": "Rust - Casting"
},
{
"code": null,
"e": 26626,
"s": 26600,
"text": "Rust - Creating a Library"
},
{
"code": null,
"e": 26650,
"s": 26626,
"text": "Rust - Generic Function"
},
{
"code": null,
"e": 26675,
"s": 26650,
"text": "Rust - Box Smart Pointer"
},
{
"code": null,
"e": 26691,
"s": 26675,
"text": "Rust - Comments"
},
{
"code": null,
"e": 26720,
"s": 26691,
"text": "Rust - Concept of Structures"
},
{
"code": null,
"e": 26753,
"s": 26720,
"text": "Rust - Concept of Smart Pointers"
},
{
"code": null,
"e": 26771,
"s": 26753,
"text": "Rust - While Loop"
}
] |
JPA - Criteria API
|
The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, and portable and easy to modify by changing the syntax. Similar to JPQL it follows abstract schema (easy to edit schema) and embedded objects. The metadata API is mingled with criteria API to model persistent entity for criteria queries.
The major advantage of the criteria API is that errors can be detected earlier during compile time. String based JPQL queries and JPA criteria based queries are same in performance and efficiency.
The criteria API is included into all versions of JPA therefore each step of criteria API is notified in the specifications of JPA.
In JPA 2.0, the criteria query API, standardization of queries are developed.
In JPA 2.1, Criteria update and delete (bulk update and delete) are included.
The Criteria API and the JPQL are closely related and are allowed to design using similar operators in their queries. It follows javax.persistence.criteria package to design a query. The query structure means the syntax criteria query.
The following simple criteria query returns all instances of the entity class in the data source.
EntityManager em = ...;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Entity class> cq = cb.createQuery(Entity.class);
Root<Entity> from = cq.from(Entity.class);
cq.select(Entity);
TypedQuery<Entity> q = em.createQuery(cq);
List<Entity> allitems = q.getResultList();
The query demonstrates the basic steps to create a criteria.
EntityManager instance is used to create a CriteriaBuilder object.
CriteriaQuery instance is used to create a query object. This query object’s attributes will be modified with the details of the query.
CriteriaQuery.from method is called to set the query root.
CriteriaQuery.select is called to set the result list type.
TypedQuery<T> instance is used to prepare a query for execution and specifying the type of the query result.
getResultList method on the TypedQuery<T> object to execute a query. This query returns a collection of entities, the result is stored in a List.
Let us consider the example of employee database. Let us assume the jpadb.employee table contains following records:
Eid Ename Salary Deg
401 Gopal 40000 Technical Manager
402 Manisha 40000 Proof reader
403 Masthanvali 35000 Technical Writer
404 Satish 30000 Technical writer
405 Krishna 30000 Technical Writer
406 Kiran 35000 Proof reader
Create a JPA Project in the eclipse IDE named JPA_Eclipselink_Criteria. All the modules of this project are shown as follows:
Create a package named com.tutorialspoint.eclipselink.entity under ‘src’ package.
Create a class named Employee.java under given package. The class Employee entity is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private int eid;
private String ename;
private double salary;
private String deg;
public Employee(int eid, String ename, double salary, String deg) {
super( );
this.eid = eid;
this.ename = ename;
this.salary = salary;
this.deg = deg;
}
public Employee( ) {
super();
}
public int getEid( ) {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname( ) {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getSalary( ) {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDeg( ) {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
@Override
public String toString() {
return "Employee [eid = " + eid + ", ename = " + ename + ", salary = " + salary + ", deg = " + deg + "]";
}
}
Persistence.xml file is required to configure the database and the registration of entity classes.
Persistence.xml will be created by the eclipse IDE while cresting a JPA Project. The configuration details are user specification. The persistence.xml file is shown as follows:
<?xml version = "1.0" encoding = "UTF-8"?>
<persistence version="2.0" xmlns = "http://java.sun.com/xml/ns/persistence"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name = "Eclipselink_JPA" transaction-type = "RESOURCE_LOCAL">
<class>com.tutorialspoint.eclipselink.entity.Employee</class>
<properties>
<property name = "javax.persistence.jdbc.url" value = "jdbc:mysql://localhost:3306/jpadb"/>
<property name = "javax.persistence.jdbc.user" value = "root"/>
<property name = "javax.persistence.jdbc.password" value = "root"/>
<property name = "javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver"/>
<property name = "eclipselink.logging.level" value = "FINE"/>
<property name = "eclipselink.ddl-generation"
value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
This module contains the service classes, which implements the Criteria query part using the MetaData API initialization. Create a package named ‘com.tutorialspoint.eclipselink.service’. The class named CriteriaAPI.java is created under given package. The DAO class is shown as follows:
package com.tutorialspoint.eclipselink.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.tutorialspoint.eclipselink.entity.Employee;
public class CriteriaApi {
public static void main(String[] args) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager( );
CriteriaBuilder criteriaBuilder = entitymanager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<Employee> from = criteriaQuery.from(Employee.class);
//select all records
System.out.println(“Select all records”);
CriteriaQuery<Object> select = c riteriaQuery.select(from);
TypedQuery<Object> typedQuery = entitymanager.createQuery(select);
List<Object> resultlist = typedQuery.getResultList();
for(Object o:resultlist) {
Employee e = (Employee)o;
System.out.println("EID : " + e.getEid() + " Ename : " + e.getEname());
}
//Ordering the records
System.out.println(“Select all records by follow ordering”);
CriteriaQuery<Object> select1 = criteriaQuery.select(from);
select1.orderBy(criteriaBuilder.asc(from.get("ename")));
TypedQuery<Object> typedQuery1 = entitymanager.createQuery(select);
List<Object> resultlist1 = typedQuery1.getResultList();
for(Object o:resultlist1){
Employee e=(Employee)o;
System.out.println("EID : " + e.getEid() + " Ename : " + e.getEname());
}
entitymanager.close( );
emfactory.close( );
}
}
After compilation and execution of the above program you will get output in the console panel of Eclipse IDE as follows:
Select All records
EID : 401 Ename : Gopal
EID : 402 Ename : Manisha
EID : 403 Ename : Masthanvali
EID : 404 Ename : Satish
EID : 405 Ename : Krishna
EID : 406 Ename : Kiran
Select All records by follow Ordering
EID : 401 Ename : Gopal
EID : 406 Ename : Kiran
EID : 405 Ename : Krishna
EID : 402 Ename : Manisha
EID : 403 Ename : Masthanvali
EID : 404 Ename : Satish
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2133,
"s": 1739,
"text": "The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, and portable and easy to modify by changing the syntax. Similar to JPQL it follows abstract schema (easy to edit schema) and embedded objects. The metadata API is mingled with criteria API to model persistent entity for criteria queries. "
},
{
"code": null,
"e": 2330,
"s": 2133,
"text": "The major advantage of the criteria API is that errors can be detected earlier during compile time. String based JPQL queries and JPA criteria based queries are same in performance and efficiency."
},
{
"code": null,
"e": 2462,
"s": 2330,
"text": "The criteria API is included into all versions of JPA therefore each step of criteria API is notified in the specifications of JPA."
},
{
"code": null,
"e": 2540,
"s": 2462,
"text": "In JPA 2.0, the criteria query API, standardization of queries are developed."
},
{
"code": null,
"e": 2618,
"s": 2540,
"text": "In JPA 2.1, Criteria update and delete (bulk update and delete) are included."
},
{
"code": null,
"e": 2855,
"s": 2618,
"text": "The Criteria API and the JPQL are closely related and are allowed to design using similar operators in their queries. It follows javax.persistence.criteria package to design a query. The query structure means the syntax criteria query. "
},
{
"code": null,
"e": 2953,
"s": 2855,
"text": "The following simple criteria query returns all instances of the entity class in the data source."
},
{
"code": null,
"e": 3236,
"s": 2953,
"text": "EntityManager em = ...;\nCriteriaBuilder cb = em.getCriteriaBuilder();\n\nCriteriaQuery<Entity class> cq = cb.createQuery(Entity.class);\nRoot<Entity> from = cq.from(Entity.class);\n\ncq.select(Entity);\nTypedQuery<Entity> q = em.createQuery(cq);\nList<Entity> allitems = q.getResultList();"
},
{
"code": null,
"e": 3297,
"s": 3236,
"text": "The query demonstrates the basic steps to create a criteria."
},
{
"code": null,
"e": 3364,
"s": 3297,
"text": "EntityManager instance is used to create a CriteriaBuilder object."
},
{
"code": null,
"e": 3500,
"s": 3364,
"text": "CriteriaQuery instance is used to create a query object. This query object’s attributes will be modified with the details of the query."
},
{
"code": null,
"e": 3559,
"s": 3500,
"text": "CriteriaQuery.from method is called to set the query root."
},
{
"code": null,
"e": 3619,
"s": 3559,
"text": "CriteriaQuery.select is called to set the result list type."
},
{
"code": null,
"e": 3728,
"s": 3619,
"text": "TypedQuery<T> instance is used to prepare a query for execution and specifying the type of the query result."
},
{
"code": null,
"e": 3874,
"s": 3728,
"text": "getResultList method on the TypedQuery<T> object to execute a query. This query returns a collection of entities, the result is stored in a List."
},
{
"code": null,
"e": 3991,
"s": 3874,
"text": "Let us consider the example of employee database. Let us assume the jpadb.employee table contains following records:"
},
{
"code": null,
"e": 4273,
"s": 3991,
"text": "Eid\tEname Salary\tDeg\n401\tGopal\t 40000\tTechnical Manager\n402\tManisha\t 40000\tProof reader\n403\tMasthanvali 35000\tTechnical Writer\n404 Satish\t 30000\tTechnical writer\n405\tKrishna\t 30000\tTechnical Writer\n406\tKiran\t 35000\tProof reader\n"
},
{
"code": null,
"e": 4399,
"s": 4273,
"text": "Create a JPA Project in the eclipse IDE named JPA_Eclipselink_Criteria. All the modules of this project are shown as follows:"
},
{
"code": null,
"e": 4482,
"s": 4399,
"text": "Create a package named com.tutorialspoint.eclipselink.entity under ‘src’ package. "
},
{
"code": null,
"e": 4585,
"s": 4482,
"text": "Create a class named Employee.java under given package. The class Employee entity is shown as follows:"
},
{
"code": null,
"e": 5873,
"s": 4585,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class Employee {\n @Id\n @GeneratedValue(strategy= GenerationType.AUTO) \t\n \n private int eid;\n private String ename;\n private double salary;\n private String deg;\n \n public Employee(int eid, String ename, double salary, String deg) {\n super( );\n this.eid = eid;\n this.ename = ename;\n this.salary = salary;\n this.deg = deg;\n }\n\n public Employee( ) {\n super();\n }\n\n public int getEid( ) {\n return eid;\n }\n \n public void setEid(int eid) {\n this.eid = eid;\n }\n\n public String getEname( ) {\n return ename;\n }\n \n public void setEname(String ename) {\n this.ename = ename;\n }\n\n public double getSalary( ) {\n return salary;\n }\n \n public void setSalary(double salary) {\n this.salary = salary;\n }\n\n public String getDeg( ) {\n return deg;\n }\n \n public void setDeg(String deg) {\n this.deg = deg;\n }\n \n @Override\n public String toString() {\n return \"Employee [eid = \" + eid + \", ename = \" + ename + \", salary = \" + salary + \", deg = \" + deg + \"]\";\n }\n}"
},
{
"code": null,
"e": 5972,
"s": 5873,
"text": "Persistence.xml file is required to configure the database and the registration of entity classes."
},
{
"code": null,
"e": 6150,
"s": 5972,
"text": "Persistence.xml will be created by the eclipse IDE while cresting a JPA Project. The configuration details are user specification. The persistence.xml file is shown as follows: "
},
{
"code": null,
"e": 7216,
"s": 6150,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<persistence version=\"2.0\" xmlns = \"http://java.sun.com/xml/ns/persistence\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n \n <persistence-unit name = \"Eclipselink_JPA\" transaction-type = \"RESOURCE_LOCAL\">\n <class>com.tutorialspoint.eclipselink.entity.Employee</class>\n \n <properties>\n <property name = \"javax.persistence.jdbc.url\" value = \"jdbc:mysql://localhost:3306/jpadb\"/>\n <property name = \"javax.persistence.jdbc.user\" value = \"root\"/>\n <property name = \"javax.persistence.jdbc.password\" value = \"root\"/>\n <property name = \"javax.persistence.jdbc.driver\" \n value=\"com.mysql.jdbc.Driver\"/>\n <property name = \"eclipselink.logging.level\" value = \"FINE\"/>\n <property name = \"eclipselink.ddl-generation\" \n value=\"create-tables\"/>\n </properties>\n \n </persistence-unit>\n</persistence>"
},
{
"code": null,
"e": 7505,
"s": 7216,
"text": "This module contains the service classes, which implements the Criteria query part using the MetaData API initialization. Create a package named ‘com.tutorialspoint.eclipselink.service’. The class named CriteriaAPI.java is created under given package. The DAO class is shown as follows: \n"
},
{
"code": null,
"e": 9335,
"s": 7505,
"text": "package com.tutorialspoint.eclipselink.service;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.TypedQuery;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Root;\n\nimport com.tutorialspoint.eclipselink.entity.Employee;\n\npublic class CriteriaApi {\n public static void main(String[] args) {\n \n EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( \"Eclipselink_JPA\" );\n EntityManager entitymanager = emfactory.createEntityManager( );\n CriteriaBuilder criteriaBuilder = entitymanager.getCriteriaBuilder();\n CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();\n Root<Employee> from = criteriaQuery.from(Employee.class);\n\n //select all records\n System.out.println(“Select all records”);\n CriteriaQuery<Object> select = c riteriaQuery.select(from);\n TypedQuery<Object> typedQuery = entitymanager.createQuery(select);\n List<Object> resultlist = typedQuery.getResultList();\n\n for(Object o:resultlist) {\n Employee e = (Employee)o;\n System.out.println(\"EID : \" + e.getEid() + \" Ename : \" + e.getEname());\n }\n\n //Ordering the records \n System.out.println(“Select all records by follow ordering”);\n CriteriaQuery<Object> select1 = criteriaQuery.select(from);\n select1.orderBy(criteriaBuilder.asc(from.get(\"ename\")));\n TypedQuery<Object> typedQuery1 = entitymanager.createQuery(select);\n List<Object> resultlist1 = typedQuery1.getResultList();\n\n for(Object o:resultlist1){\n Employee e=(Employee)o;\n System.out.println(\"EID : \" + e.getEid() + \" Ename : \" + e.getEname());\n }\n\n entitymanager.close( );\n emfactory.close( );\n }\n}"
},
{
"code": null,
"e": 9456,
"s": 9335,
"text": "After compilation and execution of the above program you will get output in the console panel of Eclipse IDE as follows:"
},
{
"code": null,
"e": 9824,
"s": 9456,
"text": "Select All records\nEID : 401 Ename : Gopal\nEID : 402 Ename : Manisha\nEID : 403 Ename : Masthanvali\nEID : 404 Ename : Satish\nEID : 405 Ename : Krishna\nEID : 406 Ename : Kiran\nSelect All records by follow Ordering\nEID : 401 Ename : Gopal\nEID : 406 Ename : Kiran\nEID : 405 Ename : Krishna\nEID : 402 Ename : Manisha\nEID : 403 Ename : Masthanvali\nEID : 404 Ename : Satish\n"
},
{
"code": null,
"e": 9831,
"s": 9824,
"text": " Print"
},
{
"code": null,
"e": 9842,
"s": 9831,
"text": " Add Notes"
}
] |
jQuery | Alertify Plugin - GeeksforGeeks
|
09 Sep, 2021
jQuery framework provides alertify.js plugin that provides pre-designed customizable notification system along with interactive browser dialogs. This extensible and themeable plugin is very useful for developers providing an optimized version of alert messages with stacking up to feature. This small library system effectively display confirmation pop ups, success or error alerts, and prompt messages with queued dialogs which can be extensively used in debugging process.
Please download the library and include the required files depending on the project requirements.
Example 1: It is easy to understand, customize and implement in your code. It does not depend on any third party libraries but easily integrate with them. The following code demonstrates the beautiful dialog boxes with its stacking up feature.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>jQuery Alertify Plugin</title> <link rel="stylesheet" href="alertify.core.css" /> <link rel="stylesheet" href="alertify.default.css" id="linkID" /> <script src="http://code.jquery.com/jquery-1.9.1.js"> </script> <script src="alertify.min.js"></script> <style> .alertify-log-custom { background: green; } .height { height: 10px; } </style></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> jQuery Alertify Plugin</b> <div class="height"></div><br> <b>Alertify Dialogs</b> <div class="height"></div> <a href="#" id="alertID">Click Alert Dialog</a><br> <a href="#" id="promptID">Click Prompt Dialog</a><br> <a href="#" id="confirmID">Click Confirm Dialog</a><br> <a href="#" id="focusID">Click Button Focus</a><br> <a href="#" id="labelsID">Click Custom Labels</a><br> <a href="#" id="orderID">Click Button Order</a> <script> function reset() { $("#linkID").attr("href", "alertify.default.css"); alertify.set({ labels: { ok: "OK", cancel: "Cancel" }, delay: 4000, buttonFocus: "ok", buttonReverse: false }); } // Alertify Standard Dialog boxes $("#alertID").on('click', function () { reset(); alertify.alert("Welcome GFG !"); alertify.alert("Alertify alert dialog"); return false; }); $("#confirmID").on('click', function () { reset(); alertify.confirm( "Please confirm the dialog box ", function (event) { if (event) { alertify.success( "You have clicked OK to confirm our" + " terms and conditions."); } else { alertify.error( "You have clicked Cancel not to confirm."); } }); return false; }); $("#promptID").on('click', function () { reset(); alertify.prompt( "This is a prompt dialog box", function (event, string) { if (event) { alertify.success( "You have clicked OK and typed: " + string); } else { alertify.error( "You have clicked Cancel"); } }, "Please enter, this is default value"); return false; }); $("#success").on('click', function () { reset(); alertify.success("Success message"); return false; }); $("#error").on('click', function () { reset(); alertify.error("Error message"); return false; }); $("#labelsID").on('click', function () { reset(); alertify.set({ labels: { ok: "Accept", cancel: "Deny" } }); alertify.confirm( "Confirm dialog with custom button labels", function (event) { if (event) { alertify.success("You have clicked OK"); } else { alertify.error("You have clicked Cancel"); } }); return false; }); $("#focusID").on('click', function () { reset(); alertify.set({ buttonFocus: "cancel" }); alertify.confirm( "Confirm dialog with cancel button focused", function (event) { if (event) { alertify.success("You have clicked OK"); } else { alertify.error("You have clicked Cancel"); } }); return false; }); $("#orderID").on('click', function () { reset(); alertify.set({ buttonReverse: true }); alertify.confirm( "Confirm dialog with reversed button order", function (event) { if (event) { alertify.success("You have clicked OK"); } else { alertify.error("You have clicked Cancel"); } }); return false; }); </script></body> </html>
Output:
Example 2: The following code demonstrates the use of log messages from alertify.js plugin.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>jQuery Alertify Plugin</title> <link rel="stylesheet" href="alertify.core.css" /> <link rel="stylesheet" href="alertify.default.css" id="linkID" /> <script src= "http://code.jquery.com/jquery-1.9.1.js"> </script> <script src="alertify.min.js"></script> <style> .alertify-log-custom { background: green; } .height { height: 10px; } </style></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> jQuery Alertify Plugin</b> <div class="height"> </div><br> <b>Alertify Logs</b> <div class="height"> </div> <a href="#" id="notificationID">Standard Log</a><br> <a href="#" id="successID">Success Log</a><br> <a href="#" id="errorID">Error Log</a><br> <a href="#" id="customID">Custom Log</a><br> <a href="#" id="delayID">Hide in 9 seconds</a><br> <a href="#" id="foreverID">Persistent Log</a> <script> function reset() { $("#linkID").attr("href", "alertify.default.css"); alertify.set({ labels: { ok: "OK", cancel: "Cancel" }, delay: 4000, buttonFocus: "ok", buttonReverse: false }); } $("#notificationID").on('click', function () { reset(); alertify.log("Standard log message"); return false; }); $("#successID").on('click', function () { reset(); alertify.success("Success log message"); return false; }); $("#errorID").on('click', function () { reset(); alertify.error("Error log message"); return false; }); // Custom Properties $("#delayID").on('click', function () { reset(); alertify.set({ delay: 9000 }); alertify.log("Hiding in 9 seconds"); return false; }); $("#foreverID").on('click', function () { reset(); alertify.log("It will stay until clicked", "", 0); return false; }); // Custom Log message $("#customID").on('click', function () { reset(); alertify.custom = alertify.extend("custom"); alertify.custom("Its a custom log message"); return false; }); </script></body> </html>
Output:
Example 3: The following code demonstrates how to implement themeable dialogs and make ajax calls using notification messages as shown in the code.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>jQuery Alertify Plugin</title> <link rel="stylesheet" href="alertify.core.css" /> <link rel="stylesheet" href="alertify.default.css" id="linkID" /> <script src= "http://code.jquery.com/jquery-1.9.1.js"> </script> <script src="alertify.min.js"></script> <style> .alertify-log-custom { background: green; } .height { height: 10px; } </style></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> jQuery Alertify Plugin</b> <div class="height"> </div><br> <b>Ajax Multiple Dialogs</b> <div class="height"> </div> <a href="#" id="ajax"> Ajax with Multiple Dialog</a> <div class="height"> </div><br /> <b>Custom Bootstrap Themes</b> <div class="height"> </div> <a href="#" id="bootstrap">Bootstrap Theme</a> <script> function reset() { $("#linkID").attr("href", "alertify.default.css"); alertify.set({ labels: { ok: "OK", cancel: "Cancel" }, delay: 4000, buttonFocus: "ok", buttonReverse: false }); } // Ajax call $("#ajax").on("click", function () { reset(); alertify.confirm("Confirm?", function (event) { if (event) { alertify.alert("Successful Ajax call after OK"); } else { alertify.alert("Successful Ajax call after Cancel"); } }); }); // Custom Themes $("#bootstrap").on('click', function () { reset(); $("#linkID").attr("href", "alertify.bootstrap.css"); alertify.prompt( "It prompts dialog with bootstrap theme", function (event) { if (event) { alertify.success("You have clicked OK"); } else { alertify.error("You have clicked Cancel"); } }, "This is Default Value"); return false; }); </script> </body> </html>
Output:
surindertarika1234
jQuery-Plugin
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
How to redirect to a particular section of a page using HTML or jQuery?
How to prevent Body from scrolling when a modal is opened using jQuery ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24792,
"s": 24764,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 25268,
"s": 24792,
"text": "jQuery framework provides alertify.js plugin that provides pre-designed customizable notification system along with interactive browser dialogs. This extensible and themeable plugin is very useful for developers providing an optimized version of alert messages with stacking up to feature. This small library system effectively display confirmation pop ups, success or error alerts, and prompt messages with queued dialogs which can be extensively used in debugging process. "
},
{
"code": null,
"e": 25367,
"s": 25268,
"text": "Please download the library and include the required files depending on the project requirements. "
},
{
"code": null,
"e": 25612,
"s": 25367,
"text": "Example 1: It is easy to understand, customize and implement in your code. It does not depend on any third party libraries but easily integrate with them. The following code demonstrates the beautiful dialog boxes with its stacking up feature. "
},
{
"code": null,
"e": 25617,
"s": 25612,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width\"> <title>jQuery Alertify Plugin</title> <link rel=\"stylesheet\" href=\"alertify.core.css\" /> <link rel=\"stylesheet\" href=\"alertify.default.css\" id=\"linkID\" /> <script src=\"http://code.jquery.com/jquery-1.9.1.js\"> </script> <script src=\"alertify.min.js\"></script> <style> .alertify-log-custom { background: green; } .height { height: 10px; } </style></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> jQuery Alertify Plugin</b> <div class=\"height\"></div><br> <b>Alertify Dialogs</b> <div class=\"height\"></div> <a href=\"#\" id=\"alertID\">Click Alert Dialog</a><br> <a href=\"#\" id=\"promptID\">Click Prompt Dialog</a><br> <a href=\"#\" id=\"confirmID\">Click Confirm Dialog</a><br> <a href=\"#\" id=\"focusID\">Click Button Focus</a><br> <a href=\"#\" id=\"labelsID\">Click Custom Labels</a><br> <a href=\"#\" id=\"orderID\">Click Button Order</a> <script> function reset() { $(\"#linkID\").attr(\"href\", \"alertify.default.css\"); alertify.set({ labels: { ok: \"OK\", cancel: \"Cancel\" }, delay: 4000, buttonFocus: \"ok\", buttonReverse: false }); } // Alertify Standard Dialog boxes $(\"#alertID\").on('click', function () { reset(); alertify.alert(\"Welcome GFG !\"); alertify.alert(\"Alertify alert dialog\"); return false; }); $(\"#confirmID\").on('click', function () { reset(); alertify.confirm( \"Please confirm the dialog box \", function (event) { if (event) { alertify.success( \"You have clicked OK to confirm our\" + \" terms and conditions.\"); } else { alertify.error( \"You have clicked Cancel not to confirm.\"); } }); return false; }); $(\"#promptID\").on('click', function () { reset(); alertify.prompt( \"This is a prompt dialog box\", function (event, string) { if (event) { alertify.success( \"You have clicked OK and typed: \" + string); } else { alertify.error( \"You have clicked Cancel\"); } }, \"Please enter, this is default value\"); return false; }); $(\"#success\").on('click', function () { reset(); alertify.success(\"Success message\"); return false; }); $(\"#error\").on('click', function () { reset(); alertify.error(\"Error message\"); return false; }); $(\"#labelsID\").on('click', function () { reset(); alertify.set({ labels: { ok: \"Accept\", cancel: \"Deny\" } }); alertify.confirm( \"Confirm dialog with custom button labels\", function (event) { if (event) { alertify.success(\"You have clicked OK\"); } else { alertify.error(\"You have clicked Cancel\"); } }); return false; }); $(\"#focusID\").on('click', function () { reset(); alertify.set({ buttonFocus: \"cancel\" }); alertify.confirm( \"Confirm dialog with cancel button focused\", function (event) { if (event) { alertify.success(\"You have clicked OK\"); } else { alertify.error(\"You have clicked Cancel\"); } }); return false; }); $(\"#orderID\").on('click', function () { reset(); alertify.set({ buttonReverse: true }); alertify.confirm( \"Confirm dialog with reversed button order\", function (event) { if (event) { alertify.success(\"You have clicked OK\"); } else { alertify.error(\"You have clicked Cancel\"); } }); return false; }); </script></body> </html>",
"e": 30279,
"s": 25617,
"text": null
},
{
"code": null,
"e": 30288,
"s": 30279,
"text": "Output: "
},
{
"code": null,
"e": 30381,
"s": 30288,
"text": "Example 2: The following code demonstrates the use of log messages from alertify.js plugin. "
},
{
"code": null,
"e": 30386,
"s": 30381,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width\"> <title>jQuery Alertify Plugin</title> <link rel=\"stylesheet\" href=\"alertify.core.css\" /> <link rel=\"stylesheet\" href=\"alertify.default.css\" id=\"linkID\" /> <script src= \"http://code.jquery.com/jquery-1.9.1.js\"> </script> <script src=\"alertify.min.js\"></script> <style> .alertify-log-custom { background: green; } .height { height: 10px; } </style></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> jQuery Alertify Plugin</b> <div class=\"height\"> </div><br> <b>Alertify Logs</b> <div class=\"height\"> </div> <a href=\"#\" id=\"notificationID\">Standard Log</a><br> <a href=\"#\" id=\"successID\">Success Log</a><br> <a href=\"#\" id=\"errorID\">Error Log</a><br> <a href=\"#\" id=\"customID\">Custom Log</a><br> <a href=\"#\" id=\"delayID\">Hide in 9 seconds</a><br> <a href=\"#\" id=\"foreverID\">Persistent Log</a> <script> function reset() { $(\"#linkID\").attr(\"href\", \"alertify.default.css\"); alertify.set({ labels: { ok: \"OK\", cancel: \"Cancel\" }, delay: 4000, buttonFocus: \"ok\", buttonReverse: false }); } $(\"#notificationID\").on('click', function () { reset(); alertify.log(\"Standard log message\"); return false; }); $(\"#successID\").on('click', function () { reset(); alertify.success(\"Success log message\"); return false; }); $(\"#errorID\").on('click', function () { reset(); alertify.error(\"Error log message\"); return false; }); // Custom Properties $(\"#delayID\").on('click', function () { reset(); alertify.set({ delay: 9000 }); alertify.log(\"Hiding in 9 seconds\"); return false; }); $(\"#foreverID\").on('click', function () { reset(); alertify.log(\"It will stay until clicked\", \"\", 0); return false; }); // Custom Log message $(\"#customID\").on('click', function () { reset(); alertify.custom = alertify.extend(\"custom\"); alertify.custom(\"Its a custom log message\"); return false; }); </script></body> </html>",
"e": 32926,
"s": 30386,
"text": null
},
{
"code": null,
"e": 32935,
"s": 32926,
"text": "Output: "
},
{
"code": null,
"e": 33086,
"s": 32935,
"text": "Example 3: The following code demonstrates how to implement themeable dialogs and make ajax calls using notification messages as shown in the code. "
},
{
"code": null,
"e": 33091,
"s": 33086,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width\"> <title>jQuery Alertify Plugin</title> <link rel=\"stylesheet\" href=\"alertify.core.css\" /> <link rel=\"stylesheet\" href=\"alertify.default.css\" id=\"linkID\" /> <script src= \"http://code.jquery.com/jquery-1.9.1.js\"> </script> <script src=\"alertify.min.js\"></script> <style> .alertify-log-custom { background: green; } .height { height: 10px; } </style></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> jQuery Alertify Plugin</b> <div class=\"height\"> </div><br> <b>Ajax Multiple Dialogs</b> <div class=\"height\"> </div> <a href=\"#\" id=\"ajax\"> Ajax with Multiple Dialog</a> <div class=\"height\"> </div><br /> <b>Custom Bootstrap Themes</b> <div class=\"height\"> </div> <a href=\"#\" id=\"bootstrap\">Bootstrap Theme</a> <script> function reset() { $(\"#linkID\").attr(\"href\", \"alertify.default.css\"); alertify.set({ labels: { ok: \"OK\", cancel: \"Cancel\" }, delay: 4000, buttonFocus: \"ok\", buttonReverse: false }); } // Ajax call $(\"#ajax\").on(\"click\", function () { reset(); alertify.confirm(\"Confirm?\", function (event) { if (event) { alertify.alert(\"Successful Ajax call after OK\"); } else { alertify.alert(\"Successful Ajax call after Cancel\"); } }); }); // Custom Themes $(\"#bootstrap\").on('click', function () { reset(); $(\"#linkID\").attr(\"href\", \"alertify.bootstrap.css\"); alertify.prompt( \"It prompts dialog with bootstrap theme\", function (event) { if (event) { alertify.success(\"You have clicked OK\"); } else { alertify.error(\"You have clicked Cancel\"); } }, \"This is Default Value\"); return false; }); </script> </body> </html>",
"e": 35398,
"s": 33091,
"text": null
},
{
"code": null,
"e": 35407,
"s": 35398,
"text": "Output: "
},
{
"code": null,
"e": 35428,
"s": 35409,
"text": "surindertarika1234"
},
{
"code": null,
"e": 35442,
"s": 35428,
"text": "jQuery-Plugin"
},
{
"code": null,
"e": 35449,
"s": 35442,
"text": "JQuery"
},
{
"code": null,
"e": 35466,
"s": 35449,
"text": "Web Technologies"
},
{
"code": null,
"e": 35564,
"s": 35466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35573,
"s": 35564,
"text": "Comments"
},
{
"code": null,
"e": 35586,
"s": 35573,
"text": "Old Comments"
},
{
"code": null,
"e": 35640,
"s": 35586,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 35708,
"s": 35640,
"text": "How to get the ID of the clicked button using JavaScript / jQuery ?"
},
{
"code": null,
"e": 35742,
"s": 35708,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 35814,
"s": 35742,
"text": "How to redirect to a particular section of a page using HTML or jQuery?"
},
{
"code": null,
"e": 35887,
"s": 35814,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 35943,
"s": 35887,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 35976,
"s": 35943,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 36038,
"s": 35976,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36081,
"s": 36038,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Advantages and Disadvantages of using Enum as Singleton in Java - GeeksforGeeks
|
22 Feb, 2021
Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards.
Advantages of using Enum as Singleton:
1. Enum Singletons are easy to write: If you have been writing Singletons before Java 5, this is by far the greatest benefit that you realize that you can have more than one instance even with double-checked locking. While this problem is solved by improving the Java memory model and guaranteeing volatile variables from Java 5 onwards, it is still difficult for many beginners to write.
Compared to double-checked locking with synchronization, Enum singletons are very easy. If you don’t think that the following code for traditional singleton with double-checked locking and Enum Singletons are compared:
Singleton using Enum in Java: By default creation of the Enum instance is thread-safe, but any other Enum method is the programmer’s responsibility.
public enum EasySingleton{
INSTANCE;
}
You can access it by EasySingleton.INSTANCE, far simpler than calling getInstance() function on Singleton.
2. Enum Singletons handled Serialization by themselves
Another problem with conventional Singletons is that they are no longer Singleton once you implement a serializable interface because the method readObject() always returns a new instance just like the Java constructor. By using the readResolve() method and discarding newly created instances, you can avoid that by substituting Singleton, as shown in the example below:
private Object readResolve(){
return INSTANCE;
}
If your Singleton Class maintains state, this can become even more complex, as you need to make them transient, but JVM guarantees serialization with Enum Singleton.
3. Creation of Enum instance is thread-safe
By default, the Enum instance is thread-safe, and you don’t need to worry about double-checked locking.
In summary, the Singleton pattern is the best way to create Singleton in Java 5 world, given the Serialization and thread-safety guaranteed and with some line of code enum.
Java
// Java program to demonstrate the example // of using Enum as Singleton enum SingletonEnum { INSTANCE; int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; }} class Main { public static void main(String[] args) { SingletonEnum singleton = SingletonEnum.INSTANCE; System.out.println(singleton.getValue()); singleton.setValue(2); System.out.println(singleton.getValue()); }}
0
2
Disadvantages of using Enum as a singleton:
1. Coding Constraints
In regular classes, there are things that can be achieved but prohibited in enum classes. Accessing a static field in the constructor, for example. Since he’s working at a special level, the programmer needs to be more careful.
2. Serializability
For singletons, it is very common to be stateful. In general, those singletons should not be serializable. There is no real example where transporting a stateful singleton from one VM to another VM makes sense; a singleton means “unique within a VM” not “unique in the universe”
If serialization really makes sense for a stateful singleton, the singleton should specify explicitly and accurately what it means in another VM to deserialize a singleton where there may already be a singleton of the same type.
We save some lines of code on enum, but the price is too high, we have to carry all the baggage and enum limitations, we inadvertently inherit enum “features” that have unintended consequences. A disadvantage turns out to be the only alleged benefit – automatic serializability.
Java-Enumeration
Picked
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
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 23872,
"s": 23557,
"text": "Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards."
},
{
"code": null,
"e": 23911,
"s": 23872,
"text": "Advantages of using Enum as Singleton:"
},
{
"code": null,
"e": 24302,
"s": 23911,
"text": "1. Enum Singletons are easy to write: If you have been writing Singletons before Java 5, this is by far the greatest benefit that you realize that you can have more than one instance even with double-checked locking. While this problem is solved by improving the Java memory model and guaranteeing volatile variables from Java 5 onwards, it is still difficult for many beginners to write."
},
{
"code": null,
"e": 24521,
"s": 24302,
"text": "Compared to double-checked locking with synchronization, Enum singletons are very easy. If you don’t think that the following code for traditional singleton with double-checked locking and Enum Singletons are compared:"
},
{
"code": null,
"e": 24670,
"s": 24521,
"text": "Singleton using Enum in Java: By default creation of the Enum instance is thread-safe, but any other Enum method is the programmer’s responsibility."
},
{
"code": null,
"e": 24711,
"s": 24670,
"text": "public enum EasySingleton{\n INSTANCE;\n}"
},
{
"code": null,
"e": 24818,
"s": 24711,
"text": "You can access it by EasySingleton.INSTANCE, far simpler than calling getInstance() function on Singleton."
},
{
"code": null,
"e": 24873,
"s": 24818,
"text": "2. Enum Singletons handled Serialization by themselves"
},
{
"code": null,
"e": 25244,
"s": 24873,
"text": "Another problem with conventional Singletons is that they are no longer Singleton once you implement a serializable interface because the method readObject() always returns a new instance just like the Java constructor. By using the readResolve() method and discarding newly created instances, you can avoid that by substituting Singleton, as shown in the example below:"
},
{
"code": null,
"e": 25302,
"s": 25244,
"text": " private Object readResolve(){\n return INSTANCE;\n }"
},
{
"code": null,
"e": 25468,
"s": 25302,
"text": "If your Singleton Class maintains state, this can become even more complex, as you need to make them transient, but JVM guarantees serialization with Enum Singleton."
},
{
"code": null,
"e": 25512,
"s": 25468,
"text": "3. Creation of Enum instance is thread-safe"
},
{
"code": null,
"e": 25616,
"s": 25512,
"text": "By default, the Enum instance is thread-safe, and you don’t need to worry about double-checked locking."
},
{
"code": null,
"e": 25789,
"s": 25616,
"text": "In summary, the Singleton pattern is the best way to create Singleton in Java 5 world, given the Serialization and thread-safety guaranteed and with some line of code enum."
},
{
"code": null,
"e": 25794,
"s": 25789,
"text": "Java"
},
{
"code": "// Java program to demonstrate the example // of using Enum as Singleton enum SingletonEnum { INSTANCE; int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; }} class Main { public static void main(String[] args) { SingletonEnum singleton = SingletonEnum.INSTANCE; System.out.println(singleton.getValue()); singleton.setValue(2); System.out.println(singleton.getValue()); }}",
"e": 26295,
"s": 25794,
"text": null
},
{
"code": null,
"e": 26300,
"s": 26295,
"text": "0\n2\n"
},
{
"code": null,
"e": 26344,
"s": 26300,
"text": "Disadvantages of using Enum as a singleton:"
},
{
"code": null,
"e": 26366,
"s": 26344,
"text": "1. Coding Constraints"
},
{
"code": null,
"e": 26594,
"s": 26366,
"text": "In regular classes, there are things that can be achieved but prohibited in enum classes. Accessing a static field in the constructor, for example. Since he’s working at a special level, the programmer needs to be more careful."
},
{
"code": null,
"e": 26613,
"s": 26594,
"text": "2. Serializability"
},
{
"code": null,
"e": 26892,
"s": 26613,
"text": "For singletons, it is very common to be stateful. In general, those singletons should not be serializable. There is no real example where transporting a stateful singleton from one VM to another VM makes sense; a singleton means “unique within a VM” not “unique in the universe”"
},
{
"code": null,
"e": 27121,
"s": 26892,
"text": "If serialization really makes sense for a stateful singleton, the singleton should specify explicitly and accurately what it means in another VM to deserialize a singleton where there may already be a singleton of the same type."
},
{
"code": null,
"e": 27400,
"s": 27121,
"text": "We save some lines of code on enum, but the price is too high, we have to carry all the baggage and enum limitations, we inadvertently inherit enum “features” that have unintended consequences. A disadvantage turns out to be the only alleged benefit – automatic serializability."
},
{
"code": null,
"e": 27417,
"s": 27400,
"text": "Java-Enumeration"
},
{
"code": null,
"e": 27424,
"s": 27417,
"text": "Picked"
},
{
"code": null,
"e": 27429,
"s": 27424,
"text": "Java"
},
{
"code": null,
"e": 27434,
"s": 27429,
"text": "Java"
},
{
"code": null,
"e": 27532,
"s": 27434,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27541,
"s": 27532,
"text": "Comments"
},
{
"code": null,
"e": 27554,
"s": 27541,
"text": "Old Comments"
},
{
"code": null,
"e": 27584,
"s": 27554,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27599,
"s": 27584,
"text": "Stream In Java"
},
{
"code": null,
"e": 27620,
"s": 27599,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27666,
"s": 27620,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27685,
"s": 27666,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27702,
"s": 27685,
"text": "Generics in Java"
},
{
"code": null,
"e": 27745,
"s": 27702,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27761,
"s": 27745,
"text": "Strings in Java"
},
{
"code": null,
"e": 27817,
"s": 27761,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Estimating tasks with statistics and simulations using Python | by Sau Sheong | Towards Data Science
|
A few months ago, when the world was a very different place, I wrote about to-do list tasks strategies. I wanted to know, given a bunch of tasks in your todo list, what strategy should you use to pick the tasks to work on first? Depending on what I actually want to achieve, how I do it can be quite different.
The assumption I made there was that the complexity of a task is fixed, that is the duration it takes to complete it is pre-determined. That’s not normally true (statistics joke alert!). Complexity and therefore duration for most tasks, even before the uncertainty brought by the pandemic, is hard to predict accurately.
If we look at tasks beyond to-do lists, for example project tasks, this becomes even worse. Project task complexity doesn’t only impact duration but it also effort and costs and therefore being able to determine the complexity is pretty important.
However project tasks are notoriously difficult to estimate, and this can mean delays and escalating costs.
Berlin’s new Brandenburg airport was in planning for 15 years before starting construction in 2006 and was supposed to open in October 2011. However the project is still ongoing and is also facing a skyrocketing budget. The latest opening date is November 2020 but with the ongoing situation it seems likely to move again.
NASA’s Space Launch System (SLS), a launch rocket that will provide the foundation for manned lunar flights and a human mission to Mars started in 2010 and has cost $18.6 billion as of 2020. In early 2020 it was announced that that it will have costs overrun of $2 billion and be delayed for at least 2 years.
This nothing new though, NASA is infamous for being excessively optimistic and underestimating projects. The James Webb Space Telescope (JWST) was originally supposed to be launched in 2007 and cost $500 million, but as of today has slipped to 2021 with an estimated cost of $10 billion. Its predecessor, the Hubble Space Telescope was originally supposed to launch in 1983 but finally launched in 1990, with the costs slipping from an original $400 million to eventually $4.7 billion. The International Space Station takes the cake though — it started off with a $36.75 billion budget and it was completed six years late with final cost of $105 billion.
Construction projects are not the only type of projects that get delayed, software development projects are often the culprit as well. In a rather infamous case to develop the Queensland Health Payroll System, the project was tendered out and won by IBM in December 2007 for $98 million, and was supposed to be rolled out in July 2008. It was finally delivered in 2010, with bugs and costing $1.2 billion.
Of course there are a lot of reasons why projects fail. Perfectly well estimated projects can suffer catastrophic results for various reasons that are impossible to predict. You can be sure that however well estimated project tasks are, none could have added in the pandemic we’re facing now, nor the after-effects to it. Nonetheless, good estimations are critical to keeping a project well on track.
There are a number of ways to do estimations. In agile methodologies (mostly software development projects), we have planning pokers, affinity groups, t-shirt sizing, bucketing and so on. In terms of estimate units, there’re t-shirt sizes (S, M, L, XL etc), Fibonacci story points, dot votes and plenty of other pretty creative ways to represent the sizing of the effort.
For more traditional project management methodologies, estimation techniques include bottom-up, top-down, parametric, analogous, three-point and so on. There are plenty of other types of estimation techniques especially in software development, including COCOMO, SEER-SEM, Putnam, PERT and many others. What we definitely don’t lack are estimation techniques.
Whichever techniques and units we use, ultimately what projects are concerned about is delivering on-time (time), within cost (budget) and something that does what it’s supposed to do (quality), whether it is a space telescope or a health payroll system.
Task estimation is hard. It’s mostly judgement-based, using the experience of the estimator (usually the person doing the task). Also, most estimates tend to be overly optimistic. In fact, there is a term, coined by psychologists Daniel Kahneman and Amos Tversky in 1979, called planning fallacy that describes precisely this. What Kahneman and Tversky found was that we have a tendency to disregard what we learnt in the past about similar tasks, and also to be overly optimistic about potential issues and even our own ability to complete the task (optimism bias). The topic is pretty fascinating, if you’re keen to learn more, you can read more from their book, Thinking, Fast and Slow.
One was of getting around it is using three-point estimation. The trick is to produce 3 data points (hence the name) for every estimation:
a — the best case estimate
b — the most likely estimate
c — the worst case estimate
This forces the estimator to think through the best, worst and most likely cases each time. While this is no silver bullet to overcome the planning fallacy, it gives us some interesting data to work on.
The project evaluation and review technique (PERT) is a tool used in project management to analyse and represent tasks in a project. It was developed for the US Navy in 1957 to manage the US Navy’s Polaris nuclear submarine missle project, but found its way to many other uses including an early use to plan the 1968 Winter Olympics in Grenoble.
PERT is a tool for large scale, one-time planning and scheduling, focusing on events and timing .PERT itself gave rise to associated tools and concepts such as the work breakdown structure, critical path and critical path analysis (CPA).
PERT also gave rise to doing three point estimations, in fact it gave its name to a family of continous probability distributions called the PERT distribution.
The PERT distribution is a continuous probability distribution that is defined by the minimum (a), most likely (b) and maximum (c) values, with the mean (or expected value) of:
The PERT distribution is actually a transformed four parameter beta distribution. The beta distribution have two parameters α and β defined on the interval [0,1], making it useful for modelling probabilities and random variables. The four parameter version of the beta distribution makes the interval [a,c] instead where a is the minimum and c is the maximum value.
You can see where this is going. By using a PERT distribution to map the estimations, we can approximate the probabilities of the estimations themselves!
This is to say, while we ask the estimator to provide the optimistic, pessimistic and most likely values for the estimations, the actual expected value could be different from the most likely value, and we can figure out how likely the tasks is going to be completed within a duration or a budget.
However this is really only for a single task. In a project, of course, we have many, many tasks and each might have different distribution parameters for a, b and c. If you’re the project manager, how would you figure out the overall estimations and probabilities?
Well, we can also try to do the maths but we’re programmers, not mathematicians (I’m saying this in a good way) so we look towards our old friend, Monte Carlo.
Of course, by Monte Carlo, I meant Monte Carlo simulations and not the casino. Monte Carlo is a popular simulation technique that uses many repeated random samplings to produce numerical data. It’s like running lots and lots of experiments and figuring out insight from all that data.
Stanislaw Ulam came up with the idea in 1947 when he was recovering from an illness. He was working on a nuclear weapons project at the Los Alamos National Laboratory then, and shared the idea with John Von Neumann, who saw the significance of the idea and he wrote the first Monte Carlo simulation. Because of the secrecy of their work, the had to come up with a code name. One of their colleagues suggested, Monte Carlo, a famous casino in Monaco where Ulam’s uncle used to borrow money from relatives to gamble and the rest is history. (You might recognize Ulam and Von Neumann, both brilliant mathematicians, scientists and early pioneers of computer science from a previous article I wrote).
Monte Carlo simulations can be used to solve any probabilistic problem. Using the law of large numbers, we can approximate the results through empirical data we create. Of course, we cannot sanely do this without computers because the technique needs to run large numbers of repeated experiments. Monte Carlo literally brute forces the results!
So how exactly do we use Monte Carlo to figure out the overall estimations of a number of project tasks? It’s quite simple actually. For every task, we create a PERT distribution using the given a (pessimistic), b (most likely) and c (optimistic) values and draw a value from that distribution. What we get is a simulated estimation for each task. When we add these estimations together we get the simulated estimation of the whole project.
Rinse, repeat.
We will end up with lots and lots of project estimations, that will also be in a probability distribution of some sort. Actually, we’ll end up with another PERT distribution but let’s see how we can prove it later. Once we have the data we can figure out the various probabilities of our estimations.
Let’s give it a spin! For this I’ll be using Python3 on Jupyter Notebook, with the usual suspects — numpy, pandas, scipy and matplotlib.
We start off with a single task and run 10 million experiments on it. It’s not as crazy as it sounds, running this script just takes 2 seconds.
Let’s walk through the script. no_of_experiments and num_bins are the number of experiments we want to run, and the number of bins we use for our histogram.
tasks is a dictionary with only 1 key-value pair. I use this because naturally we’re going to have more tasks later, so just preparing ahead. The key is the name of the task, while the value is a list of 3 elements, the first is the optimistic value a, the second is the most likely value b and the last is the pessimistic value c.
Remember what I said earlier that the PERT distribution is a transformed four parameter beta distribution? I said that because neither numpy nor scipy have PERT distribution, instead they have beta distribution. So to use the PERT distribution we need to convert a, b and c to α and β. The formula for the conversions are pretty straightforward, if you don’t want to work it out yourself, you can find it from the Wikipedia entry on PERT distribution.
and
Once we have α and β we can use numpy (or scipy, take your pick but I used numpy here) to randomly draw a number of random variables from the distribution. Here we’re drawing 10 million random variables.
Next we need to convert the random variables back to the actual values we want, which is between a and c. Finally we have this extra step to add it to a points list of all 0s, which is not really useful for just a single task but when we have more tasks it will be needed. The points list is now a list of 10 million numbers randomly drawn from a PERT distribution.
Now that we have the data, we’ll plot it using matplotlib’s hist function. We change the x axis a bit to start from 0, and also change the points to represent a probability.
Run it and this is what we get.
That’s a nice curve but what does it all mean? Let’s run some statistical analysis on it using scipy.stats.
First thing we do is to simply show the tasks, and if we have more than 1 task, we add up the optimistic, most likely and pessimistic values.
Then using the stats.describe function we get the min, max, mean, variance, skewness, kurtosis and also standard deviation values. That’s a lot of stuff from just a couple of lines of code!
Finally we print out the probabilities with 0.5, 1, 2 and 3 standard deviations.
Now let’s take a look at the results.
Tasks----- optimistic likely pessimisticTask 1 4 7 12Total 4 7 12Statistics----------minimum: 4.0 maximum: 12.0mean: 7.3standard deviation: 1.5skewness: 0.22kurtosis: -0.60Probabilities-------------* between 7.0 and 7.7 : 36.0% (within 0.5σ)* between 6.6 and 8.1 : 64.7% (within 1σ)* between 5.8 and 8.8 : 97.3% (within 2σ)* between 5.1 and 9.6 : 100.0% (within 3σ)
The tasks is quite self explanatory as well with min and max. The mean value is interesting, if we take the earlier equation for the mean of a PERT distribution, we get 7.333 which validates our answer. Using the variance for a PERT distribution which is:
We will get a variance of 2.222 and the standard deviation, which is the square root of variance will be 1.49 which again validates our answer.
For the probabilities, we simply take the area under the curve between the mean and multiples of the standard deviation σ on both sides of the mean, and that would be the probability (because the area under the curve will all add up to 1.0 or 100%).
It seems astonishing and wrong that we say the probability that the task will end up between 5.1 and 9.6 is 100% but that’s because I truncated the results to 1 decimal point. If we allow it more decimal points it would be something like 99.9994%. Nonetheless let’s look at a few interesting points.
The expected value or mean and the most likely value (which is provided by the estimator is close but not the same).
The skewness is 0.22, which means the estimations tend to lean towards being more optimistic. If it’s a negative number it means it tends towards being more pessimistic. Skewness of a distribution that is symmetrical is 0.
The kurtosis is -0.6 indicates that the peak is a bit flat and more spread out. Generally speaking, the lower the number (the kurtosis of a normal distribution is 0) the flatter the curve is and the higher the number the more peaky it is. A flatter curve means the the optimistic and pessimistic values are further away from each other, and the the peaky curve means the optimistic and pessimistic values are closer to each other.
There is a 99.9994% chance that the task is somewhere between 5.1 and 9.6. Now compare that with the optimistic value of 4 and the pessimistic value of 12. It seems wrong that if you think the task is optimistically a 4 and pessimistically a 12 to then be told off by statistics that either values have a probability of only 0.0006%!
Numerically it seems counterintuitive but you can interpret it from a different perspective. If the probability of the pessimistic value is only 0.0006% then maybe the pessimistic value estimation is wrong and should be larger. You can give it a quick try and change the tasks to:
tasks = { "Task 1": [4,7, 24],}
Running it again will give us this results:
Tasks----- optimistic likely pessimisticTask 1 4 7 24Total 4 7 24Statistics----------minimum: 4.0 maximum: 23.5mean: 9.3standard deviation: 3.3skewness: 0.70kurtosis: -0.02Probabilities-------------* between 8.5 and 10.2 : 33.7% (within 0.5σ)* between 7.7 and 11.0 : 65.0% (within 1σ)* between 6.0 and 12.7 : 96.3% (within 2σ)* between 4.3 and 14.3 : 99.6% (within 3σ)
You can immediately see that for the value 12 it falls within 2σ. You might be thinking — that’s not right, the statistics is telling you it’s a larger value now but how does it know?
The answer is that it doesn’t. As the estimator you know better how likely the value 12 is. If you think that it’s extremely unlikely, and there is a very very small chance that it might be correct, then the value 12 is probably correct. If you think it’s unlikely to be 12, but the chances are that it’s going to be larger than 0.0006%, then you should choose a larger value.
In other words, the numbers are what they are, but the judgement of the optimistic, most likely and pessimistic values depends on the estimator.
What we did before is just warming up. What we really want is to estimate multiple tasks. While we can more or less calculate the values for a single task due to the PERT distribution, it’s going to be pretty hairy to do so if you have 100 tasks for example.
Almost all the code is going to be the same, except that we have more tasks so I won’t reproduce it here.
tasks = { "Task 1": [4,7, 12], "Task 2": [2, 3, 9], "Task 3": [3, 5, 16], "Task 4": [6, 7, 23], "Task 5": [10, 12, 28],}
With this list of tasks, let’s run the script again.
Now let’s do the statistical analysis again.
Tasks----- optimistic likely pessimisticTask 1 4 7 12Task 2 2 3 9Task 3 3 5 16Task 4 6 7 23Task 5 10 12 28Total 25 34 88Statistics----------minimum: 26.3 maximum: 69.7mean: 41.5standard deviation: 4.8skewness: 0.40kurtosis: 0.06Probabilities-------------* between 40.3 and 42.7 : 32.2% (within 0.5σ)* between 39.1 and 43.9 : 67.6% (within 1σ)* between 36.6 and 46.3 : 96.1% (within 2σ)* between 34.2 and 48.8 : 99.7% (within 3σ)
Because we have multiple tasks now, we can’t look at the optimistic, most likely and pessimistic values for a single task. Also we need to consider if the tasks are dependent on each other. Let’s keep it simple and say the tasks are all dependent on each other, meaning Task 5 is dependent on Task 4, which dependent on Task 3 and so all until Task 1.
So logically for the project, the task estimation should be a total of the optimistic, likely and pessimistic columns. As a project collectively we see the optimistic total is 25, the most likely total is 34 and the pessimistic total is 88. But how accurate is it? Let’s dig deeper.
From the numbers, we see that the mean 41.5 is pretty far away from the most likely value, and the mean is actually the most likely value for this distribution! This means by adding up the most likely values, we end up having a more optimistic view that the numbers show.
The minimum is only slightly more than than the optimistic value while the maximum is quite a bit less than the pessimistic value. Again this means by adding up the pessimistic values, we are really being too pessimistic while we are only slightly more optimistic than the numbers show.
The skewness of the distribution is quite positive so the over project tends to be more optimistic while the kurtosis is slightly positive (actually it’s pretty close to 0) so the project is quite well balanced in terms of the range between the optimistic and pessimistic values.
Now let’s look at the probabilities. You will notice something interesting — there is around a 67% probability that the project values are within 1σ of the mean, 96% probability that it’s within 2σ and 99.7% within 3σ. Do the numbers look familiar?
If they do then congratulations, you weren’t sleeping during your statistics lessons, at least not when your lecturer was teaching you about the normal distribution. The empirical rule states that for normal distributions, 68% of the values are within 1σ of the mean, 95% are within 2σ and 99% are within 3σ. While the empirical rule is for normal distributions, most bell-shaped distributions (like the one we got) somewhat follow this rule, though with slightly different numbers (this is also known as the three sigma rule). This is also the reason why the earlier run for a single task also follows roughly the same numbers.
Now take a second look at the probabilities again. The numbers say that there is a 99.7% chance that the project value is somewhere between 34.2 and 48.8. Remember that if we add up all the values in the various columns, the optimistic value is 25, the most likely value for the project is 34 and the pessimistic value is 88! Neither the optimistic nor pessimistic values are real, and the most likely value is likely to be wrong too.
Adding up the columns doesn’t tell the real picture after all. And if you think about what it means, that’s actually what it should be. For the pessimistic values or the optimistic values to add up it means every task needs to be the all pessimistic or all optimistic, which is highly unlikely.
So what do the statistical numbers actually mean? The statistics we worked out here basically mean that if all our estimations are accurate, then the project values will be 99.7% likely to be between 34.2 and 48.8.
Project task estimations are tough and all the statistical analysis shown earlier doesn’t detract from the need to for expert judgement. Ultimately no matter how powerful the techniques are, if the estimation data going in is totally wrong, nothing will be able to make it right.
However, analysing the data through such techniques allow us to detect potential issues with the task estimations. It will also help us understand the estimations, not only from an individual basis (which can be helpful as you can see from above) but groups of them, in a project or otherwise.
The exercise we went through earlier has a simple dependency of a task to a previous one, but in a more realistic scenario, we would have tasks that have multiple dependencies, groups of tasks which are dependent on each other or even cross dependencies.
Once complexity increases it becomes much more harder to see the project as a whole and its estimation can go awry very easily. Using a statistical tool can help us to spot potential problems and guide us to better estimations.
Such statistical analysis also helps us better guide projections for costing and timeliness. As the tasks complete we also can use the analysis to compare with the actual values, then update and revise future task estimations for better accuracy.
Throughout the exercise earlier I discussed task values and project values but I was quite vague about the unit of measure itself. Was I referring to duration, was I looking at the time needed to complete the tasks and the projects, in days or weeks or months? Or was I looking at effort, in terms of man-days or man-weeks or man-months? How about cost, in dollars and cents? Or complexity?
Actually we can use this for any of the above as long as there is numerical value to whatever we’re trying to measure. As mentioned earlier, some in some agile methodologies, the teams come up with their own units of measuring the tasks (someone came up with NUTs, or Nebulous Units of Time, scrum even did away with units altogether) and that’s ok.
However we should also understand at the end of the day, project success is commonly measured on whether it is on time, within cost and with quality.
I used Python and Jupyter Notebook here to do all the work. For many project managers, that’s not a natural tool to use — most people are more comfortable with Microsoft Excel to do all these calculations.
The good news is that Excel is an excellent tool and has all the necessary functions to do the statistical calculations. The bad news is that Excel has a max of 1,048,576 rows and 16,384 columns per sheet. So if you’d like to do 10 million Monte Carlo simulations you might not be able to do it one simulation per row.
In fact we we did 10 million simulations per task and if you have a large number of tasks, you’re going to be out of luck. Also, even if thats not an issue, processing 1 million rows will take quite a while for Excel while our Python script running in Jupyter Notebook only took 2 seconds for a single task and around 7 seconds for 5 tasks.
Ulam and von Neumann were working on the Manhattan Project when they came up with the idea of Monte Carlo simulations, PERT was created to support the US Navy’s submarine nuclear missile project, Polaris. It seems ironic that both these techniques were invented due to military needs, both relating to research on nuclear weapons.
War and military ambitions have always been one of the strongest drivers of innovation in history. While these ambitions have brought misery to millions of people, it’s reassuring that out of such horror comes such brilliant tools that can also help make our lives easier.
|
[
{
"code": null,
"e": 483,
"s": 172,
"text": "A few months ago, when the world was a very different place, I wrote about to-do list tasks strategies. I wanted to know, given a bunch of tasks in your todo list, what strategy should you use to pick the tasks to work on first? Depending on what I actually want to achieve, how I do it can be quite different."
},
{
"code": null,
"e": 804,
"s": 483,
"text": "The assumption I made there was that the complexity of a task is fixed, that is the duration it takes to complete it is pre-determined. That’s not normally true (statistics joke alert!). Complexity and therefore duration for most tasks, even before the uncertainty brought by the pandemic, is hard to predict accurately."
},
{
"code": null,
"e": 1052,
"s": 804,
"text": "If we look at tasks beyond to-do lists, for example project tasks, this becomes even worse. Project task complexity doesn’t only impact duration but it also effort and costs and therefore being able to determine the complexity is pretty important."
},
{
"code": null,
"e": 1160,
"s": 1052,
"text": "However project tasks are notoriously difficult to estimate, and this can mean delays and escalating costs."
},
{
"code": null,
"e": 1483,
"s": 1160,
"text": "Berlin’s new Brandenburg airport was in planning for 15 years before starting construction in 2006 and was supposed to open in October 2011. However the project is still ongoing and is also facing a skyrocketing budget. The latest opening date is November 2020 but with the ongoing situation it seems likely to move again."
},
{
"code": null,
"e": 1793,
"s": 1483,
"text": "NASA’s Space Launch System (SLS), a launch rocket that will provide the foundation for manned lunar flights and a human mission to Mars started in 2010 and has cost $18.6 billion as of 2020. In early 2020 it was announced that that it will have costs overrun of $2 billion and be delayed for at least 2 years."
},
{
"code": null,
"e": 2448,
"s": 1793,
"text": "This nothing new though, NASA is infamous for being excessively optimistic and underestimating projects. The James Webb Space Telescope (JWST) was originally supposed to be launched in 2007 and cost $500 million, but as of today has slipped to 2021 with an estimated cost of $10 billion. Its predecessor, the Hubble Space Telescope was originally supposed to launch in 1983 but finally launched in 1990, with the costs slipping from an original $400 million to eventually $4.7 billion. The International Space Station takes the cake though — it started off with a $36.75 billion budget and it was completed six years late with final cost of $105 billion."
},
{
"code": null,
"e": 2854,
"s": 2448,
"text": "Construction projects are not the only type of projects that get delayed, software development projects are often the culprit as well. In a rather infamous case to develop the Queensland Health Payroll System, the project was tendered out and won by IBM in December 2007 for $98 million, and was supposed to be rolled out in July 2008. It was finally delivered in 2010, with bugs and costing $1.2 billion."
},
{
"code": null,
"e": 3255,
"s": 2854,
"text": "Of course there are a lot of reasons why projects fail. Perfectly well estimated projects can suffer catastrophic results for various reasons that are impossible to predict. You can be sure that however well estimated project tasks are, none could have added in the pandemic we’re facing now, nor the after-effects to it. Nonetheless, good estimations are critical to keeping a project well on track."
},
{
"code": null,
"e": 3627,
"s": 3255,
"text": "There are a number of ways to do estimations. In agile methodologies (mostly software development projects), we have planning pokers, affinity groups, t-shirt sizing, bucketing and so on. In terms of estimate units, there’re t-shirt sizes (S, M, L, XL etc), Fibonacci story points, dot votes and plenty of other pretty creative ways to represent the sizing of the effort."
},
{
"code": null,
"e": 3987,
"s": 3627,
"text": "For more traditional project management methodologies, estimation techniques include bottom-up, top-down, parametric, analogous, three-point and so on. There are plenty of other types of estimation techniques especially in software development, including COCOMO, SEER-SEM, Putnam, PERT and many others. What we definitely don’t lack are estimation techniques."
},
{
"code": null,
"e": 4242,
"s": 3987,
"text": "Whichever techniques and units we use, ultimately what projects are concerned about is delivering on-time (time), within cost (budget) and something that does what it’s supposed to do (quality), whether it is a space telescope or a health payroll system."
},
{
"code": null,
"e": 4932,
"s": 4242,
"text": "Task estimation is hard. It’s mostly judgement-based, using the experience of the estimator (usually the person doing the task). Also, most estimates tend to be overly optimistic. In fact, there is a term, coined by psychologists Daniel Kahneman and Amos Tversky in 1979, called planning fallacy that describes precisely this. What Kahneman and Tversky found was that we have a tendency to disregard what we learnt in the past about similar tasks, and also to be overly optimistic about potential issues and even our own ability to complete the task (optimism bias). The topic is pretty fascinating, if you’re keen to learn more, you can read more from their book, Thinking, Fast and Slow."
},
{
"code": null,
"e": 5071,
"s": 4932,
"text": "One was of getting around it is using three-point estimation. The trick is to produce 3 data points (hence the name) for every estimation:"
},
{
"code": null,
"e": 5098,
"s": 5071,
"text": "a — the best case estimate"
},
{
"code": null,
"e": 5127,
"s": 5098,
"text": "b — the most likely estimate"
},
{
"code": null,
"e": 5155,
"s": 5127,
"text": "c — the worst case estimate"
},
{
"code": null,
"e": 5358,
"s": 5155,
"text": "This forces the estimator to think through the best, worst and most likely cases each time. While this is no silver bullet to overcome the planning fallacy, it gives us some interesting data to work on."
},
{
"code": null,
"e": 5704,
"s": 5358,
"text": "The project evaluation and review technique (PERT) is a tool used in project management to analyse and represent tasks in a project. It was developed for the US Navy in 1957 to manage the US Navy’s Polaris nuclear submarine missle project, but found its way to many other uses including an early use to plan the 1968 Winter Olympics in Grenoble."
},
{
"code": null,
"e": 5942,
"s": 5704,
"text": "PERT is a tool for large scale, one-time planning and scheduling, focusing on events and timing .PERT itself gave rise to associated tools and concepts such as the work breakdown structure, critical path and critical path analysis (CPA)."
},
{
"code": null,
"e": 6102,
"s": 5942,
"text": "PERT also gave rise to doing three point estimations, in fact it gave its name to a family of continous probability distributions called the PERT distribution."
},
{
"code": null,
"e": 6279,
"s": 6102,
"text": "The PERT distribution is a continuous probability distribution that is defined by the minimum (a), most likely (b) and maximum (c) values, with the mean (or expected value) of:"
},
{
"code": null,
"e": 6645,
"s": 6279,
"text": "The PERT distribution is actually a transformed four parameter beta distribution. The beta distribution have two parameters α and β defined on the interval [0,1], making it useful for modelling probabilities and random variables. The four parameter version of the beta distribution makes the interval [a,c] instead where a is the minimum and c is the maximum value."
},
{
"code": null,
"e": 6799,
"s": 6645,
"text": "You can see where this is going. By using a PERT distribution to map the estimations, we can approximate the probabilities of the estimations themselves!"
},
{
"code": null,
"e": 7097,
"s": 6799,
"text": "This is to say, while we ask the estimator to provide the optimistic, pessimistic and most likely values for the estimations, the actual expected value could be different from the most likely value, and we can figure out how likely the tasks is going to be completed within a duration or a budget."
},
{
"code": null,
"e": 7363,
"s": 7097,
"text": "However this is really only for a single task. In a project, of course, we have many, many tasks and each might have different distribution parameters for a, b and c. If you’re the project manager, how would you figure out the overall estimations and probabilities?"
},
{
"code": null,
"e": 7523,
"s": 7363,
"text": "Well, we can also try to do the maths but we’re programmers, not mathematicians (I’m saying this in a good way) so we look towards our old friend, Monte Carlo."
},
{
"code": null,
"e": 7808,
"s": 7523,
"text": "Of course, by Monte Carlo, I meant Monte Carlo simulations and not the casino. Monte Carlo is a popular simulation technique that uses many repeated random samplings to produce numerical data. It’s like running lots and lots of experiments and figuring out insight from all that data."
},
{
"code": null,
"e": 8505,
"s": 7808,
"text": "Stanislaw Ulam came up with the idea in 1947 when he was recovering from an illness. He was working on a nuclear weapons project at the Los Alamos National Laboratory then, and shared the idea with John Von Neumann, who saw the significance of the idea and he wrote the first Monte Carlo simulation. Because of the secrecy of their work, the had to come up with a code name. One of their colleagues suggested, Monte Carlo, a famous casino in Monaco where Ulam’s uncle used to borrow money from relatives to gamble and the rest is history. (You might recognize Ulam and Von Neumann, both brilliant mathematicians, scientists and early pioneers of computer science from a previous article I wrote)."
},
{
"code": null,
"e": 8850,
"s": 8505,
"text": "Monte Carlo simulations can be used to solve any probabilistic problem. Using the law of large numbers, we can approximate the results through empirical data we create. Of course, we cannot sanely do this without computers because the technique needs to run large numbers of repeated experiments. Monte Carlo literally brute forces the results!"
},
{
"code": null,
"e": 9291,
"s": 8850,
"text": "So how exactly do we use Monte Carlo to figure out the overall estimations of a number of project tasks? It’s quite simple actually. For every task, we create a PERT distribution using the given a (pessimistic), b (most likely) and c (optimistic) values and draw a value from that distribution. What we get is a simulated estimation for each task. When we add these estimations together we get the simulated estimation of the whole project."
},
{
"code": null,
"e": 9306,
"s": 9291,
"text": "Rinse, repeat."
},
{
"code": null,
"e": 9607,
"s": 9306,
"text": "We will end up with lots and lots of project estimations, that will also be in a probability distribution of some sort. Actually, we’ll end up with another PERT distribution but let’s see how we can prove it later. Once we have the data we can figure out the various probabilities of our estimations."
},
{
"code": null,
"e": 9744,
"s": 9607,
"text": "Let’s give it a spin! For this I’ll be using Python3 on Jupyter Notebook, with the usual suspects — numpy, pandas, scipy and matplotlib."
},
{
"code": null,
"e": 9888,
"s": 9744,
"text": "We start off with a single task and run 10 million experiments on it. It’s not as crazy as it sounds, running this script just takes 2 seconds."
},
{
"code": null,
"e": 10045,
"s": 9888,
"text": "Let’s walk through the script. no_of_experiments and num_bins are the number of experiments we want to run, and the number of bins we use for our histogram."
},
{
"code": null,
"e": 10377,
"s": 10045,
"text": "tasks is a dictionary with only 1 key-value pair. I use this because naturally we’re going to have more tasks later, so just preparing ahead. The key is the name of the task, while the value is a list of 3 elements, the first is the optimistic value a, the second is the most likely value b and the last is the pessimistic value c."
},
{
"code": null,
"e": 10829,
"s": 10377,
"text": "Remember what I said earlier that the PERT distribution is a transformed four parameter beta distribution? I said that because neither numpy nor scipy have PERT distribution, instead they have beta distribution. So to use the PERT distribution we need to convert a, b and c to α and β. The formula for the conversions are pretty straightforward, if you don’t want to work it out yourself, you can find it from the Wikipedia entry on PERT distribution."
},
{
"code": null,
"e": 10833,
"s": 10829,
"text": "and"
},
{
"code": null,
"e": 11037,
"s": 10833,
"text": "Once we have α and β we can use numpy (or scipy, take your pick but I used numpy here) to randomly draw a number of random variables from the distribution. Here we’re drawing 10 million random variables."
},
{
"code": null,
"e": 11403,
"s": 11037,
"text": "Next we need to convert the random variables back to the actual values we want, which is between a and c. Finally we have this extra step to add it to a points list of all 0s, which is not really useful for just a single task but when we have more tasks it will be needed. The points list is now a list of 10 million numbers randomly drawn from a PERT distribution."
},
{
"code": null,
"e": 11577,
"s": 11403,
"text": "Now that we have the data, we’ll plot it using matplotlib’s hist function. We change the x axis a bit to start from 0, and also change the points to represent a probability."
},
{
"code": null,
"e": 11609,
"s": 11577,
"text": "Run it and this is what we get."
},
{
"code": null,
"e": 11717,
"s": 11609,
"text": "That’s a nice curve but what does it all mean? Let’s run some statistical analysis on it using scipy.stats."
},
{
"code": null,
"e": 11859,
"s": 11717,
"text": "First thing we do is to simply show the tasks, and if we have more than 1 task, we add up the optimistic, most likely and pessimistic values."
},
{
"code": null,
"e": 12049,
"s": 11859,
"text": "Then using the stats.describe function we get the min, max, mean, variance, skewness, kurtosis and also standard deviation values. That’s a lot of stuff from just a couple of lines of code!"
},
{
"code": null,
"e": 12130,
"s": 12049,
"text": "Finally we print out the probabilities with 0.5, 1, 2 and 3 standard deviations."
},
{
"code": null,
"e": 12168,
"s": 12130,
"text": "Now let’s take a look at the results."
},
{
"code": null,
"e": 12596,
"s": 12168,
"text": "Tasks----- optimistic likely pessimisticTask 1 4 7 12Total 4 7 12Statistics----------minimum: 4.0 maximum: 12.0mean: 7.3standard deviation: 1.5skewness: 0.22kurtosis: -0.60Probabilities-------------* between 7.0 and 7.7 : 36.0% (within 0.5σ)* between 6.6 and 8.1 : 64.7% (within 1σ)* between 5.8 and 8.8 : 97.3% (within 2σ)* between 5.1 and 9.6 : 100.0% (within 3σ)"
},
{
"code": null,
"e": 12852,
"s": 12596,
"text": "The tasks is quite self explanatory as well with min and max. The mean value is interesting, if we take the earlier equation for the mean of a PERT distribution, we get 7.333 which validates our answer. Using the variance for a PERT distribution which is:"
},
{
"code": null,
"e": 12996,
"s": 12852,
"text": "We will get a variance of 2.222 and the standard deviation, which is the square root of variance will be 1.49 which again validates our answer."
},
{
"code": null,
"e": 13246,
"s": 12996,
"text": "For the probabilities, we simply take the area under the curve between the mean and multiples of the standard deviation σ on both sides of the mean, and that would be the probability (because the area under the curve will all add up to 1.0 or 100%)."
},
{
"code": null,
"e": 13546,
"s": 13246,
"text": "It seems astonishing and wrong that we say the probability that the task will end up between 5.1 and 9.6 is 100% but that’s because I truncated the results to 1 decimal point. If we allow it more decimal points it would be something like 99.9994%. Nonetheless let’s look at a few interesting points."
},
{
"code": null,
"e": 13663,
"s": 13546,
"text": "The expected value or mean and the most likely value (which is provided by the estimator is close but not the same)."
},
{
"code": null,
"e": 13886,
"s": 13663,
"text": "The skewness is 0.22, which means the estimations tend to lean towards being more optimistic. If it’s a negative number it means it tends towards being more pessimistic. Skewness of a distribution that is symmetrical is 0."
},
{
"code": null,
"e": 14317,
"s": 13886,
"text": "The kurtosis is -0.6 indicates that the peak is a bit flat and more spread out. Generally speaking, the lower the number (the kurtosis of a normal distribution is 0) the flatter the curve is and the higher the number the more peaky it is. A flatter curve means the the optimistic and pessimistic values are further away from each other, and the the peaky curve means the optimistic and pessimistic values are closer to each other."
},
{
"code": null,
"e": 14651,
"s": 14317,
"text": "There is a 99.9994% chance that the task is somewhere between 5.1 and 9.6. Now compare that with the optimistic value of 4 and the pessimistic value of 12. It seems wrong that if you think the task is optimistically a 4 and pessimistically a 12 to then be told off by statistics that either values have a probability of only 0.0006%!"
},
{
"code": null,
"e": 14932,
"s": 14651,
"text": "Numerically it seems counterintuitive but you can interpret it from a different perspective. If the probability of the pessimistic value is only 0.0006% then maybe the pessimistic value estimation is wrong and should be larger. You can give it a quick try and change the tasks to:"
},
{
"code": null,
"e": 14967,
"s": 14932,
"text": "tasks = { \"Task 1\": [4,7, 24],}"
},
{
"code": null,
"e": 15011,
"s": 14967,
"text": "Running it again will give us this results:"
},
{
"code": null,
"e": 15442,
"s": 15011,
"text": "Tasks----- optimistic likely pessimisticTask 1 4 7 24Total 4 7 24Statistics----------minimum: 4.0 maximum: 23.5mean: 9.3standard deviation: 3.3skewness: 0.70kurtosis: -0.02Probabilities-------------* between 8.5 and 10.2 : 33.7% (within 0.5σ)* between 7.7 and 11.0 : 65.0% (within 1σ)* between 6.0 and 12.7 : 96.3% (within 2σ)* between 4.3 and 14.3 : 99.6% (within 3σ)"
},
{
"code": null,
"e": 15626,
"s": 15442,
"text": "You can immediately see that for the value 12 it falls within 2σ. You might be thinking — that’s not right, the statistics is telling you it’s a larger value now but how does it know?"
},
{
"code": null,
"e": 16003,
"s": 15626,
"text": "The answer is that it doesn’t. As the estimator you know better how likely the value 12 is. If you think that it’s extremely unlikely, and there is a very very small chance that it might be correct, then the value 12 is probably correct. If you think it’s unlikely to be 12, but the chances are that it’s going to be larger than 0.0006%, then you should choose a larger value."
},
{
"code": null,
"e": 16148,
"s": 16003,
"text": "In other words, the numbers are what they are, but the judgement of the optimistic, most likely and pessimistic values depends on the estimator."
},
{
"code": null,
"e": 16407,
"s": 16148,
"text": "What we did before is just warming up. What we really want is to estimate multiple tasks. While we can more or less calculate the values for a single task due to the PERT distribution, it’s going to be pretty hairy to do so if you have 100 tasks for example."
},
{
"code": null,
"e": 16513,
"s": 16407,
"text": "Almost all the code is going to be the same, except that we have more tasks so I won’t reproduce it here."
},
{
"code": null,
"e": 16649,
"s": 16513,
"text": "tasks = { \"Task 1\": [4,7, 12], \"Task 2\": [2, 3, 9], \"Task 3\": [3, 5, 16], \"Task 4\": [6, 7, 23], \"Task 5\": [10, 12, 28],}"
},
{
"code": null,
"e": 16702,
"s": 16649,
"text": "With this list of tasks, let’s run the script again."
},
{
"code": null,
"e": 16747,
"s": 16702,
"text": "Now let’s do the statistical analysis again."
},
{
"code": null,
"e": 17339,
"s": 16747,
"text": "Tasks----- optimistic likely pessimisticTask 1 4 7 12Task 2 2 3 9Task 3 3 5 16Task 4 6 7 23Task 5 10 12 28Total 25 34 88Statistics----------minimum: 26.3 maximum: 69.7mean: 41.5standard deviation: 4.8skewness: 0.40kurtosis: 0.06Probabilities-------------* between 40.3 and 42.7 : 32.2% (within 0.5σ)* between 39.1 and 43.9 : 67.6% (within 1σ)* between 36.6 and 46.3 : 96.1% (within 2σ)* between 34.2 and 48.8 : 99.7% (within 3σ)"
},
{
"code": null,
"e": 17691,
"s": 17339,
"text": "Because we have multiple tasks now, we can’t look at the optimistic, most likely and pessimistic values for a single task. Also we need to consider if the tasks are dependent on each other. Let’s keep it simple and say the tasks are all dependent on each other, meaning Task 5 is dependent on Task 4, which dependent on Task 3 and so all until Task 1."
},
{
"code": null,
"e": 17974,
"s": 17691,
"text": "So logically for the project, the task estimation should be a total of the optimistic, likely and pessimistic columns. As a project collectively we see the optimistic total is 25, the most likely total is 34 and the pessimistic total is 88. But how accurate is it? Let’s dig deeper."
},
{
"code": null,
"e": 18246,
"s": 17974,
"text": "From the numbers, we see that the mean 41.5 is pretty far away from the most likely value, and the mean is actually the most likely value for this distribution! This means by adding up the most likely values, we end up having a more optimistic view that the numbers show."
},
{
"code": null,
"e": 18533,
"s": 18246,
"text": "The minimum is only slightly more than than the optimistic value while the maximum is quite a bit less than the pessimistic value. Again this means by adding up the pessimistic values, we are really being too pessimistic while we are only slightly more optimistic than the numbers show."
},
{
"code": null,
"e": 18813,
"s": 18533,
"text": "The skewness of the distribution is quite positive so the over project tends to be more optimistic while the kurtosis is slightly positive (actually it’s pretty close to 0) so the project is quite well balanced in terms of the range between the optimistic and pessimistic values."
},
{
"code": null,
"e": 19062,
"s": 18813,
"text": "Now let’s look at the probabilities. You will notice something interesting — there is around a 67% probability that the project values are within 1σ of the mean, 96% probability that it’s within 2σ and 99.7% within 3σ. Do the numbers look familiar?"
},
{
"code": null,
"e": 19691,
"s": 19062,
"text": "If they do then congratulations, you weren’t sleeping during your statistics lessons, at least not when your lecturer was teaching you about the normal distribution. The empirical rule states that for normal distributions, 68% of the values are within 1σ of the mean, 95% are within 2σ and 99% are within 3σ. While the empirical rule is for normal distributions, most bell-shaped distributions (like the one we got) somewhat follow this rule, though with slightly different numbers (this is also known as the three sigma rule). This is also the reason why the earlier run for a single task also follows roughly the same numbers."
},
{
"code": null,
"e": 20126,
"s": 19691,
"text": "Now take a second look at the probabilities again. The numbers say that there is a 99.7% chance that the project value is somewhere between 34.2 and 48.8. Remember that if we add up all the values in the various columns, the optimistic value is 25, the most likely value for the project is 34 and the pessimistic value is 88! Neither the optimistic nor pessimistic values are real, and the most likely value is likely to be wrong too."
},
{
"code": null,
"e": 20421,
"s": 20126,
"text": "Adding up the columns doesn’t tell the real picture after all. And if you think about what it means, that’s actually what it should be. For the pessimistic values or the optimistic values to add up it means every task needs to be the all pessimistic or all optimistic, which is highly unlikely."
},
{
"code": null,
"e": 20636,
"s": 20421,
"text": "So what do the statistical numbers actually mean? The statistics we worked out here basically mean that if all our estimations are accurate, then the project values will be 99.7% likely to be between 34.2 and 48.8."
},
{
"code": null,
"e": 20916,
"s": 20636,
"text": "Project task estimations are tough and all the statistical analysis shown earlier doesn’t detract from the need to for expert judgement. Ultimately no matter how powerful the techniques are, if the estimation data going in is totally wrong, nothing will be able to make it right."
},
{
"code": null,
"e": 21210,
"s": 20916,
"text": "However, analysing the data through such techniques allow us to detect potential issues with the task estimations. It will also help us understand the estimations, not only from an individual basis (which can be helpful as you can see from above) but groups of them, in a project or otherwise."
},
{
"code": null,
"e": 21465,
"s": 21210,
"text": "The exercise we went through earlier has a simple dependency of a task to a previous one, but in a more realistic scenario, we would have tasks that have multiple dependencies, groups of tasks which are dependent on each other or even cross dependencies."
},
{
"code": null,
"e": 21693,
"s": 21465,
"text": "Once complexity increases it becomes much more harder to see the project as a whole and its estimation can go awry very easily. Using a statistical tool can help us to spot potential problems and guide us to better estimations."
},
{
"code": null,
"e": 21940,
"s": 21693,
"text": "Such statistical analysis also helps us better guide projections for costing and timeliness. As the tasks complete we also can use the analysis to compare with the actual values, then update and revise future task estimations for better accuracy."
},
{
"code": null,
"e": 22331,
"s": 21940,
"text": "Throughout the exercise earlier I discussed task values and project values but I was quite vague about the unit of measure itself. Was I referring to duration, was I looking at the time needed to complete the tasks and the projects, in days or weeks or months? Or was I looking at effort, in terms of man-days or man-weeks or man-months? How about cost, in dollars and cents? Or complexity?"
},
{
"code": null,
"e": 22681,
"s": 22331,
"text": "Actually we can use this for any of the above as long as there is numerical value to whatever we’re trying to measure. As mentioned earlier, some in some agile methodologies, the teams come up with their own units of measuring the tasks (someone came up with NUTs, or Nebulous Units of Time, scrum even did away with units altogether) and that’s ok."
},
{
"code": null,
"e": 22831,
"s": 22681,
"text": "However we should also understand at the end of the day, project success is commonly measured on whether it is on time, within cost and with quality."
},
{
"code": null,
"e": 23037,
"s": 22831,
"text": "I used Python and Jupyter Notebook here to do all the work. For many project managers, that’s not a natural tool to use — most people are more comfortable with Microsoft Excel to do all these calculations."
},
{
"code": null,
"e": 23356,
"s": 23037,
"text": "The good news is that Excel is an excellent tool and has all the necessary functions to do the statistical calculations. The bad news is that Excel has a max of 1,048,576 rows and 16,384 columns per sheet. So if you’d like to do 10 million Monte Carlo simulations you might not be able to do it one simulation per row."
},
{
"code": null,
"e": 23697,
"s": 23356,
"text": "In fact we we did 10 million simulations per task and if you have a large number of tasks, you’re going to be out of luck. Also, even if thats not an issue, processing 1 million rows will take quite a while for Excel while our Python script running in Jupyter Notebook only took 2 seconds for a single task and around 7 seconds for 5 tasks."
},
{
"code": null,
"e": 24028,
"s": 23697,
"text": "Ulam and von Neumann were working on the Manhattan Project when they came up with the idea of Monte Carlo simulations, PERT was created to support the US Navy’s submarine nuclear missile project, Polaris. It seems ironic that both these techniques were invented due to military needs, both relating to research on nuclear weapons."
}
] |
NHibernate - Mapping Component
|
In this chapter, we will be talking about mapping components. In NHibernate, component is a value object. It does not have an identity of its own.
An example of this would be a money object, a purse or a wallet might have money in it, but the exact identity of that money is irrelevant.
An example of this would be a money object, a purse or a wallet might have money in it, but the exact identity of that money is irrelevant.
It doesn't have its own primary key, but components themselves are persistent in the same table as the owning object.
It doesn't have its own primary key, but components themselves are persistent in the same table as the owning object.
Let’s have a look at a simple example in which a student has an Address, which is an object of Location class associated with it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NHibernateDemoApp {
class Student {
public virtual int ID { get; set; }
public virtual string LastName { get; set; }
public virtual string FirstName { get; set; }
public virtual StudentAcademicStanding AcademicStanding { get; set; }
public virtual Location Address { get; set; }
}
public class Location {
public virtual string Street { get; set; }
public virtual string City { get; set; }
public virtual string Province { get; set; }
public virtual string Country { get; set; }
}
public enum StudentAcademicStanding {
Excellent,
Good,
Fair,
Poor,
Terrible
}
}
Now, we also need to update the database by executing the following query, which will first drop the Student table and then create a new table that will also contain a column for Location class.
DROP TABLE [dbo].[Student]
CREATE TABLE [dbo].[Student] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[LastName] NVARCHAR (MAX) NULL,
[FirstMidName] NVARCHAR (MAX) NULL,
[AcademicStanding] NCHAR(10) NULL,
[Street] NVARCHAR (100) NULL,
[City] NVARCHAR (100) NULL,
[Province] NVARCHAR (100) NULL,
[Country] NVARCHAR (100) NULL,
CONSTRAINT [PK_dbo.Student] PRIMARY KEY CLUSTERED ([ID] ASC)
);
Now to map those columns that are not directly a part of Student class, but they are properties of Location class and Location class object is defined in the student class. We need a component to map it correctly. Let’s create a component in student.hbm.xml file as shown in the following code.
<?xml version = "1.0" encoding = "utf-8" ?>
<hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2"
assembly = "NHibernateDemoApp" namespace = "NHibernateDemoApp">
<class name = "Student">
<id name = "ID">
<generator class = "native"/>
</id>
<property name = "LastName"/>
<property name = "FirstName" column = "FirstMidName" type = "String"/>
<property name = "AcademicStanding"/>
<component name = "Address">
<property name = "Street"/>
<property name = "City"/>
<property name = "Province"/>
<property name = "Country"/>
</component>
</class>
</hibernate-mapping>
This component is the Address and it has these different properties on it. With this information, NHibernate now has enough that it can actually map this.
Now here is the Program.cs file in which a new student object is created and initialized and then saved to the database. It will then retrieve the list from the database.
using HibernatingRhinos.Profiler.Appender.NHibernate;
using NHibernate.Cache;
using NHibernate.Caches.SysCache;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Linq;
using System;
using System.Linq;
using System.Reflection;
namespace NHibernateDemoApp {
class Program {
static void Main(string[] args) {
NHibernateProfiler.Initialize();
var cfg = new Configuration();
String Data Source = asia13797\\sqlexpress;
String Initial Catalog = NHibernateDemoDB;
String Integrated Security = True;
String Connect Timeout = 15;
String Encrypt = False;
String TrustServerCertificate = False;
String ApplicationIntent = ReadWrite;
String MultiSubnetFailover = False;
cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source +
Initial Catalog + Integrated Security + Connect Timeout + Encrypt +
TrustServerCertificate + ApplicationIntent + MultiSubnetFailover";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
});
cfg.AddAssembly(Assembly.GetExecutingAssembly());
var sefact = cfg.BuildSessionFactory();
using (var session = sefact.OpenSession()) {
using (var tx = session.BeginTransaction()) {
var student1 = new Student {
ID = 1,
FirstName = "Allan",
LastName = "Bommer",
AcademicStanding = StudentAcademicStanding.Poor,
Address = new Location {
Street = "123 Street",
City = "Lahore",
Province = "Punjab",
Country = "Pakistan"
}
};
session.Save(student1);
tx.Commit();
var students = session.Query<Student>().ToList<Student>();
Console.WriteLine("\nFetch the complete list again\n");
foreach (var student in students) {
Console.WriteLine("{0} \t{1} \t{2} \t{3} \t{4} \t{5} \t{6} \t{7}",
student.ID,
student.FirstName,
student.LastName,
student.AcademicStanding,
student.Address.Street,
student.Address.City,
student.Address.Province,
student.Address.Country
);
}
}
Console.ReadLine();
}
}
}
}
Now we can run this application and NHibernate can save those values to the database. When you run the application, you will see the following output.
Fetch the complete list again
2 Allan Bommer Poor 123 Street Lahore Punjab Pakistan
Here are the values in the database.
The components allow us to separate out columns that are in a database table into their own separate class.
The other thing to notice here is because the Location is a class, it is not an entity.
The other thing to notice here is because the Location is a class, it is not an entity.
It is a value type object and it doesn't have its own primary key.
It is a value type object and it doesn't have its own primary key.
It is saved in the same table as the Student that contains it.
It is saved in the same table as the Student that contains it.
That's why we're using the component here.
That's why we're using the component here.
This allows a lot of flexibility to change our class layer, how our classes are defined versus how our database is laid out.
This allows a lot of flexibility to change our class layer, how our classes are defined versus how our database is laid out.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2480,
"s": 2333,
"text": "In this chapter, we will be talking about mapping components. In NHibernate, component is a value object. It does not have an identity of its own."
},
{
"code": null,
"e": 2620,
"s": 2480,
"text": "An example of this would be a money object, a purse or a wallet might have money in it, but the exact identity of that money is irrelevant."
},
{
"code": null,
"e": 2760,
"s": 2620,
"text": "An example of this would be a money object, a purse or a wallet might have money in it, but the exact identity of that money is irrelevant."
},
{
"code": null,
"e": 2878,
"s": 2760,
"text": "It doesn't have its own primary key, but components themselves are persistent in the same table as the owning object."
},
{
"code": null,
"e": 2996,
"s": 2878,
"text": "It doesn't have its own primary key, but components themselves are persistent in the same table as the owning object."
},
{
"code": null,
"e": 3126,
"s": 2996,
"text": "Let’s have a look at a simple example in which a student has an Address, which is an object of Location class associated with it."
},
{
"code": null,
"e": 3943,
"s": 3126,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace NHibernateDemoApp { \n\n class Student { \n public virtual int ID { get; set; } \n public virtual string LastName { get; set; } \n public virtual string FirstName { get; set; } \n public virtual StudentAcademicStanding AcademicStanding { get; set; } \n public virtual Location Address { get; set; } \n }\n\n public class Location { \n public virtual string Street { get; set; } \n public virtual string City { get; set; } \n public virtual string Province { get; set; } \n public virtual string Country { get; set; } \n }\n \n public enum StudentAcademicStanding { \n Excellent, \n Good, \n Fair, \n Poor, \n Terrible \n } \n}"
},
{
"code": null,
"e": 4138,
"s": 3943,
"text": "Now, we also need to update the database by executing the following query, which will first drop the Student table and then create a new table that will also contain a column for Location class."
},
{
"code": null,
"e": 4558,
"s": 4138,
"text": "DROP TABLE [dbo].[Student]\nCREATE TABLE [dbo].[Student] ( \n\n [ID] INT IDENTITY (1, 1) NOT NULL, \n [LastName] NVARCHAR (MAX) NULL, \n [FirstMidName] NVARCHAR (MAX) NULL, \n [AcademicStanding] NCHAR(10) NULL, \n [Street] NVARCHAR (100) NULL, \n [City] NVARCHAR (100) NULL, \n [Province] NVARCHAR (100) NULL, \n [Country] NVARCHAR (100) NULL, \n CONSTRAINT [PK_dbo.Student] PRIMARY KEY CLUSTERED ([ID] ASC) \n\n);"
},
{
"code": null,
"e": 4853,
"s": 4558,
"text": "Now to map those columns that are not directly a part of Student class, but they are properties of Location class and Location class object is defined in the student class. We need a component to map it correctly. Let’s create a component in student.hbm.xml file as shown in the following code."
},
{
"code": null,
"e": 5551,
"s": 4853,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" \n assembly = \"NHibernateDemoApp\" namespace = \"NHibernateDemoApp\"> \n\n <class name = \"Student\"> \n\t\n <id name = \"ID\"> \n <generator class = \"native\"/>\n </id> \n \n <property name = \"LastName\"/> \n\t\t\n <property name = \"FirstName\" column = \"FirstMidName\" type = \"String\"/> \n <property name = \"AcademicStanding\"/>\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 </class> \n</hibernate-mapping>"
},
{
"code": null,
"e": 5706,
"s": 5551,
"text": "This component is the Address and it has these different properties on it. With this information, NHibernate now has enough that it can actually map this."
},
{
"code": null,
"e": 5877,
"s": 5706,
"text": "Now here is the Program.cs file in which a new student object is created and initialized and then saved to the database. It will then retrieve the list from the database."
},
{
"code": null,
"e": 8642,
"s": 5877,
"text": "using HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cache; \nusing NHibernate.Caches.SysCache; \nusing NHibernate.Cfg; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \nusing NHibernate.Linq; \n\nusing System; \nusing System.Linq; \nusing System.Reflection;\nnamespace NHibernateDemoApp { \n\n class Program {\n\t\n static void Main(string[] args) { \n\t\t\n NHibernateProfiler.Initialize(); \n var cfg = new Configuration();\n\n String Data Source = asia13797\\\\sqlexpress;\n String Initial Catalog = NHibernateDemoDB;\n String Integrated Security = True;\n String Connect Timeout = 15;\n String Encrypt = False;\n String TrustServerCertificate = False;\n String ApplicationIntent = ReadWrite;\n String MultiSubnetFailover = False;\t\t\t\n \n cfg.DataBaseIntegration(x = > { x.ConnectionString = \"Data Source + \n Initial Catalog + Integrated Security + Connect Timeout + Encrypt +\n TrustServerCertificate + ApplicationIntent + MultiSubnetFailover\";\n\t\t\t\t\n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n }); \n \n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n var sefact = cfg.BuildSessionFactory(); \n\t\t\t\n using (var session = sefact.OpenSession()) { \n\t\t\t\n using (var tx = session.BeginTransaction()) { \n \n var student1 = new Student { \n ID = 1, \n FirstName = \"Allan\", \n LastName = \"Bommer\", \n AcademicStanding = StudentAcademicStanding.Poor, \n \n Address = new Location { \n Street = \"123 Street\", \n City = \"Lahore\", \n Province = \"Punjab\", \n Country = \"Pakistan\" \n } \n }; \n\t\t\t\t\t\n session.Save(student1); \n tx.Commit(); \n var students = session.Query<Student>().ToList<Student>();\n Console.WriteLine(\"\\nFetch the complete list again\\n\"); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2} \\t{3} \\t{4} \\t{5} \\t{6} \\t{7}\", \n student.ID, \n student.FirstName, \n student.LastName, \n student.AcademicStanding, \n student.Address.Street, \n student.Address.City, \n student.Address.Province, \n student.Address.Country\n ); \n } \n } \n\t\t\t\t\n Console.ReadLine(); \n } \n }\n } \n}"
},
{
"code": null,
"e": 8793,
"s": 8642,
"text": "Now we can run this application and NHibernate can save those values to the database. When you run the application, you will see the following output."
},
{
"code": null,
"e": 8879,
"s": 8793,
"text": "Fetch the complete list again\n\n2 Allan Bommer Poor 123 Street Lahore Punjab Pakistan\n"
},
{
"code": null,
"e": 8916,
"s": 8879,
"text": "Here are the values in the database."
},
{
"code": null,
"e": 9024,
"s": 8916,
"text": "The components allow us to separate out columns that are in a database table into their own separate class."
},
{
"code": null,
"e": 9112,
"s": 9024,
"text": "The other thing to notice here is because the Location is a class, it is not an entity."
},
{
"code": null,
"e": 9200,
"s": 9112,
"text": "The other thing to notice here is because the Location is a class, it is not an entity."
},
{
"code": null,
"e": 9267,
"s": 9200,
"text": "It is a value type object and it doesn't have its own primary key."
},
{
"code": null,
"e": 9334,
"s": 9267,
"text": "It is a value type object and it doesn't have its own primary key."
},
{
"code": null,
"e": 9397,
"s": 9334,
"text": "It is saved in the same table as the Student that contains it."
},
{
"code": null,
"e": 9460,
"s": 9397,
"text": "It is saved in the same table as the Student that contains it."
},
{
"code": null,
"e": 9503,
"s": 9460,
"text": "That's why we're using the component here."
},
{
"code": null,
"e": 9546,
"s": 9503,
"text": "That's why we're using the component here."
},
{
"code": null,
"e": 9671,
"s": 9546,
"text": "This allows a lot of flexibility to change our class layer, how our classes are defined versus how our database is laid out."
},
{
"code": null,
"e": 9796,
"s": 9671,
"text": "This allows a lot of flexibility to change our class layer, how our classes are defined versus how our database is laid out."
},
{
"code": null,
"e": 9803,
"s": 9796,
"text": " Print"
},
{
"code": null,
"e": 9814,
"s": 9803,
"text": " Add Notes"
}
] |
chr() in Python - GeeksforGeeks
|
15 Nov, 2017
The chr() method returns a string representing a character whose Unicode code point is an integer.Syntax:
chr(num)
num : integer value
The chr() method takes only one integer as argument.
The range may vary from 0 to 1,1141,111(0x10FFFF in base 16).
The chr() method returns a character whose unicode point is num, an integer.
If an integer is passed that is outside the range then the method returns a ValueError.
Example: Suppose we want to print ‘G e e k s f o r G e e k s’.
# Python program to illustrate # chr() builtin function print(chr(71), chr(101),chr(101), chr(107),chr(115), chr(32),chr(102), chr(111),chr(114),chr(32),chr(71), chr(101),chr(101), chr(107), chr(115))
Output:
G e e k s f o r G e e k s
Another example :
# Python program to illustrate # chr() builtin function numbers = [17, 38, 79] for number in numbers: # Convert ASCII-based number to character. letter = chr(number) print("Character of ASCII value", number, "is ", letter)
Output:
Character of ASCII value 17 is
Character of ASCII value 38 is &
Character of ASCII value 79 is O
What happens if we give something out of range?
# Python program to illustrate # chr() builtin function# if value given is # out of range # Convert ASCII-based number to characterprint(chr(400))
Output:
No Output
We wont get any output and the compiler will throw an error:
Traceback (most recent call last):
File "/home/484c76fb455a624cc137946a244a9aa5.py", line 1, in
print(chr(400))
UnicodeEncodeError: 'ascii' codec can't encode character
'\u0190' in position 0: ordinal not in range(128)
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
|
[
{
"code": null,
"e": 24075,
"s": 24047,
"text": "\n15 Nov, 2017"
},
{
"code": null,
"e": 24181,
"s": 24075,
"text": "The chr() method returns a string representing a character whose Unicode code point is an integer.Syntax:"
},
{
"code": null,
"e": 24211,
"s": 24181,
"text": "chr(num)\nnum : integer value\n"
},
{
"code": null,
"e": 24264,
"s": 24211,
"text": "The chr() method takes only one integer as argument."
},
{
"code": null,
"e": 24326,
"s": 24264,
"text": "The range may vary from 0 to 1,1141,111(0x10FFFF in base 16)."
},
{
"code": null,
"e": 24403,
"s": 24326,
"text": "The chr() method returns a character whose unicode point is num, an integer."
},
{
"code": null,
"e": 24491,
"s": 24403,
"text": "If an integer is passed that is outside the range then the method returns a ValueError."
},
{
"code": null,
"e": 24554,
"s": 24491,
"text": "Example: Suppose we want to print ‘G e e k s f o r G e e k s’."
},
{
"code": "# Python program to illustrate # chr() builtin function print(chr(71), chr(101),chr(101), chr(107),chr(115), chr(32),chr(102), chr(111),chr(114),chr(32),chr(71), chr(101),chr(101), chr(107), chr(115))",
"e": 24756,
"s": 24554,
"text": null
},
{
"code": null,
"e": 24764,
"s": 24756,
"text": "Output:"
},
{
"code": null,
"e": 24795,
"s": 24764,
"text": "G e e k s f o r G e e k s\n"
},
{
"code": null,
"e": 24813,
"s": 24795,
"text": "Another example :"
},
{
"code": "# Python program to illustrate # chr() builtin function numbers = [17, 38, 79] for number in numbers: # Convert ASCII-based number to character. letter = chr(number) print(\"Character of ASCII value\", number, \"is \", letter)",
"e": 25053,
"s": 24813,
"text": null
},
{
"code": null,
"e": 25061,
"s": 25053,
"text": "Output:"
},
{
"code": null,
"e": 25162,
"s": 25061,
"text": "Character of ASCII value 17 is \nCharacter of ASCII value 38 is &\nCharacter of ASCII value 79 is O"
},
{
"code": null,
"e": 25210,
"s": 25162,
"text": "What happens if we give something out of range?"
},
{
"code": "# Python program to illustrate # chr() builtin function# if value given is # out of range # Convert ASCII-based number to characterprint(chr(400))",
"e": 25358,
"s": 25210,
"text": null
},
{
"code": null,
"e": 25366,
"s": 25358,
"text": "Output:"
},
{
"code": null,
"e": 25377,
"s": 25366,
"text": "No Output\n"
},
{
"code": null,
"e": 25438,
"s": 25377,
"text": "We wont get any output and the compiler will throw an error:"
},
{
"code": null,
"e": 25666,
"s": 25438,
"text": "Traceback (most recent call last):\n File \"/home/484c76fb455a624cc137946a244a9aa5.py\", line 1, in \n print(chr(400))\nUnicodeEncodeError: 'ascii' codec can't encode character \n'\\u0190' in position 0: ordinal not in range(128)\n"
},
{
"code": null,
"e": 25692,
"s": 25666,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 25699,
"s": 25692,
"text": "Python"
},
{
"code": null,
"e": 25797,
"s": 25699,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25832,
"s": 25797,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25854,
"s": 25832,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25886,
"s": 25854,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25916,
"s": 25886,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25958,
"s": 25916,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25984,
"s": 25958,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26027,
"s": 25984,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26064,
"s": 26027,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26108,
"s": 26064,
"text": "Reading and Writing to text files in Python"
}
] |
Data Structures | Linked List | Question 3 - GeeksforGeeks
|
11 Jan, 2013
Consider the following function that takes reference to head of a Doubly Linked List as parameter. Assume that a node of doubly linked list has previous pointer as prev and next pointer as next.
void fun(struct node **head_ref){ struct node *temp = NULL; struct node *current = *head_ref; while (current != NULL) { temp = current->prev; current->prev = current->next; current->next = temp; current = current->prev; } if(temp != NULL ) *head_ref = temp->prev;}
Assume that reference of head of following doubly linked list is passed to above function
1 2 3 4 5 6.
What should be the modified linked list after the function call?(A) 2 1 4 3 6 5(B) 5 4 3 2 1 6.(C) 6 5 4 3 2 1.(D) 6 5 4 3 1 2Answer: (C)Explanation: The given function reverses the given doubly linked list. See Reverse a Doubly Linked List for details.
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Advantages and Disadvantages of Linked List
Introduction to Data Structures | 10 most commonly used Data Structures
FIFO vs LIFO approach in Programming
Data Structures | Stack | Question 6
Bit manipulation | Swap Endianness of a number
Data Structures | Queue | Question 11
Advantages of vector over array in C++
Data Structures | Queue | Question 2
Encryption and Decryption of String according to given technique
|
[
{
"code": null,
"e": 24441,
"s": 24413,
"text": "\n11 Jan, 2013"
},
{
"code": null,
"e": 24636,
"s": 24441,
"text": "Consider the following function that takes reference to head of a Doubly Linked List as parameter. Assume that a node of doubly linked list has previous pointer as prev and next pointer as next."
},
{
"code": "void fun(struct node **head_ref){ struct node *temp = NULL; struct node *current = *head_ref; while (current != NULL) { temp = current->prev; current->prev = current->next; current->next = temp; current = current->prev; } if(temp != NULL ) *head_ref = temp->prev;}",
"e": 24959,
"s": 24636,
"text": null
},
{
"code": null,
"e": 25049,
"s": 24959,
"text": "Assume that reference of head of following doubly linked list is passed to above function"
},
{
"code": null,
"e": 25062,
"s": 25049,
"text": "1 2 3 4 5 6."
},
{
"code": null,
"e": 25316,
"s": 25062,
"text": "What should be the modified linked list after the function call?(A) 2 1 4 3 6 5(B) 5 4 3 2 1 6.(C) 6 5 4 3 2 1.(D) 6 5 4 3 1 2Answer: (C)Explanation: The given function reverses the given doubly linked list. See Reverse a Doubly Linked List for details."
},
{
"code": null,
"e": 25332,
"s": 25316,
"text": "Data Structures"
},
{
"code": null,
"e": 25360,
"s": 25332,
"text": "Data Structures-Linked List"
},
{
"code": null,
"e": 25373,
"s": 25360,
"text": "Linked Lists"
},
{
"code": null,
"e": 25389,
"s": 25373,
"text": "Data Structures"
},
{
"code": null,
"e": 25405,
"s": 25389,
"text": "Data Structures"
},
{
"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": 25608,
"s": 25525,
"text": "Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]"
},
{
"code": null,
"e": 25652,
"s": 25608,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 25724,
"s": 25652,
"text": "Introduction to Data Structures | 10 most commonly used Data Structures"
},
{
"code": null,
"e": 25761,
"s": 25724,
"text": "FIFO vs LIFO approach in Programming"
},
{
"code": null,
"e": 25798,
"s": 25761,
"text": "Data Structures | Stack | Question 6"
},
{
"code": null,
"e": 25845,
"s": 25798,
"text": "Bit manipulation | Swap Endianness of a number"
},
{
"code": null,
"e": 25883,
"s": 25845,
"text": "Data Structures | Queue | Question 11"
},
{
"code": null,
"e": 25922,
"s": 25883,
"text": "Advantages of vector over array in C++"
},
{
"code": null,
"e": 25959,
"s": 25922,
"text": "Data Structures | Queue | Question 2"
}
] |
CICS - COBOL Basics
|
CICS programs are written in COBOL language in Mainframes. We will be discussing about writing a simple COBOL-CICS program, compiling it, and then executing it.
We will be writing a simple COBOL-CICS program which displays some message on the CICS output screen. This program is to demonstrate the steps involved in executing a COBOL-CICS program. Following are the steps to code a simple program −
Login to Mainframes and open a TSO Session.
Create a new PDS in which we will be coding our program.
Create a new member inside the PDS and code the following program −
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 WS-MESSAGE PIC X(40).
01 WS-LENGTH PIC S9(4) COMP.
PROCEDURE DIVISION.
A000-MAIN-PARA.
MOVE 'Hello World' TO WS-MESSAGE
MOVE '+12' TO WS-LENGTH
EXEC CICS SEND TEXT
FROM (WS-MESSAGE)
LENGHT(WS-LENGTH)
END-EXEC
EXEC CICS RETURN
END-EXEC.
After coding the program, we need to compile it. We can compile the program using the following JCL −
//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
//CICSCOB EXEC CICSCOB,
//COPYLIB = ABC.XYZ.COPYLIB,
//LOADLIB = ABC.XYZ.LOADLIB
//LIB JCLLIB ORDER = CICSXXX.CICS.XXXPROC
//CPLSTP EXEC DFHEITVL
//TRN.SYSIN DD DSN = ABC.XYZ.PDS(HELLO),DISP = SHR
//LKED.SYSIN DD *
NAME HELLO(R)
//
Open a CICS session.
We will now install the program using the following command −
CEMT SET PROG(HELLO) NEW.
Execute the program using the associated transaction-id. Transaction-id is provided by the Administrator. It will show the following output −
The following flowchart shows the steps used in compiling a COBOL-CICS program −
The function of a translator is to check for syntax errors in CICS commands. It translates them into equivalent COBOL statements.
The function of a compiler is to expand the COBOL copy books. It compiles the code after checking the source code for syntax errors.
The function of a Linkage Editor is to link different object modules to create a single load module.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2087,
"s": 1926,
"text": "CICS programs are written in COBOL language in Mainframes. We will be discussing about writing a simple COBOL-CICS program, compiling it, and then executing it."
},
{
"code": null,
"e": 2325,
"s": 2087,
"text": "We will be writing a simple COBOL-CICS program which displays some message on the CICS output screen. This program is to demonstrate the steps involved in executing a COBOL-CICS program. Following are the steps to code a simple program −"
},
{
"code": null,
"e": 2369,
"s": 2325,
"text": "Login to Mainframes and open a TSO Session."
},
{
"code": null,
"e": 2426,
"s": 2369,
"text": "Create a new PDS in which we will be coding our program."
},
{
"code": null,
"e": 2494,
"s": 2426,
"text": "Create a new member inside the PDS and code the following program −"
},
{
"code": null,
"e": 2868,
"s": 2494,
"text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\nDATA DIVISION.\nFILE SECTION.\nWORKING-STORAGE SECTION.\n01 WS-MESSAGE PIC X(40).\n01 WS-LENGTH PIC S9(4) COMP.\nPROCEDURE DIVISION.\nA000-MAIN-PARA.\n MOVE 'Hello World' TO WS-MESSAGE\n MOVE '+12' TO WS-LENGTH\n EXEC CICS SEND TEXT \n FROM (WS-MESSAGE)\n LENGHT(WS-LENGTH) \n END-EXEC\n EXEC CICS RETURN\n END-EXEC.\t \n"
},
{
"code": null,
"e": 2970,
"s": 2868,
"text": "After coding the program, we need to compile it. We can compile the program using the following JCL −"
},
{
"code": null,
"e": 3485,
"s": 2970,
"text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C \n//CICSCOB EXEC CICSCOB, \n//COPYLIB = ABC.XYZ.COPYLIB, \n//LOADLIB = ABC.XYZ.LOADLIB \n//LIB JCLLIB ORDER = CICSXXX.CICS.XXXPROC \n//CPLSTP EXEC DFHEITVL \n//TRN.SYSIN DD DSN = ABC.XYZ.PDS(HELLO),DISP = SHR \n//LKED.SYSIN DD * \n NAME HELLO(R) \n//\n"
},
{
"code": null,
"e": 3506,
"s": 3485,
"text": "Open a CICS session."
},
{
"code": null,
"e": 3568,
"s": 3506,
"text": "We will now install the program using the following command −"
},
{
"code": null,
"e": 3595,
"s": 3568,
"text": "CEMT SET PROG(HELLO) NEW.\n"
},
{
"code": null,
"e": 3737,
"s": 3595,
"text": "Execute the program using the associated transaction-id. Transaction-id is provided by the Administrator. It will show the following output −"
},
{
"code": null,
"e": 3818,
"s": 3737,
"text": "The following flowchart shows the steps used in compiling a COBOL-CICS program −"
},
{
"code": null,
"e": 3948,
"s": 3818,
"text": "The function of a translator is to check for syntax errors in CICS commands. It translates them into equivalent COBOL statements."
},
{
"code": null,
"e": 4081,
"s": 3948,
"text": "The function of a compiler is to expand the COBOL copy books. It compiles the code after checking the source code for syntax errors."
},
{
"code": null,
"e": 4182,
"s": 4081,
"text": "The function of a Linkage Editor is to link different object modules to create a single load module."
},
{
"code": null,
"e": 4189,
"s": 4182,
"text": " Print"
},
{
"code": null,
"e": 4200,
"s": 4189,
"text": " Add Notes"
}
] |
Pandas with Dask, For an Ultra-Fast Notebook | by Kunal Dhariwal | Towards Data Science
|
If you are into the data world then the need of using pandas might occur very frequently. Well, we all are also aware of one thing that Pandas is amazing and is more like a boon to the data world. Most of us spend at least a few minutes or even hours using pandas for data manipulation and day to day analysis. Pandas does not need much introduction but here are a few things that you should be aware of:
pandas is well suited for many different kinds of data:
Tabular data with heterogeneously-typed columns, as in an SQL table or Excel spreadsheet
Ordered and unordered (not necessarily fixed-frequency) time-series data.
Arbitrary matrix data (homogeneously typed or heterogeneous) with row and column labels
Any other form of observational/statistical data sets. The data need not be labeled at all to be placed into a pandas data structure.
Using pandas with gigabytes or terabytes of data is more like a pain in the notebook :D. I frequently use files that are into GBs and the notebook goes like “wait a minute, let me freeze now!”. By the way, my system has some amazing configuration. Dealing with a humongous amount of data cannot be done using pandas, Hence that’s where we have to start using dask. In this article I’ll demonstrate how you can use pandas with dask and speed up your notebook. In dask, reading GBs of files takes only a few seconds. Before jumping onto the demo, let me give you a brief introduction about dask.
Dask:
Dask has 3 parallel collections namely Dataframes, Bags, and Arrays. Which enables it to store data that is larger than RAM. Each of these can use data partitioned between RAM and a hard disk as well distributed across multiple nodes in a cluster. A Dask DataFrame is partitioned row-wise, grouping rows by index value for efficiency. These Pandas objects may live on disk or other machines. Dask DataFrames coordinate many Pandas DataFrames or Series arranged along the index
Dask can enable efficient parallel computations on single machines by leveraging their multi-core CPUs and streaming data efficiently from disk. It can run on a distributed cluster. Dask also allows the user to replace clusters with a single-machine scheduler which would bring down the overhead. These schedulers require no setup and can run entirely within the same process as the user’s session. Few other things about dask:
The ability to work in parallel with NumPy array and Pandas DataFrame objects
integration with other projects.
Distributed computing
Faster operation because of its low overhead and minimum serialization
Runs resiliently on clusters with thousands of cores
Real-time feedback and diagnostics
Demonstration:
The entire code used for this demonstration can be found in my Github repo and you can find the link at the end of this article. Now, let’s jump on to the demo:
Importing the libraries:
Code to calculate elapsed time and file size:
The first snippet is to calculate the elapsed time for an operation that we perform in here, for example: reading a file. In the second snippet we are displaying the file size that we’ll be using for this demo. The file size is around 4GB.
First, we’ll see a few things Dask
is better at and then we’ll skip to the things that pandas does better. This will help you to combine these two libraries and perform your analysis.
Reading a file — Pandas & Dask:
Pandas took around 5 minutes to read a file of size 4gb. Wait, the size is not everything, the number of columns and rows present in a data set plays a major role in the time consumption. Let’s see how much time Dask takes for the same file.
Holy moly, It just took around 2 milliseconds to read the same file whereas pandas took around 5 minutes. Isn’t it just amazing? Let’s perform some more operations on both the pandas data frame and the dask data frame.
Appending two files — Pandas & Dask:
To perform this operation, we’ll be reading another file and then append it to the previous one.
It took around 9 minutes to perform the above-mentioned operations. Now let’s see how we can optimize it by using Dask.
Well, Well, you just saved around another 9 minutes there. Let us see now other frequently used this we do with pandas.
Grouping the data — Pandas & Dask:
Pandas took over 6 minutes to do a simple grouping. Let’s see now how much more time we can save with dask.
Woah, you just saved whooping 6 minutes again. There numerous other things where you can save much more time if you are using dask.
Merging the datasets — Pandas & Dask:
So this is what happened. It tried for like 30 minutes and still couldn’t merge those two files with pandas. Let’s see if we can do it by using dask.
Well, It barely took me a second to do it using dask. What just happened is, Unlike pandas.read_csv which reads in the entire file before inferring data types, dask.dataframe.read_csv only reads in a sample from the beginning of the file (or first file if using a glob). These inferred data types are then enforced when reading all partitions.
Sorting — Pandas & Dask:
I tried to sort the data frame based on the values in a column and it took me around a minute and a half, that’s pretty decent. Let’s see how dask can help us with this.
Unfortunately, dask cannot even start this task because dask has no functionality of sorting although it uses pandas API. All hail pandas!
Unique & notNA — Pandas & Dask:
It took around only 1 minute to get these tasks done. Pandas does most of the things pretty well but screws in quite a few.
Dask does not support these two things as well. There are numerous other things for which you’ll have to use pandas.
Saving a Dataframe to a file — Pandas & Dask:
Pandas does a good job of saving the file. It took around 3 minutes for me to save the filtered file.
Dask does not save the file properly. It breaks the file into multiple chunks and saves these files in a folder with that mentioned name. Another problem is that you can’t read this saved file ever again. It is just a waste of time.
The solution for saving a dask data frame to a file is to convert it into a pandas data frame like this and then save the pandas data frame to a file.
Conclusion:
It is always the best option to use pandas and dask together because one can fill other’s limitations very well. When used individually, I suppose that you might run into different issues. Hence, we conclude that Pandas with Dask can save you a lot of time and resources.
Note:
Dask is faster because it doesn’t really execute anything until we use .compute(). Although, This can save a lot, a lot of time and give us more speed!
Tip:
# Use this to make pandas run fasterpd.read_csv(filepath, engine = 'c')
Do let me know if you are aware of any better alternatives than dask.
Jupyter Notebook (Code used) : https://github.com/kunaldhariwal/Medium-12-Amazing-Pandas-NumPy-Functions
LinkedIn: https://bit.ly/2u4YPoF
I hope that this has helped you to enhance your knowledge base :)
Follow me for more!
BTW, Did you know you can also use Dask with pandas for free on Saturn Cloud Click Here, a scalable data science environment in the cloud. Teams can collaborate with powerful resources, jobs, deployments, and more.
Thanks for your read and valuable time!
|
[
{
"code": null,
"e": 577,
"s": 172,
"text": "If you are into the data world then the need of using pandas might occur very frequently. Well, we all are also aware of one thing that Pandas is amazing and is more like a boon to the data world. Most of us spend at least a few minutes or even hours using pandas for data manipulation and day to day analysis. Pandas does not need much introduction but here are a few things that you should be aware of:"
},
{
"code": null,
"e": 633,
"s": 577,
"text": "pandas is well suited for many different kinds of data:"
},
{
"code": null,
"e": 722,
"s": 633,
"text": "Tabular data with heterogeneously-typed columns, as in an SQL table or Excel spreadsheet"
},
{
"code": null,
"e": 796,
"s": 722,
"text": "Ordered and unordered (not necessarily fixed-frequency) time-series data."
},
{
"code": null,
"e": 884,
"s": 796,
"text": "Arbitrary matrix data (homogeneously typed or heterogeneous) with row and column labels"
},
{
"code": null,
"e": 1018,
"s": 884,
"text": "Any other form of observational/statistical data sets. The data need not be labeled at all to be placed into a pandas data structure."
},
{
"code": null,
"e": 1612,
"s": 1018,
"text": "Using pandas with gigabytes or terabytes of data is more like a pain in the notebook :D. I frequently use files that are into GBs and the notebook goes like “wait a minute, let me freeze now!”. By the way, my system has some amazing configuration. Dealing with a humongous amount of data cannot be done using pandas, Hence that’s where we have to start using dask. In this article I’ll demonstrate how you can use pandas with dask and speed up your notebook. In dask, reading GBs of files takes only a few seconds. Before jumping onto the demo, let me give you a brief introduction about dask."
},
{
"code": null,
"e": 1618,
"s": 1612,
"text": "Dask:"
},
{
"code": null,
"e": 2095,
"s": 1618,
"text": "Dask has 3 parallel collections namely Dataframes, Bags, and Arrays. Which enables it to store data that is larger than RAM. Each of these can use data partitioned between RAM and a hard disk as well distributed across multiple nodes in a cluster. A Dask DataFrame is partitioned row-wise, grouping rows by index value for efficiency. These Pandas objects may live on disk or other machines. Dask DataFrames coordinate many Pandas DataFrames or Series arranged along the index"
},
{
"code": null,
"e": 2523,
"s": 2095,
"text": "Dask can enable efficient parallel computations on single machines by leveraging their multi-core CPUs and streaming data efficiently from disk. It can run on a distributed cluster. Dask also allows the user to replace clusters with a single-machine scheduler which would bring down the overhead. These schedulers require no setup and can run entirely within the same process as the user’s session. Few other things about dask:"
},
{
"code": null,
"e": 2601,
"s": 2523,
"text": "The ability to work in parallel with NumPy array and Pandas DataFrame objects"
},
{
"code": null,
"e": 2634,
"s": 2601,
"text": "integration with other projects."
},
{
"code": null,
"e": 2656,
"s": 2634,
"text": "Distributed computing"
},
{
"code": null,
"e": 2727,
"s": 2656,
"text": "Faster operation because of its low overhead and minimum serialization"
},
{
"code": null,
"e": 2780,
"s": 2727,
"text": "Runs resiliently on clusters with thousands of cores"
},
{
"code": null,
"e": 2815,
"s": 2780,
"text": "Real-time feedback and diagnostics"
},
{
"code": null,
"e": 2830,
"s": 2815,
"text": "Demonstration:"
},
{
"code": null,
"e": 2991,
"s": 2830,
"text": "The entire code used for this demonstration can be found in my Github repo and you can find the link at the end of this article. Now, let’s jump on to the demo:"
},
{
"code": null,
"e": 3016,
"s": 2991,
"text": "Importing the libraries:"
},
{
"code": null,
"e": 3062,
"s": 3016,
"text": "Code to calculate elapsed time and file size:"
},
{
"code": null,
"e": 3302,
"s": 3062,
"text": "The first snippet is to calculate the elapsed time for an operation that we perform in here, for example: reading a file. In the second snippet we are displaying the file size that we’ll be using for this demo. The file size is around 4GB."
},
{
"code": null,
"e": 3337,
"s": 3302,
"text": "First, we’ll see a few things Dask"
},
{
"code": null,
"e": 3486,
"s": 3337,
"text": "is better at and then we’ll skip to the things that pandas does better. This will help you to combine these two libraries and perform your analysis."
},
{
"code": null,
"e": 3518,
"s": 3486,
"text": "Reading a file — Pandas & Dask:"
},
{
"code": null,
"e": 3760,
"s": 3518,
"text": "Pandas took around 5 minutes to read a file of size 4gb. Wait, the size is not everything, the number of columns and rows present in a data set plays a major role in the time consumption. Let’s see how much time Dask takes for the same file."
},
{
"code": null,
"e": 3979,
"s": 3760,
"text": "Holy moly, It just took around 2 milliseconds to read the same file whereas pandas took around 5 minutes. Isn’t it just amazing? Let’s perform some more operations on both the pandas data frame and the dask data frame."
},
{
"code": null,
"e": 4016,
"s": 3979,
"text": "Appending two files — Pandas & Dask:"
},
{
"code": null,
"e": 4113,
"s": 4016,
"text": "To perform this operation, we’ll be reading another file and then append it to the previous one."
},
{
"code": null,
"e": 4233,
"s": 4113,
"text": "It took around 9 minutes to perform the above-mentioned operations. Now let’s see how we can optimize it by using Dask."
},
{
"code": null,
"e": 4353,
"s": 4233,
"text": "Well, Well, you just saved around another 9 minutes there. Let us see now other frequently used this we do with pandas."
},
{
"code": null,
"e": 4388,
"s": 4353,
"text": "Grouping the data — Pandas & Dask:"
},
{
"code": null,
"e": 4496,
"s": 4388,
"text": "Pandas took over 6 minutes to do a simple grouping. Let’s see now how much more time we can save with dask."
},
{
"code": null,
"e": 4628,
"s": 4496,
"text": "Woah, you just saved whooping 6 minutes again. There numerous other things where you can save much more time if you are using dask."
},
{
"code": null,
"e": 4666,
"s": 4628,
"text": "Merging the datasets — Pandas & Dask:"
},
{
"code": null,
"e": 4816,
"s": 4666,
"text": "So this is what happened. It tried for like 30 minutes and still couldn’t merge those two files with pandas. Let’s see if we can do it by using dask."
},
{
"code": null,
"e": 5160,
"s": 4816,
"text": "Well, It barely took me a second to do it using dask. What just happened is, Unlike pandas.read_csv which reads in the entire file before inferring data types, dask.dataframe.read_csv only reads in a sample from the beginning of the file (or first file if using a glob). These inferred data types are then enforced when reading all partitions."
},
{
"code": null,
"e": 5185,
"s": 5160,
"text": "Sorting — Pandas & Dask:"
},
{
"code": null,
"e": 5355,
"s": 5185,
"text": "I tried to sort the data frame based on the values in a column and it took me around a minute and a half, that’s pretty decent. Let’s see how dask can help us with this."
},
{
"code": null,
"e": 5494,
"s": 5355,
"text": "Unfortunately, dask cannot even start this task because dask has no functionality of sorting although it uses pandas API. All hail pandas!"
},
{
"code": null,
"e": 5526,
"s": 5494,
"text": "Unique & notNA — Pandas & Dask:"
},
{
"code": null,
"e": 5650,
"s": 5526,
"text": "It took around only 1 minute to get these tasks done. Pandas does most of the things pretty well but screws in quite a few."
},
{
"code": null,
"e": 5767,
"s": 5650,
"text": "Dask does not support these two things as well. There are numerous other things for which you’ll have to use pandas."
},
{
"code": null,
"e": 5813,
"s": 5767,
"text": "Saving a Dataframe to a file — Pandas & Dask:"
},
{
"code": null,
"e": 5915,
"s": 5813,
"text": "Pandas does a good job of saving the file. It took around 3 minutes for me to save the filtered file."
},
{
"code": null,
"e": 6148,
"s": 5915,
"text": "Dask does not save the file properly. It breaks the file into multiple chunks and saves these files in a folder with that mentioned name. Another problem is that you can’t read this saved file ever again. It is just a waste of time."
},
{
"code": null,
"e": 6299,
"s": 6148,
"text": "The solution for saving a dask data frame to a file is to convert it into a pandas data frame like this and then save the pandas data frame to a file."
},
{
"code": null,
"e": 6311,
"s": 6299,
"text": "Conclusion:"
},
{
"code": null,
"e": 6583,
"s": 6311,
"text": "It is always the best option to use pandas and dask together because one can fill other’s limitations very well. When used individually, I suppose that you might run into different issues. Hence, we conclude that Pandas with Dask can save you a lot of time and resources."
},
{
"code": null,
"e": 6589,
"s": 6583,
"text": "Note:"
},
{
"code": null,
"e": 6741,
"s": 6589,
"text": "Dask is faster because it doesn’t really execute anything until we use .compute(). Although, This can save a lot, a lot of time and give us more speed!"
},
{
"code": null,
"e": 6746,
"s": 6741,
"text": "Tip:"
},
{
"code": null,
"e": 6818,
"s": 6746,
"text": "# Use this to make pandas run fasterpd.read_csv(filepath, engine = 'c')"
},
{
"code": null,
"e": 6888,
"s": 6818,
"text": "Do let me know if you are aware of any better alternatives than dask."
},
{
"code": null,
"e": 6993,
"s": 6888,
"text": "Jupyter Notebook (Code used) : https://github.com/kunaldhariwal/Medium-12-Amazing-Pandas-NumPy-Functions"
},
{
"code": null,
"e": 7026,
"s": 6993,
"text": "LinkedIn: https://bit.ly/2u4YPoF"
},
{
"code": null,
"e": 7092,
"s": 7026,
"text": "I hope that this has helped you to enhance your knowledge base :)"
},
{
"code": null,
"e": 7112,
"s": 7092,
"text": "Follow me for more!"
},
{
"code": null,
"e": 7327,
"s": 7112,
"text": "BTW, Did you know you can also use Dask with pandas for free on Saturn Cloud Click Here, a scalable data science environment in the cloud. Teams can collaborate with powerful resources, jobs, deployments, and more."
}
] |
Program to find the maximum profit we can get by buying on stock market once in Python
|
Suppose we have a list of prices representing the stock prices of a company in chronological sequence, we have to find the maximum profit we could have made from buying and selling that stock only once. We have to keep in mind that we must buy before we can sell it.
So, if the input is like prices = [10, 12, 9, 6, 8, 12], then the output will be 6, as we can buy at 6 and sell at 12.
To solve this, we will follow these steps −
max_profit := 0
min_stock := infinity
for each price in prices, domax_profit := maximum of max_profit and (price - min_stock)min_stock := minimum of min_stock and price
max_profit := maximum of max_profit and (price - min_stock)
min_stock := minimum of min_stock and price
return max_profit
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, prices):
max_profit = 0
min_stock = float('inf')
for price in prices:
max_profit = max(max_profit, price - min_stock)
min_stock = min(min_stock, price)
return max_profit
ob = Solution()
print(ob.solve([10, 12, 9, 6, 8, 12]))
[10, 12, 9, 6, 8, 12]
6
|
[
{
"code": null,
"e": 1329,
"s": 1062,
"text": "Suppose we have a list of prices representing the stock prices of a company in chronological sequence, we have to find the maximum profit we could have made from buying and selling that stock only once. We have to keep in mind that we must buy before we can sell it."
},
{
"code": null,
"e": 1448,
"s": 1329,
"text": "So, if the input is like prices = [10, 12, 9, 6, 8, 12], then the output will be 6, as we can buy at 6 and sell at 12."
},
{
"code": null,
"e": 1492,
"s": 1448,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1508,
"s": 1492,
"text": "max_profit := 0"
},
{
"code": null,
"e": 1530,
"s": 1508,
"text": "min_stock := infinity"
},
{
"code": null,
"e": 1661,
"s": 1530,
"text": "for each price in prices, domax_profit := maximum of max_profit and (price - min_stock)min_stock := minimum of min_stock and price"
},
{
"code": null,
"e": 1721,
"s": 1661,
"text": "max_profit := maximum of max_profit and (price - min_stock)"
},
{
"code": null,
"e": 1765,
"s": 1721,
"text": "min_stock := minimum of min_stock and price"
},
{
"code": null,
"e": 1783,
"s": 1765,
"text": "return max_profit"
},
{
"code": null,
"e": 1853,
"s": 1783,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1864,
"s": 1853,
"text": " Live Demo"
},
{
"code": null,
"e": 2166,
"s": 1864,
"text": "class Solution:\n def solve(self, prices):\n max_profit = 0\n min_stock = float('inf')\n for price in prices:\n max_profit = max(max_profit, price - min_stock)\n min_stock = min(min_stock, price)\n return max_profit\nob = Solution()\nprint(ob.solve([10, 12, 9, 6, 8, 12]))"
},
{
"code": null,
"e": 2188,
"s": 2166,
"text": "[10, 12, 9, 6, 8, 12]"
},
{
"code": null,
"e": 2190,
"s": 2188,
"text": "6"
}
] |
How can we Implement a Queue using Stack in Java?
|
A Queue class extends Collection interface and it supports the insert and removes operations using a first-in-first-out (FIFO). A Stack is a subclass of Vector class and it represents last-in-first-out (LIFO) stack of objects. The last element added at the top of the stack (In) can be the first element to be removed (Out) from the stack. We can also implement a Queue using Stack in the below program.
import java.util.*;
public class QueueUsingStackTest {
private Stack stack1 = new Stack<>();
private Stack stack2 = new Stack<>();
public void enqueue(int element) {
stack1.push(element);
System.out.println(element + " inserted");
}
public void dequeue() {
if(stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
System.out.println(stack2.pop() + " removed");
}
public static void main(String args[]) {
QueueUsingStackTest test = new QueueUsingStackTest();
test.enqueue(10);
test.enqueue(50);
test.enqueue(100);
test.dequeue();
}
}
10 inserted
50 inserted
100 inserted
10 removed
|
[
{
"code": null,
"e": 1467,
"s": 1062,
"text": "A Queue class extends Collection interface and it supports the insert and removes operations using a first-in-first-out (FIFO). A Stack is a subclass of Vector class and it represents last-in-first-out (LIFO) stack of objects. The last element added at the top of the stack (In) can be the first element to be removed (Out) from the stack. We can also implement a Queue using Stack in the below program."
},
{
"code": null,
"e": 2139,
"s": 1467,
"text": "import java.util.*;\npublic class QueueUsingStackTest {\n private Stack stack1 = new Stack<>();\n private Stack stack2 = new Stack<>();\n public void enqueue(int element) {\n stack1.push(element);\n System.out.println(element + \" inserted\");\n }\n public void dequeue() {\n if(stack2.isEmpty()) {\n while (!stack1.isEmpty()) {\n stack2.push(stack1.pop());\n }\n }\n System.out.println(stack2.pop() + \" removed\");\n }\n public static void main(String args[]) {\n QueueUsingStackTest test = new QueueUsingStackTest();\n test.enqueue(10);\n test.enqueue(50);\n test.enqueue(100);\n test.dequeue();\n }\n}"
},
{
"code": null,
"e": 2187,
"s": 2139,
"text": "10 inserted\n50 inserted\n100 inserted\n10 removed"
}
] |
Count pairs of similar rectangles possible from a given array - GeeksforGeeks
|
08 Apr, 2022
Given a 2D array A[][2] of size N (1 ≤ N ≤ 103), where A[i][0] and A[i][1] denotes the length and breadth of rectangle i respectively.
Two rectangle i and j where (i < j) are similar if the ratio of their length and breadth is equal
A[i][0] / A[i][1] = A[j][0] / A[j][1]
The task is to count the pair of rectangles that are nearly similar.
Examples:
Input : A[][2] = {{4, 8}, {15, 30}, {3, 6}, {10, 20}}Output: 6Explanation: Pairs of similar rectangles are (0, 1), {0, 2), (0, 3), (1, 2), (1, 3), (2, 3). For every rectangle, ratio of length : breadth is 1 : 2
Input : A[][2] = {{2, 3}, {4, 5}, {7, 8}}Output: 0Explanation: No pair of similar rectangles exists.
Method 1 (Simple Comparison Method)
Approach: Follow the steps to solve the problem
Traverse the array.
For every pair such that (i < j), check whether the rectangles are similar or not by checking if the condition A[i][0] / A[i][1] = A[j][0] / A[j][1] is satisfied or not.
If found to be true, increment the count.
Finally, print the count obtained.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach #include <iostream>using namespace std; // Function to calculate the count// of similar rectanglesint getCount(int rows, int columns, int A[][2]){ int res = 0; for (int i = 0; i < rows; i++) { for (int j = i + 1; j < rows; j++) { if (A[i][0] * 1LL * A[j][1] == A[i][1] * 1LL * A[j][0]) { res++; } } } return res;} // Driver Codeint main(){ // Input int A[][2] = { { 4, 8 }, { 10, 20 }, { 15, 30 }, { 3, 6 } }; int columns = 2; int rows = sizeof(A) / sizeof(A[0]); cout << getCount(rows, columns, A); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to calculate the count// of similar rectanglesstatic int getCount(int rows, int columns, int[][] A){ int res = 0; for(int i = 0; i < rows; i++) { for(int j = i + 1; j < rows; j++) { if (A[i][0] * A[j][1] == A[i][1] * A[j][0]) { res++; } } } return res;} // Driver Codepublic static void main(String[] args){ // Input int[][] A = { { 4, 8 }, { 10, 20 }, { 15, 30 }, { 3, 6 } }; int columns = 2; int rows = 4; System.out.print(getCount(rows, columns, A));}} // This code is contributed by code_hunt.
# Python3 program for the above approach # Function to calculate the count# of similar rectanglesdef getCount(rows, columns, A): res = 0 for i in range(rows): for j in range(i + 1, rows, 1): if (A[i][0] * A[j][1] == A[i][1] * A[j][0]): res += 1 return res # Driver Codeif __name__ == '__main__': # Input A = [ [ 4, 8 ], [ 10, 20 ], [ 15, 30 ], [ 3, 6 ] ] columns = 2 rows = len(A) print(getCount(rows, columns, A)) # This code is contributed by SURENDRA_GANGWAR
// C# program for the above approachusing System; class GFG{ // Function to calculate the count// of similar rectanglesstatic int getCount(int rows, int columns, int[,] A){ int res = 0; for(int i = 0; i < rows; i++) { for(int j = i + 1; j < rows; j++) { if (A[i, 0] * A[j, 1] == A[i, 1] * A[j, 0]) { res++; } } } return res;} // Driver codestatic void Main(){ // Input int[,] A = { { 4, 8 }, { 10, 20 }, { 15, 30 }, { 3, 6 } }; int columns = 2; int rows = 4; Console.Write(getCount(rows, columns, A));}} // This code is contributed by divyesh072019
<script> // Javascript program for the above approach // Function to calculate the count// of similar rectanglesfunction getCount(rows, columns, A){ var res = 0; for(var i = 0; i < rows; i++) { for(var j = i + 1; j < rows; j++) { if (A[i][0] * A[j][1] == A[i][1] * A[j][0]) { res++; } } } return res;} // Driver Code // Inputvar A = [ [ 4, 8 ], [ 10, 20 ], [ 15, 30 ], [ 3, 6 ] ];var columns = 2;var rows = 4; document.write(getCount(rows, columns, A)); // This code is contributed by kirti </script>
6
Time Complexity: O(N2)Auxiliary Space: O(1)
Method 2 (Using HashMap)
Instead of comparing one rectangle’s ratio to another rectangle’s directly, we can store all the calculated ratios in the HashMap. Since HashMap has the access cost of O(1), that would allow a fast lookup for other rectangles with the same ratio and store them together. The number of pairs of similar rectangles can be derived from the number of rectangles with the same ratio using \frac{N \times (N – 1)}{2}. The reason one can use the mentioned equation to find the number of pairs of similar rectangles is that the number of pairs increases by each time a rectangle with the same ratio is added.
C++
Java
Python3
C#
Javascript
// C++ Program for the hashmap Approach#include <iostream>#include <unordered_map>using namespace std; // Get the count of all pairs of similar rectangles int getCount(int rows, int columns, int sides[][2]){ // Initialize the result value and // map to store the ratio to the rectangles int ans = 0; unordered_map<double, int> umap; // Calculate the rectangular ratio and save them for (int i = 0; i < rows; i++) { double ratio = (double)sides[i][0] / sides[i][1]; umap[ratio]++; } // Calculate pairs of similar rectangles from its common ratio for (auto x : umap) { int value = x.second; if (value > 1) { ans += (value * (value - 1)) / 2; } } return ans;} int main(){ int sides[4][2] = {{4, 8}, {10, 20}, {15, 30}, {3, 6}}; int rows = 4; int columns = 2; cout << getCount(rows, columns, sides); return 0; //this code is contributed by krishna_6431}
import java.util.*; class GFG { // Get the count of all pairs of similar rectangles public static int getCount(int rows, int columns, int[][] sides) { // Initialize the result value and // map to store the ratio to the rectangles int res = 0; Map<Double, Integer> ratio = new HashMap<Double, Integer>(); // Calculate the rectangular ratio and save them for (int i = 0; i < rows; i++) { double rectRatio = (double) sides[i][0] / sides[i][1]; if (ratio.get(rectRatio) == null) { ratio.put(rectRatio, 0); } ratio.put(rectRatio, ratio.get(rectRatio) + 1); } // Calculate pairs of similar rectangles from // its common ratio for (double key : ratio.keySet()) { int val = ratio.get(key); if (val > 1) { res += (val * (val - 1)) / 2; } } return res; } public static void main(String[] args) { int[][] A = {{4, 8}, {10, 20}, {15, 30}, {3, 6}}; int columns = 2; int rows = 4; System.out.println(getCount(rows, columns, A)); }} // This code is contributed by nathnet
# Python 3 Program for the hashmap Approachfrom collections import defaultdict # Get the count of all pairs of similar rectanglesdef getCount(rows, columns, sides): # Initialize the result value and # map to store the ratio to the rectangles ans = 0 umap = defaultdict(int) # Calculate the rectangular ratio and save them for i in range(rows): ratio = sides[i][0] / sides[i][1] umap[ratio] += 1 # Calculate pairs of similar rectangles from its common ratio for x in umap: value = umap[x] if (value > 1): ans += (value * (value - 1)) / 2 return ans # Driver codeif __name__ == "__main__": sides = [[4, 8], [10, 20], [15, 30], [3, 6]] rows = 4 columns = 2 print(int(getCount(rows, columns, sides))) # This code is contributed by ukasp.
using System;using System.Collections.Generic; class GFG { // Get the count of all pairs of similar rectangles public static int getCount(int rows, int columns, int[, ] sides) { // Initialize the result value and // map to store the ratio to the rectangles int res = 0; Dictionary<double, int> ratio = new Dictionary<double, int>(); // Calculate the rectangular ratio and save them for (int i = 0; i < rows; i++) { double rectRatio = (double)sides[i, 0] / sides[i, 1]; if (!ratio.ContainsKey(rectRatio)) { ratio[rectRatio] = 0; } ratio[rectRatio] = ratio[rectRatio] + 1; } // Calculate pairs of similar rectangles from // its common ratio foreach(KeyValuePair<double, int> p in ratio) { int val = p.Value; if (val > 1) { res += (val * (val - 1)) / 2; } } return res; } // Driver code public static void Main(string[] args) { int[, ] A = { { 4, 8 }, { 10, 20 }, { 15, 30 }, { 3, 6 } }; int columns = 2; int rows = 4; Console.WriteLine(getCount(rows, columns, A)); }} // This code is contributed by ukasp.
<script> // JavaScript Program for the hashmap Approach // Get the count of all pairs of similar rectanglesfunction getCount(rows, columns, sides){ // Initialize the result value and // map to store the ratio to the rectangles let ans = 0; let umap = new Map(); // Calculate the rectangular ratio and save them for (let i = 0; i < rows; i++) { let ratio = sides[i][0] / sides[i][1]; if(umap.has(ratio)){ umap.set(ratio,umap.get(ratio)+1); } else umap.set(ratio,1); } // Calculate pairs of similar rectangles from its common ratio for (let [x,y] of umap) { let value = y; if (value > 1) { ans += (value * (value - 1)) / 2; } } return ans;} // driver codelet sides = [[4, 8], [10, 20], [15, 30], [3, 6]];let rows = 4;let columns = 2;document.write(getCount(rows, columns, sides)); // This code is contributed by shinjanpatra </script>
6
Time Complexity: O(N)
Auxiliary Space: O(N)
divyesh072019
code_hunt
SURENDRA_GANGWAR
Kirti_Mangal
nathnet
krishna_6431
ukasp
yasharth234
shinjanpatra
Geometric-Lines
square-rectangle
Arrays
Geometric
Mathematical
Searching
Arrays
Searching
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Closest Pair of Points using Divide and Conquer algorithm
How to check if two given line segments intersect?
Program for distance between two points on earth
How to check if a given point lies inside or outside a polygon?
Find if two rectangles overlap
|
[
{
"code": null,
"e": 25626,
"s": 25598,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 25761,
"s": 25626,
"text": "Given a 2D array A[][2] of size N (1 ≤ N ≤ 103), where A[i][0] and A[i][1] denotes the length and breadth of rectangle i respectively."
},
{
"code": null,
"e": 25859,
"s": 25761,
"text": "Two rectangle i and j where (i < j) are similar if the ratio of their length and breadth is equal"
},
{
"code": null,
"e": 25897,
"s": 25859,
"text": "A[i][0] / A[i][1] = A[j][0] / A[j][1]"
},
{
"code": null,
"e": 25967,
"s": 25897,
"text": "The task is to count the pair of rectangles that are nearly similar. "
},
{
"code": null,
"e": 25978,
"s": 25967,
"text": "Examples: "
},
{
"code": null,
"e": 26189,
"s": 25978,
"text": "Input : A[][2] = {{4, 8}, {15, 30}, {3, 6}, {10, 20}}Output: 6Explanation: Pairs of similar rectangles are (0, 1), {0, 2), (0, 3), (1, 2), (1, 3), (2, 3). For every rectangle, ratio of length : breadth is 1 : 2"
},
{
"code": null,
"e": 26290,
"s": 26189,
"text": "Input : A[][2] = {{2, 3}, {4, 5}, {7, 8}}Output: 0Explanation: No pair of similar rectangles exists."
},
{
"code": null,
"e": 26326,
"s": 26290,
"text": "Method 1 (Simple Comparison Method)"
},
{
"code": null,
"e": 26375,
"s": 26326,
"text": "Approach: Follow the steps to solve the problem "
},
{
"code": null,
"e": 26395,
"s": 26375,
"text": "Traverse the array."
},
{
"code": null,
"e": 26565,
"s": 26395,
"text": "For every pair such that (i < j), check whether the rectangles are similar or not by checking if the condition A[i][0] / A[i][1] = A[j][0] / A[j][1] is satisfied or not."
},
{
"code": null,
"e": 26607,
"s": 26565,
"text": "If found to be true, increment the count."
},
{
"code": null,
"e": 26642,
"s": 26607,
"text": "Finally, print the count obtained."
},
{
"code": null,
"e": 26694,
"s": 26642,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26698,
"s": 26694,
"text": "C++"
},
{
"code": null,
"e": 26703,
"s": 26698,
"text": "Java"
},
{
"code": null,
"e": 26711,
"s": 26703,
"text": "Python3"
},
{
"code": null,
"e": 26714,
"s": 26711,
"text": "C#"
},
{
"code": null,
"e": 26725,
"s": 26714,
"text": "Javascript"
},
{
"code": "// C++ Program for the above approach #include <iostream>using namespace std; // Function to calculate the count// of similar rectanglesint getCount(int rows, int columns, int A[][2]){ int res = 0; for (int i = 0; i < rows; i++) { for (int j = i + 1; j < rows; j++) { if (A[i][0] * 1LL * A[j][1] == A[i][1] * 1LL * A[j][0]) { res++; } } } return res;} // Driver Codeint main(){ // Input int A[][2] = { { 4, 8 }, { 10, 20 }, { 15, 30 }, { 3, 6 } }; int columns = 2; int rows = sizeof(A) / sizeof(A[0]); cout << getCount(rows, columns, A); return 0;}",
"e": 27394,
"s": 26725,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to calculate the count// of similar rectanglesstatic int getCount(int rows, int columns, int[][] A){ int res = 0; for(int i = 0; i < rows; i++) { for(int j = i + 1; j < rows; j++) { if (A[i][0] * A[j][1] == A[i][1] * A[j][0]) { res++; } } } return res;} // Driver Codepublic static void main(String[] args){ // Input int[][] A = { { 4, 8 }, { 10, 20 }, { 15, 30 }, { 3, 6 } }; int columns = 2; int rows = 4; System.out.print(getCount(rows, columns, A));}} // This code is contributed by code_hunt.",
"e": 28131,
"s": 27394,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to calculate the count# of similar rectanglesdef getCount(rows, columns, A): res = 0 for i in range(rows): for j in range(i + 1, rows, 1): if (A[i][0] * A[j][1] == A[i][1] * A[j][0]): res += 1 return res # Driver Codeif __name__ == '__main__': # Input A = [ [ 4, 8 ], [ 10, 20 ], [ 15, 30 ], [ 3, 6 ] ] columns = 2 rows = len(A) print(getCount(rows, columns, A)) # This code is contributed by SURENDRA_GANGWAR",
"e": 28706,
"s": 28131,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to calculate the count// of similar rectanglesstatic int getCount(int rows, int columns, int[,] A){ int res = 0; for(int i = 0; i < rows; i++) { for(int j = i + 1; j < rows; j++) { if (A[i, 0] * A[j, 1] == A[i, 1] * A[j, 0]) { res++; } } } return res;} // Driver codestatic void Main(){ // Input int[,] A = { { 4, 8 }, { 10, 20 }, { 15, 30 }, { 3, 6 } }; int columns = 2; int rows = 4; Console.Write(getCount(rows, columns, A));}} // This code is contributed by divyesh072019",
"e": 29415,
"s": 28706,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to calculate the count// of similar rectanglesfunction getCount(rows, columns, A){ var res = 0; for(var i = 0; i < rows; i++) { for(var j = i + 1; j < rows; j++) { if (A[i][0] * A[j][1] == A[i][1] * A[j][0]) { res++; } } } return res;} // Driver Code // Inputvar A = [ [ 4, 8 ], [ 10, 20 ], [ 15, 30 ], [ 3, 6 ] ];var columns = 2;var rows = 4; document.write(getCount(rows, columns, A)); // This code is contributed by kirti </script>",
"e": 30026,
"s": 29415,
"text": null
},
{
"code": null,
"e": 30028,
"s": 30026,
"text": "6"
},
{
"code": null,
"e": 30072,
"s": 30028,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30097,
"s": 30072,
"text": "Method 2 (Using HashMap)"
},
{
"code": null,
"e": 30699,
"s": 30097,
"text": "Instead of comparing one rectangle’s ratio to another rectangle’s directly, we can store all the calculated ratios in the HashMap. Since HashMap has the access cost of O(1), that would allow a fast lookup for other rectangles with the same ratio and store them together. The number of pairs of similar rectangles can be derived from the number of rectangles with the same ratio using \\frac{N \\times (N – 1)}{2}. The reason one can use the mentioned equation to find the number of pairs of similar rectangles is that the number of pairs increases by each time a rectangle with the same ratio is added."
},
{
"code": null,
"e": 30703,
"s": 30699,
"text": "C++"
},
{
"code": null,
"e": 30708,
"s": 30703,
"text": "Java"
},
{
"code": null,
"e": 30716,
"s": 30708,
"text": "Python3"
},
{
"code": null,
"e": 30719,
"s": 30716,
"text": "C#"
},
{
"code": null,
"e": 30730,
"s": 30719,
"text": "Javascript"
},
{
"code": "// C++ Program for the hashmap Approach#include <iostream>#include <unordered_map>using namespace std; // Get the count of all pairs of similar rectangles int getCount(int rows, int columns, int sides[][2]){ // Initialize the result value and // map to store the ratio to the rectangles int ans = 0; unordered_map<double, int> umap; // Calculate the rectangular ratio and save them for (int i = 0; i < rows; i++) { double ratio = (double)sides[i][0] / sides[i][1]; umap[ratio]++; } // Calculate pairs of similar rectangles from its common ratio for (auto x : umap) { int value = x.second; if (value > 1) { ans += (value * (value - 1)) / 2; } } return ans;} int main(){ int sides[4][2] = {{4, 8}, {10, 20}, {15, 30}, {3, 6}}; int rows = 4; int columns = 2; cout << getCount(rows, columns, sides); return 0; //this code is contributed by krishna_6431}",
"e": 31693,
"s": 30730,
"text": null
},
{
"code": "import java.util.*; class GFG { // Get the count of all pairs of similar rectangles public static int getCount(int rows, int columns, int[][] sides) { // Initialize the result value and // map to store the ratio to the rectangles int res = 0; Map<Double, Integer> ratio = new HashMap<Double, Integer>(); // Calculate the rectangular ratio and save them for (int i = 0; i < rows; i++) { double rectRatio = (double) sides[i][0] / sides[i][1]; if (ratio.get(rectRatio) == null) { ratio.put(rectRatio, 0); } ratio.put(rectRatio, ratio.get(rectRatio) + 1); } // Calculate pairs of similar rectangles from // its common ratio for (double key : ratio.keySet()) { int val = ratio.get(key); if (val > 1) { res += (val * (val - 1)) / 2; } } return res; } public static void main(String[] args) { int[][] A = {{4, 8}, {10, 20}, {15, 30}, {3, 6}}; int columns = 2; int rows = 4; System.out.println(getCount(rows, columns, A)); }} // This code is contributed by nathnet",
"e": 32993,
"s": 31693,
"text": null
},
{
"code": "# Python 3 Program for the hashmap Approachfrom collections import defaultdict # Get the count of all pairs of similar rectanglesdef getCount(rows, columns, sides): # Initialize the result value and # map to store the ratio to the rectangles ans = 0 umap = defaultdict(int) # Calculate the rectangular ratio and save them for i in range(rows): ratio = sides[i][0] / sides[i][1] umap[ratio] += 1 # Calculate pairs of similar rectangles from its common ratio for x in umap: value = umap[x] if (value > 1): ans += (value * (value - 1)) / 2 return ans # Driver codeif __name__ == \"__main__\": sides = [[4, 8], [10, 20], [15, 30], [3, 6]] rows = 4 columns = 2 print(int(getCount(rows, columns, sides))) # This code is contributed by ukasp.",
"e": 33817,
"s": 32993,
"text": null
},
{
"code": "using System;using System.Collections.Generic; class GFG { // Get the count of all pairs of similar rectangles public static int getCount(int rows, int columns, int[, ] sides) { // Initialize the result value and // map to store the ratio to the rectangles int res = 0; Dictionary<double, int> ratio = new Dictionary<double, int>(); // Calculate the rectangular ratio and save them for (int i = 0; i < rows; i++) { double rectRatio = (double)sides[i, 0] / sides[i, 1]; if (!ratio.ContainsKey(rectRatio)) { ratio[rectRatio] = 0; } ratio[rectRatio] = ratio[rectRatio] + 1; } // Calculate pairs of similar rectangles from // its common ratio foreach(KeyValuePair<double, int> p in ratio) { int val = p.Value; if (val > 1) { res += (val * (val - 1)) / 2; } } return res; } // Driver code public static void Main(string[] args) { int[, ] A = { { 4, 8 }, { 10, 20 }, { 15, 30 }, { 3, 6 } }; int columns = 2; int rows = 4; Console.WriteLine(getCount(rows, columns, A)); }} // This code is contributed by ukasp.",
"e": 35149,
"s": 33817,
"text": null
},
{
"code": "<script> // JavaScript Program for the hashmap Approach // Get the count of all pairs of similar rectanglesfunction getCount(rows, columns, sides){ // Initialize the result value and // map to store the ratio to the rectangles let ans = 0; let umap = new Map(); // Calculate the rectangular ratio and save them for (let i = 0; i < rows; i++) { let ratio = sides[i][0] / sides[i][1]; if(umap.has(ratio)){ umap.set(ratio,umap.get(ratio)+1); } else umap.set(ratio,1); } // Calculate pairs of similar rectangles from its common ratio for (let [x,y] of umap) { let value = y; if (value > 1) { ans += (value * (value - 1)) / 2; } } return ans;} // driver codelet sides = [[4, 8], [10, 20], [15, 30], [3, 6]];let rows = 4;let columns = 2;document.write(getCount(rows, columns, sides)); // This code is contributed by shinjanpatra </script>",
"e": 36102,
"s": 35149,
"text": null
},
{
"code": null,
"e": 36104,
"s": 36102,
"text": "6"
},
{
"code": null,
"e": 36126,
"s": 36104,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 36148,
"s": 36126,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 36162,
"s": 36148,
"text": "divyesh072019"
},
{
"code": null,
"e": 36172,
"s": 36162,
"text": "code_hunt"
},
{
"code": null,
"e": 36189,
"s": 36172,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 36202,
"s": 36189,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 36210,
"s": 36202,
"text": "nathnet"
},
{
"code": null,
"e": 36223,
"s": 36210,
"text": "krishna_6431"
},
{
"code": null,
"e": 36229,
"s": 36223,
"text": "ukasp"
},
{
"code": null,
"e": 36241,
"s": 36229,
"text": "yasharth234"
},
{
"code": null,
"e": 36254,
"s": 36241,
"text": "shinjanpatra"
},
{
"code": null,
"e": 36270,
"s": 36254,
"text": "Geometric-Lines"
},
{
"code": null,
"e": 36287,
"s": 36270,
"text": "square-rectangle"
},
{
"code": null,
"e": 36294,
"s": 36287,
"text": "Arrays"
},
{
"code": null,
"e": 36304,
"s": 36294,
"text": "Geometric"
},
{
"code": null,
"e": 36317,
"s": 36304,
"text": "Mathematical"
},
{
"code": null,
"e": 36327,
"s": 36317,
"text": "Searching"
},
{
"code": null,
"e": 36334,
"s": 36327,
"text": "Arrays"
},
{
"code": null,
"e": 36344,
"s": 36334,
"text": "Searching"
},
{
"code": null,
"e": 36357,
"s": 36344,
"text": "Mathematical"
},
{
"code": null,
"e": 36367,
"s": 36357,
"text": "Geometric"
},
{
"code": null,
"e": 36465,
"s": 36367,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36533,
"s": 36465,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36581,
"s": 36533,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36625,
"s": 36581,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36657,
"s": 36625,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36680,
"s": 36657,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36738,
"s": 36680,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 36789,
"s": 36738,
"text": "How to check if two given line segments intersect?"
},
{
"code": null,
"e": 36838,
"s": 36789,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 36902,
"s": 36838,
"text": "How to check if a given point lies inside or outside a polygon?"
}
] |
Mobile Marketing Campaigns: ROAS (Return On Ad Spend) | by Gonçalo Guimarães Gomes | Towards Data Science
|
As a marketing data analyst, the job is to combine efforts to properly conduct a digital marketing data analysis to accurately monitor and evaluate the performance of all of the company’s ongoing digital actions and campaigns.
What I am specifically referring to is the creation of an effective analytical system capable of monitoring the metrics and key performance indicators, from which it is possible to measure and optimize the results of the digital operational efforts our marketing department team is conducting.
The dataset contains information collected during the 1 month since each activation, of some marketing campaigns (Vungle and Facebook partners), implemented to get users to install and try out a mobile application, specifically an online game for Android and iOS smartphones.
The goal is to determine the overall performance and monitor the return on ads spend (ROAS) along the period of analysis delivering updates insights to the marketing department.
Media source (the name of the advertising partner)
Campaign name (the name of the advertising campaign)
Cost (the spend on marketing)
Installs (the number of installs generated)
D01 Total Revenue
D03 Total Revenue
D07 Total Revenue
D30 Total Revenue
The Dx Total Revenue is the total revenue generated within the first x days after the install from users who installed as a direct response to a specific marketing campaign.
CPI (Cost Per Install) CPI = Cost of Campaign / App Installs
Dx ROAS (Return On Ads Spend) in wich x = [1, 3, 7, 30]ROAS is a measurement that determines the efficacy of a digital advertising campaign and it can be understood as the following:ROAS = Total Campaign Revenue / Ad Campaign Costs
The following are some of the business questions we will be answering:
Q1. Are there more Vungle or Facebook campaigns?
Q2. Which partner’s campaign has generated more user installs?
Q3. Of how much is the overall CPI of Facebook?
Q4. How many Facebook campaigns have provided installs above the average?
Q5. Of how much is the overall CPI of Vungle?
Q6. How many Vungle campaigns have provided installs above the average?
Q7. Do both platforms have similar performance (cost vs. install)?
Q8. Of how much is the overall D30 ROAS of Facebook?
Q9. Of how much is the overall D30 ROAS of Vungle?
Q10. Overall Cost vs. D30_ROAS comparison of both platforms
Q11. Is there any correlation between the stages during the campaigns?
Q12. The campaigns with the highest ROAS have the highest Total Revenue?
Q13. Do the campaigns with a ROAS on DAY_1 under 10% break-even after the first month?
Q14. Is it safe to assume the campaigns with a ROAS on DAY_7 higher than 70% will break even after 30 days?
Q15. Monitoring the overall ROAS evolution of both platforms
We will be conducting this Exploratory Data Analysis in Python 3.You can find the entire code here.The ‘mkt_ua_campaigns.csv’ dataset can be downloaded here.
We will start by importing the Python libraries that will be needed (pandas, numpy, matplotlib.pyplot, seaborn and regex), loading the dataset from the CSV file, inspecting the number of rows (89 observations) and features (8 columns), no missing values, and displaying a few rows.
Notice there is an anomalous pattern with the values of the ‘Installs’ variable: when is a Facebook campaign, there is a comma separating the thousands, and there no comma in the Vungle campaigns.
Secondly, the features ‘Cost’, and D(01 to 30) Total Revenue expresses dollars as a categoric type, which includes the ‘$’ symbol.
To transform the variables’ data types into numeric, those issues must be solved and the dataset cleaned as follows.
# Lowering columns' capital letters for easy typingdf.columns = map(str.lower, df.columns)# Selecting columns cols= ["cost","installs","d01 total revenue","d03 total revenue","d07 total. revenue","d30 total revenue"]# Cleaning unvalid charactersdf[cols] = (df[cols].replace({‘,’:’’}, regex=True))df["cost"] = (df["cost"].str.replace('$','')).str.strip()df["d01 total revenue"] = (df["d01 total revenue"].str.replace('$','')).str.strip()df["d03 total revenue"] = (df["d03 total revenue"].str.replace('$','')).str.strip()df["d07 total revenue"] = (df["d07 total revenue"].str.replace('$','')).str.strip()df["d30 total revenue"] = (df["d30 total revenue"].str.replace('$','')).str.strip()# Transforming columns as float (numeric type)df[cols] = df[cols].astype(float).copy()
Now that we have all set up and ready to move forward, it is time to calculate our KPIs from which we’ll be able to analyze the performance of both the overall evolution and by zooming in a campaign by campaign.
First, I’ll start by determining the CPI (cost per install) of each campaign. To perform the calculation, we simply divide the cost of each campaign by the number of installations that each one has generated.
# Determine "Cost Per Install" in a new columndf["cpi"] = df.apply(lambda x: x["cost"] / x["installs"],axis=1)
Let’s also calculate the ROAS (return on ads spend) on the first, the third, the seventh, and the thirtieth days counting from the first day the user has installed the app. To do so, we divide the total revenue generated by the total cost of the campaign for each desired day.
# Calculations to determine "dx_roas" in new columnsdf["d01_roas"] = df.apply(lambda x: x["d01 total revenue"] / x["cost"], axis=1)df["d03_roas"] = df.apply(lambda x: x["d03 total revenue"] / x["cost"], axis=1)df["d07_roas"] = df.apply(lambda x: x["d07 total revenue"] / x["cost"], axis=1)df["d30_roas"] = df.apply(lambda x: x["d30 total revenue"] / x["cost"], axis=1)
Let’s display our final dataset and take a close look at our metrics and KPIs. From this point, we are ready to extract some important and relevant insights from the data.
From a total of 89 campaigns, 77 are running on Facebook and only 12 through the Vungle platform, corresponding to 87% and 13% respectively.
# Side tableabsolut = df["media source"].value_counts().to_frame()percent = (df["media source"].value_counts(normalize=True)*100).to_frame().rename(columns={"media source":"percent"})out_bal = pd.concat([absolut,percent],axis=1).round(decimals=2)display(out_bal)# Pie graphabsolut.plot(kind='pie', subplots=True, autopct='%1.2f%%', explode= (0.05, 0.05), startangle=80, legend=False, fontsize=12, figsize=(16,7))# Paramsplt.xticks(rotation=0, horizontalalignment="center")plt.title("Total marketing campaigns", fontsize=10, loc="right");
Vungle has generated a total of 242112 installs (55%) whereas Facebook is responsible for 197357 installs (45%).
# Bar plotax = df.groupby(["media source"])["installs"].sum().plot(kind="bar", figsize=(9,6), fontsize=12, color=sns.color_palette("rocket"), table=False)for p in ax.patches: ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 7), textcoords='offset points')# Paramsplt.xlabel("media source", fontsize=10)plt.xticks(rotation=0, horizontalalignment="center")plt.ylabel("Absolute frequency", fontsize=10)plt.title("Overall installs proportion", fontsize=10, loc="right")# side tableinstalls = df.groupby(["media source"])["installs"].sum().sort_values(ascending=False).to_frame()installs["percent"] = (installs.apply(lambda x: x/x.sum())*100).round(2)display(installs)
To find the overall CPI, we sum the costs of all Facebook campaigns and divide it by the total Facebook installs. The result is 1.97 dollars. For an easier calculation, we can select only the Facebook campaigns.
# Filtering records from Facebook onlyfb = df[["media source","cost","installs"]].copy()fb = fb[fb["media source"] == "Facebook"].copy()
# Calculating Costs Per Installing (Facebook)fb.cost.sum() / fb.installs.sum()>> 1.9671306312925307# Visualizing Costs vs. Installs sorted by highest costfb = fb.reset_index().copy()fb.drop(["index"], axis=1, inplace=True)fb.plot.line()plt.xlabel('Number of campaigns')plt.ylabel('Absolute Frequency')plt.title('Costs vs. Installs [Facebook]', fontsize=10, loc="right")plt.show()
2563 is the average number of installs per campaign. 14 Facebook campaigns have generated installs above the Facebook average, and only 6 Facebook campaigns have generated installs above the total average (4937).
# Filtering records from Facebook onlyfb_mean = df[df["media source"] == "Facebook"].copy()# Visualizing comparisons between Facebook campaings and between Facebook average campaings and total average campaignsax = fb_mean.groupby("campaign name")["installs"].mean().sort_values(ascending=False).head(15).plot(kind="bar", figsize=(16,9), fontsize=12, color=sns.color_palette("rocket"), table=False)# Paramsplt.xticks(rotation=30, horizontalalignment="right")plt.ylabel("Absolute values", fontsize=10)plt.xlabel("Facebook campaigns", fontsize=10)plt.title("Facebook campaigns vs. Facebook average installs", fontsize=10, loc="right")plt.axhline(fb_mean.groupby("campaign name")["installs"].mean().mean(), linewidth=2, color ="r")plt.axhline(df.groupby("campaign name")["installs"].mean().mean(), linewidth=2, color ="b")plt.legend(('Facebook average installs', 'Total average installs'))plt.tight_layout()
To determine the overall CPI of Vungle, the procedure is similar to the previous one in which we sum the costs of all Vungle campaigns and divide it by the total number of the Vungle installs. The result is 0.74 dollars. Again, we can select only the Vungle campaigns.
# Filtering records from Vungle onlyvun = df[["media source","cost","installs"]].copy()vun = vun[vun["media source"] == "Vungle"].copy()
# Calculating Costs Per Installing (Vungle)vun.cost.sum() / vun.installs.sum()>> 0.7351143272535026# Visualizing Costs vs. Installs sorted by highest costvun.reset_index(drop=True, inplace=True)vun.plot.line()plt.xlabel('Number of campaigns')plt.ylabel('Absolute Frequency')plt.title('Costs vs. Installs [Vungle]', fontsize=10, loc="right")plt.show()
20176 is the average number of installs per campaign. Only 3 Vungle campaigns have generated installs above the Vungle average, and 11 Vungle campaigns have generated installs above the total average (4937).
# Filtering records from Facebook onlyvn_mean = df[df["media source"] == "Vungle"].copy()# Visualizing comparisons between Vungle campaings and between Vungle average campaings and total average campaignsax = vn_mean.groupby("campaign name")["installs"].mean().sort_values(ascending=False).plot(kind="bar", figsize=(16,9), fontsize=12, color=sns.color_palette("rocket"), table=False)# Paramsplt.xticks(rotation=30, horizontalalignment="right")plt.ylabel("Absolute values", fontsize=10)plt.xlabel("Vungle campaigns", fontsize=10)plt.title("Vungle campaigns vs. average installs", fontsize=10, loc="right")plt.axhline(vn_mean.groupby("campaign name")["installs"].mean().mean(), linewidth=2, color ="r")plt.axhline(df.groupby("campaign name")["installs"].mean().mean(), linewidth=2, color ="b")plt.legend(('Vungle average installs', 'Total average installs'))plt.tight_layout()
Actually, there is a colossal difference between both platforms when the comparison is made in terms of cost vs. installations they generate.
With $177980 of total investment in the advertisement, Vungle is capable of generating 242112 installations, whereas Facebook generates 197357 installs but with an amount of $388227 invested.
# Concatenating both Facebook + Vungle datasetscpi2brand = pd.concat([fb, vun])# Bar plotax = cpi2brand.groupby(["media source"])[["cost","installs"]].sum().plot(kind="bar", figsize=(9,6), fontsize=12, color=sns.color_palette("rocket"), table=False)for p in ax.patches: ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 7), textcoords='offset points')# Paramsplt.xlabel("media source", fontsize=10)plt.xticks(rotation=0, horizontalalignment="center")plt.ylabel("Absolute frequency", fontsize=10)plt.title("Overall Cost vs Installs comparison [Facebook + Vungle]", fontsize=10, loc="right")# side tableinstalls = cpi2brand.groupby(["media source"])[["cost","installs"]].sum().sort_values(by="cost", ascending=False)display(installs)
To determine the Return On Ads Spend after 30 days, we need to sum the total revenue on the 30th day and divide it by the total invested on Facebook.
The result is that on the 30th day, 72,65% of ROAS was captured for Facebook.
# Selecting Facebook segment datasetfb_d30 = df[["media source","cost","d30 total revenue"]].copy()fb_d30 = fb_d30[fb_d30["media source"] == "Facebook"].copy()
# Calculating Return On Advert Spend (Facebook) over 30 daysfb_d30["d30 total revenue"].sum() / fb_d30.cost.sum()>> 0.7265414306578368# Visualizing Costs vs. installs over 30 days sorted by highest cost (Facebook)fb_d30.plot.line()plt.xlabel('Number of campaigns')plt.ylabel('Absolute Frequency')plt.title('Costs vs. d30 total revenue [Facebook]', fontsize=10, loc="right")plt.show()
To determine the D30 ROAS of Vungle, sum the total revenue on the 30th day, and divide it by the total invested on the platform.
The result is that on the 30th day, 92,88% of ROAS was captured for Vungle.
# Selecting Vungle segment datasetvun_d30 = df[["media source","cost","d30 total revenue"]].copy()vun_d30 = vun_d30[vun_d30["media source"] == "Vungle"].copy()
# Calculating Return On Ads Spend (Vungle) after 30 daysfb_d30["d30 total revenue"].sum() / fb_d30.cost.sum()>> 0.9287728958309922# Visualizing Costs vs. installs over 30 days sorted by highest cost (Vungle)vun_d30.plot.line()plt.xlabel('Number of campaigns')plt.ylabel('Absolute Frequency')plt.title('Costs vs. d30 total revenue [Vungle]', fontsize=10, loc="right")plt.show()
To determine this result, we must vertically concatenate (axis=0) the above sub-datasets of both D30_ROAS Facebook and Vungle, and then group them by their cost and the total revenue on the 30th day.
The result, displayed in the bar chart below, tells us that 30 days after, Vungle campaigns generated $165303 which is almost the revenue needed to reach that platform break-even point, translated by a total cost of $177980. On the opposite direction is Facebook with a total investment of $388277 and revenue of $282063.
# Concatenating both Facebook + Vungle datasetsroas2brand = pd.concat([fb_d30, vun_d30])# Bar plotax = roas2brand.groupby(["media source"])[["cost","d30 total revenue"]].sum().plot(kind="bar", figsize=(9,6), fontsize=12, color=sns.color_palette("rocket"), table=False)for p in ax.patches: ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 7), textcoords='offset points')# Paramsplt.xlabel("media source", fontsize=10)plt.xticks(rotation=0, horizontalalignment="center")plt.ylabel("Absolute frequency", fontsize=10)plt.title("Overall Cost vs Roas _d30 comparison [Facebook + Vungle]", fontsize=10, loc="right")# side tableroas = roas2brand.groupby(["media source"])[["cost","d30 total revenue"]].sum().sort_values(by="cost", ascending=False)display(roas)
Let’s display a correlation heatmap (Pearson method).
mask = np.triu(df.corr(), 1)plt.figure(figsize=(19, 9))sns.heatmap(df.corr(), annot=True, vmax=1, vmin=-1, square=False, cmap="BrBG", mask=mask);
From the analysis of the correlations map we can easily spot many strong correlations as one might be expecting. But what I am really interested in is to verify the correlation between the ROAS on day 1, 3 and 7 and ROAS on the 30th day.
The d30_ROAS has a positive and strong correlated with d01_ROAS of 71%, an even more strong and positive correlation with d03_ROAS, of 86%, but the strongest correlation is between d07_ROAS and d30_ROAS of 90.37%.
# Calculating corr. coef. between ROAS 7 days and 30 daysdf['d07_roas'].corr(df['d30_roas'])>> 0.9037410337635488# Display scatter plot: d07_ROAS and d30_ROASdf.plot(x="d07_roas", y="d30_roas", kind="scatter", figsize=(9,6), fontsize=12)plt.title("Correlation d07_ROAS and d30_ROAS", fontsize=10, loc="right")plt.xticks(rotation=0, horizontalalignment="center");
We need to check the campaigns with the maximum revenue for d01, d03, d07 and d30, and also the ones with the maximum ROAS for the exact same periods and compare both pairs to verify if they match.
Assigning maximum ROAS on 1st day, and maximum total revenue on 1st day.
# Selecting columns to work withhigh_d01 = df[["campaign name","cost","d01 total revenue","d01_roas"]].copy()
# Highest d01_roasd01_roas_max = high_d01['d01_roas'].max()high_d01.loc[high_d01['d01_roas'] == d01_roas_max, 'campaign name']>> 59 IMT-FB-Android-RoW2-AE-Playables-Feed# Highest d01 total revenued01_total_max = high_d01['d01 total revenue'].max()high_d01.loc[high_d01['d01 total revenue'] == d01_total_max, 'campaign name']>> 0 IMT-FB-iOS-EN-US-AE-Playables
The campaigns with the highest d01_roas and the highest d01 total revenue don’t match.
Assigning maximum ROAS on 3rd, and maximum total revenue on 3rd day.
# Selecting columns to work withhigh_d03 = df[["campaign name","cost","d03 total revenue","d03_roas"]].copy()
# Highest d03_roasd03_roas_max = high_d03['d03_roas'].max()high_d03.loc[high_d03['d03_roas'] == d03_roas_max, 'campaign name']>> 86 IMT-FB-Android-RoW2-AE-Value-Video-FANIS# Highest d03 total revenued03_total_max = high_d03['d03 total revenue'].max()high_d03.loc[high_d03['d03 total revenue'] == d03_total_max, 'campaign name']>> 0 IMT-FB-iOS-EN-US-AE-Playables
The campaigns with the highest d03_roas and the highest d03 total revenue don’t match.
Assigning maximum ROAS on 7th, and maximum total revenue on 7thday.
# Selecting columns to work withhigh_d07 = df[["campaign name","cost","d07 total revenue","d07_roas"]].copy()
# Highest d07_roasd07_roas_max = high_d07['d07_roas'].max()high_d07.loc[high_d07['d07_roas'] == d07_roas_max, 'campaign name']>> 86 IMT-FB-Android-RoW2-AE-Value-Video-FANIS# Highest d07 total revenud07_total_max = high_d07['d07 total revenue'].max()high_d07.loc[high_d07['d07 total revenue'] == d07_total_max, 'campaign name']>> 0 IMT-FB-iOS-EN-US-AE-Playables
The campaigns with the highest d07_roas and the highest d07 total revenue don’t match.
Assigning maximum ROAS on 30th, and maximum total revenue on 30th day.
# Selecting columns to work withhigh_d30 = df[["campaign name","cost","d30 total revenue","d30_roas"]].copy()
# Highest d30_roasd30_roas_max = high_d30['d30_roas'].max()high_d30.loc[high_d30['d30_roas'] == d30_roas_max, 'campaign name']>> 2 IMT-Vungle-iOS-CN# Highest d30 total revenued30_total_max = high_d30['d30 total revenue'].max()high_d30.loc[high_d30['d30 total revenue'] == d30_total_max, 'campaign name']>> 0 IMT-FB-iOS-EN-US-AE-Playables
The campaigns with the highest d30_roas and the highest d30 total revenue don’t match.
The threshold where the revenue reaches and gets equal to its costs determines the break-even point of a campaign.
To check if all campaings that start below 10% on the first day did not break-even after the 30 days, we need to select the campaigns who’s d01_ROAS would be lower than 10%, and select the campaigns from the segment in which the d30 total revenue is higher than or at least equal to its costs.
# Selecting campaigns segment of ROAS d01 under 10%d01_roas_under10 = d01_roas_under10[d01_roas_under10["d01_roas"] < 0.10].copy()# Filtering campaigns segment in wihch "d30 total revenue" is higher than its costd01_roas_under10[d01_roas_under10["d30 total revenue"] > d01_roas_under10["cost"]]
>> The 3 above campaings did break-even after 30 days.
Let’s select all the campaigns with a d07_ROAS higher than 70%, and select all the campaigns from the segment in which the d30 total revenue is lower than its costs.
# Selecting campaigns segment of ROAS 7 days above 70%d07_roas_up70 = df[df["d07_roas"] > 0.70].copy()
# Filtering campaigns segment in which "d30 total revenue" is lower than its cost(d07_roas_up70[d07_roas_up70["d30 total revenue"] < d07_roas_up70["cost"]]).values.any()>> False
All Campaigns with a D07 ROAS higher than 70% did break-even after 30 days.
In the next histogram, we can observe that the majority of campaigns with a ROAS on the 1st day is highly concentrated around 10% with a few campaigns reaching almost 20%.
On the other hand, after 3 days, the majority of campaigns is concentrated between 15% and 35% with some reaching a ROAS between 40% and 55% and even almost 80% in a few cases.
# Display histogram: d01_roas vs d03_roas evolution comparisond01_roas = df.d01_roasd03_roas = df.d03_roasd01 = np.array(d01_roas)d03 = np.array(d03_roas)plt.figure(figsize=(14,8))plt.hist(d01, bins=89, density=True, color="g", alpha = 0.7, label="d01_roas")plt.hist(d03, bins=89, density=True, color="r", alpha = 0.5, label="d03_roas")plt.legend(loc='upper right')plt.xlabel("Relative observations", fontsize=10)plt.xticks(rotation=0, horizontalalignment="center")plt.ylabel("Density scale", fontsize=10)plt.title("d01_roas vs. d03_roas", fontsize=10, loc="right")plt.show()
Although there is a big cluster of campaigns below 20% on the 3rd day, more than half are concentrated between 30% and 45% of ROAS. We can see that there are a few campaigns beyond 60% and even 100% surpassing the break-even.
As expected, after 30 days we can see a fair distribution of the campaigns from the d30_ROAS perspective. There is a cluster that didn’t even go beyond 20% and with this valuable information, the marketing team can investigate what went wrong with the campaigns that don’t have a great return on ad spend and redefine those operations.
To determine the overall performance and estimate the campaigns’ return on ad spend (ROAS), we have analyzed some important metrics and have made some KPI calculations concerning the amount invested in marketing operations and advertising, the number of well-succeeded app installations carried out by the users, and monitored the evolution of the partial return in each timeframe delivering important insights to the marketing team.
In a marketing environment, the metrics are indicators by which the results of tactic operations can be measured, such as purchases made on an e-commerce website, installations of a mobile application, the user’s behavior concerning exposure to an ad, and are not associated with any conversion goal, that is, to a specific objective.
On the other hand, the Key Performance Indicators (KPIs) are management tools that allow monitoring, evaluating and controlling the performance levels of a company, product, or service, regarding specific or general operational objectives, contributing to an overall understanding of the evolution, performance, impact, intensity, and direction of the results concerning the defined marketing strategy.
The marketing report is concluded but so much more could be deeper investigated and analysed from this point on.
You can find the entire code here.
The ‘mkt_ua_campaigns.csv’ dataset can be downloaded here.
Check out other articles you might also like:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Linkedin
Twitter
Medium
GitHub
Kaggle
Email
Good readings, great codings!
|
[
{
"code": null,
"e": 399,
"s": 172,
"text": "As a marketing data analyst, the job is to combine efforts to properly conduct a digital marketing data analysis to accurately monitor and evaluate the performance of all of the company’s ongoing digital actions and campaigns."
},
{
"code": null,
"e": 693,
"s": 399,
"text": "What I am specifically referring to is the creation of an effective analytical system capable of monitoring the metrics and key performance indicators, from which it is possible to measure and optimize the results of the digital operational efforts our marketing department team is conducting."
},
{
"code": null,
"e": 969,
"s": 693,
"text": "The dataset contains information collected during the 1 month since each activation, of some marketing campaigns (Vungle and Facebook partners), implemented to get users to install and try out a mobile application, specifically an online game for Android and iOS smartphones."
},
{
"code": null,
"e": 1147,
"s": 969,
"text": "The goal is to determine the overall performance and monitor the return on ads spend (ROAS) along the period of analysis delivering updates insights to the marketing department."
},
{
"code": null,
"e": 1198,
"s": 1147,
"text": "Media source (the name of the advertising partner)"
},
{
"code": null,
"e": 1251,
"s": 1198,
"text": "Campaign name (the name of the advertising campaign)"
},
{
"code": null,
"e": 1281,
"s": 1251,
"text": "Cost (the spend on marketing)"
},
{
"code": null,
"e": 1325,
"s": 1281,
"text": "Installs (the number of installs generated)"
},
{
"code": null,
"e": 1343,
"s": 1325,
"text": "D01 Total Revenue"
},
{
"code": null,
"e": 1361,
"s": 1343,
"text": "D03 Total Revenue"
},
{
"code": null,
"e": 1379,
"s": 1361,
"text": "D07 Total Revenue"
},
{
"code": null,
"e": 1397,
"s": 1379,
"text": "D30 Total Revenue"
},
{
"code": null,
"e": 1571,
"s": 1397,
"text": "The Dx Total Revenue is the total revenue generated within the first x days after the install from users who installed as a direct response to a specific marketing campaign."
},
{
"code": null,
"e": 1632,
"s": 1571,
"text": "CPI (Cost Per Install) CPI = Cost of Campaign / App Installs"
},
{
"code": null,
"e": 1864,
"s": 1632,
"text": "Dx ROAS (Return On Ads Spend) in wich x = [1, 3, 7, 30]ROAS is a measurement that determines the efficacy of a digital advertising campaign and it can be understood as the following:ROAS = Total Campaign Revenue / Ad Campaign Costs"
},
{
"code": null,
"e": 1935,
"s": 1864,
"text": "The following are some of the business questions we will be answering:"
},
{
"code": null,
"e": 1984,
"s": 1935,
"text": "Q1. Are there more Vungle or Facebook campaigns?"
},
{
"code": null,
"e": 2047,
"s": 1984,
"text": "Q2. Which partner’s campaign has generated more user installs?"
},
{
"code": null,
"e": 2095,
"s": 2047,
"text": "Q3. Of how much is the overall CPI of Facebook?"
},
{
"code": null,
"e": 2169,
"s": 2095,
"text": "Q4. How many Facebook campaigns have provided installs above the average?"
},
{
"code": null,
"e": 2215,
"s": 2169,
"text": "Q5. Of how much is the overall CPI of Vungle?"
},
{
"code": null,
"e": 2287,
"s": 2215,
"text": "Q6. How many Vungle campaigns have provided installs above the average?"
},
{
"code": null,
"e": 2354,
"s": 2287,
"text": "Q7. Do both platforms have similar performance (cost vs. install)?"
},
{
"code": null,
"e": 2407,
"s": 2354,
"text": "Q8. Of how much is the overall D30 ROAS of Facebook?"
},
{
"code": null,
"e": 2458,
"s": 2407,
"text": "Q9. Of how much is the overall D30 ROAS of Vungle?"
},
{
"code": null,
"e": 2518,
"s": 2458,
"text": "Q10. Overall Cost vs. D30_ROAS comparison of both platforms"
},
{
"code": null,
"e": 2589,
"s": 2518,
"text": "Q11. Is there any correlation between the stages during the campaigns?"
},
{
"code": null,
"e": 2662,
"s": 2589,
"text": "Q12. The campaigns with the highest ROAS have the highest Total Revenue?"
},
{
"code": null,
"e": 2749,
"s": 2662,
"text": "Q13. Do the campaigns with a ROAS on DAY_1 under 10% break-even after the first month?"
},
{
"code": null,
"e": 2857,
"s": 2749,
"text": "Q14. Is it safe to assume the campaigns with a ROAS on DAY_7 higher than 70% will break even after 30 days?"
},
{
"code": null,
"e": 2918,
"s": 2857,
"text": "Q15. Monitoring the overall ROAS evolution of both platforms"
},
{
"code": null,
"e": 3076,
"s": 2918,
"text": "We will be conducting this Exploratory Data Analysis in Python 3.You can find the entire code here.The ‘mkt_ua_campaigns.csv’ dataset can be downloaded here."
},
{
"code": null,
"e": 3358,
"s": 3076,
"text": "We will start by importing the Python libraries that will be needed (pandas, numpy, matplotlib.pyplot, seaborn and regex), loading the dataset from the CSV file, inspecting the number of rows (89 observations) and features (8 columns), no missing values, and displaying a few rows."
},
{
"code": null,
"e": 3555,
"s": 3358,
"text": "Notice there is an anomalous pattern with the values of the ‘Installs’ variable: when is a Facebook campaign, there is a comma separating the thousands, and there no comma in the Vungle campaigns."
},
{
"code": null,
"e": 3686,
"s": 3555,
"text": "Secondly, the features ‘Cost’, and D(01 to 30) Total Revenue expresses dollars as a categoric type, which includes the ‘$’ symbol."
},
{
"code": null,
"e": 3803,
"s": 3686,
"text": "To transform the variables’ data types into numeric, those issues must be solved and the dataset cleaned as follows."
},
{
"code": null,
"e": 4575,
"s": 3803,
"text": "# Lowering columns' capital letters for easy typingdf.columns = map(str.lower, df.columns)# Selecting columns cols= [\"cost\",\"installs\",\"d01 total revenue\",\"d03 total revenue\",\"d07 total. revenue\",\"d30 total revenue\"]# Cleaning unvalid charactersdf[cols] = (df[cols].replace({‘,’:’’}, regex=True))df[\"cost\"] = (df[\"cost\"].str.replace('$','')).str.strip()df[\"d01 total revenue\"] = (df[\"d01 total revenue\"].str.replace('$','')).str.strip()df[\"d03 total revenue\"] = (df[\"d03 total revenue\"].str.replace('$','')).str.strip()df[\"d07 total revenue\"] = (df[\"d07 total revenue\"].str.replace('$','')).str.strip()df[\"d30 total revenue\"] = (df[\"d30 total revenue\"].str.replace('$','')).str.strip()# Transforming columns as float (numeric type)df[cols] = df[cols].astype(float).copy()"
},
{
"code": null,
"e": 4787,
"s": 4575,
"text": "Now that we have all set up and ready to move forward, it is time to calculate our KPIs from which we’ll be able to analyze the performance of both the overall evolution and by zooming in a campaign by campaign."
},
{
"code": null,
"e": 4996,
"s": 4787,
"text": "First, I’ll start by determining the CPI (cost per install) of each campaign. To perform the calculation, we simply divide the cost of each campaign by the number of installations that each one has generated."
},
{
"code": null,
"e": 5107,
"s": 4996,
"text": "# Determine \"Cost Per Install\" in a new columndf[\"cpi\"] = df.apply(lambda x: x[\"cost\"] / x[\"installs\"],axis=1)"
},
{
"code": null,
"e": 5384,
"s": 5107,
"text": "Let’s also calculate the ROAS (return on ads spend) on the first, the third, the seventh, and the thirtieth days counting from the first day the user has installed the app. To do so, we divide the total revenue generated by the total cost of the campaign for each desired day."
},
{
"code": null,
"e": 5753,
"s": 5384,
"text": "# Calculations to determine \"dx_roas\" in new columnsdf[\"d01_roas\"] = df.apply(lambda x: x[\"d01 total revenue\"] / x[\"cost\"], axis=1)df[\"d03_roas\"] = df.apply(lambda x: x[\"d03 total revenue\"] / x[\"cost\"], axis=1)df[\"d07_roas\"] = df.apply(lambda x: x[\"d07 total revenue\"] / x[\"cost\"], axis=1)df[\"d30_roas\"] = df.apply(lambda x: x[\"d30 total revenue\"] / x[\"cost\"], axis=1)"
},
{
"code": null,
"e": 5925,
"s": 5753,
"text": "Let’s display our final dataset and take a close look at our metrics and KPIs. From this point, we are ready to extract some important and relevant insights from the data."
},
{
"code": null,
"e": 6066,
"s": 5925,
"text": "From a total of 89 campaigns, 77 are running on Facebook and only 12 through the Vungle platform, corresponding to 87% and 13% respectively."
},
{
"code": null,
"e": 6604,
"s": 6066,
"text": "# Side tableabsolut = df[\"media source\"].value_counts().to_frame()percent = (df[\"media source\"].value_counts(normalize=True)*100).to_frame().rename(columns={\"media source\":\"percent\"})out_bal = pd.concat([absolut,percent],axis=1).round(decimals=2)display(out_bal)# Pie graphabsolut.plot(kind='pie', subplots=True, autopct='%1.2f%%', explode= (0.05, 0.05), startangle=80, legend=False, fontsize=12, figsize=(16,7))# Paramsplt.xticks(rotation=0, horizontalalignment=\"center\")plt.title(\"Total marketing campaigns\", fontsize=10, loc=\"right\");"
},
{
"code": null,
"e": 6717,
"s": 6604,
"text": "Vungle has generated a total of 242112 installs (55%) whereas Facebook is responsible for 197357 installs (45%)."
},
{
"code": null,
"e": 7459,
"s": 6717,
"text": "# Bar plotax = df.groupby([\"media source\"])[\"installs\"].sum().plot(kind=\"bar\", figsize=(9,6), fontsize=12, color=sns.color_palette(\"rocket\"), table=False)for p in ax.patches: ax.annotate(\"%.2f\" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 7), textcoords='offset points')# Paramsplt.xlabel(\"media source\", fontsize=10)plt.xticks(rotation=0, horizontalalignment=\"center\")plt.ylabel(\"Absolute frequency\", fontsize=10)plt.title(\"Overall installs proportion\", fontsize=10, loc=\"right\")# side tableinstalls = df.groupby([\"media source\"])[\"installs\"].sum().sort_values(ascending=False).to_frame()installs[\"percent\"] = (installs.apply(lambda x: x/x.sum())*100).round(2)display(installs)"
},
{
"code": null,
"e": 7671,
"s": 7459,
"text": "To find the overall CPI, we sum the costs of all Facebook campaigns and divide it by the total Facebook installs. The result is 1.97 dollars. For an easier calculation, we can select only the Facebook campaigns."
},
{
"code": null,
"e": 7808,
"s": 7671,
"text": "# Filtering records from Facebook onlyfb = df[[\"media source\",\"cost\",\"installs\"]].copy()fb = fb[fb[\"media source\"] == \"Facebook\"].copy()"
},
{
"code": null,
"e": 8188,
"s": 7808,
"text": "# Calculating Costs Per Installing (Facebook)fb.cost.sum() / fb.installs.sum()>> 1.9671306312925307# Visualizing Costs vs. Installs sorted by highest costfb = fb.reset_index().copy()fb.drop([\"index\"], axis=1, inplace=True)fb.plot.line()plt.xlabel('Number of campaigns')plt.ylabel('Absolute Frequency')plt.title('Costs vs. Installs [Facebook]', fontsize=10, loc=\"right\")plt.show()"
},
{
"code": null,
"e": 8401,
"s": 8188,
"text": "2563 is the average number of installs per campaign. 14 Facebook campaigns have generated installs above the Facebook average, and only 6 Facebook campaigns have generated installs above the total average (4937)."
},
{
"code": null,
"e": 9306,
"s": 8401,
"text": "# Filtering records from Facebook onlyfb_mean = df[df[\"media source\"] == \"Facebook\"].copy()# Visualizing comparisons between Facebook campaings and between Facebook average campaings and total average campaignsax = fb_mean.groupby(\"campaign name\")[\"installs\"].mean().sort_values(ascending=False).head(15).plot(kind=\"bar\", figsize=(16,9), fontsize=12, color=sns.color_palette(\"rocket\"), table=False)# Paramsplt.xticks(rotation=30, horizontalalignment=\"right\")plt.ylabel(\"Absolute values\", fontsize=10)plt.xlabel(\"Facebook campaigns\", fontsize=10)plt.title(\"Facebook campaigns vs. Facebook average installs\", fontsize=10, loc=\"right\")plt.axhline(fb_mean.groupby(\"campaign name\")[\"installs\"].mean().mean(), linewidth=2, color =\"r\")plt.axhline(df.groupby(\"campaign name\")[\"installs\"].mean().mean(), linewidth=2, color =\"b\")plt.legend(('Facebook average installs', 'Total average installs'))plt.tight_layout()"
},
{
"code": null,
"e": 9575,
"s": 9306,
"text": "To determine the overall CPI of Vungle, the procedure is similar to the previous one in which we sum the costs of all Vungle campaigns and divide it by the total number of the Vungle installs. The result is 0.74 dollars. Again, we can select only the Vungle campaigns."
},
{
"code": null,
"e": 9712,
"s": 9575,
"text": "# Filtering records from Vungle onlyvun = df[[\"media source\",\"cost\",\"installs\"]].copy()vun = vun[vun[\"media source\"] == \"Vungle\"].copy()"
},
{
"code": null,
"e": 10063,
"s": 9712,
"text": "# Calculating Costs Per Installing (Vungle)vun.cost.sum() / vun.installs.sum()>> 0.7351143272535026# Visualizing Costs vs. Installs sorted by highest costvun.reset_index(drop=True, inplace=True)vun.plot.line()plt.xlabel('Number of campaigns')plt.ylabel('Absolute Frequency')plt.title('Costs vs. Installs [Vungle]', fontsize=10, loc=\"right\")plt.show()"
},
{
"code": null,
"e": 10271,
"s": 10063,
"text": "20176 is the average number of installs per campaign. Only 3 Vungle campaigns have generated installs above the Vungle average, and 11 Vungle campaigns have generated installs above the total average (4937)."
},
{
"code": null,
"e": 11146,
"s": 10271,
"text": "# Filtering records from Facebook onlyvn_mean = df[df[\"media source\"] == \"Vungle\"].copy()# Visualizing comparisons between Vungle campaings and between Vungle average campaings and total average campaignsax = vn_mean.groupby(\"campaign name\")[\"installs\"].mean().sort_values(ascending=False).plot(kind=\"bar\", figsize=(16,9), fontsize=12, color=sns.color_palette(\"rocket\"), table=False)# Paramsplt.xticks(rotation=30, horizontalalignment=\"right\")plt.ylabel(\"Absolute values\", fontsize=10)plt.xlabel(\"Vungle campaigns\", fontsize=10)plt.title(\"Vungle campaigns vs. average installs\", fontsize=10, loc=\"right\")plt.axhline(vn_mean.groupby(\"campaign name\")[\"installs\"].mean().mean(), linewidth=2, color =\"r\")plt.axhline(df.groupby(\"campaign name\")[\"installs\"].mean().mean(), linewidth=2, color =\"b\")plt.legend(('Vungle average installs', 'Total average installs'))plt.tight_layout()"
},
{
"code": null,
"e": 11288,
"s": 11146,
"text": "Actually, there is a colossal difference between both platforms when the comparison is made in terms of cost vs. installations they generate."
},
{
"code": null,
"e": 11480,
"s": 11288,
"text": "With $177980 of total investment in the advertisement, Vungle is capable of generating 242112 installations, whereas Facebook generates 197357 installs but with an amount of $388227 invested."
},
{
"code": null,
"e": 12289,
"s": 11480,
"text": "# Concatenating both Facebook + Vungle datasetscpi2brand = pd.concat([fb, vun])# Bar plotax = cpi2brand.groupby([\"media source\"])[[\"cost\",\"installs\"]].sum().plot(kind=\"bar\", figsize=(9,6), fontsize=12, color=sns.color_palette(\"rocket\"), table=False)for p in ax.patches: ax.annotate(\"%.2f\" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 7), textcoords='offset points')# Paramsplt.xlabel(\"media source\", fontsize=10)plt.xticks(rotation=0, horizontalalignment=\"center\")plt.ylabel(\"Absolute frequency\", fontsize=10)plt.title(\"Overall Cost vs Installs comparison [Facebook + Vungle]\", fontsize=10, loc=\"right\")# side tableinstalls = cpi2brand.groupby([\"media source\"])[[\"cost\",\"installs\"]].sum().sort_values(by=\"cost\", ascending=False)display(installs)"
},
{
"code": null,
"e": 12439,
"s": 12289,
"text": "To determine the Return On Ads Spend after 30 days, we need to sum the total revenue on the 30th day and divide it by the total invested on Facebook."
},
{
"code": null,
"e": 12517,
"s": 12439,
"text": "The result is that on the 30th day, 72,65% of ROAS was captured for Facebook."
},
{
"code": null,
"e": 12677,
"s": 12517,
"text": "# Selecting Facebook segment datasetfb_d30 = df[[\"media source\",\"cost\",\"d30 total revenue\"]].copy()fb_d30 = fb_d30[fb_d30[\"media source\"] == \"Facebook\"].copy()"
},
{
"code": null,
"e": 13061,
"s": 12677,
"text": "# Calculating Return On Advert Spend (Facebook) over 30 daysfb_d30[\"d30 total revenue\"].sum() / fb_d30.cost.sum()>> 0.7265414306578368# Visualizing Costs vs. installs over 30 days sorted by highest cost (Facebook)fb_d30.plot.line()plt.xlabel('Number of campaigns')plt.ylabel('Absolute Frequency')plt.title('Costs vs. d30 total revenue [Facebook]', fontsize=10, loc=\"right\")plt.show()"
},
{
"code": null,
"e": 13190,
"s": 13061,
"text": "To determine the D30 ROAS of Vungle, sum the total revenue on the 30th day, and divide it by the total invested on the platform."
},
{
"code": null,
"e": 13266,
"s": 13190,
"text": "The result is that on the 30th day, 92,88% of ROAS was captured for Vungle."
},
{
"code": null,
"e": 13426,
"s": 13266,
"text": "# Selecting Vungle segment datasetvun_d30 = df[[\"media source\",\"cost\",\"d30 total revenue\"]].copy()vun_d30 = vun_d30[vun_d30[\"media source\"] == \"Vungle\"].copy()"
},
{
"code": null,
"e": 13803,
"s": 13426,
"text": "# Calculating Return On Ads Spend (Vungle) after 30 daysfb_d30[\"d30 total revenue\"].sum() / fb_d30.cost.sum()>> 0.9287728958309922# Visualizing Costs vs. installs over 30 days sorted by highest cost (Vungle)vun_d30.plot.line()plt.xlabel('Number of campaigns')plt.ylabel('Absolute Frequency')plt.title('Costs vs. d30 total revenue [Vungle]', fontsize=10, loc=\"right\")plt.show()"
},
{
"code": null,
"e": 14003,
"s": 13803,
"text": "To determine this result, we must vertically concatenate (axis=0) the above sub-datasets of both D30_ROAS Facebook and Vungle, and then group them by their cost and the total revenue on the 30th day."
},
{
"code": null,
"e": 14325,
"s": 14003,
"text": "The result, displayed in the bar chart below, tells us that 30 days after, Vungle campaigns generated $165303 which is almost the revenue needed to reach that platform break-even point, translated by a total cost of $177980. On the opposite direction is Facebook with a total investment of $388277 and revenue of $282063."
},
{
"code": null,
"e": 15156,
"s": 14325,
"text": "# Concatenating both Facebook + Vungle datasetsroas2brand = pd.concat([fb_d30, vun_d30])# Bar plotax = roas2brand.groupby([\"media source\"])[[\"cost\",\"d30 total revenue\"]].sum().plot(kind=\"bar\", figsize=(9,6), fontsize=12, color=sns.color_palette(\"rocket\"), table=False)for p in ax.patches: ax.annotate(\"%.2f\" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 7), textcoords='offset points')# Paramsplt.xlabel(\"media source\", fontsize=10)plt.xticks(rotation=0, horizontalalignment=\"center\")plt.ylabel(\"Absolute frequency\", fontsize=10)plt.title(\"Overall Cost vs Roas _d30 comparison [Facebook + Vungle]\", fontsize=10, loc=\"right\")# side tableroas = roas2brand.groupby([\"media source\"])[[\"cost\",\"d30 total revenue\"]].sum().sort_values(by=\"cost\", ascending=False)display(roas)"
},
{
"code": null,
"e": 15210,
"s": 15156,
"text": "Let’s display a correlation heatmap (Pearson method)."
},
{
"code": null,
"e": 15356,
"s": 15210,
"text": "mask = np.triu(df.corr(), 1)plt.figure(figsize=(19, 9))sns.heatmap(df.corr(), annot=True, vmax=1, vmin=-1, square=False, cmap=\"BrBG\", mask=mask);"
},
{
"code": null,
"e": 15594,
"s": 15356,
"text": "From the analysis of the correlations map we can easily spot many strong correlations as one might be expecting. But what I am really interested in is to verify the correlation between the ROAS on day 1, 3 and 7 and ROAS on the 30th day."
},
{
"code": null,
"e": 15808,
"s": 15594,
"text": "The d30_ROAS has a positive and strong correlated with d01_ROAS of 71%, an even more strong and positive correlation with d03_ROAS, of 86%, but the strongest correlation is between d07_ROAS and d30_ROAS of 90.37%."
},
{
"code": null,
"e": 16171,
"s": 15808,
"text": "# Calculating corr. coef. between ROAS 7 days and 30 daysdf['d07_roas'].corr(df['d30_roas'])>> 0.9037410337635488# Display scatter plot: d07_ROAS and d30_ROASdf.plot(x=\"d07_roas\", y=\"d30_roas\", kind=\"scatter\", figsize=(9,6), fontsize=12)plt.title(\"Correlation d07_ROAS and d30_ROAS\", fontsize=10, loc=\"right\")plt.xticks(rotation=0, horizontalalignment=\"center\");"
},
{
"code": null,
"e": 16369,
"s": 16171,
"text": "We need to check the campaigns with the maximum revenue for d01, d03, d07 and d30, and also the ones with the maximum ROAS for the exact same periods and compare both pairs to verify if they match."
},
{
"code": null,
"e": 16442,
"s": 16369,
"text": "Assigning maximum ROAS on 1st day, and maximum total revenue on 1st day."
},
{
"code": null,
"e": 16552,
"s": 16442,
"text": "# Selecting columns to work withhigh_d01 = df[[\"campaign name\",\"cost\",\"d01 total revenue\",\"d01_roas\"]].copy()"
},
{
"code": null,
"e": 16917,
"s": 16552,
"text": "# Highest d01_roasd01_roas_max = high_d01['d01_roas'].max()high_d01.loc[high_d01['d01_roas'] == d01_roas_max, 'campaign name']>> 59 IMT-FB-Android-RoW2-AE-Playables-Feed# Highest d01 total revenued01_total_max = high_d01['d01 total revenue'].max()high_d01.loc[high_d01['d01 total revenue'] == d01_total_max, 'campaign name']>> 0 IMT-FB-iOS-EN-US-AE-Playables"
},
{
"code": null,
"e": 17004,
"s": 16917,
"text": "The campaigns with the highest d01_roas and the highest d01 total revenue don’t match."
},
{
"code": null,
"e": 17073,
"s": 17004,
"text": "Assigning maximum ROAS on 3rd, and maximum total revenue on 3rd day."
},
{
"code": null,
"e": 17183,
"s": 17073,
"text": "# Selecting columns to work withhigh_d03 = df[[\"campaign name\",\"cost\",\"d03 total revenue\",\"d03_roas\"]].copy()"
},
{
"code": null,
"e": 17551,
"s": 17183,
"text": "# Highest d03_roasd03_roas_max = high_d03['d03_roas'].max()high_d03.loc[high_d03['d03_roas'] == d03_roas_max, 'campaign name']>> 86 IMT-FB-Android-RoW2-AE-Value-Video-FANIS# Highest d03 total revenued03_total_max = high_d03['d03 total revenue'].max()high_d03.loc[high_d03['d03 total revenue'] == d03_total_max, 'campaign name']>> 0 IMT-FB-iOS-EN-US-AE-Playables"
},
{
"code": null,
"e": 17638,
"s": 17551,
"text": "The campaigns with the highest d03_roas and the highest d03 total revenue don’t match."
},
{
"code": null,
"e": 17706,
"s": 17638,
"text": "Assigning maximum ROAS on 7th, and maximum total revenue on 7thday."
},
{
"code": null,
"e": 17816,
"s": 17706,
"text": "# Selecting columns to work withhigh_d07 = df[[\"campaign name\",\"cost\",\"d07 total revenue\",\"d07_roas\"]].copy()"
},
{
"code": null,
"e": 18183,
"s": 17816,
"text": "# Highest d07_roasd07_roas_max = high_d07['d07_roas'].max()high_d07.loc[high_d07['d07_roas'] == d07_roas_max, 'campaign name']>> 86 IMT-FB-Android-RoW2-AE-Value-Video-FANIS# Highest d07 total revenud07_total_max = high_d07['d07 total revenue'].max()high_d07.loc[high_d07['d07 total revenue'] == d07_total_max, 'campaign name']>> 0 IMT-FB-iOS-EN-US-AE-Playables"
},
{
"code": null,
"e": 18270,
"s": 18183,
"text": "The campaigns with the highest d07_roas and the highest d07 total revenue don’t match."
},
{
"code": null,
"e": 18341,
"s": 18270,
"text": "Assigning maximum ROAS on 30th, and maximum total revenue on 30th day."
},
{
"code": null,
"e": 18451,
"s": 18341,
"text": "# Selecting columns to work withhigh_d30 = df[[\"campaign name\",\"cost\",\"d30 total revenue\",\"d30_roas\"]].copy()"
},
{
"code": null,
"e": 18795,
"s": 18451,
"text": "# Highest d30_roasd30_roas_max = high_d30['d30_roas'].max()high_d30.loc[high_d30['d30_roas'] == d30_roas_max, 'campaign name']>> 2 IMT-Vungle-iOS-CN# Highest d30 total revenued30_total_max = high_d30['d30 total revenue'].max()high_d30.loc[high_d30['d30 total revenue'] == d30_total_max, 'campaign name']>> 0 IMT-FB-iOS-EN-US-AE-Playables"
},
{
"code": null,
"e": 18882,
"s": 18795,
"text": "The campaigns with the highest d30_roas and the highest d30 total revenue don’t match."
},
{
"code": null,
"e": 18997,
"s": 18882,
"text": "The threshold where the revenue reaches and gets equal to its costs determines the break-even point of a campaign."
},
{
"code": null,
"e": 19291,
"s": 18997,
"text": "To check if all campaings that start below 10% on the first day did not break-even after the 30 days, we need to select the campaigns who’s d01_ROAS would be lower than 10%, and select the campaigns from the segment in which the d30 total revenue is higher than or at least equal to its costs."
},
{
"code": null,
"e": 19586,
"s": 19291,
"text": "# Selecting campaigns segment of ROAS d01 under 10%d01_roas_under10 = d01_roas_under10[d01_roas_under10[\"d01_roas\"] < 0.10].copy()# Filtering campaigns segment in wihch \"d30 total revenue\" is higher than its costd01_roas_under10[d01_roas_under10[\"d30 total revenue\"] > d01_roas_under10[\"cost\"]]"
},
{
"code": null,
"e": 19641,
"s": 19586,
"text": ">> The 3 above campaings did break-even after 30 days."
},
{
"code": null,
"e": 19807,
"s": 19641,
"text": "Let’s select all the campaigns with a d07_ROAS higher than 70%, and select all the campaigns from the segment in which the d30 total revenue is lower than its costs."
},
{
"code": null,
"e": 19910,
"s": 19807,
"text": "# Selecting campaigns segment of ROAS 7 days above 70%d07_roas_up70 = df[df[\"d07_roas\"] > 0.70].copy()"
},
{
"code": null,
"e": 20088,
"s": 19910,
"text": "# Filtering campaigns segment in which \"d30 total revenue\" is lower than its cost(d07_roas_up70[d07_roas_up70[\"d30 total revenue\"] < d07_roas_up70[\"cost\"]]).values.any()>> False"
},
{
"code": null,
"e": 20164,
"s": 20088,
"text": "All Campaigns with a D07 ROAS higher than 70% did break-even after 30 days."
},
{
"code": null,
"e": 20336,
"s": 20164,
"text": "In the next histogram, we can observe that the majority of campaigns with a ROAS on the 1st day is highly concentrated around 10% with a few campaigns reaching almost 20%."
},
{
"code": null,
"e": 20513,
"s": 20336,
"text": "On the other hand, after 3 days, the majority of campaigns is concentrated between 15% and 35% with some reaching a ROAS between 40% and 55% and even almost 80% in a few cases."
},
{
"code": null,
"e": 21089,
"s": 20513,
"text": "# Display histogram: d01_roas vs d03_roas evolution comparisond01_roas = df.d01_roasd03_roas = df.d03_roasd01 = np.array(d01_roas)d03 = np.array(d03_roas)plt.figure(figsize=(14,8))plt.hist(d01, bins=89, density=True, color=\"g\", alpha = 0.7, label=\"d01_roas\")plt.hist(d03, bins=89, density=True, color=\"r\", alpha = 0.5, label=\"d03_roas\")plt.legend(loc='upper right')plt.xlabel(\"Relative observations\", fontsize=10)plt.xticks(rotation=0, horizontalalignment=\"center\")plt.ylabel(\"Density scale\", fontsize=10)plt.title(\"d01_roas vs. d03_roas\", fontsize=10, loc=\"right\")plt.show()"
},
{
"code": null,
"e": 21315,
"s": 21089,
"text": "Although there is a big cluster of campaigns below 20% on the 3rd day, more than half are concentrated between 30% and 45% of ROAS. We can see that there are a few campaigns beyond 60% and even 100% surpassing the break-even."
},
{
"code": null,
"e": 21651,
"s": 21315,
"text": "As expected, after 30 days we can see a fair distribution of the campaigns from the d30_ROAS perspective. There is a cluster that didn’t even go beyond 20% and with this valuable information, the marketing team can investigate what went wrong with the campaigns that don’t have a great return on ad spend and redefine those operations."
},
{
"code": null,
"e": 22085,
"s": 21651,
"text": "To determine the overall performance and estimate the campaigns’ return on ad spend (ROAS), we have analyzed some important metrics and have made some KPI calculations concerning the amount invested in marketing operations and advertising, the number of well-succeeded app installations carried out by the users, and monitored the evolution of the partial return in each timeframe delivering important insights to the marketing team."
},
{
"code": null,
"e": 22420,
"s": 22085,
"text": "In a marketing environment, the metrics are indicators by which the results of tactic operations can be measured, such as purchases made on an e-commerce website, installations of a mobile application, the user’s behavior concerning exposure to an ad, and are not associated with any conversion goal, that is, to a specific objective."
},
{
"code": null,
"e": 22823,
"s": 22420,
"text": "On the other hand, the Key Performance Indicators (KPIs) are management tools that allow monitoring, evaluating and controlling the performance levels of a company, product, or service, regarding specific or general operational objectives, contributing to an overall understanding of the evolution, performance, impact, intensity, and direction of the results concerning the defined marketing strategy."
},
{
"code": null,
"e": 22936,
"s": 22823,
"text": "The marketing report is concluded but so much more could be deeper investigated and analysed from this point on."
},
{
"code": null,
"e": 22971,
"s": 22936,
"text": "You can find the entire code here."
},
{
"code": null,
"e": 23030,
"s": 22971,
"text": "The ‘mkt_ua_campaigns.csv’ dataset can be downloaded here."
},
{
"code": null,
"e": 23076,
"s": 23030,
"text": "Check out other articles you might also like:"
},
{
"code": null,
"e": 23099,
"s": 23076,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 23122,
"s": 23099,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 23145,
"s": 23122,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 23154,
"s": 23145,
"text": "Linkedin"
},
{
"code": null,
"e": 23162,
"s": 23154,
"text": "Twitter"
},
{
"code": null,
"e": 23169,
"s": 23162,
"text": "Medium"
},
{
"code": null,
"e": 23176,
"s": 23169,
"text": "GitHub"
},
{
"code": null,
"e": 23183,
"s": 23176,
"text": "Kaggle"
},
{
"code": null,
"e": 23189,
"s": 23183,
"text": "Email"
}
] |
Convert the ASCII value sentence to its equivalent string in C++
|
In this tutorial, we will be discussing a program to convert the ASCII value sentence to its equivalent string.
For this we will be provided with a string containing the ASCII codes. Our task is to convert the given string into the equivalent characters and print it back.
Live Demo
#include <bits/stdc++.h>
using namespace std;
//converting the ASCII sequence into
//character string
void convert_ASCII(string str, int len){
int num = 0;
for (int i = 0; i < len; i++) {
//appending the current digit
num = num * 10 + (str[i] - '0');
//checking if number is within range
if (num >= 32 && num <= 122) {
char ch = (char)num;
cout << ch;
num = 0;
}
}
}
int main(){
string str = "104101108108111443211911111410810033";
int len = str.length();
convert_ASCII(str, len);
return 0;
}
hello, world!
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to convert the ASCII value sentence to its equivalent string."
},
{
"code": null,
"e": 1335,
"s": 1174,
"text": "For this we will be provided with a string containing the ASCII codes. Our task is to convert the given string into the equivalent characters and print it back."
},
{
"code": null,
"e": 1346,
"s": 1335,
"text": " Live Demo"
},
{
"code": null,
"e": 1917,
"s": 1346,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n//converting the ASCII sequence into\n//character string\nvoid convert_ASCII(string str, int len){\n int num = 0;\n for (int i = 0; i < len; i++) {\n //appending the current digit\n num = num * 10 + (str[i] - '0');\n //checking if number is within range\n if (num >= 32 && num <= 122) {\n char ch = (char)num;\n cout << ch;\n num = 0;\n }\n }\n}\nint main(){\n string str = \"104101108108111443211911111410810033\";\n int len = str.length();\n convert_ASCII(str, len);\n return 0;\n}"
},
{
"code": null,
"e": 1931,
"s": 1917,
"text": "hello, world!"
}
] |
Exploratory Data Analysis with Well Log Data | by Andy McDonald | Towards Data Science
|
Once data has been collated and sorted through, the next step in the Data Science process is to carry out Exploratory Data Analysis (EDA). This step allows us to identify patterns within the data, understand relationships between the features (well logs) and identify possible outliers that may exist within the dataset. In this stage, we gain an understanding about the data and check whether further processing is required or if cleaning is necessary.
As petrophysicists/geoscientists we commonly use log plots, histograms and crossplots (scatter plots) to analyse and explore well log data. Python provides a great toolset for visualising the data from different perspectives in a quick and easy way.
In this article we will use a subset of the dataset that was released by Xeek and FORCE as part of a competition to predict facies from well logs. We will be visualising the data using a mixture of matplotlib, seaborn and missingno data visualisation libraries.
The visualisations we will cover will allow us to:
Identify where we have or don’t have data
Understand the data distribution
Visualise data affected by bad hole conditions
The notebook for this article can be found on my Python and Petrophysics Github series which can accessed at the link below:
https://github.com/andymcdgeo/Petrophysics-Python-Series
The first step for any project is loading the required libraries and data.
For this workthrough, we are going to call upon a number of plotting libraries: seaborn, matplotlib and missingno as well as math, pandas, and numpy.
import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport mathimport missingno as msnoimport numpy as np
The dataset we are using forms part of a Machine Learning competition run by Xeek and FORCE (https://xeek.ai/challenges/force-well-logs/overview). The objective of the competition was to predict lithology from a dataset consisting 98 training wells each with varying degrees of log completeness. The objective was to predict lithofacies based on the log measurements.
In order to keep the plots and data manageable in this article I have used a subset of 12 wells from the training data. The data has already been collated into a single csv file with no need to worry about curve mnemonics. To load the subset of data in we can call upon pd.read_csv.
data = pd.read_csv('Data/xeek_train_subset.csv')
Once the data has been loaded, we can confirm the number and names of the wells using the following commands:
# Counts the number of unique values in the WELL columndata['WELL'].nunique()
Which will return 12 as expected.
# Gets the unique names from the WELL columndata['WELL'].unique()
This returns an array object with the well names.
array(['15/9-13', '15/9-15', '15/9-17', '16/1-2', '16/1-6 A', '16/10-1', '16/10-2', '16/10-3', '16/10-5', '16/11-1 ST3', '16/2-11 A', '16/2-16'], dtype=object)
Missing data within well logging can arise for a number of reasons including:
Tool failures & problems
Missing by choice (i.e. tools not run due to budgetary constraints)
Human error
Vintage datasets
Issues arising from the borehole environment
There are a number of ways that we can use to identify where we have data and where we don’t. We will look at 2 ways to visualise missing data.
The first method we will look at is using the missingno library, which provides a nice little toolbox, created by Aleksy Bilgour, as a way to visualise and understand data completeness. More details on the library can be found at https://github.com/ResidentMario/missingno. If you don’t have this library, you can quickly install it using pip install missingno into your terminal.
The missingno toolbox contains a number of different visualisations, but for this article we will focus on the matrix plot and bar plot. The matrix plot can be called by:
msno.matrix(data)
This shows us the data density across all of the features (log curves). Over on the right hand side of the figure we have sparkline, which illustrates where we have maximum or minimum nullity in the data.
From the visualisation we can can see that only a handful of columns are complete WELL, DEPTH_MD, GR, GROUP, LITHOFACIES_LITHOLOGY and LITHOFACIES_CONFIDENCE.
Others have near full data values such DTC, CALI, and ROP, whereas some have very poor data coverage such as RMIC, SGR and ROPA.
We can also call upon msno.bar(data) to generate a bar chart showing the amount of non-null data values within each column (log curve). Along the top of the chart, we get a total count of the non-null data values.
With a quick glance at the matrix plot and bar chart, you can get a sense of what data is missing from your dataset, especially if you have a large number of columns in your dataset.
In my previous article: Visualising Well Data Coverage Using Matplotlib I covered a method of viewing the data coverage on a well by well basis. This allows you to see where the gaps are in your key curves.
If we wanted to generate a plot for all of the curves per well we could save each one out as a file or present the data in a single column. In this example, I have only selected common curves that a petrophysicist may use in an interpretation.
data_nan = data[['WELL','DEPTH_MD','CALI', 'BS', 'GR', 'NPHI', 'RHOB', 'PEF', 'RDEP', 'RMED', 'DTC', 'DTS']].copy()for num, col in enumerate(data_nan.columns[2:]): data_nan[col] = data_nan[col].notnull() * (num + 1) data_nan[col].replace(0, num, inplace=True) print(col, num) #Print out the col name and number to verify it worksgrouped = data_nan.groupby('WELL')#Setup the labels we want to display on the x-axislabels = ['CALI', 'BS', 'GR', 'NPHI', 'RHOB', 'PEF', 'RDEP', 'RMED', 'DTC', 'DTS']#Setup the figure and the subplotsfig, axs = plt.subplots(4, 3, figsize=(20,20))#Loop through each well and column in the grouped dataframefor (name, df), ax in zip(grouped, axs.flat): ax.set_xlim(0,9) #Setup the depth range ax.set_ylim(5000, 0) #Create multiple fill betweens for each curve# This is between # the number representing null values and the number representing # actual values ax.fill_betweenx(df.DEPTH_MD, 0, df.CALI, facecolor='grey') ax.fill_betweenx(df.DEPTH_MD, 1, df.BS, facecolor='lightgrey') ax.fill_betweenx(df.DEPTH_MD, 2, df.GR, facecolor='mediumseagreen') ax.fill_betweenx(df.DEPTH_MD, 3, df.NPHI, facecolor='lightblue') ax.fill_betweenx(df.DEPTH_MD, 4, df.RHOB, facecolor='lightcoral') ax.fill_betweenx(df.DEPTH_MD, 5, df.PEF, facecolor='violet') ax.fill_betweenx(df.DEPTH_MD, 6, df.RDEP, facecolor='darksalmon') ax.fill_betweenx(df.DEPTH_MD, 7, df.RMED, facecolor='wheat') ax.fill_betweenx(df.DEPTH_MD, 8, df.DTC, facecolor='thistle') ax.fill_betweenx(df.DEPTH_MD, 9, df.DTS, facecolor='tan') #Setup the grid, axis labels and ticks ax.grid(axis='x', alpha=0.5, color='black') ax.set_ylabel('DEPTH (m)', fontsize=14, fontweight='bold') #Position vertical lines at the boundaries between the bars ax.set_xticks([1,2,3,4,5,6,7,8,9,10], minor=False) #Position the curve names in the centre of each column ax.set_xticks([0.5, 1.5 ,2.5 ,3.5 ,4.5 ,5.5 ,6.5 , 7.5, 8.5, 9.5], minor=True) #Setup the x-axis tick labels ax.set_xticklabels(labels, rotation='vertical', minor=True, verticalalignment='bottom') ax.set_xticklabels('', minor=False) ax.tick_params(axis='x', which='minor', pad=-10) #Assign the well name as the title to each subplot ax.set_title(name, fontsize=16, fontweight='bold')plt.savefig('missingdata.png')plt.tight_layout()plt.subplots_adjust(hspace=0.15, wspace=0.25)plt.show()
From the generated image, we can identify where the gaps are in our main curves. From this plot we can determine which wells would be useful to carry forward for machine learning modelling or for further investigation.
In this section, we will look at a number of visualisations that can be used to gain insight into our data and how that data relations to lithofacies and geological stratigraphy.
There are multiple plotting and data visualisation libraries with the Python world. One of these is Seaborn, which is a data visualisation library built on top of matplotlib and works closely with pandas. It provides an easy and more intuitive way to display and explore your data.
The following examples illustrate a few different plots that can be used to quickly gain insight into your data using a mixture of FacetGrid and matplotlib.
FacetGrid provides an easier and smoother way of plotting multiple subplots in a grid using a small amount of code compared to matplotlib.
Before we can use our data, we first have to convert our numeric lithology data to actual descriptive labels. This is achieved by using a simple dictionary:
lithology_numbers = {30000: 'Sandstone', 65030: 'Sandstone/Shale', 65000: 'Shale', 80000: 'Marl', 74000: 'Dolomite', 70000: 'Limestone', 70032: 'Chalk', 88000: 'Halite', 86000: 'Anhydrite', 99000: 'Tuff', 90000: 'Coal', 93000: 'Basement'}
In our dataframe, we create a new column called LITH and using the map function we can quickly get our descriptive labels like so:
data['LITH'] = data['FORCE_2020_LITHOFACIES_LITHOLOGY'].map(lithology_numbers)
For the first FacetGrid, we will look at the density-neutron data by formation. When we do this we only need to specify a few lines of code as opposed to multiple lines or using a for loop as seen in the example above with missing data. We can initialise the FacetGrid with the density neutron data and passing the LITH column into the col parameter. Additionally, we can use the col_wrap parameter to specify how many columns we want on our grid.
Finally, as we are familiar with working with density-neutron data on crossplots using certain scales we need to set the xlim and ylim accordingly, otherwise it will autoscale.
g = sns.FacetGrid(data, col='LITH', col_wrap=4)g.map(sns.scatterplot, 'NPHI', 'RHOB', alpha=0.5)g.set(xlim=(-0.15, 1))g.set(ylim=(3, 1))
This will generate a series of mini scatterplots/crossplots of the density-neutron data split by lithology. You can see from the code above, all we had to specify were the type of plot, the axes and setting the axis limits, and from this we have a nice plot we can use right away.
We can further enhance the density neutron data by looking at the lithology distribution across multiple wells. Using the converted LITH data column we can create shading for different lithology types by supplying LITH to the hue parameter. We can then supply the WELL column from the dataframe into the col parameter.
The marker can be changed by supplying a value to the marker and size parameters. This will help clean up the plots so we can see more of the data.
Finally, as we are using a hue, we can automatically generate a legend using add_legend().
g = sns.FacetGrid(data, col='WELL', hue='LITH', col_wrap=4)g.map(sns.scatterplot, 'NPHI', 'RHOB', linewidth=1, size=0.1, marker='+')g.set(xlim=(-0.15, 1))g.set(ylim=(3, 1))g.add_legend()
We can easily swap out the grouping option for the geological GROUP column to view the lithology variation by group.
g = sns.FacetGrid(data, col='GROUP', hue='LITH', col_wrap=4)g.map(sns.scatterplot, 'NPHI', 'RHOB', linewidth=1, size=0.1, marker='+')g.set(xlim=(-0.15, 1))g.set(ylim=(3, 1))g.add_legend()
From this chart, we can quickly see that the Rotliegendes Gp is primarily sandstone and that the Nordaland Gp is a mixture of Shale and Sandstone/Shale lithologies.
The Seaborn library also has a very powerful visualisation known as a pairplot which can be called through a single line of code. This allows us to compare, on a grid, multiple columns/measurements against each other. The equivalent code in matplotlib would extend several lines.
Prior to displaying the pairplot we need to modify the data we are using. Firstly, we will work with a subset of the data consisting of some commonly used well logs. If we used all of the columns in the example for this article, we would be unable to view the details. Secondly, we need to drop any missing data values, otherwise issues can arise when plotting.
To create a list of the curves we want:
key_logs = ['CALI', 'GR', 'NPHI', 'RHOB', 'PEF', 'RDEP', 'RMED', 'DTC', 'DTS']
We can then take a subset of our data:
subset = data[key_logs]subset = subset.dropna()
Once we have the list of key curves we can pass it in to the vars argument in the pair plot.
sns.pairplot(subset, vars=key_logs, diag_kind='hist', plot_kws={'alpha':0.6, 'edgecolor':'k'})
This produces multiple scatter plots with a histogram of each of the curves along the diagonal. As you can see this allows us to quickly understand how data is distributed and correlated between the different logging curves. A very powerful plot!
In this section we will briefly look at a way to visualise where we have badhole data caused by borehole enlargement. Deterioration of the borehole wall can happen for a number of different reasons including undercompacted rocks and variations in stresses acting on those rocks such as variations in mud weight.
As identified in the missing data section only 10 of our wells have a bitsize curve. Therefore, 2 wells will not be plotted. We can use the bitsize curve alongside the caliper curve to create a difference caliper. Negative numbers indicate the borehole has shrunk in size (e.g. shale swelling) and positive numbers indicate the borehole has increased in size.
data['DIF_CAL'] = data['CALI'] - data['BS']
As we will be using matplotlib for these plots we first need to group the dataframe by WELL:
grouped = data.groupby('WELL')
Then calculate the number of rows we need for our plot:
nrows = int(math.ceil(len(grouped)/3.))
Finally, we can use a small for loop to go through each well and add a subplot of density vs neutron to our figure. The c argument in df.plot allows us to specify a column in our dataframe to colour the data. In this case we will use the DIF_CAL data we calculated.
fig, axs = plt.subplots(nrows, 3, figsize=(20,20))for (name, df), ax in zip(grouped, axs.flat): df.plot(kind='scatter', x='NPHI', y='RHOB', ax=ax, c='DIF_CAL', cmap='jet', vmin=-1, vmax=10) ax.set_xlim(-0.15,1) ax.set_ylim(3,1) ax.set_title(name)plt.tight_layout()
From a quick glance we can see that we may have issues with the data in two of the wells: 15/9–15 and 16/1–2. These should then be investigated further.
We can also apply the same idea to our lithologies. If we find that a lithology is badly affected by badhole conditions, there could be potential consequences when attempting to predict that lithology using machine learning algorithms.
To do this, we group the data by LITH and use the same plotting logic as above.
# Determine number of rowsnrows = int(math.ceil(len(grouped)/3.))# Group our datagrouped_lith = data.groupby('LITH')# Plot our datafig, axs = plt.subplots(nrows, 3, figsize=(20,20))for (name, df), ax in zip(grouped_lith, axs.flat): df.plot(kind='scatter', x='NPHI', y='RHOB', c='DIF_CAL', cmap='jet', ax=ax, vmin=-1, vmax=10) ax.set_xlim(-0.05,1) ax.set_ylim(3,0) ax.set_title(name)plt.tight_layout()
From the plot, we can see that all lithologies have a large degree of ‘good’ data in them.
In this article, we have covered some of thee ways in which you can explore and visualise well log data using common Python libraries. We have seen how to use Seaborn to quickly plot multiple datasets on single figures and split that data by wells and lithology. We have also seen how to quickly identify missing data and data affected by badhole conditions.
Exploring your data is a great way to become familiar with it and understand it, especially prior to carrying out machine learning or further interpretation.
Bormann P., Aursand P., Dilib F., Dischington P., Manral S. 2020. 2020 FORCE Machine Learning Contest. https://github.com/bolgebrygg/Force-2020-Machine-Learning-competition
FORCE: Machine Predicted Lithology: https://xeek.ai/challenges/force-well-logs/overview
|
[
{
"code": null,
"e": 625,
"s": 171,
"text": "Once data has been collated and sorted through, the next step in the Data Science process is to carry out Exploratory Data Analysis (EDA). This step allows us to identify patterns within the data, understand relationships between the features (well logs) and identify possible outliers that may exist within the dataset. In this stage, we gain an understanding about the data and check whether further processing is required or if cleaning is necessary."
},
{
"code": null,
"e": 875,
"s": 625,
"text": "As petrophysicists/geoscientists we commonly use log plots, histograms and crossplots (scatter plots) to analyse and explore well log data. Python provides a great toolset for visualising the data from different perspectives in a quick and easy way."
},
{
"code": null,
"e": 1137,
"s": 875,
"text": "In this article we will use a subset of the dataset that was released by Xeek and FORCE as part of a competition to predict facies from well logs. We will be visualising the data using a mixture of matplotlib, seaborn and missingno data visualisation libraries."
},
{
"code": null,
"e": 1188,
"s": 1137,
"text": "The visualisations we will cover will allow us to:"
},
{
"code": null,
"e": 1230,
"s": 1188,
"text": "Identify where we have or don’t have data"
},
{
"code": null,
"e": 1263,
"s": 1230,
"text": "Understand the data distribution"
},
{
"code": null,
"e": 1310,
"s": 1263,
"text": "Visualise data affected by bad hole conditions"
},
{
"code": null,
"e": 1435,
"s": 1310,
"text": "The notebook for this article can be found on my Python and Petrophysics Github series which can accessed at the link below:"
},
{
"code": null,
"e": 1492,
"s": 1435,
"text": "https://github.com/andymcdgeo/Petrophysics-Python-Series"
},
{
"code": null,
"e": 1567,
"s": 1492,
"text": "The first step for any project is loading the required libraries and data."
},
{
"code": null,
"e": 1717,
"s": 1567,
"text": "For this workthrough, we are going to call upon a number of plotting libraries: seaborn, matplotlib and missingno as well as math, pandas, and numpy."
},
{
"code": null,
"e": 1842,
"s": 1717,
"text": "import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport mathimport missingno as msnoimport numpy as np"
},
{
"code": null,
"e": 2210,
"s": 1842,
"text": "The dataset we are using forms part of a Machine Learning competition run by Xeek and FORCE (https://xeek.ai/challenges/force-well-logs/overview). The objective of the competition was to predict lithology from a dataset consisting 98 training wells each with varying degrees of log completeness. The objective was to predict lithofacies based on the log measurements."
},
{
"code": null,
"e": 2493,
"s": 2210,
"text": "In order to keep the plots and data manageable in this article I have used a subset of 12 wells from the training data. The data has already been collated into a single csv file with no need to worry about curve mnemonics. To load the subset of data in we can call upon pd.read_csv."
},
{
"code": null,
"e": 2542,
"s": 2493,
"text": "data = pd.read_csv('Data/xeek_train_subset.csv')"
},
{
"code": null,
"e": 2652,
"s": 2542,
"text": "Once the data has been loaded, we can confirm the number and names of the wells using the following commands:"
},
{
"code": null,
"e": 2730,
"s": 2652,
"text": "# Counts the number of unique values in the WELL columndata['WELL'].nunique()"
},
{
"code": null,
"e": 2764,
"s": 2730,
"text": "Which will return 12 as expected."
},
{
"code": null,
"e": 2830,
"s": 2764,
"text": "# Gets the unique names from the WELL columndata['WELL'].unique()"
},
{
"code": null,
"e": 2880,
"s": 2830,
"text": "This returns an array object with the well names."
},
{
"code": null,
"e": 3040,
"s": 2880,
"text": "array(['15/9-13', '15/9-15', '15/9-17', '16/1-2', '16/1-6 A', '16/10-1', '16/10-2', '16/10-3', '16/10-5', '16/11-1 ST3', '16/2-11 A', '16/2-16'], dtype=object)"
},
{
"code": null,
"e": 3118,
"s": 3040,
"text": "Missing data within well logging can arise for a number of reasons including:"
},
{
"code": null,
"e": 3143,
"s": 3118,
"text": "Tool failures & problems"
},
{
"code": null,
"e": 3211,
"s": 3143,
"text": "Missing by choice (i.e. tools not run due to budgetary constraints)"
},
{
"code": null,
"e": 3223,
"s": 3211,
"text": "Human error"
},
{
"code": null,
"e": 3240,
"s": 3223,
"text": "Vintage datasets"
},
{
"code": null,
"e": 3285,
"s": 3240,
"text": "Issues arising from the borehole environment"
},
{
"code": null,
"e": 3429,
"s": 3285,
"text": "There are a number of ways that we can use to identify where we have data and where we don’t. We will look at 2 ways to visualise missing data."
},
{
"code": null,
"e": 3810,
"s": 3429,
"text": "The first method we will look at is using the missingno library, which provides a nice little toolbox, created by Aleksy Bilgour, as a way to visualise and understand data completeness. More details on the library can be found at https://github.com/ResidentMario/missingno. If you don’t have this library, you can quickly install it using pip install missingno into your terminal."
},
{
"code": null,
"e": 3981,
"s": 3810,
"text": "The missingno toolbox contains a number of different visualisations, but for this article we will focus on the matrix plot and bar plot. The matrix plot can be called by:"
},
{
"code": null,
"e": 3999,
"s": 3981,
"text": "msno.matrix(data)"
},
{
"code": null,
"e": 4204,
"s": 3999,
"text": "This shows us the data density across all of the features (log curves). Over on the right hand side of the figure we have sparkline, which illustrates where we have maximum or minimum nullity in the data."
},
{
"code": null,
"e": 4363,
"s": 4204,
"text": "From the visualisation we can can see that only a handful of columns are complete WELL, DEPTH_MD, GR, GROUP, LITHOFACIES_LITHOLOGY and LITHOFACIES_CONFIDENCE."
},
{
"code": null,
"e": 4492,
"s": 4363,
"text": "Others have near full data values such DTC, CALI, and ROP, whereas some have very poor data coverage such as RMIC, SGR and ROPA."
},
{
"code": null,
"e": 4706,
"s": 4492,
"text": "We can also call upon msno.bar(data) to generate a bar chart showing the amount of non-null data values within each column (log curve). Along the top of the chart, we get a total count of the non-null data values."
},
{
"code": null,
"e": 4889,
"s": 4706,
"text": "With a quick glance at the matrix plot and bar chart, you can get a sense of what data is missing from your dataset, especially if you have a large number of columns in your dataset."
},
{
"code": null,
"e": 5096,
"s": 4889,
"text": "In my previous article: Visualising Well Data Coverage Using Matplotlib I covered a method of viewing the data coverage on a well by well basis. This allows you to see where the gaps are in your key curves."
},
{
"code": null,
"e": 5340,
"s": 5096,
"text": "If we wanted to generate a plot for all of the curves per well we could save each one out as a file or present the data in a single column. In this example, I have only selected common curves that a petrophysicist may use in an interpretation."
},
{
"code": null,
"e": 7780,
"s": 5340,
"text": "data_nan = data[['WELL','DEPTH_MD','CALI', 'BS', 'GR', 'NPHI', 'RHOB', 'PEF', 'RDEP', 'RMED', 'DTC', 'DTS']].copy()for num, col in enumerate(data_nan.columns[2:]): data_nan[col] = data_nan[col].notnull() * (num + 1) data_nan[col].replace(0, num, inplace=True) print(col, num) #Print out the col name and number to verify it worksgrouped = data_nan.groupby('WELL')#Setup the labels we want to display on the x-axislabels = ['CALI', 'BS', 'GR', 'NPHI', 'RHOB', 'PEF', 'RDEP', 'RMED', 'DTC', 'DTS']#Setup the figure and the subplotsfig, axs = plt.subplots(4, 3, figsize=(20,20))#Loop through each well and column in the grouped dataframefor (name, df), ax in zip(grouped, axs.flat): ax.set_xlim(0,9) #Setup the depth range ax.set_ylim(5000, 0) #Create multiple fill betweens for each curve# This is between # the number representing null values and the number representing # actual values ax.fill_betweenx(df.DEPTH_MD, 0, df.CALI, facecolor='grey') ax.fill_betweenx(df.DEPTH_MD, 1, df.BS, facecolor='lightgrey') ax.fill_betweenx(df.DEPTH_MD, 2, df.GR, facecolor='mediumseagreen') ax.fill_betweenx(df.DEPTH_MD, 3, df.NPHI, facecolor='lightblue') ax.fill_betweenx(df.DEPTH_MD, 4, df.RHOB, facecolor='lightcoral') ax.fill_betweenx(df.DEPTH_MD, 5, df.PEF, facecolor='violet') ax.fill_betweenx(df.DEPTH_MD, 6, df.RDEP, facecolor='darksalmon') ax.fill_betweenx(df.DEPTH_MD, 7, df.RMED, facecolor='wheat') ax.fill_betweenx(df.DEPTH_MD, 8, df.DTC, facecolor='thistle') ax.fill_betweenx(df.DEPTH_MD, 9, df.DTS, facecolor='tan') #Setup the grid, axis labels and ticks ax.grid(axis='x', alpha=0.5, color='black') ax.set_ylabel('DEPTH (m)', fontsize=14, fontweight='bold') #Position vertical lines at the boundaries between the bars ax.set_xticks([1,2,3,4,5,6,7,8,9,10], minor=False) #Position the curve names in the centre of each column ax.set_xticks([0.5, 1.5 ,2.5 ,3.5 ,4.5 ,5.5 ,6.5 , 7.5, 8.5, 9.5], minor=True) #Setup the x-axis tick labels ax.set_xticklabels(labels, rotation='vertical', minor=True, verticalalignment='bottom') ax.set_xticklabels('', minor=False) ax.tick_params(axis='x', which='minor', pad=-10) #Assign the well name as the title to each subplot ax.set_title(name, fontsize=16, fontweight='bold')plt.savefig('missingdata.png')plt.tight_layout()plt.subplots_adjust(hspace=0.15, wspace=0.25)plt.show()"
},
{
"code": null,
"e": 7999,
"s": 7780,
"text": "From the generated image, we can identify where the gaps are in our main curves. From this plot we can determine which wells would be useful to carry forward for machine learning modelling or for further investigation."
},
{
"code": null,
"e": 8178,
"s": 7999,
"text": "In this section, we will look at a number of visualisations that can be used to gain insight into our data and how that data relations to lithofacies and geological stratigraphy."
},
{
"code": null,
"e": 8460,
"s": 8178,
"text": "There are multiple plotting and data visualisation libraries with the Python world. One of these is Seaborn, which is a data visualisation library built on top of matplotlib and works closely with pandas. It provides an easy and more intuitive way to display and explore your data."
},
{
"code": null,
"e": 8617,
"s": 8460,
"text": "The following examples illustrate a few different plots that can be used to quickly gain insight into your data using a mixture of FacetGrid and matplotlib."
},
{
"code": null,
"e": 8756,
"s": 8617,
"text": "FacetGrid provides an easier and smoother way of plotting multiple subplots in a grid using a small amount of code compared to matplotlib."
},
{
"code": null,
"e": 8913,
"s": 8756,
"text": "Before we can use our data, we first have to convert our numeric lithology data to actual descriptive labels. This is achieved by using a simple dictionary:"
},
{
"code": null,
"e": 9328,
"s": 8913,
"text": "lithology_numbers = {30000: 'Sandstone', 65030: 'Sandstone/Shale', 65000: 'Shale', 80000: 'Marl', 74000: 'Dolomite', 70000: 'Limestone', 70032: 'Chalk', 88000: 'Halite', 86000: 'Anhydrite', 99000: 'Tuff', 90000: 'Coal', 93000: 'Basement'}"
},
{
"code": null,
"e": 9459,
"s": 9328,
"text": "In our dataframe, we create a new column called LITH and using the map function we can quickly get our descriptive labels like so:"
},
{
"code": null,
"e": 9538,
"s": 9459,
"text": "data['LITH'] = data['FORCE_2020_LITHOFACIES_LITHOLOGY'].map(lithology_numbers)"
},
{
"code": null,
"e": 9986,
"s": 9538,
"text": "For the first FacetGrid, we will look at the density-neutron data by formation. When we do this we only need to specify a few lines of code as opposed to multiple lines or using a for loop as seen in the example above with missing data. We can initialise the FacetGrid with the density neutron data and passing the LITH column into the col parameter. Additionally, we can use the col_wrap parameter to specify how many columns we want on our grid."
},
{
"code": null,
"e": 10163,
"s": 9986,
"text": "Finally, as we are familiar with working with density-neutron data on crossplots using certain scales we need to set the xlim and ylim accordingly, otherwise it will autoscale."
},
{
"code": null,
"e": 10300,
"s": 10163,
"text": "g = sns.FacetGrid(data, col='LITH', col_wrap=4)g.map(sns.scatterplot, 'NPHI', 'RHOB', alpha=0.5)g.set(xlim=(-0.15, 1))g.set(ylim=(3, 1))"
},
{
"code": null,
"e": 10581,
"s": 10300,
"text": "This will generate a series of mini scatterplots/crossplots of the density-neutron data split by lithology. You can see from the code above, all we had to specify were the type of plot, the axes and setting the axis limits, and from this we have a nice plot we can use right away."
},
{
"code": null,
"e": 10900,
"s": 10581,
"text": "We can further enhance the density neutron data by looking at the lithology distribution across multiple wells. Using the converted LITH data column we can create shading for different lithology types by supplying LITH to the hue parameter. We can then supply the WELL column from the dataframe into the col parameter."
},
{
"code": null,
"e": 11048,
"s": 10900,
"text": "The marker can be changed by supplying a value to the marker and size parameters. This will help clean up the plots so we can see more of the data."
},
{
"code": null,
"e": 11139,
"s": 11048,
"text": "Finally, as we are using a hue, we can automatically generate a legend using add_legend()."
},
{
"code": null,
"e": 11326,
"s": 11139,
"text": "g = sns.FacetGrid(data, col='WELL', hue='LITH', col_wrap=4)g.map(sns.scatterplot, 'NPHI', 'RHOB', linewidth=1, size=0.1, marker='+')g.set(xlim=(-0.15, 1))g.set(ylim=(3, 1))g.add_legend()"
},
{
"code": null,
"e": 11443,
"s": 11326,
"text": "We can easily swap out the grouping option for the geological GROUP column to view the lithology variation by group."
},
{
"code": null,
"e": 11631,
"s": 11443,
"text": "g = sns.FacetGrid(data, col='GROUP', hue='LITH', col_wrap=4)g.map(sns.scatterplot, 'NPHI', 'RHOB', linewidth=1, size=0.1, marker='+')g.set(xlim=(-0.15, 1))g.set(ylim=(3, 1))g.add_legend()"
},
{
"code": null,
"e": 11796,
"s": 11631,
"text": "From this chart, we can quickly see that the Rotliegendes Gp is primarily sandstone and that the Nordaland Gp is a mixture of Shale and Sandstone/Shale lithologies."
},
{
"code": null,
"e": 12076,
"s": 11796,
"text": "The Seaborn library also has a very powerful visualisation known as a pairplot which can be called through a single line of code. This allows us to compare, on a grid, multiple columns/measurements against each other. The equivalent code in matplotlib would extend several lines."
},
{
"code": null,
"e": 12438,
"s": 12076,
"text": "Prior to displaying the pairplot we need to modify the data we are using. Firstly, we will work with a subset of the data consisting of some commonly used well logs. If we used all of the columns in the example for this article, we would be unable to view the details. Secondly, we need to drop any missing data values, otherwise issues can arise when plotting."
},
{
"code": null,
"e": 12478,
"s": 12438,
"text": "To create a list of the curves we want:"
},
{
"code": null,
"e": 12557,
"s": 12478,
"text": "key_logs = ['CALI', 'GR', 'NPHI', 'RHOB', 'PEF', 'RDEP', 'RMED', 'DTC', 'DTS']"
},
{
"code": null,
"e": 12596,
"s": 12557,
"text": "We can then take a subset of our data:"
},
{
"code": null,
"e": 12644,
"s": 12596,
"text": "subset = data[key_logs]subset = subset.dropna()"
},
{
"code": null,
"e": 12737,
"s": 12644,
"text": "Once we have the list of key curves we can pass it in to the vars argument in the pair plot."
},
{
"code": null,
"e": 12832,
"s": 12737,
"text": "sns.pairplot(subset, vars=key_logs, diag_kind='hist', plot_kws={'alpha':0.6, 'edgecolor':'k'})"
},
{
"code": null,
"e": 13079,
"s": 12832,
"text": "This produces multiple scatter plots with a histogram of each of the curves along the diagonal. As you can see this allows us to quickly understand how data is distributed and correlated between the different logging curves. A very powerful plot!"
},
{
"code": null,
"e": 13391,
"s": 13079,
"text": "In this section we will briefly look at a way to visualise where we have badhole data caused by borehole enlargement. Deterioration of the borehole wall can happen for a number of different reasons including undercompacted rocks and variations in stresses acting on those rocks such as variations in mud weight."
},
{
"code": null,
"e": 13751,
"s": 13391,
"text": "As identified in the missing data section only 10 of our wells have a bitsize curve. Therefore, 2 wells will not be plotted. We can use the bitsize curve alongside the caliper curve to create a difference caliper. Negative numbers indicate the borehole has shrunk in size (e.g. shale swelling) and positive numbers indicate the borehole has increased in size."
},
{
"code": null,
"e": 13795,
"s": 13751,
"text": "data['DIF_CAL'] = data['CALI'] - data['BS']"
},
{
"code": null,
"e": 13888,
"s": 13795,
"text": "As we will be using matplotlib for these plots we first need to group the dataframe by WELL:"
},
{
"code": null,
"e": 13919,
"s": 13888,
"text": "grouped = data.groupby('WELL')"
},
{
"code": null,
"e": 13975,
"s": 13919,
"text": "Then calculate the number of rows we need for our plot:"
},
{
"code": null,
"e": 14015,
"s": 13975,
"text": "nrows = int(math.ceil(len(grouped)/3.))"
},
{
"code": null,
"e": 14281,
"s": 14015,
"text": "Finally, we can use a small for loop to go through each well and add a subplot of density vs neutron to our figure. The c argument in df.plot allows us to specify a column in our dataframe to colour the data. In this case we will use the DIF_CAL data we calculated."
},
{
"code": null,
"e": 14558,
"s": 14281,
"text": "fig, axs = plt.subplots(nrows, 3, figsize=(20,20))for (name, df), ax in zip(grouped, axs.flat): df.plot(kind='scatter', x='NPHI', y='RHOB', ax=ax, c='DIF_CAL', cmap='jet', vmin=-1, vmax=10) ax.set_xlim(-0.15,1) ax.set_ylim(3,1) ax.set_title(name)plt.tight_layout()"
},
{
"code": null,
"e": 14711,
"s": 14558,
"text": "From a quick glance we can see that we may have issues with the data in two of the wells: 15/9–15 and 16/1–2. These should then be investigated further."
},
{
"code": null,
"e": 14947,
"s": 14711,
"text": "We can also apply the same idea to our lithologies. If we find that a lithology is badly affected by badhole conditions, there could be potential consequences when attempting to predict that lithology using machine learning algorithms."
},
{
"code": null,
"e": 15027,
"s": 14947,
"text": "To do this, we group the data by LITH and use the same plotting logic as above."
},
{
"code": null,
"e": 15440,
"s": 15027,
"text": "# Determine number of rowsnrows = int(math.ceil(len(grouped)/3.))# Group our datagrouped_lith = data.groupby('LITH')# Plot our datafig, axs = plt.subplots(nrows, 3, figsize=(20,20))for (name, df), ax in zip(grouped_lith, axs.flat): df.plot(kind='scatter', x='NPHI', y='RHOB', c='DIF_CAL', cmap='jet', ax=ax, vmin=-1, vmax=10) ax.set_xlim(-0.05,1) ax.set_ylim(3,0) ax.set_title(name)plt.tight_layout()"
},
{
"code": null,
"e": 15531,
"s": 15440,
"text": "From the plot, we can see that all lithologies have a large degree of ‘good’ data in them."
},
{
"code": null,
"e": 15890,
"s": 15531,
"text": "In this article, we have covered some of thee ways in which you can explore and visualise well log data using common Python libraries. We have seen how to use Seaborn to quickly plot multiple datasets on single figures and split that data by wells and lithology. We have also seen how to quickly identify missing data and data affected by badhole conditions."
},
{
"code": null,
"e": 16048,
"s": 15890,
"text": "Exploring your data is a great way to become familiar with it and understand it, especially prior to carrying out machine learning or further interpretation."
},
{
"code": null,
"e": 16221,
"s": 16048,
"text": "Bormann P., Aursand P., Dilib F., Dischington P., Manral S. 2020. 2020 FORCE Machine Learning Contest. https://github.com/bolgebrygg/Force-2020-Machine-Learning-competition"
}
] |
Material - Alert Icons
|
This chapter explains the usage of Google's (Material) Alert icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below.
<!DOCTYPE html>
<html>
<head>
<link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
<style>
i.custom {font-size: 2em; color: green;}
</style>
</head>
<body>
<i class = "material-icons custom">accessibility</i>
</body>
</html>
The following table contains the usage and results of Google's (Material) Alert icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs −
26 Lectures
2 hours
Neha Gupta
20 Lectures
2 hours
Asif Hussain
43 Lectures
5 hours
Sharad Kumar
411 Lectures
38.5 hours
In28Minutes Official
71 Lectures
10 hours
Chaand Sheikh
207 Lectures
33 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2749,
"s": 2566,
"text": "This chapter explains the usage of Google's (Material) Alert icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below."
},
{
"code": null,
"e": 3067,
"s": 2749,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://fonts.googleapis.com/icon?family=Material+Icons\" rel = \"stylesheet\">\n\t\t\n <style>\n i.custom {font-size: 2em; color: green;}\n </style>\n\t\t\n </head>\n\t\n <body>\n <i class = \"material-icons custom\">accessibility</i>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3265,
"s": 3067,
"text": "The following table contains the usage and results of Google's (Material) Alert icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs −"
},
{
"code": null,
"e": 3298,
"s": 3265,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3310,
"s": 3298,
"text": " Neha Gupta"
},
{
"code": null,
"e": 3343,
"s": 3310,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3357,
"s": 3343,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3390,
"s": 3357,
"text": "\n 43 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3404,
"s": 3390,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 3441,
"s": 3404,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 3463,
"s": 3441,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3497,
"s": 3463,
"text": "\n 71 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3512,
"s": 3497,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3547,
"s": 3512,
"text": "\n 207 Lectures \n 33 hours \n"
},
{
"code": null,
"e": 3575,
"s": 3547,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3582,
"s": 3575,
"text": " Print"
},
{
"code": null,
"e": 3593,
"s": 3582,
"text": " Add Notes"
}
] |
Functions in JavaScript - GeeksforGeeks
|
22 Jun, 2020
A function is a set of statements that take inputs, do some specific computation, and produces output. Basically, a function is a set of statements that performs some tasks or does some computation and then return the result to the user.
The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call that function.
Like other programming languages, JavaScript also supports the use of functions. You must already have seen some commonly used functions in JavaScript like alert(), this is a built-in function in JavaScript. But JavaScript allows us to create user-defined functions also.
We can create functions in JavaScript using the keyword function. The basic syntax to create a function in JavaScript is shown below.
Syntax:
function functionName(Parameter1, Parameter2, ..)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function, separated by name of function and parameters within parenthesis. The part of function inside the curly braces {} is the body of the function.
Function Definition
Before, using a user-defined function in JavaScript we have to create one. We can use the above syntax to create a function in JavaScript. A function definition is sometimes also termed as function declaration or function statement.
Below are the rules for creating a function in JavaScript:
Every function should begin with the keyword function followed by,
A user defined function name which should be unique,
A list of parameters enclosed within parenthesis and separated by commas,
A list of statement composing the body of the function enclosed within curly braces {}.
Example:
function calcAddition(number1, number2) { return number1 + number2; }
In the above example, we have created a function named calcAddition, this function accepts two numbers as parameters and returns the addition of these two numbers.
Function Parameters
Till now we have heard a lot about function parameters but haven\’t discussed them in detail. Parameters are additional information passed to a function. For example, in the above example, the task of the function calcAddition is to calculate addition of two numbers. These two numbers on which we want to perform the addition operation are passed to this function as parameters. The parameters are passed to the function within parentheses after the function name and separated by commas. A function in JavaScript can have any number of parameters and also at the same time a function in JavaScript can not have a single parameter.
Calling Functions: After defining a function, the next step is to call them to make use of the function. We can call a function by using the function name separated by the value of parameters enclosed between parenthesis and a semicolon at the end. Below syntax shows how to call functions in JavaScript:
functionName( Value1, Value2, ..);
Below is a sample program that illustrate working of functions in JavaScript:
<script type = "text/javascript"> // Function definitionfunction welcomeMsg(name) { document.write("Hello " + name + " welcome to GeeksforGeeks");} // creating a variablevar nameVal = "Admin"; // calling the functionwelcomeMsg(nameVal); </script>
Output:
Hello Admin welcome to GeeksforGeeks
Return Statement: There are some situations when we want to return some values from a function after performing some operations. In such cases, we can make use of the return statement in JavaScript. This is an optional statement and most of the times the last statement in a JavaScript function. Look at our first example with the function named as calcAddition. This function is calculating two numbers and then returning the result. The most basic syntax of using the return statement is:
return value;
The return statement begins with the keyword return separated by the value which we want to return from it. We can use an expression also instead of directly returning the value.
Javascript | Arrow functions
JavaScript | escape()
JavaScript | unescape()
JavaScript | Window print()
Javascript | Window Blur() and Window Focus() Method
JavaScript | console.log()
JavaScript | parseFloat()
JavaScript | uneval()
JavaScript | parseInt()
JavaScript | match()
JavaScript | Date.parse()
JavaScipt | Replace() Method
JavaScript | Map.get( )
JavaScript | Map.entries( )
JavaScript | Map.clear( )
JavaScript | Map.delete()
JavaScript | Map.has( )
More>>
ManasChhabra2
javascript-basics
javascript-functions
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
|
[
{
"code": null,
"e": 30082,
"s": 30054,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 30320,
"s": 30082,
"text": "A function is a set of statements that take inputs, do some specific computation, and produces output. Basically, a function is a set of statements that performs some tasks or does some computation and then return the result to the user."
},
{
"code": null,
"e": 30513,
"s": 30320,
"text": "The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call that function."
},
{
"code": null,
"e": 30785,
"s": 30513,
"text": "Like other programming languages, JavaScript also supports the use of functions. You must already have seen some commonly used functions in JavaScript like alert(), this is a built-in function in JavaScript. But JavaScript allows us to create user-defined functions also."
},
{
"code": null,
"e": 30919,
"s": 30785,
"text": "We can create functions in JavaScript using the keyword function. The basic syntax to create a function in JavaScript is shown below."
},
{
"code": null,
"e": 30927,
"s": 30919,
"text": "Syntax:"
},
{
"code": null,
"e": 31003,
"s": 30927,
"text": "function functionName(Parameter1, Parameter2, ..)\n{\n // Function body\n}\n"
},
{
"code": null,
"e": 31224,
"s": 31003,
"text": "To create a function in JavaScript, we have to first use the keyword function, separated by name of function and parameters within parenthesis. The part of function inside the curly braces {} is the body of the function."
},
{
"code": null,
"e": 31244,
"s": 31224,
"text": "Function Definition"
},
{
"code": null,
"e": 31477,
"s": 31244,
"text": "Before, using a user-defined function in JavaScript we have to create one. We can use the above syntax to create a function in JavaScript. A function definition is sometimes also termed as function declaration or function statement."
},
{
"code": null,
"e": 31536,
"s": 31477,
"text": "Below are the rules for creating a function in JavaScript:"
},
{
"code": null,
"e": 31603,
"s": 31536,
"text": "Every function should begin with the keyword function followed by,"
},
{
"code": null,
"e": 31656,
"s": 31603,
"text": "A user defined function name which should be unique,"
},
{
"code": null,
"e": 31730,
"s": 31656,
"text": "A list of parameters enclosed within parenthesis and separated by commas,"
},
{
"code": null,
"e": 31818,
"s": 31730,
"text": "A list of statement composing the body of the function enclosed within curly braces {}."
},
{
"code": null,
"e": 31827,
"s": 31818,
"text": "Example:"
},
{
"code": "function calcAddition(number1, number2) { return number1 + number2; }",
"e": 31901,
"s": 31827,
"text": null
},
{
"code": null,
"e": 32065,
"s": 31901,
"text": "In the above example, we have created a function named calcAddition, this function accepts two numbers as parameters and returns the addition of these two numbers."
},
{
"code": null,
"e": 32085,
"s": 32065,
"text": "Function Parameters"
},
{
"code": null,
"e": 32718,
"s": 32085,
"text": "Till now we have heard a lot about function parameters but haven\\’t discussed them in detail. Parameters are additional information passed to a function. For example, in the above example, the task of the function calcAddition is to calculate addition of two numbers. These two numbers on which we want to perform the addition operation are passed to this function as parameters. The parameters are passed to the function within parentheses after the function name and separated by commas. A function in JavaScript can have any number of parameters and also at the same time a function in JavaScript can not have a single parameter."
},
{
"code": null,
"e": 33023,
"s": 32718,
"text": "Calling Functions: After defining a function, the next step is to call them to make use of the function. We can call a function by using the function name separated by the value of parameters enclosed between parenthesis and a semicolon at the end. Below syntax shows how to call functions in JavaScript:"
},
{
"code": null,
"e": 33059,
"s": 33023,
"text": "functionName( Value1, Value2, ..);\n"
},
{
"code": null,
"e": 33137,
"s": 33059,
"text": "Below is a sample program that illustrate working of functions in JavaScript:"
},
{
"code": "<script type = \"text/javascript\"> // Function definitionfunction welcomeMsg(name) { document.write(\"Hello \" + name + \" welcome to GeeksforGeeks\");} // creating a variablevar nameVal = \"Admin\"; // calling the functionwelcomeMsg(nameVal); </script>",
"e": 33390,
"s": 33137,
"text": null
},
{
"code": null,
"e": 33398,
"s": 33390,
"text": "Output:"
},
{
"code": null,
"e": 33436,
"s": 33398,
"text": "Hello Admin welcome to GeeksforGeeks\n"
},
{
"code": null,
"e": 33927,
"s": 33436,
"text": "Return Statement: There are some situations when we want to return some values from a function after performing some operations. In such cases, we can make use of the return statement in JavaScript. This is an optional statement and most of the times the last statement in a JavaScript function. Look at our first example with the function named as calcAddition. This function is calculating two numbers and then returning the result. The most basic syntax of using the return statement is:"
},
{
"code": null,
"e": 33942,
"s": 33927,
"text": "return value;\n"
},
{
"code": null,
"e": 34121,
"s": 33942,
"text": "The return statement begins with the keyword return separated by the value which we want to return from it. We can use an expression also instead of directly returning the value."
},
{
"code": null,
"e": 34150,
"s": 34121,
"text": "Javascript | Arrow functions"
},
{
"code": null,
"e": 34172,
"s": 34150,
"text": "JavaScript | escape()"
},
{
"code": null,
"e": 34196,
"s": 34172,
"text": "JavaScript | unescape()"
},
{
"code": null,
"e": 34224,
"s": 34196,
"text": "JavaScript | Window print()"
},
{
"code": null,
"e": 34277,
"s": 34224,
"text": "Javascript | Window Blur() and Window Focus() Method"
},
{
"code": null,
"e": 34304,
"s": 34277,
"text": "JavaScript | console.log()"
},
{
"code": null,
"e": 34330,
"s": 34304,
"text": "JavaScript | parseFloat()"
},
{
"code": null,
"e": 34352,
"s": 34330,
"text": "JavaScript | uneval()"
},
{
"code": null,
"e": 34376,
"s": 34352,
"text": "JavaScript | parseInt()"
},
{
"code": null,
"e": 34397,
"s": 34376,
"text": "JavaScript | match()"
},
{
"code": null,
"e": 34423,
"s": 34397,
"text": "JavaScript | Date.parse()"
},
{
"code": null,
"e": 34452,
"s": 34423,
"text": "JavaScipt | Replace() Method"
},
{
"code": null,
"e": 34476,
"s": 34452,
"text": "JavaScript | Map.get( )"
},
{
"code": null,
"e": 34504,
"s": 34476,
"text": "JavaScript | Map.entries( )"
},
{
"code": null,
"e": 34530,
"s": 34504,
"text": "JavaScript | Map.clear( )"
},
{
"code": null,
"e": 34556,
"s": 34530,
"text": "JavaScript | Map.delete()"
},
{
"code": null,
"e": 34580,
"s": 34556,
"text": "JavaScript | Map.has( )"
},
{
"code": null,
"e": 34587,
"s": 34580,
"text": "More>>"
},
{
"code": null,
"e": 34601,
"s": 34587,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 34619,
"s": 34601,
"text": "javascript-basics"
},
{
"code": null,
"e": 34640,
"s": 34619,
"text": "javascript-functions"
},
{
"code": null,
"e": 34656,
"s": 34640,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 34667,
"s": 34656,
"text": "JavaScript"
},
{
"code": null,
"e": 34765,
"s": 34667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34774,
"s": 34765,
"text": "Comments"
},
{
"code": null,
"e": 34787,
"s": 34774,
"text": "Old Comments"
},
{
"code": null,
"e": 34832,
"s": 34787,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34901,
"s": 34832,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 34962,
"s": 34901,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 35034,
"s": 34962,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 35061,
"s": 35034,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 35113,
"s": 35061,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 35159,
"s": 35113,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 35212,
"s": 35159,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 35253,
"s": 35212,
"text": "Difference Between PUT and PATCH Request"
}
] |
How can I filter JSON data with multiple objects?
|
To filter JSON data with multiple objects, you can use the concept of filter along with ==.
const jsonObject=
[
{
studentId:101,
studentName:"David"
},
{
studentId:102,
studentName:"Mike"
},
{
studentId:103,
studentName:"David"
},
{
studentId:104,
studentName:"Bob"
}
]
var result=jsonObject.filter(obj=> obj.studentName == "David");
console.log(result);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo194.js. This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo194.js
[
{ studentId: 101, studentName: 'David' },
{ studentId: 103, studentName: 'David' }
]
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To filter JSON data with multiple objects, you can use the concept of filter along with ==."
},
{
"code": null,
"e": 1489,
"s": 1154,
"text": "const jsonObject=\n[\n {\n studentId:101,\n studentName:\"David\"\n },\n {\n studentId:102,\n studentName:\"Mike\"\n },\n {\n studentId:103,\n studentName:\"David\"\n },\n {\n studentId:104,\n studentName:\"Bob\"\n }\n]\nvar result=jsonObject.filter(obj=> obj.studentName == \"David\");\nconsole.log(result);"
},
{
"code": null,
"e": 1555,
"s": 1489,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1573,
"s": 1555,
"text": "node fileName.js."
},
{
"code": null,
"e": 1648,
"s": 1573,
"text": "Here, my file name is demo194.js. This will produce the following output −"
},
{
"code": null,
"e": 1791,
"s": 1648,
"text": "PS C:\\Users\\Amit\\javascript-code> node demo194.js\n[\n { studentId: 101, studentName: 'David' },\n { studentId: 103, studentName: 'David' }\n]"
}
] |
How to control the width and height of the default Alert Dialog in iOS?
|
There will be instance where you might get a requirement to control / manipulate width and height the Alert while developing iOS application. If you’re not familiar with the same, it can trouble you.
Here we will be seeing how to control the width and height of default alert box, For controlling the height and width we will be using NSLayoutConstraint.
To read more about UIAlertController refer −
https://developer.apple.com/documentation/uikit/uialertcontroller
In this, we will be creating a new project where we will have a button, on tapping that button we will show alert with custom message.
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “changeheightandwidth”
Step 2 − In Main.storyboard create one button and name it tap, create @IBAction in ViewController.swift and name outlet btnAtap.
Step 3 − Write the following code in your button method.
Create object of UIAlertController.
let alert = UIAlertController(title: "Your Title", message: "Your Message", preferredStyle: UIAlertController.Style.alert)
Create height and width constraints.
// height constraint
let constraintHeight = NSLayoutConstraint(
item: alert.view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute:
NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)
alert.view.addConstraint(constraintHeight)
// width constraint
let constraintWidth = NSLayoutConstraint(
item: alert.view!, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute:
NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 300)
alert.view.addConstraint(constraintWidth)
Present the alert view with actions.
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancel)
let OKAY = UIAlertAction(title: "Done", style: .default, handler: nil)
alert.addAction(OKAY)
self.present(alert, animated: true, completion: nil)
Step 4− Run the code.
For complete code,
@IBAction func btnATap(_ sender: Any) {
let alert = UIAlertController(title: "Your Title", message: "Your Message", preferredStyle: UIAlertController.Style.alert)
// height constraint
let constraintHeight = NSLayoutConstraint(
item: alert.view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute:
NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)
alert.view.addConstraint(constraintHeight)
// width constraint
let constraintWidth = NSLayoutConstraint(
item: alert.view!, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute:
NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 300)
alert.view.addConstraint(constraintWidth)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancel)
let OKAY = UIAlertAction(title: "Done", style: .default, handler: nil)
alert.addAction(OKAY)
self.present(alert, animated: true, completion: nil)
}
|
[
{
"code": null,
"e": 1262,
"s": 1062,
"text": "There will be instance where you might get a requirement to control / manipulate width and height the Alert while developing iOS application. If you’re not familiar with the same, it can trouble you."
},
{
"code": null,
"e": 1417,
"s": 1262,
"text": "Here we will be seeing how to control the width and height of default alert box, For controlling the height and width we will be using NSLayoutConstraint."
},
{
"code": null,
"e": 1462,
"s": 1417,
"text": "To read more about UIAlertController refer −"
},
{
"code": null,
"e": 1529,
"s": 1462,
"text": " https://developer.apple.com/documentation/uikit/uialertcontroller"
},
{
"code": null,
"e": 1664,
"s": 1529,
"text": "In this, we will be creating a new project where we will have a button, on tapping that button we will show alert with custom message."
},
{
"code": null,
"e": 1763,
"s": 1664,
"text": "Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “changeheightandwidth”"
},
{
"code": null,
"e": 1892,
"s": 1763,
"text": "Step 2 − In Main.storyboard create one button and name it tap, create @IBAction in ViewController.swift and name outlet btnAtap."
},
{
"code": null,
"e": 1949,
"s": 1892,
"text": "Step 3 − Write the following code in your button method."
},
{
"code": null,
"e": 1985,
"s": 1949,
"text": "Create object of UIAlertController."
},
{
"code": null,
"e": 2108,
"s": 1985,
"text": "let alert = UIAlertController(title: \"Your Title\", message: \"Your Message\", preferredStyle: UIAlertController.Style.alert)"
},
{
"code": null,
"e": 2145,
"s": 2108,
"text": "Create height and width constraints."
},
{
"code": null,
"e": 2792,
"s": 2145,
"text": "// height constraint\nlet constraintHeight = NSLayoutConstraint(\n item: alert.view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute:\n NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)\nalert.view.addConstraint(constraintHeight)\n\n// width constraint\nlet constraintWidth = NSLayoutConstraint(\n item: alert.view!, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute:\n NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 300)\nalert.view.addConstraint(constraintWidth)"
},
{
"code": null,
"e": 2829,
"s": 2792,
"text": "Present the alert view with actions."
},
{
"code": null,
"e": 3073,
"s": 2829,
"text": "let cancel = UIAlertAction(title: \"Cancel\", style: .cancel, handler: nil)\nalert.addAction(cancel)\nlet OKAY = UIAlertAction(title: \"Done\", style: .default, handler: nil)\nalert.addAction(OKAY)\nself.present(alert, animated: true, completion: nil)"
},
{
"code": null,
"e": 3095,
"s": 3073,
"text": "Step 4− Run the code."
},
{
"code": null,
"e": 3114,
"s": 3095,
"text": "For complete code,"
},
{
"code": null,
"e": 4220,
"s": 3114,
"text": "@IBAction func btnATap(_ sender: Any) {\n let alert = UIAlertController(title: \"Your Title\", message: \"Your Message\", preferredStyle: UIAlertController.Style.alert)\n\n // height constraint\n let constraintHeight = NSLayoutConstraint(\n item: alert.view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute:\n NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)\n alert.view.addConstraint(constraintHeight)\n\n // width constraint\n let constraintWidth = NSLayoutConstraint(\n item: alert.view!, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute:\n NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 300)\n alert.view.addConstraint(constraintWidth)\n\n let cancel = UIAlertAction(title: \"Cancel\", style: .cancel, handler: nil)\n alert.addAction(cancel)\n let OKAY = UIAlertAction(title: \"Done\", style: .default, handler: nil)\n alert.addAction(OKAY)\n self.present(alert, animated: true, completion: nil)\n}"
}
] |
queue::swap() in C++ STL
|
In this article we will be discussing the working, syntax and examples of queue::swap() function in C++ STL.
Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue.
queue::swap() is an inbuilt function in C++ STL which is declared in header file. queue::swap() is used to swap the contents of the queue containers. This function accepts one parameter, which is the other queue container with whom we wish to swap the contents of the associated queue container.
myqueue1.swap(myqueue2);
This function accepts one parameter the second queue container with whom we wish to swap the associated queue.
This function returns nothing.
Input: queue<int> odd = {1, 3, 5};
queue<int> eve = {2. 4. 6};
Output:
Odd: 2 4 6
Eve: 1 3 5
Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
queue<int> Queue_1, Queue_2;
for(int i=0 ;i<=5 ;i++){
Queue_1.push(i);
}
for(int i=5 ;i<=10 ;i++){
Queue_2.push(i);
}
//call swap function
Queue_1.swap(Queue_2);
cout<<"Element in Queue_1 are: ";
while (!Queue_1.empty()){
cout << ' ' << Queue_1.front();
Queue_1.pop();
}
cout<<"\nElement in Queue_2 are: ";
while (!Queue_2.empty()){
cout << ' ' << Queue_2.front();
Queue_2.pop();
}
}
If we run the above code it will generate the following output −
Element in Queue_1 are: 5 6 7 8 9 10
Element in Queue_1 are: 0 1 2 3 4 5
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "In this article we will be discussing the working, syntax and examples of queue::swap() function in C++ STL."
},
{
"code": null,
"e": 1585,
"s": 1171,
"text": "Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue."
},
{
"code": null,
"e": 1882,
"s": 1585,
"text": "queue::swap() is an inbuilt function in C++ STL which is declared in header file. queue::swap() is used to swap the contents of the queue containers. This function accepts one parameter, which is the other queue container with whom we wish to swap the contents of the associated queue container."
},
{
"code": null,
"e": 1907,
"s": 1882,
"text": "myqueue1.swap(myqueue2);"
},
{
"code": null,
"e": 2018,
"s": 1907,
"text": "This function accepts one parameter the second queue container with whom we wish to swap the associated queue."
},
{
"code": null,
"e": 2049,
"s": 2018,
"text": "This function returns nothing."
},
{
"code": null,
"e": 2160,
"s": 2049,
"text": "Input: queue<int> odd = {1, 3, 5};\n queue<int> eve = {2. 4. 6};\nOutput:\n Odd: 2 4 6\n Eve: 1 3 5"
},
{
"code": null,
"e": 2171,
"s": 2160,
"text": " Live Demo"
},
{
"code": null,
"e": 2700,
"s": 2171,
"text": "#include <iostream>\n#include <queue>\nusing namespace std;\nint main(){\n queue<int> Queue_1, Queue_2;\n for(int i=0 ;i<=5 ;i++){\n Queue_1.push(i);\n }\n for(int i=5 ;i<=10 ;i++){\n Queue_2.push(i);\n }\n //call swap function\n Queue_1.swap(Queue_2);\n cout<<\"Element in Queue_1 are: \";\n while (!Queue_1.empty()){\n cout << ' ' << Queue_1.front();\n Queue_1.pop();\n }\n cout<<\"\\nElement in Queue_2 are: \";\n while (!Queue_2.empty()){\n cout << ' ' << Queue_2.front();\n Queue_2.pop();\n }\n}"
},
{
"code": null,
"e": 2765,
"s": 2700,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 2838,
"s": 2765,
"text": "Element in Queue_1 are: 5 6 7 8 9 10\nElement in Queue_1 are: 0 1 2 3 4 5"
}
] |
How to convert a Python for loop to while loop?
|
Unlike while loop, for loop in Python doesn't need a counting variable to keep count of number of iterations. Hence, to convert a for loop into equivalent while loop, this fact must be taken into consideration.
Following is a simple for loop that traverses over a range
for x in range(5):
print (x)
To convert into a while loop, we initialize a counting variable to 0 before the loop begins and increment it by 1 in every iteration as long as it is less than 5
x=0
while x<5:
x=x+1
print (x)
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "Unlike while loop, for loop in Python doesn't need a counting variable to keep count of number of iterations. Hence, to convert a for loop into equivalent while loop, this fact must be taken into consideration."
},
{
"code": null,
"e": 1332,
"s": 1273,
"text": "Following is a simple for loop that traverses over a range"
},
{
"code": null,
"e": 1368,
"s": 1332,
"text": "for x in range(5):\n print (x)\n\n"
},
{
"code": null,
"e": 1530,
"s": 1368,
"text": "To convert into a while loop, we initialize a counting variable to 0 before the loop begins and increment it by 1 in every iteration as long as it is less than 5"
},
{
"code": null,
"e": 1571,
"s": 1530,
"text": "x=0\nwhile x<5:\n x=x+1\n print (x)"
}
] |
Initialize a static Map in Java using Double Brace Initialization - GeeksforGeeks
|
03 Dec, 2019
In this article, a static map is created and initialised in Java using Double Brace Initialization.
Static Map in JavaA static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class.
Double Brace InitializationIn Double Brace Initialization:
The first brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behaviour of their parent class. So, in our case, we are actually creating a subclass of HashMap class, so this inner class is capable of using put() method.
The second braces are instance initializers. The code an instance initializers inside is executed whenever an instance is created.
Approach:
Pass the map values as Key and Value pair in the Double braces.
A static factory Map instance is returned.
Store it in Map and use.
Below is the implementation of the above approach:
Example 1:
// Java program to create a static map// using Double Brace Initialization import java.util.*; class GFG { // Declaring and instantiating the static map // using Double Brace Initialization private static Map<String, String> map = new HashMap<String, String>() {{ put("1", "GFG"); put("2", "Geek"); put("3", "GeeksForGeeks"); }}; // Driver code public static void main(String[] args) { System.out.println(map); }}
{1=GFG, 2=Geek, 3=GeeksForGeeks}
Example 2: To show with 10 key-value pairs
// Java program to create a static map// using Double Brace Initialization import java.util.*; class GFG { // Declaring and instantiating the static map // using Double Brace Initialization private static Map<String, String> map = new HashMap<String, String>() {{ put("1", "GFG"); put("2", "Geek"); put("3", "GeeksForGeeks"); put("4", "G"); put("5", "e"); put("6", "e"); put("7", "k"); put("8", "s"); put("9", "f"); put("10", "o"); }}; // Driver code public static void main(String[] args) { System.out.println(map); }}
{1=GFG, 2=Geek, 3=GeeksForGeeks, 4=G, 5=e, 6=e, 7=k, 8=s, 9=f, 10=o}
Related Articles:
Initialize a static map in Java with Examples
Initialize a static Map using Stream in Java
Initialize a static Map using Java 9 Map.of()
java-map
Static Keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n03 Dec, 2019"
},
{
"code": null,
"e": 24048,
"s": 23948,
"text": "In this article, a static map is created and initialised in Java using Double Brace Initialization."
},
{
"code": null,
"e": 24197,
"s": 24048,
"text": "Static Map in JavaA static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class."
},
{
"code": null,
"e": 24256,
"s": 24197,
"text": "Double Brace InitializationIn Double Brace Initialization:"
},
{
"code": null,
"e": 24516,
"s": 24256,
"text": "The first brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behaviour of their parent class. So, in our case, we are actually creating a subclass of HashMap class, so this inner class is capable of using put() method."
},
{
"code": null,
"e": 24647,
"s": 24516,
"text": "The second braces are instance initializers. The code an instance initializers inside is executed whenever an instance is created."
},
{
"code": null,
"e": 24657,
"s": 24647,
"text": "Approach:"
},
{
"code": null,
"e": 24721,
"s": 24657,
"text": "Pass the map values as Key and Value pair in the Double braces."
},
{
"code": null,
"e": 24764,
"s": 24721,
"text": "A static factory Map instance is returned."
},
{
"code": null,
"e": 24789,
"s": 24764,
"text": "Store it in Map and use."
},
{
"code": null,
"e": 24840,
"s": 24789,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24851,
"s": 24840,
"text": "Example 1:"
},
{
"code": "// Java program to create a static map// using Double Brace Initialization import java.util.*; class GFG { // Declaring and instantiating the static map // using Double Brace Initialization private static Map<String, String> map = new HashMap<String, String>() {{ put(\"1\", \"GFG\"); put(\"2\", \"Geek\"); put(\"3\", \"GeeksForGeeks\"); }}; // Driver code public static void main(String[] args) { System.out.println(map); }}",
"e": 25346,
"s": 24851,
"text": null
},
{
"code": null,
"e": 25380,
"s": 25346,
"text": "{1=GFG, 2=Geek, 3=GeeksForGeeks}\n"
},
{
"code": null,
"e": 25423,
"s": 25380,
"text": "Example 2: To show with 10 key-value pairs"
},
{
"code": "// Java program to create a static map// using Double Brace Initialization import java.util.*; class GFG { // Declaring and instantiating the static map // using Double Brace Initialization private static Map<String, String> map = new HashMap<String, String>() {{ put(\"1\", \"GFG\"); put(\"2\", \"Geek\"); put(\"3\", \"GeeksForGeeks\"); put(\"4\", \"G\"); put(\"5\", \"e\"); put(\"6\", \"e\"); put(\"7\", \"k\"); put(\"8\", \"s\"); put(\"9\", \"f\"); put(\"10\", \"o\"); }}; // Driver code public static void main(String[] args) { System.out.println(map); }}",
"e": 26101,
"s": 25423,
"text": null
},
{
"code": null,
"e": 26171,
"s": 26101,
"text": "{1=GFG, 2=Geek, 3=GeeksForGeeks, 4=G, 5=e, 6=e, 7=k, 8=s, 9=f, 10=o}\n"
},
{
"code": null,
"e": 26189,
"s": 26171,
"text": "Related Articles:"
},
{
"code": null,
"e": 26235,
"s": 26189,
"text": "Initialize a static map in Java with Examples"
},
{
"code": null,
"e": 26280,
"s": 26235,
"text": "Initialize a static Map using Stream in Java"
},
{
"code": null,
"e": 26326,
"s": 26280,
"text": "Initialize a static Map using Java 9 Map.of()"
},
{
"code": null,
"e": 26335,
"s": 26326,
"text": "java-map"
},
{
"code": null,
"e": 26350,
"s": 26335,
"text": "Static Keyword"
},
{
"code": null,
"e": 26355,
"s": 26350,
"text": "Java"
},
{
"code": null,
"e": 26360,
"s": 26355,
"text": "Java"
},
{
"code": null,
"e": 26458,
"s": 26360,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26473,
"s": 26458,
"text": "Stream In Java"
},
{
"code": null,
"e": 26519,
"s": 26473,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26540,
"s": 26519,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26559,
"s": 26540,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26589,
"s": 26559,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26606,
"s": 26589,
"text": "Generics in Java"
},
{
"code": null,
"e": 26649,
"s": 26606,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26678,
"s": 26649,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26699,
"s": 26678,
"text": "Introduction to Java"
}
] |
How to output colored text to a Linux terminal?
|
Here we will see how to print some lines into the linux terminal with some color. Here we are doing anything special into C++ code. We are just using some linux terminal commands to do this. The command for this kind of output is like below.
\033[1;31m Sample Text \033[0m
There are some codes for text styles and colors. These are listed below.
Some additional options are like below −
#include<iostream>
using namespace std;
main() {
cout << "\033[1;31mThis is bold red text\033[0m\n";
cout << "\033[;32mGreen Text\033[0m\n";
cout << "\033[4;33mYellow underlined text\033[0m\n";
cout << "\033[;34mBlue text\033[0m\n";
}
|
[
{
"code": null,
"e": 1304,
"s": 1062,
"text": "Here we will see how to print some lines into the linux terminal with some color. Here we are doing anything special into C++ code. We are just using some linux terminal commands to do this. The command for this kind of output is like below."
},
{
"code": null,
"e": 1335,
"s": 1304,
"text": "\\033[1;31m Sample Text \\033[0m"
},
{
"code": null,
"e": 1408,
"s": 1335,
"text": "There are some codes for text styles and colors. These are listed below."
},
{
"code": null,
"e": 1449,
"s": 1408,
"text": "Some additional options are like below −"
},
{
"code": null,
"e": 1696,
"s": 1449,
"text": "#include<iostream>\nusing namespace std;\nmain() {\n cout << \"\\033[1;31mThis is bold red text\\033[0m\\n\";\n cout << \"\\033[;32mGreen Text\\033[0m\\n\";\n cout << \"\\033[4;33mYellow underlined text\\033[0m\\n\";\n cout << \"\\033[;34mBlue text\\033[0m\\n\";\n}"
}
] |
Exit Methods in C# Application
|
The Environment.Exit() method terminates the process and returns an exit code to the operating system −
Environment.Exit(exitCode);
Use exitCode as 0 (zero) to show that the process completed successfully.
Use exitCode as a non-zero number to show an error, for example −
Environment.Exit(1) − Return a value 1 to show that the file you want is not present
Environment.Exit(1) − Return a value 1 to show that the file you want is not present
Environment.Exit(2) − Return a value 2 to indicate that the file is in an incorrect format.
Environment.Exit(2) − Return a value 2 to indicate that the file is in an incorrect format.
To close a subapplication or current thread in a Windows Form, use theSystem.Windows.Forms.Application.ExitThread( ).
private void buttonClose_Click(object sender, EventArgs eventArgs) {
System.Windows.Forms.Application.ExitThread( );
}
|
[
{
"code": null,
"e": 1166,
"s": 1062,
"text": "The Environment.Exit() method terminates the process and returns an exit code to the operating system −"
},
{
"code": null,
"e": 1194,
"s": 1166,
"text": "Environment.Exit(exitCode);"
},
{
"code": null,
"e": 1268,
"s": 1194,
"text": "Use exitCode as 0 (zero) to show that the process completed successfully."
},
{
"code": null,
"e": 1334,
"s": 1268,
"text": "Use exitCode as a non-zero number to show an error, for example −"
},
{
"code": null,
"e": 1419,
"s": 1334,
"text": "Environment.Exit(1) − Return a value 1 to show that the file you want is not present"
},
{
"code": null,
"e": 1504,
"s": 1419,
"text": "Environment.Exit(1) − Return a value 1 to show that the file you want is not present"
},
{
"code": null,
"e": 1596,
"s": 1504,
"text": "Environment.Exit(2) − Return a value 2 to indicate that the file is in an incorrect format."
},
{
"code": null,
"e": 1688,
"s": 1596,
"text": "Environment.Exit(2) − Return a value 2 to indicate that the file is in an incorrect format."
},
{
"code": null,
"e": 1806,
"s": 1688,
"text": "To close a subapplication or current thread in a Windows Form, use theSystem.Windows.Forms.Application.ExitThread( )."
},
{
"code": null,
"e": 1928,
"s": 1806,
"text": "private void buttonClose_Click(object sender, EventArgs eventArgs) {\n System.Windows.Forms.Application.ExitThread( );\n}"
}
] |
C# | Operator Overloading - GeeksforGeeks
|
07 Aug, 2021
The concept of overloading a function can also be applied to operators. Operator overloading gives the ability to use the same operator to do various operations. It provides additional capabilities to C# operators when they are applied to user-defined data types. It enables to make user-defined implementations of various operations where one or both of the operands are of a user-defined class. Only the predefined set of C# operators can be overloaded. To make operations on a user-defined data type is not as simple as the operations on a built-in data type. To use operators with user-defined data types, they need to be overloaded according to a programmer’s requirement. An operator can be overloaded by defining a function to it. The function of the operator is declared by using the operator keyword.
Syntax :
access specifier className operator Operator_symbol (parameters)
{
// Code
}
Note : Operator overloading is basically the mechanism of providing a special meaning to an ideal C# operator w.r.t. a user-defined data type such as structures or classes.
The following table describes the overloading ability of the various operators available in C# :
The return type can be of any type except void for unary operators like !, ~, + and dot (.) but the return type must be the type of ‘Type’ for – and ++ operators and must be a bool type for true as well as false operators. But do remember that the true and false operators can be overloaded as pairs only. The compilation error arises if a class declares one of these operators without declaring the other.
The following syntax shows the use of Unary operator –
operator (object);
here, operator is a symbol that denotes a unary operator.
operator a;
Example :
Input : 15, -25
Output : -15, 25
Input : -22, 18
Output : 22, -18
C#
// C# program to illustrate the// unary operator overloadingusing System;namespace Calculator { class Calculator { public int number1 , number2; public Calculator(int num1 , int num2) { number1 = num1; number2 = num2; } // Function to perform operation// By changing sign of integerspublic static Calculator operator -(Calculator c1){ c1.number1 = -c1.number1; c1.number2 = -c1.number2; return c1;} // Function to print the numberspublic void Print(){ Console.WriteLine ("Number1 = " + number1); Console.WriteLine ("Number2 = " + number2);}} class EntryPoint{ // Driver Code static void Main(String []args) { // using overloaded - operator // with the class object Calculator calc = new Calculator(15, -25); calc = -calc; // To display the result calc.Print(); }}}
Output :
Number1 = -15
Number2 = 25
Binary Operators will work with two Operands. Examples of binary operators include the Arithmetic Operators (+, -, *, /, %), Arithmetic Assignment operators (+=, -+, *=, /+, %=) and Relational Operators etc. Overloading a binary operator is similar to overloading a unary operator, except that a binary operator requires an additional parameter.
Syntax :
operator operator (object1, object2);
Here, second "operator" is a symbol that
denotes a binary operator.
operator + (a, b);
Example :
Input : 200, 40
Output : 240
Input : 300, 20
Output : 320
C#
// C# program to illustrate the// Binary Operator Overloadingusing System;namespace BinaryOverload { class Calculator { public int number = 0; // no-argument constructor public Calculator() {} // parameterized constructor public Calculator(int n) { number = n; } // Overloading of Binary "+" operator public static Calculator operator + (Calculator Calc1, Calculator Calc2) { Calculator Calc3 = new Calculator(0); Calc3.number = Calc2.number + Calc1.number; return Calc3; } // function to display result public void display() { Console.WriteLine("{0}", number); }} class CalNum { // Driver Code static void Main(string[] args) { Calculator num1 = new Calculator(200); Calculator num2 = new Calculator(40); Calculator num3 = new Calculator(); num3 = num1 + num2; num1.display(); // Displays 200 num2.display(); // Displays 40 num3.display(); // Displays 240 }}}
Output :
200
40
240
Benefits of Operator Overloading :
Operator Overloading provides additional capabilities to C# operators when they are applied to user-defined data types.
Operators may be considered as functions internal to the compiler.
abhishek0719kadiyan
CSharp Operators
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
Introduction to .NET Framework
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
C# | Replace() Method
Top 50 C# Interview Questions & Answers
|
[
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n07 Aug, 2021"
},
{
"code": null,
"e": 25079,
"s": 24268,
"text": "The concept of overloading a function can also be applied to operators. Operator overloading gives the ability to use the same operator to do various operations. It provides additional capabilities to C# operators when they are applied to user-defined data types. It enables to make user-defined implementations of various operations where one or both of the operands are of a user-defined class. Only the predefined set of C# operators can be overloaded. To make operations on a user-defined data type is not as simple as the operations on a built-in data type. To use operators with user-defined data types, they need to be overloaded according to a programmer’s requirement. An operator can be overloaded by defining a function to it. The function of the operator is declared by using the operator keyword. "
},
{
"code": null,
"e": 25089,
"s": 25079,
"text": "Syntax : "
},
{
"code": null,
"e": 25172,
"s": 25089,
"text": "access specifier className operator Operator_symbol (parameters)\n{\n // Code\n}"
},
{
"code": null,
"e": 25345,
"s": 25172,
"text": "Note : Operator overloading is basically the mechanism of providing a special meaning to an ideal C# operator w.r.t. a user-defined data type such as structures or classes."
},
{
"code": null,
"e": 25444,
"s": 25345,
"text": "The following table describes the overloading ability of the various operators available in C# : "
},
{
"code": null,
"e": 25852,
"s": 25444,
"text": "The return type can be of any type except void for unary operators like !, ~, + and dot (.) but the return type must be the type of ‘Type’ for – and ++ operators and must be a bool type for true as well as false operators. But do remember that the true and false operators can be overloaded as pairs only. The compilation error arises if a class declares one of these operators without declaring the other. "
},
{
"code": null,
"e": 25909,
"s": 25852,
"text": "The following syntax shows the use of Unary operator – "
},
{
"code": null,
"e": 26001,
"s": 25909,
"text": "operator (object); \nhere, operator is a symbol that denotes a unary operator. \noperator a; "
},
{
"code": null,
"e": 26013,
"s": 26001,
"text": "Example : "
},
{
"code": null,
"e": 26081,
"s": 26013,
"text": "Input : 15, -25\nOutput : -15, 25\n\nInput : -22, 18\nOutput : 22, -18 "
},
{
"code": null,
"e": 26084,
"s": 26081,
"text": "C#"
},
{
"code": "// C# program to illustrate the// unary operator overloadingusing System;namespace Calculator { class Calculator { public int number1 , number2; public Calculator(int num1 , int num2) { number1 = num1; number2 = num2; } // Function to perform operation// By changing sign of integerspublic static Calculator operator -(Calculator c1){ c1.number1 = -c1.number1; c1.number2 = -c1.number2; return c1;} // Function to print the numberspublic void Print(){ Console.WriteLine (\"Number1 = \" + number1); Console.WriteLine (\"Number2 = \" + number2);}} class EntryPoint{ // Driver Code static void Main(String []args) { // using overloaded - operator // with the class object Calculator calc = new Calculator(15, -25); calc = -calc; // To display the result calc.Print(); }}}",
"e": 26989,
"s": 26084,
"text": null
},
{
"code": null,
"e": 26999,
"s": 26989,
"text": "Output : "
},
{
"code": null,
"e": 27026,
"s": 26999,
"text": "Number1 = -15\nNumber2 = 25"
},
{
"code": null,
"e": 27373,
"s": 27026,
"text": "Binary Operators will work with two Operands. Examples of binary operators include the Arithmetic Operators (+, -, *, /, %), Arithmetic Assignment operators (+=, -+, *=, /+, %=) and Relational Operators etc. Overloading a binary operator is similar to overloading a unary operator, except that a binary operator requires an additional parameter. "
},
{
"code": null,
"e": 27383,
"s": 27373,
"text": "Syntax : "
},
{
"code": null,
"e": 27512,
"s": 27383,
"text": "operator operator (object1, object2); \nHere, second \"operator\" is a symbol that \ndenotes a binary operator. \noperator + (a, b); "
},
{
"code": null,
"e": 27524,
"s": 27512,
"text": "Example : "
},
{
"code": null,
"e": 27585,
"s": 27524,
"text": "Input : 200, 40\nOutput : 240\n\nInput : 300, 20 \nOutput : 320 "
},
{
"code": null,
"e": 27588,
"s": 27585,
"text": "C#"
},
{
"code": "// C# program to illustrate the// Binary Operator Overloadingusing System;namespace BinaryOverload { class Calculator { public int number = 0; // no-argument constructor public Calculator() {} // parameterized constructor public Calculator(int n) { number = n; } // Overloading of Binary \"+\" operator public static Calculator operator + (Calculator Calc1, Calculator Calc2) { Calculator Calc3 = new Calculator(0); Calc3.number = Calc2.number + Calc1.number; return Calc3; } // function to display result public void display() { Console.WriteLine(\"{0}\", number); }} class CalNum { // Driver Code static void Main(string[] args) { Calculator num1 = new Calculator(200); Calculator num2 = new Calculator(40); Calculator num3 = new Calculator(); num3 = num1 + num2; num1.display(); // Displays 200 num2.display(); // Displays 40 num3.display(); // Displays 240 }}}",
"e": 28733,
"s": 27588,
"text": null
},
{
"code": null,
"e": 28743,
"s": 28733,
"text": "Output : "
},
{
"code": null,
"e": 28754,
"s": 28743,
"text": "200\n40\n240"
},
{
"code": null,
"e": 28790,
"s": 28754,
"text": "Benefits of Operator Overloading : "
},
{
"code": null,
"e": 28910,
"s": 28790,
"text": "Operator Overloading provides additional capabilities to C# operators when they are applied to user-defined data types."
},
{
"code": null,
"e": 28977,
"s": 28910,
"text": "Operators may be considered as functions internal to the compiler."
},
{
"code": null,
"e": 28999,
"s": 28979,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 29016,
"s": 28999,
"text": "CSharp Operators"
},
{
"code": null,
"e": 29019,
"s": 29016,
"text": "C#"
},
{
"code": null,
"e": 29117,
"s": 29019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29135,
"s": 29117,
"text": "Destructors in C#"
},
{
"code": null,
"e": 29150,
"s": 29135,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29190,
"s": 29150,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 29213,
"s": 29190,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29244,
"s": 29213,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 29266,
"s": 29244,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29282,
"s": 29266,
"text": "C# | Data Types"
},
{
"code": null,
"e": 29310,
"s": 29282,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29332,
"s": 29310,
"text": "C# | Replace() Method"
}
] |
Number of K length subsequences with minimum sum - GeeksforGeeks
|
10 Mar, 2022
Given an array arr[] of size N and an integer K, the task is to find the number of K length subsequences of this array such that the sum of these subsequences is the minimum possible.
Examples:
Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 1 Subsequences of length 2 are (1, 2), (1, 3), (1, 4), (2, 3), (2, 4) and (3, 4). The minimum sum is 3 and the only subsequence with this sum is (1, 2).
Input: arr[] = {2, 1, 2, 2, 2, 1}, K = 3 Output: 4
Approach: The minimum possible sum of a subsequence of length K from the given array is the sum of the K smallest elements of the array. Let X be the maximum element among the K smallest elements of the array, and let the number of times it occurs among the K, the smallest elements of the array, be Y, and, its total occurrence, in the complete array, be cntX. Now, there are cntXCY ways to select this element, in the K smallest elements, which is the count of required subsequences.
Below is the implementation of the above approach:
C++
Java
C#
Python3
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the value of// Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to return the count// of valid subsequencesint cntSubSeq(int arr[], int n, int k){ // Sort the array sort(arr, arr + n); // Maximum among the minimum K elements int num = arr[k - 1]; // Y will store the frequency of num // in the minimum K elements int Y = 0; for (int i = k - 1; i >= 0; i--) { if (arr[i] == num) Y++; } // cntX will store the frequency of // num in the complete array int cntX = Y; for (int i = k; i < n; i++) { if (arr[i] == num) cntX++; } return binomialCoeff(cntX, Y);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(int); int k = 2; cout << cntSubSeq(arr, n, k); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int C[][] = new int [n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // Function to return the count // of valid subsequences static int cntSubSeq(int arr[], int n, int k) { // Sort the array Arrays.sort(arr); // Maximum among the minimum K elements int num = arr[k - 1]; // Y will store the frequency of num // in the minimum K elements int Y = 0; for (int i = k - 1; i >= 0; i--) { if (arr[i] == num) Y++; } // cntX will store the frequency of // num in the complete array int cntX = Y; for (int i = k; i < n; i++) { if (arr[i] == num) cntX++; } return binomialCoeff(cntX, Y); } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 3, 4 }; int n = arr.length; int k = 2; System.out.println(cntSubSeq(arr, n, k)); }} // This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to return the value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int [,]C = new int [n + 1, k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n, k]; } // Function to return the count // of valid subsequences static int cntSubSeq(int []arr, int n, int k) { // Sort the array Array.Sort(arr); // Maximum among the minimum K elements int num = arr[k - 1]; // Y will store the frequency of num // in the minimum K elements int Y = 0; for (int i = k - 1; i >= 0; i--) { if (arr[i] == num) Y++; } // cntX will store the frequency of // num in the complete array int cntX = Y; for (int i = k; i < n; i++) { if (arr[i] == num) cntX++; } return binomialCoeff(cntX, Y); } // Driver code public static void Main (String[] args) { int []arr = { 1, 2, 3, 4 }; int n = arr.Length; int k = 2; Console.WriteLine(cntSubSeq(arr, n, k)); }} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach # Function to return the value of# Binomial Coefficient C(n, k)def binomialCoeff(n, k) : C = [[0 for i in range(n + 1)] for j in range(k + 1)] # Calculate value of Binomial Coefficient # in bottom up manner for i in range (0, n + 1 ): for j in range (0, min(i, k) + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using previously # stored values else : C[i][j] = C[i - 1][j - 1] + C[i - 1][j] return C[n][k] # Function to return the count# of valid subsequencesdef cntSubSeq(arr, n, k) : # Sort the array arr.sort() # Maximum among the minimum K elements num = arr[k - 1]; # Y will store the frequency of num # in the minimum K elements Y = 0; for i in range (k - 1, -1, 1) : if (arr[i] == num): Y += 1 # cntX will store the frequency of # num in the complete array cntX = Y; for i in range (k, n): if (arr[i] == num) : cntX += 1 return binomialCoeff(cntX, Y) # Driver codearr = [ 1, 2, 3, 4 ]n = len(arr)k = 2print(cntSubSeq(arr, n, k)) # This code is contributed by ihritik
<script>// Javascript implementation of the// above approach // Function for the binomial coefficientfunction binomialCoeff(n, k){ var C = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < C.length; i++) { C[i] = new Array(k + 1); } var i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to return the count// of valid subsequencesfunction cntSubSeq(arr, n, k){ // Sort the array arr.sort(); // Maximum among the minimum K elements var num = arr[k - 1]; // Y will store the frequency of num // in the minimum K elements var Y = 0; for (var i = k - 1; i >= 0; i--) { if (arr[i] == num) Y+=1; } // cntX will store the frequency of // num in the complete array var cntX = Y; for (var i = k; i < n; i++) { if (arr[i] == num) cntX+=1; } return binomialCoeff(cntX, Y);} // Driver codevar arr = [ 1, 2, 3, 4 ];var n = arr.length;var k = 2;document.write(cntSubSeq(arr, n, k)); // This code is contributed by ShubhamSingh10</script>
1
Time Complexity: o(n2)
Auxiliary Space: O(n * k)
ankthon
29AjayKumar
nidhi_biet
ihritik
SHUBHAMSINGH10
anikakapoor
subhammahato348
subsequence
Arrays
Combinatorial
Mathematical
Arrays
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Factorial of a large number
|
[
{
"code": null,
"e": 25362,
"s": 25334,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 25546,
"s": 25362,
"text": "Given an array arr[] of size N and an integer K, the task is to find the number of K length subsequences of this array such that the sum of these subsequences is the minimum possible."
},
{
"code": null,
"e": 25557,
"s": 25546,
"text": "Examples: "
},
{
"code": null,
"e": 25753,
"s": 25557,
"text": "Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 1 Subsequences of length 2 are (1, 2), (1, 3), (1, 4), (2, 3), (2, 4) and (3, 4). The minimum sum is 3 and the only subsequence with this sum is (1, 2)."
},
{
"code": null,
"e": 25806,
"s": 25753,
"text": "Input: arr[] = {2, 1, 2, 2, 2, 1}, K = 3 Output: 4 "
},
{
"code": null,
"e": 26292,
"s": 25806,
"text": "Approach: The minimum possible sum of a subsequence of length K from the given array is the sum of the K smallest elements of the array. Let X be the maximum element among the K smallest elements of the array, and let the number of times it occurs among the K, the smallest elements of the array, be Y, and, its total occurrence, in the complete array, be cntX. Now, there are cntXCY ways to select this element, in the K smallest elements, which is the count of required subsequences."
},
{
"code": null,
"e": 26344,
"s": 26292,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26348,
"s": 26344,
"text": "C++"
},
{
"code": null,
"e": 26353,
"s": 26348,
"text": "Java"
},
{
"code": null,
"e": 26356,
"s": 26353,
"text": "C#"
},
{
"code": null,
"e": 26364,
"s": 26356,
"text": "Python3"
},
{
"code": null,
"e": 26375,
"s": 26364,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the value of// Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to return the count// of valid subsequencesint cntSubSeq(int arr[], int n, int k){ // Sort the array sort(arr, arr + n); // Maximum among the minimum K elements int num = arr[k - 1]; // Y will store the frequency of num // in the minimum K elements int Y = 0; for (int i = k - 1; i >= 0; i--) { if (arr[i] == num) Y++; } // cntX will store the frequency of // num in the complete array int cntX = Y; for (int i = k; i < n; i++) { if (arr[i] == num) cntX++; } return binomialCoeff(cntX, Y);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(int); int k = 2; cout << cntSubSeq(arr, n, k); return 0;}",
"e": 27754,
"s": 26375,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int C[][] = new int [n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // Function to return the count // of valid subsequences static int cntSubSeq(int arr[], int n, int k) { // Sort the array Arrays.sort(arr); // Maximum among the minimum K elements int num = arr[k - 1]; // Y will store the frequency of num // in the minimum K elements int Y = 0; for (int i = k - 1; i >= 0; i--) { if (arr[i] == num) Y++; } // cntX will store the frequency of // num in the complete array int cntX = Y; for (int i = k; i < n; i++) { if (arr[i] == num) cntX++; } return binomialCoeff(cntX, Y); } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 3, 4 }; int n = arr.length; int k = 2; System.out.println(cntSubSeq(arr, n, k)); }} // This code is contributed by AnkitRai01",
"e": 29522,
"s": 27754,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int [,]C = new int [n + 1, k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n, k]; } // Function to return the count // of valid subsequences static int cntSubSeq(int []arr, int n, int k) { // Sort the array Array.Sort(arr); // Maximum among the minimum K elements int num = arr[k - 1]; // Y will store the frequency of num // in the minimum K elements int Y = 0; for (int i = k - 1; i >= 0; i--) { if (arr[i] == num) Y++; } // cntX will store the frequency of // num in the complete array int cntX = Y; for (int i = k; i < n; i++) { if (arr[i] == num) cntX++; } return binomialCoeff(cntX, Y); } // Driver code public static void Main (String[] args) { int []arr = { 1, 2, 3, 4 }; int n = arr.Length; int k = 2; Console.WriteLine(cntSubSeq(arr, n, k)); }} // This code is contributed by 29AjayKumar",
"e": 31284,
"s": 29522,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the value of# Binomial Coefficient C(n, k)def binomialCoeff(n, k) : C = [[0 for i in range(n + 1)] for j in range(k + 1)] # Calculate value of Binomial Coefficient # in bottom up manner for i in range (0, n + 1 ): for j in range (0, min(i, k) + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using previously # stored values else : C[i][j] = C[i - 1][j - 1] + C[i - 1][j] return C[n][k] # Function to return the count# of valid subsequencesdef cntSubSeq(arr, n, k) : # Sort the array arr.sort() # Maximum among the minimum K elements num = arr[k - 1]; # Y will store the frequency of num # in the minimum K elements Y = 0; for i in range (k - 1, -1, 1) : if (arr[i] == num): Y += 1 # cntX will store the frequency of # num in the complete array cntX = Y; for i in range (k, n): if (arr[i] == num) : cntX += 1 return binomialCoeff(cntX, Y) # Driver codearr = [ 1, 2, 3, 4 ]n = len(arr)k = 2print(cntSubSeq(arr, n, k)) # This code is contributed by ihritik",
"e": 32542,
"s": 31284,
"text": null
},
{
"code": "<script>// Javascript implementation of the// above approach // Function for the binomial coefficientfunction binomialCoeff(n, k){ var C = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < C.length; i++) { C[i] = new Array(k + 1); } var i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to return the count// of valid subsequencesfunction cntSubSeq(arr, n, k){ // Sort the array arr.sort(); // Maximum among the minimum K elements var num = arr[k - 1]; // Y will store the frequency of num // in the minimum K elements var Y = 0; for (var i = k - 1; i >= 0; i--) { if (arr[i] == num) Y+=1; } // cntX will store the frequency of // num in the complete array var cntX = Y; for (var i = k; i < n; i++) { if (arr[i] == num) cntX+=1; } return binomialCoeff(cntX, Y);} // Driver codevar arr = [ 1, 2, 3, 4 ];var n = arr.length;var k = 2;document.write(cntSubSeq(arr, n, k)); // This code is contributed by ShubhamSingh10</script>",
"e": 34010,
"s": 32542,
"text": null
},
{
"code": null,
"e": 34012,
"s": 34010,
"text": "1"
},
{
"code": null,
"e": 34037,
"s": 34014,
"text": "Time Complexity: o(n2)"
},
{
"code": null,
"e": 34063,
"s": 34037,
"text": "Auxiliary Space: O(n * k)"
},
{
"code": null,
"e": 34071,
"s": 34063,
"text": "ankthon"
},
{
"code": null,
"e": 34083,
"s": 34071,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34094,
"s": 34083,
"text": "nidhi_biet"
},
{
"code": null,
"e": 34102,
"s": 34094,
"text": "ihritik"
},
{
"code": null,
"e": 34117,
"s": 34102,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 34129,
"s": 34117,
"text": "anikakapoor"
},
{
"code": null,
"e": 34145,
"s": 34129,
"text": "subhammahato348"
},
{
"code": null,
"e": 34157,
"s": 34145,
"text": "subsequence"
},
{
"code": null,
"e": 34164,
"s": 34157,
"text": "Arrays"
},
{
"code": null,
"e": 34178,
"s": 34164,
"text": "Combinatorial"
},
{
"code": null,
"e": 34191,
"s": 34178,
"text": "Mathematical"
},
{
"code": null,
"e": 34198,
"s": 34191,
"text": "Arrays"
},
{
"code": null,
"e": 34211,
"s": 34198,
"text": "Mathematical"
},
{
"code": null,
"e": 34225,
"s": 34211,
"text": "Combinatorial"
},
{
"code": null,
"e": 34323,
"s": 34225,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34391,
"s": 34323,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34439,
"s": 34391,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34483,
"s": 34439,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34515,
"s": 34483,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34538,
"s": 34515,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34598,
"s": 34538,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34636,
"s": 34598,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 34713,
"s": 34636,
"text": "itertools.combinations() module in Python to print all possible combinations"
}
] |
Format specifiers in C
|
The format specifiers are used in C for input and output purposes. Using this concept the compiler can understand that what type of data is in a variable during taking input using the scanf() function and printing using printf() function. Here is a list of format specifiers.
These are the basic format specifiers. We can add some other parts with the format specifiers. These are like below −
A minus symbol (-) sign tells left alignment
A minus symbol (-) sign tells left alignment
A number after % specifies the minimum field width. If string is less than the width, it will be filled with spaces
A number after % specifies the minimum field width. If string is less than the width, it will be filled with spaces
A period (.) is used to separate field width and precision
A period (.) is used to separate field width and precision
Live Demo
#include <stdio.h>
main() {
char ch = 'B';
printf("%c\n", ch); //printing character data
//print decimal or integer data with d and i
int x = 45, y = 90;
printf("%d\n", x);
printf("%i\n", y);
float f = 12.67;
printf("%f\n", f); //print float value
printf("%e\n", f); //print in scientific notation
int a = 67;
printf("%o\n", a); //print in octal format
printf("%x\n", a); //print in hex format
char str[] = "Hello World";
printf("%s\n", str);
printf("%20s\n", str); //shift to the right 20 characters including the string
printf("%-20s\n", str); //left align
printf("%20.5s\n", str); //shift to the right 20 characters including the string, and print string up to 5 character
printf("%-20.5s\n", str); //left align and print string up to 5 character
}
B
45
90
12.670000
1.267000e+001
103
43
Hello World
Hello World
Hello World
Hello
Hello
We can use these format specifiers for the scanf() function also in the same manner. So we can take the input from scanf() like above how we have printed.
|
[
{
"code": null,
"e": 1338,
"s": 1062,
"text": "The format specifiers are used in C for input and output purposes. Using this concept the compiler can understand that what type of data is in a variable during taking input using the scanf() function and printing using printf() function. Here is a list of format specifiers."
},
{
"code": null,
"e": 1456,
"s": 1338,
"text": "These are the basic format specifiers. We can add some other parts with the format specifiers. These are like below −"
},
{
"code": null,
"e": 1501,
"s": 1456,
"text": "A minus symbol (-) sign tells left alignment"
},
{
"code": null,
"e": 1546,
"s": 1501,
"text": "A minus symbol (-) sign tells left alignment"
},
{
"code": null,
"e": 1662,
"s": 1546,
"text": "A number after % specifies the minimum field width. If string is less than the width, it will be filled with spaces"
},
{
"code": null,
"e": 1778,
"s": 1662,
"text": "A number after % specifies the minimum field width. If string is less than the width, it will be filled with spaces"
},
{
"code": null,
"e": 1837,
"s": 1778,
"text": "A period (.) is used to separate field width and precision"
},
{
"code": null,
"e": 1896,
"s": 1837,
"text": "A period (.) is used to separate field width and precision"
},
{
"code": null,
"e": 1907,
"s": 1896,
"text": " Live Demo"
},
{
"code": null,
"e": 2713,
"s": 1907,
"text": "#include <stdio.h>\nmain() {\n char ch = 'B';\n printf(\"%c\\n\", ch); //printing character data\n //print decimal or integer data with d and i\n int x = 45, y = 90;\n printf(\"%d\\n\", x);\n printf(\"%i\\n\", y);\n float f = 12.67;\n printf(\"%f\\n\", f); //print float value\n printf(\"%e\\n\", f); //print in scientific notation\n int a = 67;\n printf(\"%o\\n\", a); //print in octal format\n printf(\"%x\\n\", a); //print in hex format\n char str[] = \"Hello World\";\n printf(\"%s\\n\", str);\n printf(\"%20s\\n\", str); //shift to the right 20 characters including the string\n printf(\"%-20s\\n\", str); //left align\n printf(\"%20.5s\\n\", str); //shift to the right 20 characters including the string, and print string up to 5 character\n printf(\"%-20.5s\\n\", str); //left align and print string up to 5 character\n}"
},
{
"code": null,
"e": 2800,
"s": 2713,
"text": "B\n45\n90\n12.670000\n1.267000e+001\n103\n43\nHello World\nHello World\nHello World\nHello\nHello"
},
{
"code": null,
"e": 2955,
"s": 2800,
"text": "We can use these format specifiers for the scanf() function also in the same manner. So we can take the input from scanf() like above how we have printed."
}
] |
Perl | List Functions - GeeksforGeeks
|
07 May, 2019
A list in Perl is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol whereas list variables start with @ symbol.List provides various pre-defined Functions to perform operations with ease. Some of these Functions are as below:
join() functionjoin() function is used to combine the elements of a List into a single string with the use of a separator provided to separate each element. This function returns the joined string. A separator can work only between the pairs. A separator can’t be placed at either end of the string. In order to join the strings without a separator, an empty parameter is passed to the function.Syntax: join(Separator, List)Parameter:Separator: provided to separate each element while joiningList: to be converted to single StringReturns: a joined StringExample :#!/usr/bin/perl # Initializing list with alphabets A to Z@list = (A..Z); # Printing the original listprint "List: @list\n"; # Using join function introducing# hyphen between each alphabetsprint "\nString after join operation:\n";print join("-", @list);Output:List: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
String after join operation:
A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z
Syntax: join(Separator, List)
Parameter:
Separator: provided to separate each element while joining
List: to be converted to single String
Returns: a joined String
Example :
#!/usr/bin/perl # Initializing list with alphabets A to Z@list = (A..Z); # Printing the original listprint "List: @list\n"; # Using join function introducing# hyphen between each alphabetsprint "\nString after join operation:\n";print join("-", @list);
Output:
List: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
String after join operation:
A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z
reverse() functionReverse() function in Perl returns the elements of List in reverse order in a list context. While in a scalar context, it returns a concatenated string of the values of List, with all characters in opposite order. It returns String in Scalar Context and List in List Context.Syntax: reverse ListParameter:List: list to be reversedReturns: elements in reverse orderExample:# Initializing a list@list = ("Raj", "E123", 12000); # Reversing the list@rname = reverse(@list); # Printing the reversed listprint "Reversed list is @rname"; # Initializing a scalar$string = "GeeksforGeeks"; # Reversing a scalar$r = reverse($string);print "\nReversed string is $r";Output:Reversed list is 12000 E123 Raj
Reversed string is skeeGrofskeeG
Syntax: reverse List
Parameter:List: list to be reversed
Returns: elements in reverse order
Example:
# Initializing a list@list = ("Raj", "E123", 12000); # Reversing the list@rname = reverse(@list); # Printing the reversed listprint "Reversed list is @rname"; # Initializing a scalar$string = "GeeksforGeeks"; # Reversing a scalar$r = reverse($string);print "\nReversed string is $r";
Output:
Reversed list is 12000 E123 Raj
Reversed string is skeeGrofskeeG
map() functionmap() function in Perl evaluates the operator provided as a parameter for each element of List. For each iteration, $_ holds the value of the current element, which can also be assigned to allow the value of the element to be updated. map() function runs an expression on each element of an array and returns a new array with the updated results. It returns the total number of elements generated in scalar context and list of values in list context.Syntax: map(operation, List)Parameter:operation: to be performed on list elementsList: whose elements need to be changedExample :# Initializing a list@Dept = ('comp', 'inft', 'extc', 'mech'); # Converting first character capital@upd1 = map(ucfirst, @Dept); # Printing listprint "List with First char capital: ";foreach $i (@upd1) { print "$i, ";} # Converting all characters capital@upd2 = map(uc, @Dept); # Printing listprint "\nList with all char capital: ";foreach $i (@upd2) { print "$i, ";}Output:List with First char capital: Comp, Inft, Extc, Mech,
List with all char capital: COMP, INFT, EXTC, MECH,
Syntax: map(operation, List)Parameter:
operation: to be performed on list elements
List: whose elements need to be changed
Example :
# Initializing a list@Dept = ('comp', 'inft', 'extc', 'mech'); # Converting first character capital@upd1 = map(ucfirst, @Dept); # Printing listprint "List with First char capital: ";foreach $i (@upd1) { print "$i, ";} # Converting all characters capital@upd2 = map(uc, @Dept); # Printing listprint "\nList with all char capital: ";foreach $i (@upd2) { print "$i, ";}
Output:
List with First char capital: Comp, Inft, Extc, Mech,
List with all char capital: COMP, INFT, EXTC, MECH,
sort() functionsort() function in Perl is used to arrange the List according to the condition of sorting specified to the function. If no condition is specified, then it sorts according to normal alphabetical sequence.If a condition is specified then the function sorts the List according to the condition.Syntax: sort(condition, List)Example# Initializing two lists@country = ('India', 'Qatar', 'Bangladesh', 'France', 'Italy');@capital = ('Delhi', 'Lahore', 'Dhaka', 'Paris', 'Rome'); # Printing countries in sorted orderprint"Countries in sorted order: \n";print sort @country;print "\n"; # Printing sorted country and capital valuesprint "\nCombining both the lists in sorted order:\n";print sort @country, @capital;print "\n"; # Initializing a list with number@list = (19, 4, 54, 33, 99, 2); # Sorting in descending order@s = sort{$b <=> $a} @list;print "\nPrinting numbers in sorted order:\n";foreach $i(@s){ print "$i, ";}Output:Countries in sorted order:
BangladeshFranceIndiaItalyQatar
Combining both the lists in sorted order:
BangladeshDelhiDhakaFranceIndiaItalyLahoreParisQatarRome
Printing numbers in sorted order:
99, 54, 33, 19, 4, 2,
Syntax: sort(condition, List)
Example
# Initializing two lists@country = ('India', 'Qatar', 'Bangladesh', 'France', 'Italy');@capital = ('Delhi', 'Lahore', 'Dhaka', 'Paris', 'Rome'); # Printing countries in sorted orderprint"Countries in sorted order: \n";print sort @country;print "\n"; # Printing sorted country and capital valuesprint "\nCombining both the lists in sorted order:\n";print sort @country, @capital;print "\n"; # Initializing a list with number@list = (19, 4, 54, 33, 99, 2); # Sorting in descending order@s = sort{$b <=> $a} @list;print "\nPrinting numbers in sorted order:\n";foreach $i(@s){ print "$i, ";}
Output:
Countries in sorted order:
BangladeshFranceIndiaItalyQatar
Combining both the lists in sorted order:
BangladeshDelhiDhakaFranceIndiaItalyLahoreParisQatarRome
Printing numbers in sorted order:
99, 54, 33, 19, 4, 2,
Perl-Arrays
perl-list
Perl-List-Functions
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Data Types
Perl | Multidimensional Hashes
Perl | Basic Syntax of a Perl Program
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Perl | File Handling Introduction
Perl | Opening and Reading a File
Perl | Writing to a File
Perl | defined() Function
Perl | ne operator
|
[
{
"code": null,
"e": 24070,
"s": 24042,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 24510,
"s": 24070,
"text": "A list in Perl is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol whereas list variables start with @ symbol.List provides various pre-defined Functions to perform operations with ease. Some of these Functions are as below:"
},
{
"code": null,
"e": 25476,
"s": 24510,
"text": "join() functionjoin() function is used to combine the elements of a List into a single string with the use of a separator provided to separate each element. This function returns the joined string. A separator can work only between the pairs. A separator can’t be placed at either end of the string. In order to join the strings without a separator, an empty parameter is passed to the function.Syntax: join(Separator, List)Parameter:Separator: provided to separate each element while joiningList: to be converted to single StringReturns: a joined StringExample :#!/usr/bin/perl # Initializing list with alphabets A to Z@list = (A..Z); # Printing the original listprint \"List: @list\\n\"; # Using join function introducing# hyphen between each alphabetsprint \"\\nString after join operation:\\n\";print join(\"-\", @list);Output:List: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z\n\nString after join operation:\nA-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z\n"
},
{
"code": null,
"e": 25506,
"s": 25476,
"text": "Syntax: join(Separator, List)"
},
{
"code": null,
"e": 25517,
"s": 25506,
"text": "Parameter:"
},
{
"code": null,
"e": 25576,
"s": 25517,
"text": "Separator: provided to separate each element while joining"
},
{
"code": null,
"e": 25615,
"s": 25576,
"text": "List: to be converted to single String"
},
{
"code": null,
"e": 25640,
"s": 25615,
"text": "Returns: a joined String"
},
{
"code": null,
"e": 25650,
"s": 25640,
"text": "Example :"
},
{
"code": "#!/usr/bin/perl # Initializing list with alphabets A to Z@list = (A..Z); # Printing the original listprint \"List: @list\\n\"; # Using join function introducing# hyphen between each alphabetsprint \"\\nString after join operation:\\n\";print join(\"-\", @list);",
"e": 25906,
"s": 25650,
"text": null
},
{
"code": null,
"e": 25914,
"s": 25906,
"text": "Output:"
},
{
"code": null,
"e": 26055,
"s": 25914,
"text": "List: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z\n\nString after join operation:\nA-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z\n"
},
{
"code": null,
"e": 26805,
"s": 26055,
"text": "reverse() functionReverse() function in Perl returns the elements of List in reverse order in a list context. While in a scalar context, it returns a concatenated string of the values of List, with all characters in opposite order. It returns String in Scalar Context and List in List Context.Syntax: reverse ListParameter:List: list to be reversedReturns: elements in reverse orderExample:# Initializing a list@list = (\"Raj\", \"E123\", 12000); # Reversing the list@rname = reverse(@list); # Printing the reversed listprint \"Reversed list is @rname\"; # Initializing a scalar$string = \"GeeksforGeeks\"; # Reversing a scalar$r = reverse($string);print \"\\nReversed string is $r\";Output:Reversed list is 12000 E123 Raj\nReversed string is skeeGrofskeeG\n"
},
{
"code": null,
"e": 26826,
"s": 26805,
"text": "Syntax: reverse List"
},
{
"code": null,
"e": 26862,
"s": 26826,
"text": "Parameter:List: list to be reversed"
},
{
"code": null,
"e": 26897,
"s": 26862,
"text": "Returns: elements in reverse order"
},
{
"code": null,
"e": 26906,
"s": 26897,
"text": "Example:"
},
{
"code": "# Initializing a list@list = (\"Raj\", \"E123\", 12000); # Reversing the list@rname = reverse(@list); # Printing the reversed listprint \"Reversed list is @rname\"; # Initializing a scalar$string = \"GeeksforGeeks\"; # Reversing a scalar$r = reverse($string);print \"\\nReversed string is $r\";",
"e": 27194,
"s": 26906,
"text": null
},
{
"code": null,
"e": 27202,
"s": 27194,
"text": "Output:"
},
{
"code": null,
"e": 27268,
"s": 27202,
"text": "Reversed list is 12000 E123 Raj\nReversed string is skeeGrofskeeG\n"
},
{
"code": null,
"e": 28350,
"s": 27268,
"text": "map() functionmap() function in Perl evaluates the operator provided as a parameter for each element of List. For each iteration, $_ holds the value of the current element, which can also be assigned to allow the value of the element to be updated. map() function runs an expression on each element of an array and returns a new array with the updated results. It returns the total number of elements generated in scalar context and list of values in list context.Syntax: map(operation, List)Parameter:operation: to be performed on list elementsList: whose elements need to be changedExample :# Initializing a list@Dept = ('comp', 'inft', 'extc', 'mech'); # Converting first character capital@upd1 = map(ucfirst, @Dept); # Printing listprint \"List with First char capital: \";foreach $i (@upd1) { print \"$i, \";} # Converting all characters capital@upd2 = map(uc, @Dept); # Printing listprint \"\\nList with all char capital: \";foreach $i (@upd2) { print \"$i, \";}Output:List with First char capital: Comp, Inft, Extc, Mech, \nList with all char capital: COMP, INFT, EXTC, MECH, "
},
{
"code": null,
"e": 28389,
"s": 28350,
"text": "Syntax: map(operation, List)Parameter:"
},
{
"code": null,
"e": 28433,
"s": 28389,
"text": "operation: to be performed on list elements"
},
{
"code": null,
"e": 28473,
"s": 28433,
"text": "List: whose elements need to be changed"
},
{
"code": null,
"e": 28483,
"s": 28473,
"text": "Example :"
},
{
"code": "# Initializing a list@Dept = ('comp', 'inft', 'extc', 'mech'); # Converting first character capital@upd1 = map(ucfirst, @Dept); # Printing listprint \"List with First char capital: \";foreach $i (@upd1) { print \"$i, \";} # Converting all characters capital@upd2 = map(uc, @Dept); # Printing listprint \"\\nList with all char capital: \";foreach $i (@upd2) { print \"$i, \";}",
"e": 28858,
"s": 28483,
"text": null
},
{
"code": null,
"e": 28866,
"s": 28858,
"text": "Output:"
},
{
"code": null,
"e": 28974,
"s": 28866,
"text": "List with First char capital: Comp, Inft, Extc, Mech, \nList with all char capital: COMP, INFT, EXTC, MECH, "
},
{
"code": null,
"e": 30135,
"s": 28974,
"text": "sort() functionsort() function in Perl is used to arrange the List according to the condition of sorting specified to the function. If no condition is specified, then it sorts according to normal alphabetical sequence.If a condition is specified then the function sorts the List according to the condition.Syntax: sort(condition, List)Example# Initializing two lists@country = ('India', 'Qatar', 'Bangladesh', 'France', 'Italy');@capital = ('Delhi', 'Lahore', 'Dhaka', 'Paris', 'Rome'); # Printing countries in sorted orderprint\"Countries in sorted order: \\n\";print sort @country;print \"\\n\"; # Printing sorted country and capital valuesprint \"\\nCombining both the lists in sorted order:\\n\";print sort @country, @capital;print \"\\n\"; # Initializing a list with number@list = (19, 4, 54, 33, 99, 2); # Sorting in descending order@s = sort{$b <=> $a} @list;print \"\\nPrinting numbers in sorted order:\\n\";foreach $i(@s){ print \"$i, \";}Output:Countries in sorted order: \nBangladeshFranceIndiaItalyQatar\n\nCombining both the lists in sorted order:\nBangladeshDelhiDhakaFranceIndiaItalyLahoreParisQatarRome\n\nPrinting numbers in sorted order:\n99, 54, 33, 19, 4, 2, "
},
{
"code": null,
"e": 30165,
"s": 30135,
"text": "Syntax: sort(condition, List)"
},
{
"code": null,
"e": 30173,
"s": 30165,
"text": "Example"
},
{
"code": "# Initializing two lists@country = ('India', 'Qatar', 'Bangladesh', 'France', 'Italy');@capital = ('Delhi', 'Lahore', 'Dhaka', 'Paris', 'Rome'); # Printing countries in sorted orderprint\"Countries in sorted order: \\n\";print sort @country;print \"\\n\"; # Printing sorted country and capital valuesprint \"\\nCombining both the lists in sorted order:\\n\";print sort @country, @capital;print \"\\n\"; # Initializing a list with number@list = (19, 4, 54, 33, 99, 2); # Sorting in descending order@s = sort{$b <=> $a} @list;print \"\\nPrinting numbers in sorted order:\\n\";foreach $i(@s){ print \"$i, \";}",
"e": 30768,
"s": 30173,
"text": null
},
{
"code": null,
"e": 30776,
"s": 30768,
"text": "Output:"
},
{
"code": null,
"e": 30994,
"s": 30776,
"text": "Countries in sorted order: \nBangladeshFranceIndiaItalyQatar\n\nCombining both the lists in sorted order:\nBangladeshDelhiDhakaFranceIndiaItalyLahoreParisQatarRome\n\nPrinting numbers in sorted order:\n99, 54, 33, 19, 4, 2, "
},
{
"code": null,
"e": 31006,
"s": 30994,
"text": "Perl-Arrays"
},
{
"code": null,
"e": 31016,
"s": 31006,
"text": "perl-list"
},
{
"code": null,
"e": 31036,
"s": 31016,
"text": "Perl-List-Functions"
},
{
"code": null,
"e": 31043,
"s": 31036,
"text": "Picked"
},
{
"code": null,
"e": 31048,
"s": 31043,
"text": "Perl"
},
{
"code": null,
"e": 31053,
"s": 31048,
"text": "Perl"
},
{
"code": null,
"e": 31151,
"s": 31053,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31192,
"s": 31151,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 31210,
"s": 31192,
"text": "Perl | Data Types"
},
{
"code": null,
"e": 31241,
"s": 31210,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 31279,
"s": 31241,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 31379,
"s": 31279,
"text": "Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)"
},
{
"code": null,
"e": 31413,
"s": 31379,
"text": "Perl | File Handling Introduction"
},
{
"code": null,
"e": 31447,
"s": 31413,
"text": "Perl | Opening and Reading a File"
},
{
"code": null,
"e": 31472,
"s": 31447,
"text": "Perl | Writing to a File"
},
{
"code": null,
"e": 31498,
"s": 31472,
"text": "Perl | defined() Function"
}
] |
Pointer to an Array | Array Pointer - GeeksforGeeks
|
21 Sep, 2021
Prerequisite: Pointers Introduction
Pointer to Array
Consider the following program:
C++
C
#include <iostream>using namespace std; int main(){int arr[5] = { 1, 2, 3, 4, 5 };int *ptr = arr; cout <<"\n"<< ptr;return 0;} // thus code is contributed by shivanisinghss2110
#include<stdio.h> int main(){ int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf("%p\n", ptr); return 0;}
In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays. Syntax:
data_type (*var_name)[size_of_array];
Example:
int (*ptr)[10];
Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’. Note : The pointer that points to the 0th element of array and the pointer that points to the whole array are totally different. The following program shows this:
C++
C
// C++ program to understand difference between// pointer to an integer and pointer to an// array of integers.#include <iostream>using namespace std;int main(){ // Pointer to an integer int *p; // Pointer to an array of 5 integers int (*ptr)[5]; int arr[5]; // Points to 0th element of the arr. p = arr; // Points to the whole array arr. ptr = &arr; cout << "p =" << p <<", ptr = "<< ptr<< endl; p++; ptr++; cout << "p =" << p <<", ptr = "<< ptr<< endl; return 0;} // This code is contributed by SHUBHAMSINGH10
// C program to understand difference between// pointer to an integer and pointer to an// array of integers.#include<stdio.h> int main(){ // Pointer to an integer int *p; // Pointer to an array of 5 integers int (*ptr)[5]; int arr[5]; // Points to 0th element of the arr. p = arr; // Points to the whole array arr. ptr = &arr; printf("p = %p, ptr = %p\n", p, ptr); p++; ptr++; printf("p = %p, ptr = %p\n", p, ptr); return 0;}
Output:
p = 0x7fff4f32fd50, ptr = 0x7fff4f32fd50
p = 0x7fff4f32fd54, ptr = 0x7fff4f32fd64
p: is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole array arr.
The base type of p is int while base type of ptr is ‘an array of 5 integers’.
We know that the pointer arithmetic is performed relative to the base size, so if we write ptr++, then the pointer ptr will be shifted forward by 20 bytes.
The following figure shows the pointer p and ptr. Darker arrow denotes pointer to an array.
On dereferencing a pointer expression we get a value pointed to by that pointer expression. Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points.
C++
C
// C++ program to illustrate sizes of// pointer of array#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 3, 5, 6, 7, 9 }; int *p = arr; int (*ptr)[5] = &arr; cout << "p = "<< p <<", ptr = " << ptr << endl; cout << "*p = "<< *p <<", *ptr = " << *ptr << endl; cout << "sizeof(p) = "<< sizeof(p) << ", sizeof(*p) = " << sizeof(*p) << endl; cout << "sizeof(ptr) = "<< sizeof(ptr) << ", sizeof(*ptr) = " << sizeof(*ptr) << endl; return 0;} // This code is contributed by shubhamsingh10
// C program to illustrate sizes of// pointer of array#include<stdio.h> int main(){ int arr[] = { 3, 5, 6, 7, 9 }; int *p = arr; int (*ptr)[5] = &arr; printf("p = %p, ptr = %p\n", p, ptr); printf("*p = %d, *ptr = %p\n", *p, *ptr); printf("sizeof(p) = %lu, sizeof(*p) = %lu\n", sizeof(p), sizeof(*p)); printf("sizeof(ptr) = %lu, sizeof(*ptr) = %lu\n", sizeof(ptr), sizeof(*ptr)); return 0;}
Output:
p = 0x7ffde1ee5010, ptr = 0x7ffde1ee5010
*p = 3, *ptr = 0x7ffde1ee5010
sizeof(p) = 8, sizeof(*p) = 4
sizeof(ptr) = 8, sizeof(*ptr) = 20
Pointer to Multidimensional Arrays:
Pointers and two dimensional Arrays: In a two dimensional array, we can access each element by using two subscripts, where first subscript represents the row number and second subscript represents the column number. The elements of 2-D array can be accessed with the help of pointer notation also. Suppose arr is a 2-D array, we can access any element arr[i][j] of the array using the pointer expression *(*(arr + i) + j). Now we’ll see how this expression can be derived. Let us take a two dimensional array arr[3][4]:
int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
Since memory in a computer is organized linearly it is not possible to store the 2-D array in rows and columns. The concept of rows and columns is only theoretical, actually, a 2-D array is stored in row-major order i.e rows are placed next to each other. The following figure shows how the above 2-D array will be stored in memory.
Each row can be considered as a 1-D array, so a two-dimensional array can be considered as a collection of one-dimensional arrays that are placed one after another. In other words, we can say that 2-D dimensional arrays that are placed one after another. So here arr is an array of 3 elements where each element is a 1-D array of 4 integers. We know that the name of an array is a constant pointer that points to 0th 1-D array and contains address 5000. Since arr is a ‘pointer to an array of 4 integers’, according to pointer arithmetic the expression arr + 1 will represent the address 5016 and expression arr + 2 will represent address 5032. So we can say that arr points to the 0th 1-D array, arr + 1 points to the 1st 1-D array and arr + 2 points to the 2nd 1-D array.
In general we can write:
arr + i Points to ith element of arr ->
Points to ith 1-D array
Since arr + i points to ith element of arr, on dereferencing it will get ith element of arr which is of course a 1-D array. Thus the expression *(arr + i) gives us the base address of ith 1-D array.
We know, the pointer expression *(arr + i) is equivalent to the subscript expression arr[i]. So *(arr + i) which is same as arr[i] gives us the base address of ith 1-D array.
To access an individual element of our 2-D array, we should be able to access any jth element of ith 1-D array.
Since the base type of *(arr + i) is int and it contains the address of 0th element of ith 1-D array, we can get the addresses of subsequent elements in the ith 1-D array by adding integer values to *(arr + i).
For example *(arr + i) + 1 will represent the address of 1st element of 1stelement of ith 1-D array and *(arr+i)+2 will represent the address of 2nd element of ith 1-D array.
Similarly *(arr + i) + j will represent the address of jth element of ith 1-D array. On dereferencing this expression we can get the jth element of the ith 1-D array.
Pointers and Three Dimensional Arrays In a three dimensional array we can access each element by using three subscripts. Let us take a 3-D array-
int arr[2][3][2] = { {{5, 10}, {6, 11}, {7, 12}}, {{20, 30}, {21, 31}, {22, 32}} };
We can consider a three dimensional array to be an array of 2-D array i.e each element of a 3-D array is considered to be a 2-D array. The 3-D array arr can be considered as an array consisting of two elements where each element is a 2-D array. The name of the array arr is a pointer to the 0th 2-D array.
Thus the pointer expression *(*(*(arr + i ) + j ) + k) is equivalent to the subscript expression arr[i][j][k]. We know the expression *(arr + i) is equivalent to arr[i] and the expression *(*(arr + i) + j) is equivalent arr[i][j]. So we can say that arr[i] represents the base address of ith 2-D array and arr[i][j] represents the base address of the jth 1-D array.
C++
C
// C++ program to print the elements of 3-D// array using pointer notation#include <iostream>using namespace std;int main(){ int arr[2][3][2] = { { {5, 10}, {6, 11}, {7, 12}, }, { {20, 30}, {21, 31}, {22, 32}, } }; int i, j, k; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { for (k = 0; k < 2; k++) cout << *(*(*(arr + i) + j) +k) << "\t"; cout <<"\n"; } } return 0;} // this code is contributed by shivanisinghss2110
// C program to print the elements of 3-D// array using pointer notation#include<stdio.h>int main(){ int arr[2][3][2] = { { {5, 10}, {6, 11}, {7, 12}, }, { {20, 30}, {21, 31}, {22, 32}, } }; int i, j, k; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { for (k = 0; k < 2; k++) printf("%d\t", *(*(*(arr + i) + j) +k)); printf("\n"); } } return 0;}
Output:
5 10
6 11
7 12
20 30
21 31
22 32
The following figure shows how the 3-D array used in the above program is stored in memory.
Subscripting Pointer to an Array
Suppose arr is a 2-D array with 3 rows and 4 columns and ptr is a pointer to an array of 4 integers, and ptr contains the base address of array arr.
int arr[3][4] = {{10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33}};
int (*ptr)[4];
ptr = arr;
Since ptr is a pointer to an array of 4 integers, ptr + i will point to ith row. On dereferencing ptr + i, we get base address of ith row. To access the address of jth element of ith row we can add j to the pointer expression *(ptr + i). So the pointer expression *(ptr + i) + j gives the address of jth element of ith row and the pointer expression *(*(ptr + i)+j) gives the value of the jth element of ith row. We know that the pointer expression *(*(ptr + i) + j) is equivalent to subscript expression ptr[i][j]. So if we have a pointer variable containing the base address of 2-D array, then we can access the elements of array by double subscripting that pointer variable.
C++
C
// C++ program to print elements of a 2-D array// by scripting a pointer to an array#include <iostream>using namespace std; int main(){ int arr[3][4] = { {10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33} }; int (*ptr)[4]; ptr = arr; cout << ptr<< " "<< ptr + 1<< " "<< ptr + 2 << endl; cout << *ptr<< " "<< *(ptr + 1)<< " "<< *(ptr + 2)<< endl; cout << **ptr<< " "<< *(*(ptr + 1) + 2)<< " "<< *(*(ptr + 2) + 3)<< endl; cout << ptr[0][0]<< " "<< ptr[1][2]<< " "<< ptr[2][3]<< endl; return 0;} // This code is contributed by shivanisinghss2110
// C program to print elements of a 2-D array// by scripting a pointer to an array#include<stdio.h> int main(){ int arr[3][4] = { {10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33} }; int (*ptr)[4]; ptr = arr; printf("%p %p %p\n", ptr, ptr + 1, ptr + 2); printf("%p %p %p\n", *ptr, *(ptr + 1), *(ptr + 2)); printf("%d %d %d\n", **ptr, *(*(ptr + 1) + 2), *(*(ptr + 2) + 3)); printf("%d %d %d\n", ptr[0][0], ptr[1][2], ptr[2][3]); return 0;}
Output:
0x7ffead967560 0x7ffead967570 0x7ffead967580
0x7ffead967560 0x7ffead967570 0x7ffead967580
10 22 33
10 22 33
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.,
flandraco
BabisSarantoglou
nidhi_biet
SHUBHAMSINGH10
shivanisinghss2110
simmytarika5
C-Pointers
cpp-pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Operator Overloading in C++
Socket Programming in C/C++
|
[
{
"code": null,
"e": 24390,
"s": 24362,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 24428,
"s": 24390,
"text": "Prerequisite: Pointers Introduction "
},
{
"code": null,
"e": 24445,
"s": 24428,
"text": "Pointer to Array"
},
{
"code": null,
"e": 24478,
"s": 24445,
"text": "Consider the following program: "
},
{
"code": null,
"e": 24482,
"s": 24478,
"text": "C++"
},
{
"code": null,
"e": 24484,
"s": 24482,
"text": "C"
},
{
"code": "#include <iostream>using namespace std; int main(){int arr[5] = { 1, 2, 3, 4, 5 };int *ptr = arr; cout <<\"\\n\"<< ptr;return 0;} // thus code is contributed by shivanisinghss2110",
"e": 24661,
"s": 24484,
"text": null
},
{
"code": "#include<stdio.h> int main(){ int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf(\"%p\\n\", ptr); return 0;}",
"e": 24776,
"s": 24661,
"text": null
},
{
"code": null,
"e": 25050,
"s": 24776,
"text": "In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays. Syntax: "
},
{
"code": null,
"e": 25088,
"s": 25050,
"text": "data_type (*var_name)[size_of_array];"
},
{
"code": null,
"e": 25098,
"s": 25088,
"text": "Example: "
},
{
"code": null,
"e": 25114,
"s": 25098,
"text": "int (*ptr)[10];"
},
{
"code": null,
"e": 25550,
"s": 25114,
"text": "Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’. Note : The pointer that points to the 0th element of array and the pointer that points to the whole array are totally different. The following program shows this: "
},
{
"code": null,
"e": 25554,
"s": 25550,
"text": "C++"
},
{
"code": null,
"e": 25556,
"s": 25554,
"text": "C"
},
{
"code": "// C++ program to understand difference between// pointer to an integer and pointer to an// array of integers.#include <iostream>using namespace std;int main(){ // Pointer to an integer int *p; // Pointer to an array of 5 integers int (*ptr)[5]; int arr[5]; // Points to 0th element of the arr. p = arr; // Points to the whole array arr. ptr = &arr; cout << \"p =\" << p <<\", ptr = \"<< ptr<< endl; p++; ptr++; cout << \"p =\" << p <<\", ptr = \"<< ptr<< endl; return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 26134,
"s": 25556,
"text": null
},
{
"code": "// C program to understand difference between// pointer to an integer and pointer to an// array of integers.#include<stdio.h> int main(){ // Pointer to an integer int *p; // Pointer to an array of 5 integers int (*ptr)[5]; int arr[5]; // Points to 0th element of the arr. p = arr; // Points to the whole array arr. ptr = &arr; printf(\"p = %p, ptr = %p\\n\", p, ptr); p++; ptr++; printf(\"p = %p, ptr = %p\\n\", p, ptr); return 0;}",
"e": 26637,
"s": 26134,
"text": null
},
{
"code": null,
"e": 26646,
"s": 26637,
"text": "Output: "
},
{
"code": null,
"e": 26728,
"s": 26646,
"text": "p = 0x7fff4f32fd50, ptr = 0x7fff4f32fd50\np = 0x7fff4f32fd54, ptr = 0x7fff4f32fd64"
},
{
"code": null,
"e": 26836,
"s": 26728,
"text": "p: is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole array arr. "
},
{
"code": null,
"e": 26914,
"s": 26836,
"text": "The base type of p is int while base type of ptr is ‘an array of 5 integers’."
},
{
"code": null,
"e": 27070,
"s": 26914,
"text": "We know that the pointer arithmetic is performed relative to the base size, so if we write ptr++, then the pointer ptr will be shifted forward by 20 bytes."
},
{
"code": null,
"e": 27164,
"s": 27070,
"text": "The following figure shows the pointer p and ptr. Darker arrow denotes pointer to an array. "
},
{
"code": null,
"e": 27503,
"s": 27164,
"text": "On dereferencing a pointer expression we get a value pointed to by that pointer expression. Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points. "
},
{
"code": null,
"e": 27507,
"s": 27503,
"text": "C++"
},
{
"code": null,
"e": 27509,
"s": 27507,
"text": "C"
},
{
"code": "// C++ program to illustrate sizes of// pointer of array#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 3, 5, 6, 7, 9 }; int *p = arr; int (*ptr)[5] = &arr; cout << \"p = \"<< p <<\", ptr = \" << ptr << endl; cout << \"*p = \"<< *p <<\", *ptr = \" << *ptr << endl; cout << \"sizeof(p) = \"<< sizeof(p) << \", sizeof(*p) = \" << sizeof(*p) << endl; cout << \"sizeof(ptr) = \"<< sizeof(ptr) << \", sizeof(*ptr) = \" << sizeof(*ptr) << endl; return 0;} // This code is contributed by shubhamsingh10",
"e": 28064,
"s": 27509,
"text": null
},
{
"code": "// C program to illustrate sizes of// pointer of array#include<stdio.h> int main(){ int arr[] = { 3, 5, 6, 7, 9 }; int *p = arr; int (*ptr)[5] = &arr; printf(\"p = %p, ptr = %p\\n\", p, ptr); printf(\"*p = %d, *ptr = %p\\n\", *p, *ptr); printf(\"sizeof(p) = %lu, sizeof(*p) = %lu\\n\", sizeof(p), sizeof(*p)); printf(\"sizeof(ptr) = %lu, sizeof(*ptr) = %lu\\n\", sizeof(ptr), sizeof(*ptr)); return 0;}",
"e": 28536,
"s": 28064,
"text": null
},
{
"code": null,
"e": 28545,
"s": 28536,
"text": "Output: "
},
{
"code": null,
"e": 28681,
"s": 28545,
"text": "p = 0x7ffde1ee5010, ptr = 0x7ffde1ee5010\n*p = 3, *ptr = 0x7ffde1ee5010\nsizeof(p) = 8, sizeof(*p) = 4\nsizeof(ptr) = 8, sizeof(*ptr) = 20"
},
{
"code": null,
"e": 28717,
"s": 28681,
"text": "Pointer to Multidimensional Arrays:"
},
{
"code": null,
"e": 29239,
"s": 28717,
"text": "Pointers and two dimensional Arrays: In a two dimensional array, we can access each element by using two subscripts, where first subscript represents the row number and second subscript represents the column number. The elements of 2-D array can be accessed with the help of pointer notation also. Suppose arr is a 2-D array, we can access any element arr[i][j] of the array using the pointer expression *(*(arr + i) + j). Now we’ll see how this expression can be derived. Let us take a two dimensional array arr[3][4]: "
},
{
"code": null,
"e": 29304,
"s": 29239,
"text": "int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };"
},
{
"code": null,
"e": 29638,
"s": 29304,
"text": "Since memory in a computer is organized linearly it is not possible to store the 2-D array in rows and columns. The concept of rows and columns is only theoretical, actually, a 2-D array is stored in row-major order i.e rows are placed next to each other. The following figure shows how the above 2-D array will be stored in memory. "
},
{
"code": null,
"e": 30414,
"s": 29638,
"text": "Each row can be considered as a 1-D array, so a two-dimensional array can be considered as a collection of one-dimensional arrays that are placed one after another. In other words, we can say that 2-D dimensional arrays that are placed one after another. So here arr is an array of 3 elements where each element is a 1-D array of 4 integers. We know that the name of an array is a constant pointer that points to 0th 1-D array and contains address 5000. Since arr is a ‘pointer to an array of 4 integers’, according to pointer arithmetic the expression arr + 1 will represent the address 5016 and expression arr + 2 will represent address 5032. So we can say that arr points to the 0th 1-D array, arr + 1 points to the 1st 1-D array and arr + 2 points to the 2nd 1-D array. "
},
{
"code": null,
"e": 30440,
"s": 30414,
"text": "In general we can write: "
},
{
"code": null,
"e": 30505,
"s": 30440,
"text": "arr + i Points to ith element of arr ->\nPoints to ith 1-D array"
},
{
"code": null,
"e": 30706,
"s": 30507,
"text": "Since arr + i points to ith element of arr, on dereferencing it will get ith element of arr which is of course a 1-D array. Thus the expression *(arr + i) gives us the base address of ith 1-D array."
},
{
"code": null,
"e": 30881,
"s": 30706,
"text": "We know, the pointer expression *(arr + i) is equivalent to the subscript expression arr[i]. So *(arr + i) which is same as arr[i] gives us the base address of ith 1-D array."
},
{
"code": null,
"e": 30993,
"s": 30881,
"text": "To access an individual element of our 2-D array, we should be able to access any jth element of ith 1-D array."
},
{
"code": null,
"e": 31204,
"s": 30993,
"text": "Since the base type of *(arr + i) is int and it contains the address of 0th element of ith 1-D array, we can get the addresses of subsequent elements in the ith 1-D array by adding integer values to *(arr + i)."
},
{
"code": null,
"e": 31379,
"s": 31204,
"text": "For example *(arr + i) + 1 will represent the address of 1st element of 1stelement of ith 1-D array and *(arr+i)+2 will represent the address of 2nd element of ith 1-D array."
},
{
"code": null,
"e": 31546,
"s": 31379,
"text": "Similarly *(arr + i) + j will represent the address of jth element of ith 1-D array. On dereferencing this expression we can get the jth element of the ith 1-D array."
},
{
"code": null,
"e": 31694,
"s": 31546,
"text": "Pointers and Three Dimensional Arrays In a three dimensional array we can access each element by using three subscripts. Let us take a 3-D array- "
},
{
"code": null,
"e": 31778,
"s": 31694,
"text": "int arr[2][3][2] = { {{5, 10}, {6, 11}, {7, 12}}, {{20, 30}, {21, 31}, {22, 32}} };"
},
{
"code": null,
"e": 32086,
"s": 31778,
"text": "We can consider a three dimensional array to be an array of 2-D array i.e each element of a 3-D array is considered to be a 2-D array. The 3-D array arr can be considered as an array consisting of two elements where each element is a 2-D array. The name of the array arr is a pointer to the 0th 2-D array. "
},
{
"code": null,
"e": 32453,
"s": 32086,
"text": "Thus the pointer expression *(*(*(arr + i ) + j ) + k) is equivalent to the subscript expression arr[i][j][k]. We know the expression *(arr + i) is equivalent to arr[i] and the expression *(*(arr + i) + j) is equivalent arr[i][j]. So we can say that arr[i] represents the base address of ith 2-D array and arr[i][j] represents the base address of the jth 1-D array. "
},
{
"code": null,
"e": 32457,
"s": 32453,
"text": "C++"
},
{
"code": null,
"e": 32459,
"s": 32457,
"text": "C"
},
{
"code": "// C++ program to print the elements of 3-D// array using pointer notation#include <iostream>using namespace std;int main(){ int arr[2][3][2] = { { {5, 10}, {6, 11}, {7, 12}, }, { {20, 30}, {21, 31}, {22, 32}, } }; int i, j, k; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { for (k = 0; k < 2; k++) cout << *(*(*(arr + i) + j) +k) << \"\\t\"; cout <<\"\\n\"; } } return 0;} // this code is contributed by shivanisinghss2110",
"e": 33171,
"s": 32459,
"text": null
},
{
"code": "// C program to print the elements of 3-D// array using pointer notation#include<stdio.h>int main(){ int arr[2][3][2] = { { {5, 10}, {6, 11}, {7, 12}, }, { {20, 30}, {21, 31}, {22, 32}, } }; int i, j, k; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { for (k = 0; k < 2; k++) printf(\"%d\\t\", *(*(*(arr + i) + j) +k)); printf(\"\\n\"); } } return 0;}",
"e": 33809,
"s": 33171,
"text": null
},
{
"code": null,
"e": 33818,
"s": 33809,
"text": "Output: "
},
{
"code": null,
"e": 33889,
"s": 33818,
"text": "5 10 \n6 11 \n7 12 \n20 30 \n21 31 \n22 32"
},
{
"code": null,
"e": 33983,
"s": 33889,
"text": "The following figure shows how the 3-D array used in the above program is stored in memory. "
},
{
"code": null,
"e": 34016,
"s": 33983,
"text": "Subscripting Pointer to an Array"
},
{
"code": null,
"e": 34166,
"s": 34016,
"text": "Suppose arr is a 2-D array with 3 rows and 4 columns and ptr is a pointer to an array of 4 integers, and ptr contains the base address of array arr. "
},
{
"code": null,
"e": 34264,
"s": 34166,
"text": "int arr[3][4] = {{10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33}};\nint (*ptr)[4];\nptr = arr;"
},
{
"code": null,
"e": 34946,
"s": 34266,
"text": "Since ptr is a pointer to an array of 4 integers, ptr + i will point to ith row. On dereferencing ptr + i, we get base address of ith row. To access the address of jth element of ith row we can add j to the pointer expression *(ptr + i). So the pointer expression *(ptr + i) + j gives the address of jth element of ith row and the pointer expression *(*(ptr + i)+j) gives the value of the jth element of ith row. We know that the pointer expression *(*(ptr + i) + j) is equivalent to subscript expression ptr[i][j]. So if we have a pointer variable containing the base address of 2-D array, then we can access the elements of array by double subscripting that pointer variable. "
},
{
"code": null,
"e": 34950,
"s": 34946,
"text": "C++"
},
{
"code": null,
"e": 34952,
"s": 34950,
"text": "C"
},
{
"code": "// C++ program to print elements of a 2-D array// by scripting a pointer to an array#include <iostream>using namespace std; int main(){ int arr[3][4] = { {10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33} }; int (*ptr)[4]; ptr = arr; cout << ptr<< \" \"<< ptr + 1<< \" \"<< ptr + 2 << endl; cout << *ptr<< \" \"<< *(ptr + 1)<< \" \"<< *(ptr + 2)<< endl; cout << **ptr<< \" \"<< *(*(ptr + 1) + 2)<< \" \"<< *(*(ptr + 2) + 3)<< endl; cout << ptr[0][0]<< \" \"<< ptr[1][2]<< \" \"<< ptr[2][3]<< endl; return 0;} // This code is contributed by shivanisinghss2110",
"e": 35579,
"s": 34952,
"text": null
},
{
"code": "// C program to print elements of a 2-D array// by scripting a pointer to an array#include<stdio.h> int main(){ int arr[3][4] = { {10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33} }; int (*ptr)[4]; ptr = arr; printf(\"%p %p %p\\n\", ptr, ptr + 1, ptr + 2); printf(\"%p %p %p\\n\", *ptr, *(ptr + 1), *(ptr + 2)); printf(\"%d %d %d\\n\", **ptr, *(*(ptr + 1) + 2), *(*(ptr + 2) + 3)); printf(\"%d %d %d\\n\", ptr[0][0], ptr[1][2], ptr[2][3]); return 0;}",
"e": 36103,
"s": 35579,
"text": null
},
{
"code": null,
"e": 36113,
"s": 36103,
"text": "Output: "
},
{
"code": null,
"e": 36221,
"s": 36113,
"text": "0x7ffead967560 0x7ffead967570 0x7ffead967580\n0x7ffead967560 0x7ffead967570 0x7ffead967580\n10 22 33\n10 22 33"
},
{
"code": null,
"e": 36643,
"s": 36221,
"text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above., "
},
{
"code": null,
"e": 36653,
"s": 36643,
"text": "flandraco"
},
{
"code": null,
"e": 36670,
"s": 36653,
"text": "BabisSarantoglou"
},
{
"code": null,
"e": 36681,
"s": 36670,
"text": "nidhi_biet"
},
{
"code": null,
"e": 36696,
"s": 36681,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 36715,
"s": 36696,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 36728,
"s": 36715,
"text": "simmytarika5"
},
{
"code": null,
"e": 36739,
"s": 36728,
"text": "C-Pointers"
},
{
"code": null,
"e": 36751,
"s": 36739,
"text": "cpp-pointer"
},
{
"code": null,
"e": 36762,
"s": 36751,
"text": "C Language"
},
{
"code": null,
"e": 36766,
"s": 36762,
"text": "C++"
},
{
"code": null,
"e": 36770,
"s": 36766,
"text": "CPP"
},
{
"code": null,
"e": 36868,
"s": 36770,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36903,
"s": 36868,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 36931,
"s": 36903,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 36977,
"s": 36931,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 37017,
"s": 36977,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 37029,
"s": 37017,
"text": "fork() in C"
},
{
"code": null,
"e": 37047,
"s": 37029,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 37093,
"s": 37047,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 37136,
"s": 37093,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 37164,
"s": 37136,
"text": "Operator Overloading in C++"
}
] |
Pipeline with Grid Search, ColumnTransformer, Feature Selection with python | Towards Data Science
|
Table of Contents 1. Introduction2. Pipeline3. Pipeline with Grid Search4. Pipeline with ColumnTransformer, GridSearchCV5. Pipeline with Feature Selection
Preparing the dataset for the algorithm, designing the model, and adjusting the hyperparameters of the algorithm, which is at the discretion of the developer, to generalize the model and to reach the optimum accuracy value were mentioned in the previous articles. As we know, there are alternative solutions at the developer’s disposal for both model preprocessing, data preprocessing and adjusting the hyperparameters of the algorithm. The developer is responsible for applying the most appropriate combinations and keeping his project optimum in terms of both accuracy and generalization. This article includes implementing all these mentioned operations and more in one go with the pipeline offered by sklearn. All headers are supported with python implementation.
In its most basic form, the pipeline is to implement the specified data preprocessing operations and the model into the dataset with a single line:
IN[1]iris=load_iris()iris_data =iris.datairis_target=iris.targetIN[2]x_train,x_test,y_train,y_test = train_test_split(iris_data, iris_target,test_size=0.2, random_state=2021)pip_iris = Pipeline([("scaler", RobustScaler()),("lr",LogisticRegression())])pip_iris.fit(x_train,y_train)iris_score=pip_iris.score(x_test,y_test)print(iris_score)OUT[2]0.9333333333333333
Iris dataset was separated with train_test_split as usual and RobustScaler() was chosen as the scaler method for the dataset known to be a numeric dataset, and LogisticRegression was chosen as the classifier. The pipeline also contains various attributes such as .fit, .score just like grid search. Train dataset was fitted with the .fit command in the created pipeline and the score was created with .score.
Grid Search evaluated hyperparameter combinations in the algorithm or any operation with defined hyperparameters, informing the user about the accuracy rate or best hyperparameter combinations with various attributes(more information click here). Using GridSearchCV with the Pipeline is a very effective way of eliminating workload and confusion. Now let’s test the Logistic Regression algorithm we implemented above with various combinations of hyperparameters for it:
IN[3]x_train,x_test,y_train,y_test = train_test_split(iris_data, iris_target,test_size=0.2, random_state=2021)pip_iris_gs = Pipeline([("scaler", RobustScaler()),("lr",LogisticRegression(solver='saga'))])param_grids={'lr__C':[0.001,0.1,2,10], 'lr__penalty':['l1','l2']}gs=GridSearchCV(pip_iris_gs,param_grids)gs.fit(x_train,y_train)test_score = gs.score(x_test,y_test)print("test score:",test_score)print("best parameters: ",gs.best_params_)print("best score: ", gs.best_score_)OUT[3]test score: 0.9333333333333333best parameters: {'lr__C': 2, 'lr__penalty': 'l1'}best score: 0.9583333333333334
In addition to the above, ‘C’ and ‘penalty’ values are defined as param_grids by creating a dictionary by the user. Later, the pipeline containing the algorithm and scaling was added to the GridSearchCV as an estimator. The training dataset is trained with .fit command and evaluated with .score. In addition, information was obtained about the model created with the help of various attributes in GridSearchCV.
So far, only the dataset -iris dataset- which is containing only numerical data has been used. To make the situation more complex, let’s use the toy dataset, which contains both numerical and categorical data, and apply:
Normalize the ‘Income’ column with MinMaxScaler()
Encode Categorical Columns with OneHotEncoder()
Group the ‘Age’ column with binning.
First, let’s take a quick look at the dataset:
IN[4]toy = pd.read_csv('toy_dataset.csv')toy_final=toy.drop(['Number'],axis=1)IN[5]toy_final.isna().sum()OUT[5]City 0Gender 0Age 0Income 0Illness 0dtype: int64IN[6]numeric_cols=toy.select_dtypes(include=np.number).columnsprint("numeric_cols:",numeric_cols)categorical_cols=toy.select_dtypes(exclude=np.number).columnsprint("categorical_cols:",categorical_cols)print("shape:",toy_final.shape)OUT[6]numeric_cols: Index(['Number', 'Age', 'Income'], dtype='object')categorical_cols: Index(['City', 'Gender', 'Illness'], dtype='object')shape: (150000, 5)
Now let’s perform the operations mentioned above:
IN[7]bins = KBinsDiscretizer(n_bins=5, encode='onehot-dense', strategy='uniform')ct = ColumnTransformer([ ('normalization', MinMaxScaler(), ['Income']), ('binning', bins, ['Age']), ('categorical-to-numeric', OneHotEncoder(sparse=False, handle_unknown='ignore'), ['City','Gender'])], remainder='drop')x_train, x_test, y_train, y_test = train_test_split(toy_final.drop('Illness', axis=1), toy_final.Illness, test_size=0.2, random_state=0)param_grid_lr=[{'lr__solver':['saga'],'lr__C':[0.1,1,10],'lr__penalty':['elasticnet','l1','l2']}, {'lr__solver':['lbfgs'],'lr__C':[0.1,1,10],'lr__penalty':['l2']}]IN[8]pipe_lr = Pipeline([ ('columntransform', ct), ('lr', LogisticRegression()), ])gs_lr =GridSearchCV(pipe_lr,param_grid_lr,cv=5)gs_lr.fit(x_train,y_train)test_score_lr = gs_lr.score(x_test,y_test)print("test score:",test_score_lr)print("best parameters: ",gs_lr.best_params_)print("best score: ", gs_lr.best_score_)OUT[8]test score: 0.9198666666666667best parameters: {'lr__C': 0.1, 'lr__penalty': 'l1', 'lr__solver': 'saga'}best score: 0.9188750000000001
The bins method with the KBinsDiscretizer() presented in the sklearn library is set to 5 groups and encode by OneHotEncoder. Preprocessing processes to be applied with ColumnTransformer() were gathered in one hand. These operations are:-Normalization for ‘Income’ column,-Discretization for ‘Age’ column,-Encode with OneHotEncoder() for categorical columns
The dataset was then split into training and testing. A dictionary (param_grids_lr) was created with the selected hyperparameters to evaluate the parameter combinations. The data preprocessing methods to be applied were collected in one hand with ColumnTransformer(more information click here)and the algorithm-LogisticRegression- were placed in the pipeline. As in the examples above, the model is completed by selecting the Cross-Validation value of 5 in the GridSearchCV.
The param_grid_lr dictionary is created as algorithm+double underscore + hyperparameter. LogisticRegression() is defined as lr and we know the ‘C’ is the hyperparameter of LogisticRegression so, lr__C is used. To see the all available hyperparameter that can be used, lr.get_params().keys() is applied.
Now let’s try the model we prepared with DecisionTreeClassifier():
IN[9]pipe_dt = Pipeline([ ('columntransform', ct), ('dt', DecisionTreeClassifier()),])param_grid_dt={'dt__max_depth':[2,3,4,5,6,7,8]}gs_dt =GridSearchCV(pipe_dt,param_grid_dt,cv=5)gs_dt.fit(x_train,y_train)test_score_dt = gs_dt.score(x_test,y_test)print("test score:",test_score_dt)print("best parameters: ",gs_dt.best_params_)print("best score: ", gs_dt.best_score_)OUT[9]test score: 0.9198333333333333best parameters: {'dt__max_depth': 2}best score: 0.9188750000000001
The max_depth values we selected were fit one by one and the most successful one was determined by grid search.
As mentioned in the introduction, using the pipeline and GridSearchCV is a very effective way to evaluate hyperparameter combinations and compile them easily. It is very useful not only for data preprocessing and algorithms but also for data cleaning(SimpleImputer), feature processing(SelectKBest, SelectPercentile , more information click here), etc. Now let’s apply the following to the breast_cancer dataset containing 30 features:
— Standardization to numerical values with StandardScaler()
— PolynomialFeatures() to numerical values
— ANOVA with SelectPercentile()
— LogisticRegression hyperparameters(‘C’ and ‘penalty’)
— tune Cross-Validation=3
IN[10]cancer=load_breast_cancer()cancer_data =cancer.datacancer_target =cancer.targetIN[11]anova = SelectPercentile()poly = PolynomialFeatures()lr=LogisticRegression(solver='saga')param_grid_cancer=dict(poly__degree=[2,3,4], anova__percentile=[20, 30, 40, 50], lr__C=[0.01,0.1,1,10], lr__penalty=['l1','l2'] )pipe_cancer = Pipeline([ ('standardization',StandardScaler()), ('poly',poly), ('anova',anova), ('lr',lr) ])gs_final = GridSearchCV(pipe_cancer,param_grid_cancer,cv=3,n_jobs=-1)x_train, x_test, y_train, y_test = train_test_split(cancer_data, cancer_target,test_size=0.2,random_state=2021)gs_final.fit(x_train,y_train)test_score_final = gs_final.score(x_test,y_test)print("test score:",test_score_final)print("best parameters: ",gs_final.best_params_)print("best score: ", gs_final.best_score_)OUT[11]test score: 0.9736842105263158best parameters: {'anova__percentile': 20, 'lr__C': 0.1, 'lr__penalty': 'l1', 'poly__degree': 2}best score: 0.9626612059951203
Hyperparameter combinations to be tested with param_grid_cancer have been defined:
degree=[2,3,4] for PolynomialFeatures()
percentile= [20, 30, 40, 50] for SelectPercentile()
C=[0.01,0.1,1,10] for LogisticRegression()
penalty=[‘l1’,’l2’] for LogisticRegression()
All these were piped in with StandardScaler(). Then the cross-validation value was set to 3 in GridSearchCV. Dataset was split with train_test_split and was fitted with .fit as always. When the ‘percentile ’which is in SelectPercentile is set 20%, ‘C’ value in LogisticRegression is set 0.1, ‘penalty’ parameter in LogisticRegression is set ‘L1’, and ‘degree ’in PolynomialFeatures is set 2, the accuracy is highest.
The pipeline is useful in evaluating many things that are required when creating a pipeline model, collectively, from a single source. make_pipeline can be used as well as Pipeline. make_pipeline automatically creates the necessary names for the steps, so just adding the process is sufficient.
|
[
{
"code": null,
"e": 202,
"s": 47,
"text": "Table of Contents 1. Introduction2. Pipeline3. Pipeline with Grid Search4. Pipeline with ColumnTransformer, GridSearchCV5. Pipeline with Feature Selection"
},
{
"code": null,
"e": 970,
"s": 202,
"text": "Preparing the dataset for the algorithm, designing the model, and adjusting the hyperparameters of the algorithm, which is at the discretion of the developer, to generalize the model and to reach the optimum accuracy value were mentioned in the previous articles. As we know, there are alternative solutions at the developer’s disposal for both model preprocessing, data preprocessing and adjusting the hyperparameters of the algorithm. The developer is responsible for applying the most appropriate combinations and keeping his project optimum in terms of both accuracy and generalization. This article includes implementing all these mentioned operations and more in one go with the pipeline offered by sklearn. All headers are supported with python implementation."
},
{
"code": null,
"e": 1118,
"s": 970,
"text": "In its most basic form, the pipeline is to implement the specified data preprocessing operations and the model into the dataset with a single line:"
},
{
"code": null,
"e": 1481,
"s": 1118,
"text": "IN[1]iris=load_iris()iris_data =iris.datairis_target=iris.targetIN[2]x_train,x_test,y_train,y_test = train_test_split(iris_data, iris_target,test_size=0.2, random_state=2021)pip_iris = Pipeline([(\"scaler\", RobustScaler()),(\"lr\",LogisticRegression())])pip_iris.fit(x_train,y_train)iris_score=pip_iris.score(x_test,y_test)print(iris_score)OUT[2]0.9333333333333333"
},
{
"code": null,
"e": 1890,
"s": 1481,
"text": "Iris dataset was separated with train_test_split as usual and RobustScaler() was chosen as the scaler method for the dataset known to be a numeric dataset, and LogisticRegression was chosen as the classifier. The pipeline also contains various attributes such as .fit, .score just like grid search. Train dataset was fitted with the .fit command in the created pipeline and the score was created with .score."
},
{
"code": null,
"e": 2360,
"s": 1890,
"text": "Grid Search evaluated hyperparameter combinations in the algorithm or any operation with defined hyperparameters, informing the user about the accuracy rate or best hyperparameter combinations with various attributes(more information click here). Using GridSearchCV with the Pipeline is a very effective way of eliminating workload and confusion. Now let’s test the Logistic Regression algorithm we implemented above with various combinations of hyperparameters for it:"
},
{
"code": null,
"e": 2968,
"s": 2360,
"text": "IN[3]x_train,x_test,y_train,y_test = train_test_split(iris_data, iris_target,test_size=0.2, random_state=2021)pip_iris_gs = Pipeline([(\"scaler\", RobustScaler()),(\"lr\",LogisticRegression(solver='saga'))])param_grids={'lr__C':[0.001,0.1,2,10], 'lr__penalty':['l1','l2']}gs=GridSearchCV(pip_iris_gs,param_grids)gs.fit(x_train,y_train)test_score = gs.score(x_test,y_test)print(\"test score:\",test_score)print(\"best parameters: \",gs.best_params_)print(\"best score: \", gs.best_score_)OUT[3]test score: 0.9333333333333333best parameters: {'lr__C': 2, 'lr__penalty': 'l1'}best score: 0.9583333333333334"
},
{
"code": null,
"e": 3380,
"s": 2968,
"text": "In addition to the above, ‘C’ and ‘penalty’ values are defined as param_grids by creating a dictionary by the user. Later, the pipeline containing the algorithm and scaling was added to the GridSearchCV as an estimator. The training dataset is trained with .fit command and evaluated with .score. In addition, information was obtained about the model created with the help of various attributes in GridSearchCV."
},
{
"code": null,
"e": 3601,
"s": 3380,
"text": "So far, only the dataset -iris dataset- which is containing only numerical data has been used. To make the situation more complex, let’s use the toy dataset, which contains both numerical and categorical data, and apply:"
},
{
"code": null,
"e": 3651,
"s": 3601,
"text": "Normalize the ‘Income’ column with MinMaxScaler()"
},
{
"code": null,
"e": 3699,
"s": 3651,
"text": "Encode Categorical Columns with OneHotEncoder()"
},
{
"code": null,
"e": 3736,
"s": 3699,
"text": "Group the ‘Age’ column with binning."
},
{
"code": null,
"e": 3783,
"s": 3736,
"text": "First, let’s take a quick look at the dataset:"
},
{
"code": null,
"e": 4357,
"s": 3783,
"text": "IN[4]toy = pd.read_csv('toy_dataset.csv')toy_final=toy.drop(['Number'],axis=1)IN[5]toy_final.isna().sum()OUT[5]City 0Gender 0Age 0Income 0Illness 0dtype: int64IN[6]numeric_cols=toy.select_dtypes(include=np.number).columnsprint(\"numeric_cols:\",numeric_cols)categorical_cols=toy.select_dtypes(exclude=np.number).columnsprint(\"categorical_cols:\",categorical_cols)print(\"shape:\",toy_final.shape)OUT[6]numeric_cols: Index(['Number', 'Age', 'Income'], dtype='object')categorical_cols: Index(['City', 'Gender', 'Illness'], dtype='object')shape: (150000, 5)"
},
{
"code": null,
"e": 4407,
"s": 4357,
"text": "Now let’s perform the operations mentioned above:"
},
{
"code": null,
"e": 5548,
"s": 4407,
"text": "IN[7]bins = KBinsDiscretizer(n_bins=5, encode='onehot-dense', strategy='uniform')ct = ColumnTransformer([ ('normalization', MinMaxScaler(), ['Income']), ('binning', bins, ['Age']), ('categorical-to-numeric', OneHotEncoder(sparse=False, handle_unknown='ignore'), ['City','Gender'])], remainder='drop')x_train, x_test, y_train, y_test = train_test_split(toy_final.drop('Illness', axis=1), toy_final.Illness, test_size=0.2, random_state=0)param_grid_lr=[{'lr__solver':['saga'],'lr__C':[0.1,1,10],'lr__penalty':['elasticnet','l1','l2']}, {'lr__solver':['lbfgs'],'lr__C':[0.1,1,10],'lr__penalty':['l2']}]IN[8]pipe_lr = Pipeline([ ('columntransform', ct), ('lr', LogisticRegression()), ])gs_lr =GridSearchCV(pipe_lr,param_grid_lr,cv=5)gs_lr.fit(x_train,y_train)test_score_lr = gs_lr.score(x_test,y_test)print(\"test score:\",test_score_lr)print(\"best parameters: \",gs_lr.best_params_)print(\"best score: \", gs_lr.best_score_)OUT[8]test score: 0.9198666666666667best parameters: {'lr__C': 0.1, 'lr__penalty': 'l1', 'lr__solver': 'saga'}best score: 0.9188750000000001"
},
{
"code": null,
"e": 5905,
"s": 5548,
"text": "The bins method with the KBinsDiscretizer() presented in the sklearn library is set to 5 groups and encode by OneHotEncoder. Preprocessing processes to be applied with ColumnTransformer() were gathered in one hand. These operations are:-Normalization for ‘Income’ column,-Discretization for ‘Age’ column,-Encode with OneHotEncoder() for categorical columns"
},
{
"code": null,
"e": 6380,
"s": 5905,
"text": "The dataset was then split into training and testing. A dictionary (param_grids_lr) was created with the selected hyperparameters to evaluate the parameter combinations. The data preprocessing methods to be applied were collected in one hand with ColumnTransformer(more information click here)and the algorithm-LogisticRegression- were placed in the pipeline. As in the examples above, the model is completed by selecting the Cross-Validation value of 5 in the GridSearchCV."
},
{
"code": null,
"e": 6683,
"s": 6380,
"text": "The param_grid_lr dictionary is created as algorithm+double underscore + hyperparameter. LogisticRegression() is defined as lr and we know the ‘C’ is the hyperparameter of LogisticRegression so, lr__C is used. To see the all available hyperparameter that can be used, lr.get_params().keys() is applied."
},
{
"code": null,
"e": 6750,
"s": 6683,
"text": "Now let’s try the model we prepared with DecisionTreeClassifier():"
},
{
"code": null,
"e": 7229,
"s": 6750,
"text": "IN[9]pipe_dt = Pipeline([ ('columntransform', ct), ('dt', DecisionTreeClassifier()),])param_grid_dt={'dt__max_depth':[2,3,4,5,6,7,8]}gs_dt =GridSearchCV(pipe_dt,param_grid_dt,cv=5)gs_dt.fit(x_train,y_train)test_score_dt = gs_dt.score(x_test,y_test)print(\"test score:\",test_score_dt)print(\"best parameters: \",gs_dt.best_params_)print(\"best score: \", gs_dt.best_score_)OUT[9]test score: 0.9198333333333333best parameters: {'dt__max_depth': 2}best score: 0.9188750000000001"
},
{
"code": null,
"e": 7341,
"s": 7229,
"text": "The max_depth values we selected were fit one by one and the most successful one was determined by grid search."
},
{
"code": null,
"e": 7777,
"s": 7341,
"text": "As mentioned in the introduction, using the pipeline and GridSearchCV is a very effective way to evaluate hyperparameter combinations and compile them easily. It is very useful not only for data preprocessing and algorithms but also for data cleaning(SimpleImputer), feature processing(SelectKBest, SelectPercentile , more information click here), etc. Now let’s apply the following to the breast_cancer dataset containing 30 features:"
},
{
"code": null,
"e": 7837,
"s": 7777,
"text": "— Standardization to numerical values with StandardScaler()"
},
{
"code": null,
"e": 7880,
"s": 7837,
"text": "— PolynomialFeatures() to numerical values"
},
{
"code": null,
"e": 7912,
"s": 7880,
"text": "— ANOVA with SelectPercentile()"
},
{
"code": null,
"e": 7968,
"s": 7912,
"text": "— LogisticRegression hyperparameters(‘C’ and ‘penalty’)"
},
{
"code": null,
"e": 7994,
"s": 7968,
"text": "— tune Cross-Validation=3"
},
{
"code": null,
"e": 9050,
"s": 7994,
"text": "IN[10]cancer=load_breast_cancer()cancer_data =cancer.datacancer_target =cancer.targetIN[11]anova = SelectPercentile()poly = PolynomialFeatures()lr=LogisticRegression(solver='saga')param_grid_cancer=dict(poly__degree=[2,3,4], anova__percentile=[20, 30, 40, 50], lr__C=[0.01,0.1,1,10], lr__penalty=['l1','l2'] )pipe_cancer = Pipeline([ ('standardization',StandardScaler()), ('poly',poly), ('anova',anova), ('lr',lr) ])gs_final = GridSearchCV(pipe_cancer,param_grid_cancer,cv=3,n_jobs=-1)x_train, x_test, y_train, y_test = train_test_split(cancer_data, cancer_target,test_size=0.2,random_state=2021)gs_final.fit(x_train,y_train)test_score_final = gs_final.score(x_test,y_test)print(\"test score:\",test_score_final)print(\"best parameters: \",gs_final.best_params_)print(\"best score: \", gs_final.best_score_)OUT[11]test score: 0.9736842105263158best parameters: {'anova__percentile': 20, 'lr__C': 0.1, 'lr__penalty': 'l1', 'poly__degree': 2}best score: 0.9626612059951203"
},
{
"code": null,
"e": 9133,
"s": 9050,
"text": "Hyperparameter combinations to be tested with param_grid_cancer have been defined:"
},
{
"code": null,
"e": 9173,
"s": 9133,
"text": "degree=[2,3,4] for PolynomialFeatures()"
},
{
"code": null,
"e": 9225,
"s": 9173,
"text": "percentile= [20, 30, 40, 50] for SelectPercentile()"
},
{
"code": null,
"e": 9268,
"s": 9225,
"text": "C=[0.01,0.1,1,10] for LogisticRegression()"
},
{
"code": null,
"e": 9313,
"s": 9268,
"text": "penalty=[‘l1’,’l2’] for LogisticRegression()"
},
{
"code": null,
"e": 9730,
"s": 9313,
"text": "All these were piped in with StandardScaler(). Then the cross-validation value was set to 3 in GridSearchCV. Dataset was split with train_test_split and was fitted with .fit as always. When the ‘percentile ’which is in SelectPercentile is set 20%, ‘C’ value in LogisticRegression is set 0.1, ‘penalty’ parameter in LogisticRegression is set ‘L1’, and ‘degree ’in PolynomialFeatures is set 2, the accuracy is highest."
}
] |
How to create plot in R with different shape of points?
|
In base R, the plot with different shape of points can be created by using pch argument inside the plot function. The list of pch values with shape is as written below −
pch = 0 display square
pch = 1 display circle
pch = 2 display triangle point up
pch = 3 display plus
pch = 4 display cross
pch = 5 display diamond
pch = 6 display triangle point down
pch = 7 display square cross
pch = 8 display star
pch = 9 display diamond plus
pch = 10 display circle plus
pch = 11 display triangles up and down
pch = 12 display square plus
pch = 13 display circle cross
pch = 14 display square and triangle down
pch = 15 display filled square
pch = 16 display filled circle
pch = 17 display filled triangle point-up
pch = 18 display filled diamond
pch = 19 display solid circle
pch = 20 display bullet (smaller circle)
pch = 21 display filled circle blue
pch = 22 display filled square blue
pch = 23 display filled diamond blue
pch = 24 display filled triangle point-up blue
pch = 25 display filled triangle point down blue
Consider the below vectors and create a point chart with three different shapes −
Live Demo
x<-sample(0:5,20,replace=TRUE)
y<-sample(1:10,20,replace=TRUE)
plot(x,y,pch=c(16,17,18))
Creating the same plot with different colors of the shapes −
plot(x,y,pch=c(16,17,18),col=c("red","yellow","blue"))
|
[
{
"code": null,
"e": 1232,
"s": 1062,
"text": "In base R, the plot with different shape of points can be created by using pch argument inside the plot function. The list of pch values with shape is as written below −"
},
{
"code": null,
"e": 2075,
"s": 1232,
"text": "pch = 0 display square\npch = 1 display circle\npch = 2 display triangle point up\npch = 3 display plus\npch = 4 display cross\npch = 5 display diamond\npch = 6 display triangle point down\npch = 7 display square cross\npch = 8 display star\npch = 9 display diamond plus\npch = 10 display circle plus\npch = 11 display triangles up and down\npch = 12 display square plus\npch = 13 display circle cross\npch = 14 display square and triangle down\npch = 15 display filled square\npch = 16 display filled circle\npch = 17 display filled triangle point-up\npch = 18 display filled diamond\npch = 19 display solid circle\npch = 20 display bullet (smaller circle)\npch = 21 display filled circle blue\npch = 22 display filled square blue\npch = 23 display filled diamond blue\npch = 24 display filled triangle point-up blue\npch = 25 display filled triangle point down blue"
},
{
"code": null,
"e": 2157,
"s": 2075,
"text": "Consider the below vectors and create a point chart with three different shapes −"
},
{
"code": null,
"e": 2168,
"s": 2157,
"text": " Live Demo"
},
{
"code": null,
"e": 2257,
"s": 2168,
"text": "x<-sample(0:5,20,replace=TRUE)\ny<-sample(1:10,20,replace=TRUE)\nplot(x,y,pch=c(16,17,18))"
},
{
"code": null,
"e": 2318,
"s": 2257,
"text": "Creating the same plot with different colors of the shapes −"
},
{
"code": null,
"e": 2373,
"s": 2318,
"text": "plot(x,y,pch=c(16,17,18),col=c(\"red\",\"yellow\",\"blue\"))"
}
] |
What is strcmp() Function in C language?
|
The C library function int strcmp(const char *str1, const char *str2) compares the string pointed to, by str1 to the string pointed to by str2.
An array of characters is called a string.
Following is the declaration for an array −
char stringname [size];
For example − char string[50]; string of length 50 characters
Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants −
char string[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.
This function compares two strings.
This function compares two strings.
It returns the ASCII difference of the first two non – matching characters in both the strings.
It returns the ASCII difference of the first two non – matching characters in both the strings.
The syntax is as follows −
int strcmp (string1, string2);
If the difference is equal to zero ------ string1 = string2
If the difference is positive ------- string1> string2
If the difference is negative ------- string1 <string2
The following program shows the usage of strcmp() function −
Live Demo
#include<stdio.h>
main ( ){
char a[50], b [50];
int d;
printf ("enter 2 strings:\n");
scanf ("%s %s", a,b);
d = strcmp (a,b);
if (d==0)
printf("%s is equal to %s", a,b);
else if (d>0)
printf("%s is greater than %s",a,b);
else if (d<0)
printf("%s is less than %s", a,b);
}
When the above program is executed, it produces the following result −
enter 2 strings:
bhanu
priya
bhanu is less than priya
Let’s see another example on strcmp().
Given below is the C program to compare two strings using strcmp library function −
Live Demo
#include<stdio.h>
#include<string.h>
void main(){
//Declaring two strings//
char string1[25],string2[25];
int value;
//Reading string 1 and String 2//
printf("Enter String 1: ");
gets(string1);
printf("Enter String 2: ");
gets(string2);
//Comparing using library function//
value = strcmp(string1,string2);
//If conditions//
if(value==0){
printf("%s is same as %s",string1,string2);
}
else if(value>0){
printf("%s is greater than %s",string1,string2);
}
else{
printf("%s is less than %s",string1,string2);
}
}
When the above program is executed, it produces the following result −
Enter String 1: Tutorials
Enter String 2: Point
Tutorials is greater than Point
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "The C library function int strcmp(const char *str1, const char *str2) compares the string pointed to, by str1 to the string pointed to by str2."
},
{
"code": null,
"e": 1249,
"s": 1206,
"text": "An array of characters is called a string."
},
{
"code": null,
"e": 1293,
"s": 1249,
"text": "Following is the declaration for an array −"
},
{
"code": null,
"e": 1317,
"s": 1293,
"text": "char stringname [size];"
},
{
"code": null,
"e": 1379,
"s": 1317,
"text": "For example − char string[50]; string of length 50 characters"
},
{
"code": null,
"e": 1413,
"s": 1379,
"text": "Using single character constant −"
},
{
"code": null,
"e": 1464,
"s": 1413,
"text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}"
},
{
"code": null,
"e": 1489,
"s": 1464,
"text": "Using string constants −"
},
{
"code": null,
"e": 1517,
"s": 1489,
"text": "char string[10] = \"Hello\":;"
},
{
"code": null,
"e": 1615,
"s": 1517,
"text": "Accessing − There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’."
},
{
"code": null,
"e": 1651,
"s": 1615,
"text": "This function compares two strings."
},
{
"code": null,
"e": 1687,
"s": 1651,
"text": "This function compares two strings."
},
{
"code": null,
"e": 1783,
"s": 1687,
"text": "It returns the ASCII difference of the first two non – matching characters in both the strings."
},
{
"code": null,
"e": 1879,
"s": 1783,
"text": "It returns the ASCII difference of the first two non – matching characters in both the strings."
},
{
"code": null,
"e": 1906,
"s": 1879,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1937,
"s": 1906,
"text": "int strcmp (string1, string2);"
},
{
"code": null,
"e": 1997,
"s": 1937,
"text": "If the difference is equal to zero ------ string1 = string2"
},
{
"code": null,
"e": 2052,
"s": 1997,
"text": "If the difference is positive ------- string1> string2"
},
{
"code": null,
"e": 2107,
"s": 2052,
"text": "If the difference is negative ------- string1 <string2"
},
{
"code": null,
"e": 2168,
"s": 2107,
"text": "The following program shows the usage of strcmp() function −"
},
{
"code": null,
"e": 2179,
"s": 2168,
"text": " Live Demo"
},
{
"code": null,
"e": 2493,
"s": 2179,
"text": "#include<stdio.h>\nmain ( ){\n char a[50], b [50];\n int d;\n printf (\"enter 2 strings:\\n\");\n scanf (\"%s %s\", a,b);\n d = strcmp (a,b);\n if (d==0)\n printf(\"%s is equal to %s\", a,b);\n else if (d>0)\n printf(\"%s is greater than %s\",a,b);\n else if (d<0)\n printf(\"%s is less than %s\", a,b);\n}"
},
{
"code": null,
"e": 2564,
"s": 2493,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2618,
"s": 2564,
"text": "enter 2 strings:\nbhanu\npriya\nbhanu is less than priya"
},
{
"code": null,
"e": 2657,
"s": 2618,
"text": "Let’s see another example on strcmp()."
},
{
"code": null,
"e": 2741,
"s": 2657,
"text": "Given below is the C program to compare two strings using strcmp library function −"
},
{
"code": null,
"e": 2752,
"s": 2741,
"text": " Live Demo"
},
{
"code": null,
"e": 3331,
"s": 2752,
"text": "#include<stdio.h>\n#include<string.h>\nvoid main(){\n //Declaring two strings//\n char string1[25],string2[25];\n int value;\n //Reading string 1 and String 2//\n printf(\"Enter String 1: \");\n gets(string1);\n printf(\"Enter String 2: \");\n gets(string2);\n //Comparing using library function//\n value = strcmp(string1,string2);\n //If conditions//\n if(value==0){\n printf(\"%s is same as %s\",string1,string2);\n }\n else if(value>0){\n printf(\"%s is greater than %s\",string1,string2);\n }\n else{\n printf(\"%s is less than %s\",string1,string2);\n }\n}"
},
{
"code": null,
"e": 3402,
"s": 3331,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3482,
"s": 3402,
"text": "Enter String 1: Tutorials\nEnter String 2: Point\nTutorials is greater than Point"
}
] |
DocumentDB SQL - Joins
|
In relational databases, the Joins clause is used to combine records from two or more tables in a database, and the need to join across tables is very important while designing normalized schemas. Since DocumentDB deals with the denormalized data model of schema-free documents, the JOIN in DocumentDB SQL is the logical equivalent of a "selfjoin".
Let’s consider the three documents as in the previous examples.
Following is the AndersenFamily document.
{
"id": "AndersenFamily",
"lastName": "Andersen",
"parents": [
{ "firstName": "Thomas", "relationship": "father" },
{ "firstName": "Mary Kay", "relationship": "mother" }
],
"children": [
{
"firstName": "Henriette Thaulow",
"gender": "female",
"grade": 5,
"pets": [ { "givenName": "Fluffy", "type": "Rabbit" } ]
}
],
"location": { "state": "WA", "county": "King", "city": "Seattle" },
"isRegistered": true
}
Following is the SmithFamily document.
{
"id": "SmithFamily",
"parents": [
{ "familyName": "Smith", "givenName": "James" },
{ "familyName": "Curtis", "givenName": "Helen" }
],
"children": [
{
"givenName": "Michelle",
"gender": "female",
"grade": 1
},
{
"givenName": "John",
"gender": "male",
"grade": 7,
"pets": [
{ "givenName": "Tweetie", "type": "Bird" }
]
}
],
"location": {
"state": "NY",
"county": "Queens",
"city": "Forest Hills"
},
"isRegistered": true
}
Following is the WakefieldFamily document.
{
"id": "WakefieldFamily",
"parents": [
{ "familyName": "Wakefield", "givenName": "Robin" },
{ "familyName": "Miller", "givenName": "Ben" }
],
"children": [
{
"familyName": "Merriam",
"givenName": "Jesse",
"gender": "female",
"grade": 6,
"pets": [
{ "givenName": "Charlie Brown", "type": "Dog" },
{ "givenName": "Tiger", "type": "Cat" },
{ "givenName": "Princess", "type": "Cat" }
]
},
{
"familyName": "Miller",
"givenName": "Lisa",
"gender": "female",
"grade": 3,
"pets": [
{ "givenName": "Jake", "type": "Snake" }
]
}
],
"location": { "state": "NY", "county": "Manhattan", "city": "NY" },
"isRegistered": false
}
Let’s take a look at an example to understand how the JOIN clause works.
Following is the query which will join the root to children subdocument.
SELECT f.id
FROM Families f
JOIN c IN f.children
When the above query is executed, it will produce the following output.
[
{
"id": "WakefieldFamily"
},
{
"id": "WakefieldFamily"
},
{
"id": "SmithFamily"
},
{
"id": "SmithFamily"
},
{
"id": "AndersenFamily"
}
]
In the above example, the join is between the document root and the children sub-root which makes a cross-product between two JSON objects. Following are certain points to note −
In the FROM clause, the JOIN clause is an iterator.
In the FROM clause, the JOIN clause is an iterator.
The first two documents WakefieldFamily and SmithFamily contain two children, hence the result set also contains the cross-product which produces a separate object for each child.
The first two documents WakefieldFamily and SmithFamily contain two children, hence the result set also contains the cross-product which produces a separate object for each child.
The third document AndersenFamily contains only one children, hence there is only a single object corresponding to this document.
The third document AndersenFamily contains only one children, hence there is only a single object corresponding to this document.
Let’s take a look at the same example, however this time we retrieve the child name as well for better understanding of JOIN clause.
Following is the query which will join the root to children subdocument.
SELECT
f.id AS familyName,
c.givenName AS childGivenName,
c.firstName AS childFirstName
FROM Families f
JOIN c IN f.children
When the above query is executed, it produces the following output.
[
{
"familyName": "WakefieldFamily",
"childGivenName": "Jesse"
},
{
"familyName": "WakefieldFamily",
"childGivenName": "Lisa"
},
{
"familyName": "SmithFamily",
"childGivenName": "Michelle"
},
{
"familyName": "SmithFamily",
"childGivenName": "John"
},
{
"familyName": "AndersenFamily",
"childFirstName": "Henriette Thaulow"
}
]
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2534,
"s": 2185,
"text": "In relational databases, the Joins clause is used to combine records from two or more tables in a database, and the need to join across tables is very important while designing normalized schemas. Since DocumentDB deals with the denormalized data model of schema-free documents, the JOIN in DocumentDB SQL is the logical equivalent of a \"selfjoin\"."
},
{
"code": null,
"e": 2598,
"s": 2534,
"text": "Let’s consider the three documents as in the previous examples."
},
{
"code": null,
"e": 2640,
"s": 2598,
"text": "Following is the AndersenFamily document."
},
{
"code": null,
"e": 3161,
"s": 2640,
"text": "{ \n \"id\": \"AndersenFamily\", \n \"lastName\": \"Andersen\", \n\t\n \"parents\": [ \n { \"firstName\": \"Thomas\", \"relationship\": \"father\" }, \n { \"firstName\": \"Mary Kay\", \"relationship\": \"mother\" } \n ],\n \n \"children\": [ \n { \n \"firstName\": \"Henriette Thaulow\", \n \"gender\": \"female\", \n \"grade\": 5, \n \"pets\": [ { \"givenName\": \"Fluffy\", \"type\": \"Rabbit\" } ] \n } \n ], \n \n \"location\": { \"state\": \"WA\", \"county\": \"King\", \"city\": \"Seattle\" }, \n \"isRegistered\": true \n}\n"
},
{
"code": null,
"e": 3200,
"s": 3161,
"text": "Following is the SmithFamily document."
},
{
"code": null,
"e": 3829,
"s": 3200,
"text": "{ \n \"id\": \"SmithFamily\", \n\t\n \"parents\": [ \n { \"familyName\": \"Smith\", \"givenName\": \"James\" }, \n { \"familyName\": \"Curtis\", \"givenName\": \"Helen\" } \n ],\n \n \"children\": [ \n {\n \"givenName\": \"Michelle\", \n \"gender\": \"female\", \n \"grade\": 1 \n },\n\t\t\n { \n \"givenName\": \"John\", \n \"gender\": \"male\", \n \"grade\": 7,\n\t\t\t\n \"pets\": [ \n { \"givenName\": \"Tweetie\", \"type\": \"Bird\" } \n ] \n } \n ],\n \n \"location\": { \n \"state\": \"NY\", \n \"county\": \"Queens\", \n \"city\": \"Forest Hills\" \n },\n \n \"isRegistered\": true \n} \n"
},
{
"code": null,
"e": 3872,
"s": 3829,
"text": "Following is the WakefieldFamily document."
},
{
"code": null,
"e": 4748,
"s": 3872,
"text": "{ \n \"id\": \"WakefieldFamily\", \n\t\n \"parents\": [ \n { \"familyName\": \"Wakefield\", \"givenName\": \"Robin\" }, \n { \"familyName\": \"Miller\", \"givenName\": \"Ben\" } \n ],\n \n \"children\": [ \n { \n \"familyName\": \"Merriam\", \n \"givenName\": \"Jesse\", \n \"gender\": \"female\", \n \"grade\": 6,\n\t\t\t\n \"pets\": [ \n { \"givenName\": \"Charlie Brown\", \"type\": \"Dog\" },\n { \"givenName\": \"Tiger\", \"type\": \"Cat\" }, \n { \"givenName\": \"Princess\", \"type\": \"Cat\" } \n ] \n },\n\t\t\n { \n \"familyName\": \"Miller\", \n \"givenName\": \"Lisa\", \n \"gender\": \"female\", \n \"grade\": 3,\n\t\t\t\n \"pets\": [ \n { \"givenName\": \"Jake\", \"type\": \"Snake\" } \n ] \n } \n ], \n \n \"location\": { \"state\": \"NY\", \"county\": \"Manhattan\", \"city\": \"NY\" }, \n \"isRegistered\": false \n} \n"
},
{
"code": null,
"e": 4821,
"s": 4748,
"text": "Let’s take a look at an example to understand how the JOIN clause works."
},
{
"code": null,
"e": 4894,
"s": 4821,
"text": "Following is the query which will join the root to children subdocument."
},
{
"code": null,
"e": 4945,
"s": 4894,
"text": "SELECT f.id \nFROM Families f \nJOIN c IN f.children"
},
{
"code": null,
"e": 5017,
"s": 4945,
"text": "When the above query is executed, it will produce the following output."
},
{
"code": null,
"e": 5237,
"s": 5017,
"text": "[ \n { \n \"id\": \"WakefieldFamily\" \n },\n\t\n { \n \"id\": \"WakefieldFamily\" \n },\n\t\n { \n \"id\": \"SmithFamily\" \n },\n\t\n { \n \"id\": \"SmithFamily\" \n },\n\t\n { \n \"id\": \"AndersenFamily\" \n } \n]\n"
},
{
"code": null,
"e": 5416,
"s": 5237,
"text": "In the above example, the join is between the document root and the children sub-root which makes a cross-product between two JSON objects. Following are certain points to note −"
},
{
"code": null,
"e": 5468,
"s": 5416,
"text": "In the FROM clause, the JOIN clause is an iterator."
},
{
"code": null,
"e": 5520,
"s": 5468,
"text": "In the FROM clause, the JOIN clause is an iterator."
},
{
"code": null,
"e": 5700,
"s": 5520,
"text": "The first two documents WakefieldFamily and SmithFamily contain two children, hence the result set also contains the cross-product which produces a separate object for each child."
},
{
"code": null,
"e": 5880,
"s": 5700,
"text": "The first two documents WakefieldFamily and SmithFamily contain two children, hence the result set also contains the cross-product which produces a separate object for each child."
},
{
"code": null,
"e": 6010,
"s": 5880,
"text": "The third document AndersenFamily contains only one children, hence there is only a single object corresponding to this document."
},
{
"code": null,
"e": 6140,
"s": 6010,
"text": "The third document AndersenFamily contains only one children, hence there is only a single object corresponding to this document."
},
{
"code": null,
"e": 6273,
"s": 6140,
"text": "Let’s take a look at the same example, however this time we retrieve the child name as well for better understanding of JOIN clause."
},
{
"code": null,
"e": 6346,
"s": 6273,
"text": "Following is the query which will join the root to children subdocument."
},
{
"code": null,
"e": 6487,
"s": 6346,
"text": "SELECT \n f.id AS familyName, \n c.givenName AS childGivenName, \n c.firstName AS childFirstName \nFROM Families f \nJOIN c IN f.children"
},
{
"code": null,
"e": 6555,
"s": 6487,
"text": "When the above query is executed, it produces the following output."
},
{
"code": null,
"e": 6999,
"s": 6555,
"text": "[ \n { \n \"familyName\": \"WakefieldFamily\", \n \"childGivenName\": \"Jesse\" \n },\n\t\n { \n \"familyName\": \"WakefieldFamily\", \n \"childGivenName\": \"Lisa\" \n },\n\t\n { \n \"familyName\": \"SmithFamily\", \n \"childGivenName\": \"Michelle\" \n },\n\t\n { \n \"familyName\": \"SmithFamily\", \n \"childGivenName\": \"John\" \n },\n\t\n { \n \"familyName\": \"AndersenFamily\", \n \"childFirstName\": \"Henriette Thaulow\" \n } \n] \n"
},
{
"code": null,
"e": 7006,
"s": 6999,
"text": " Print"
},
{
"code": null,
"e": 7017,
"s": 7006,
"text": " Add Notes"
}
] |
Perl pack Function
|
This function evaluates the expressions in LIST and packs them into a binary structure specified by EXPR. The format is specified using the characters shown in Table below −
Each character may be optionally followed by a number, which specifies a repeat count for the type of value being packed.that is nibbles, chars, or even bits, according to the format. A value of * repeats for as many values remain in LIST. Values can be unpacked with the unpack function.
For example, a5 indicates that five letters are expected. b32 indicates that 32 bits are expected. h8 indicates that 8 nybbles ( or 4 bytes) are expected. P10 indicates that the structure is 10 bytes long.
Following is the simple syntax for this function −
pack EXPR, LIST
This function returns a packed version of the data in LIST using TEMPLATE to determine how it is coded.
This function returns a packed version of the data in LIST using TEMPLATE to determine how it is coded.
Here is the table which gives values to be used in TEMPLATE.
a
ASCII character string padded with null characters
A
ASCII character string padded with spaces
b
String of bits, lowest first
B
String of bits, highest first
c
A signed character (range usually -128 to 127)
C
An unsigned character (usually 8 bits)
d
A double-precision floating-point number
f
A single-precision floating-point number
h
Hexadecimal string, lowest digit first
H
Hexadecimal string, highest digit first
i
A signed integer
I
An unsigned integer
l
A signed long integer
L
An unsigned long integer
n
A short integer in network order
N
A long integer in network order
p
A pointer to a string
s
A signed short integer
S
An unsigned short integer
u
Convert to uuencode format
v
A short integer in VAX (little-endian) order
V
A long integer in VAX order
x
A null byte
X
Indicates "go back one byte"
@
Fill with nulls (ASCII 0)
Following is the example code showing its basic usage −
#!/usr/bin/perl -w
$bits = pack("c", 65);
# prints A, which is ASCII 65.
print "bits are $bits\n";
$bits = pack( "x" );
# $bits is now a null chracter.
print "bits are $bits\n";
$bits = pack( "sai", 255, "T", 30 );
# creates a seven charcter string on most computers'
print "bits are $bits\n";
@array = unpack( "sai", "$bits" );
#Array now contains three elements: 255, T and 30.
print "Array $array[0]\n";
print "Array $array[1]\n";
print "Array $array[2]\n";
When above code is executed, it produces the following result −
bits are A
bits are
bits are �T
Array 255
Array T
Array 30
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2394,
"s": 2220,
"text": "This function evaluates the expressions in LIST and packs them into a binary structure specified by EXPR. The format is specified using the characters shown in Table below −"
},
{
"code": null,
"e": 2683,
"s": 2394,
"text": "Each character may be optionally followed by a number, which specifies a repeat count for the type of value being packed.that is nibbles, chars, or even bits, according to the format. A value of * repeats for as many values remain in LIST. Values can be unpacked with the unpack function."
},
{
"code": null,
"e": 2889,
"s": 2683,
"text": "For example, a5 indicates that five letters are expected. b32 indicates that 32 bits are expected. h8 indicates that 8 nybbles ( or 4 bytes) are expected. P10 indicates that the structure is 10 bytes long."
},
{
"code": null,
"e": 2940,
"s": 2889,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2957,
"s": 2940,
"text": "pack EXPR, LIST\n"
},
{
"code": null,
"e": 3061,
"s": 2957,
"text": "This function returns a packed version of the data in LIST using TEMPLATE to determine how it is coded."
},
{
"code": null,
"e": 3165,
"s": 3061,
"text": "This function returns a packed version of the data in LIST using TEMPLATE to determine how it is coded."
},
{
"code": null,
"e": 3226,
"s": 3165,
"text": "Here is the table which gives values to be used in TEMPLATE."
},
{
"code": null,
"e": 3228,
"s": 3226,
"text": "a"
},
{
"code": null,
"e": 3279,
"s": 3228,
"text": "ASCII character string padded with null characters"
},
{
"code": null,
"e": 3281,
"s": 3279,
"text": "A"
},
{
"code": null,
"e": 3323,
"s": 3281,
"text": "ASCII character string padded with spaces"
},
{
"code": null,
"e": 3325,
"s": 3323,
"text": "b"
},
{
"code": null,
"e": 3354,
"s": 3325,
"text": "String of bits, lowest first"
},
{
"code": null,
"e": 3356,
"s": 3354,
"text": "B"
},
{
"code": null,
"e": 3386,
"s": 3356,
"text": "String of bits, highest first"
},
{
"code": null,
"e": 3388,
"s": 3386,
"text": "c"
},
{
"code": null,
"e": 3435,
"s": 3388,
"text": "A signed character (range usually -128 to 127)"
},
{
"code": null,
"e": 3437,
"s": 3435,
"text": "C"
},
{
"code": null,
"e": 3476,
"s": 3437,
"text": "An unsigned character (usually 8 bits)"
},
{
"code": null,
"e": 3478,
"s": 3476,
"text": "d"
},
{
"code": null,
"e": 3519,
"s": 3478,
"text": "A double-precision floating-point number"
},
{
"code": null,
"e": 3521,
"s": 3519,
"text": "f"
},
{
"code": null,
"e": 3562,
"s": 3521,
"text": "A single-precision floating-point number"
},
{
"code": null,
"e": 3564,
"s": 3562,
"text": "h"
},
{
"code": null,
"e": 3603,
"s": 3564,
"text": "Hexadecimal string, lowest digit first"
},
{
"code": null,
"e": 3605,
"s": 3603,
"text": "H"
},
{
"code": null,
"e": 3645,
"s": 3605,
"text": "Hexadecimal string, highest digit first"
},
{
"code": null,
"e": 3647,
"s": 3645,
"text": "i"
},
{
"code": null,
"e": 3664,
"s": 3647,
"text": "A signed integer"
},
{
"code": null,
"e": 3666,
"s": 3664,
"text": "I"
},
{
"code": null,
"e": 3686,
"s": 3666,
"text": "An unsigned integer"
},
{
"code": null,
"e": 3688,
"s": 3686,
"text": "l"
},
{
"code": null,
"e": 3710,
"s": 3688,
"text": "A signed long integer"
},
{
"code": null,
"e": 3712,
"s": 3710,
"text": "L"
},
{
"code": null,
"e": 3737,
"s": 3712,
"text": "An unsigned long integer"
},
{
"code": null,
"e": 3739,
"s": 3737,
"text": "n"
},
{
"code": null,
"e": 3772,
"s": 3739,
"text": "A short integer in network order"
},
{
"code": null,
"e": 3774,
"s": 3772,
"text": "N"
},
{
"code": null,
"e": 3806,
"s": 3774,
"text": "A long integer in network order"
},
{
"code": null,
"e": 3808,
"s": 3806,
"text": "p"
},
{
"code": null,
"e": 3830,
"s": 3808,
"text": "A pointer to a string"
},
{
"code": null,
"e": 3832,
"s": 3830,
"text": "s"
},
{
"code": null,
"e": 3855,
"s": 3832,
"text": "A signed short integer"
},
{
"code": null,
"e": 3857,
"s": 3855,
"text": "S"
},
{
"code": null,
"e": 3883,
"s": 3857,
"text": "An unsigned short integer"
},
{
"code": null,
"e": 3885,
"s": 3883,
"text": "u"
},
{
"code": null,
"e": 3912,
"s": 3885,
"text": "Convert to uuencode format"
},
{
"code": null,
"e": 3914,
"s": 3912,
"text": "v"
},
{
"code": null,
"e": 3959,
"s": 3914,
"text": "A short integer in VAX (little-endian) order"
},
{
"code": null,
"e": 3961,
"s": 3959,
"text": "V"
},
{
"code": null,
"e": 3989,
"s": 3961,
"text": "A long integer in VAX order"
},
{
"code": null,
"e": 3991,
"s": 3989,
"text": "x"
},
{
"code": null,
"e": 4003,
"s": 3991,
"text": "A null byte"
},
{
"code": null,
"e": 4005,
"s": 4003,
"text": "X"
},
{
"code": null,
"e": 4034,
"s": 4005,
"text": "Indicates \"go back one byte\""
},
{
"code": null,
"e": 4036,
"s": 4034,
"text": "@"
},
{
"code": null,
"e": 4062,
"s": 4036,
"text": "Fill with nulls (ASCII 0)"
},
{
"code": null,
"e": 4118,
"s": 4062,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 4582,
"s": 4118,
"text": "#!/usr/bin/perl -w\n\n$bits = pack(\"c\", 65);\n# prints A, which is ASCII 65.\nprint \"bits are $bits\\n\";\n$bits = pack( \"x\" );\n# $bits is now a null chracter.\nprint \"bits are $bits\\n\";\n$bits = pack( \"sai\", 255, \"T\", 30 );\n# creates a seven charcter string on most computers'\nprint \"bits are $bits\\n\";\n\n@array = unpack( \"sai\", \"$bits\" );\n\n#Array now contains three elements: 255, T and 30.\nprint \"Array $array[0]\\n\";\nprint \"Array $array[1]\\n\";\nprint \"Array $array[2]\\n\";"
},
{
"code": null,
"e": 4646,
"s": 4582,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4707,
"s": 4646,
"text": "bits are A\nbits are \nbits are �T\nArray 255\nArray T\nArray 30\n"
},
{
"code": null,
"e": 4742,
"s": 4707,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4756,
"s": 4742,
"text": " Devi Killada"
},
{
"code": null,
"e": 4791,
"s": 4756,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4811,
"s": 4791,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4844,
"s": 4811,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4860,
"s": 4844,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4893,
"s": 4860,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4910,
"s": 4893,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 4943,
"s": 4910,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4966,
"s": 4943,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5001,
"s": 4966,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5024,
"s": 5001,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5031,
"s": 5024,
"text": " Print"
},
{
"code": null,
"e": 5042,
"s": 5031,
"text": " Add Notes"
}
] |
Building a network graph from Twitter data | by Mananai Saengsuwan | Towards Data Science
|
In this article, we will build a data science project. We collect data from Twitter because it has an enormous amount of data and it allows us to get those. We prefer Java because it’s a compiled language and it has a strong concurrency library. Finally, we summarise those data by using Gephi which is an open-source graph platform.
We need the followings to do the project:
Java IDE. Our choice is Eclipse.
Twitter4j libraries. Get the jar files and the tutorial from here.
Twitter developer account. We need this in order to call Twitter API. There are a few resources mentioned how to get access.
Any JDBC compliant database. We use Sqlite. It’s very light-weighted. No software installation required. No daemon process. Just copy Sqlite jar file into the project. However, there are some limitations which require workarounds.
Gephi which is an open source graph tool. Download it from here.
By the way, readers could use whatever language or platform they like, Python or Node.js. Our sample code is in Java.
The followings are steps to build the Twitter network graph:
Collect tweets and users and save them into a database.
Retrieve users’ friends. From the list of users from the previous step, get friends of those. We will save these into tables
Filter for the data we’d like to see in the graph
Export the data to CSV files
Import CSV files to Gephi. Do some formating, layout. We will get a twitter social graph
For the first step, we collect sample tweets and then write those to tables. To do this:
Create a twitter stream object. Sample the stream. The API provides random subset of all tweets.
For each tweet received, submit a callable task to an executor service. The task will do database operations and/or further processing.
Below is the code:
The code in the callable task will save tweets and related objects like users to tables. By using executor service, we decouple tweet processing and database related task. Even if sometimes tweets are coming faster than the database could process, our app still would not miss anything. Also, since we use Sqlite database and there could be only one writing to the database at a single moment, the executor service must be Single Thread Executor. The following is a part of code of the task:
From the previous step, we get a list of users we’d like to know all their friends. Twitter API returns friend IDs of a specified user but no more than 5,000 IDs at a single request. We need to call multiple times if that user has more than that. Also, Twitter has rate limits. It allows only 15 requests per 15-minute window. Basically, 1 request per minute.
So, we get friend IDs. Need other API calls to convert user IDs to user objects. Twitter provides API for this. For each request, we could query up to 100 user IDs. The rate limit for this is 300 request per 15-minute window. So, it’s 20 requests per minute.
More details of Twitter API and rate limits here.
To handle rate limits effectively, we will have 2 threads. the 1st thread will invoke friend IDs query. The 2nd thread will do users look up part. The friend finder thread will pass the user ids to the user lookup thread via a blocking queue. Basically, we use producer-consumer pattern here.
The following code is partial of FriendsLookupRunnable.
Some key points:
The run method of this runnable would poll a user id from a blocking queue of user ids to process.
For each id, call getFriendIds method. This method returns list of friend ids. Each user id and friend id pair is inserted into User_friend table.
The result friend ids are also put into another blocking queue. These IDs would be retrieved by the other thread to process.
The getFriendIds method keeps track when was the last time it was called and make sure there is enough delay between each call (1 minute) by using Thread.sleep().
Even though we do that, there are very rare cases that rate limit exceeded exception occur. So, we catch TwitterException and compare the exception status code. If rate limit did exceed, we just retry the query.
There are some other exceptions. For instance, when a user is protected, twitter API will give you an unauthorised error.
The following is the command to create User_Friend table which stores result of the 1st thread:
CREATE TABLE User_Friend ( user_id INT (8), friend_id INT (8), PRIMARY KEY (user_id,friend_id));
The following code is UsersLookupRunnable class.
Here are some key points:
In the run method, there is a while loop to retrieve user ids from the queue. It then will call lookupUsers method to do the actual lookup
Since Twitter lookupUsers API could handle no more than 100 user ids at a time, we will chop a user IDs array into arrays of 100 or lesser elements before calling the Twitter API.
The lookupUsers method keeps track when was the last time it was called and make sure there is enough delay between each call (3 seconds) by using Thread.sleep().
The method returns users list which would be inserted into User table. The structure of the table should be similar to Twitter user interface.
The following is the command to create User table which stores the result of the 2nd thread:
CREATE TABLE User ( id INT (8) PRIMARY KEY, name VARCHAR (100), screen_name VARCHAR (100), description VARCHAR (255), email VARCHAR (50), favorites_count INT, followers_count INT, friends_count INT, statuses_count INT, lang VARCHAR (10), location VARCHAR (255), url VARCHAR (255), imageurl VARCHAR (255), is_protected INT (1), is_verified INT (1), created VARCHAR (20), last_modified VARCHAR (20));
The main method would do these:
Setup database connection
Creates 2 blocking queues
Prepares the user IDs list. Adds it to the first blocking queue.
Creates 2 runnable and 2 threads.
Starts the 2 threads.
Adds shutdown hook. So, when the process get kill, it will interrupt both threads.
Wait until both 2 threads finish.
Cleanup the database
The code should look something like this:
Sometimes, we’d like to see only part of the whole data. It’s quite simple to do this because data is in SQL tables already. Let’s say we’d like to see how top 100 users with most followers in our sample tweets follow each others. Here are what to do:
Create tables for storing the results. Below is the SQL statements used:
CREATE TABLE Graph_Friend_Edge ( Source INT, Target INT );CREATE TABLE Graph_Friend_Node ( id INT PRIMARY KEY, label VARCHAR (50), name VARCHAR (100),);
Populate the edge table with only top users. The following is the SQL:
insert into graph_friend_edge(source, target)select user_id, friend_id from user_friendjoin user u1 on friend_id=u1.idjoin user u2 on user_id=u2.idwhere user_id in(select friend_id from user_friendgroup by friend_id order by count(*) desc limit 100)and friend_id in(select friend_id from user_friend group by friend_id order by count(*) desc limit 100);
Then, populate the node table with this SQL:
insert into graph_friend_node(id, label, name)select n.id, u.screen_name, u.namefrom(select source id from graph_friend_edgeunionselect target id from graph_friend_edge) n join user u on n.id = u.id;
This part is simple. Use database tool to export data to CSV files.
Export user_friend table to edge CSV file.
Export user table to node CSV file.
Gephi is an open-source graph analysis and visualisation. There are many Gephi tutorials out there. Take a look here. For importing CSV files tutorial, find it here.
The followings are overview of steps to do in our project:
Open Gephi. Create a new project.
Import edge and node CSV files. The initial graph may look unimpressed like this:
We need to show node labels. Configure node size and colours. Apply some layout.
Enable node labels
Configure node size and label size proportional to in-degree (number of incoming edges)
Choose layout to “ForceAtlas2” and run it.
Run community detection algorithm
Set node colour according to Modularity Class. This will colour node according to the community that it detected.
After these are done, the graph looks more meaningful:
User’s screen names show up as node labels.
Nodes with more followers in this group appear bigger.
Edges, arrow lines, represent follow relationships
Nodes with the same colours are in the same communities according to the graph algorithm.
We have built Java applications to collect tweets, users and friends data from Twitter and put into a relational database. We’ve done some filter on the data. Then, imported to Gephi, graph platform and visualisation tool and produce a social network graph.
This is a very small part of what we could have done with the Twitter data. Gephi has a lot more to offer us. Also, there are more Graph analytics platforms out there. Neo4j, for example, could allow us to store data to its database and do run graph algorithms.
|
[
{
"code": null,
"e": 505,
"s": 171,
"text": "In this article, we will build a data science project. We collect data from Twitter because it has an enormous amount of data and it allows us to get those. We prefer Java because it’s a compiled language and it has a strong concurrency library. Finally, we summarise those data by using Gephi which is an open-source graph platform."
},
{
"code": null,
"e": 547,
"s": 505,
"text": "We need the followings to do the project:"
},
{
"code": null,
"e": 580,
"s": 547,
"text": "Java IDE. Our choice is Eclipse."
},
{
"code": null,
"e": 647,
"s": 580,
"text": "Twitter4j libraries. Get the jar files and the tutorial from here."
},
{
"code": null,
"e": 772,
"s": 647,
"text": "Twitter developer account. We need this in order to call Twitter API. There are a few resources mentioned how to get access."
},
{
"code": null,
"e": 1003,
"s": 772,
"text": "Any JDBC compliant database. We use Sqlite. It’s very light-weighted. No software installation required. No daemon process. Just copy Sqlite jar file into the project. However, there are some limitations which require workarounds."
},
{
"code": null,
"e": 1068,
"s": 1003,
"text": "Gephi which is an open source graph tool. Download it from here."
},
{
"code": null,
"e": 1186,
"s": 1068,
"text": "By the way, readers could use whatever language or platform they like, Python or Node.js. Our sample code is in Java."
},
{
"code": null,
"e": 1247,
"s": 1186,
"text": "The followings are steps to build the Twitter network graph:"
},
{
"code": null,
"e": 1303,
"s": 1247,
"text": "Collect tweets and users and save them into a database."
},
{
"code": null,
"e": 1428,
"s": 1303,
"text": "Retrieve users’ friends. From the list of users from the previous step, get friends of those. We will save these into tables"
},
{
"code": null,
"e": 1478,
"s": 1428,
"text": "Filter for the data we’d like to see in the graph"
},
{
"code": null,
"e": 1507,
"s": 1478,
"text": "Export the data to CSV files"
},
{
"code": null,
"e": 1596,
"s": 1507,
"text": "Import CSV files to Gephi. Do some formating, layout. We will get a twitter social graph"
},
{
"code": null,
"e": 1685,
"s": 1596,
"text": "For the first step, we collect sample tweets and then write those to tables. To do this:"
},
{
"code": null,
"e": 1782,
"s": 1685,
"text": "Create a twitter stream object. Sample the stream. The API provides random subset of all tweets."
},
{
"code": null,
"e": 1918,
"s": 1782,
"text": "For each tweet received, submit a callable task to an executor service. The task will do database operations and/or further processing."
},
{
"code": null,
"e": 1937,
"s": 1918,
"text": "Below is the code:"
},
{
"code": null,
"e": 2429,
"s": 1937,
"text": "The code in the callable task will save tweets and related objects like users to tables. By using executor service, we decouple tweet processing and database related task. Even if sometimes tweets are coming faster than the database could process, our app still would not miss anything. Also, since we use Sqlite database and there could be only one writing to the database at a single moment, the executor service must be Single Thread Executor. The following is a part of code of the task:"
},
{
"code": null,
"e": 2789,
"s": 2429,
"text": "From the previous step, we get a list of users we’d like to know all their friends. Twitter API returns friend IDs of a specified user but no more than 5,000 IDs at a single request. We need to call multiple times if that user has more than that. Also, Twitter has rate limits. It allows only 15 requests per 15-minute window. Basically, 1 request per minute."
},
{
"code": null,
"e": 3048,
"s": 2789,
"text": "So, we get friend IDs. Need other API calls to convert user IDs to user objects. Twitter provides API for this. For each request, we could query up to 100 user IDs. The rate limit for this is 300 request per 15-minute window. So, it’s 20 requests per minute."
},
{
"code": null,
"e": 3098,
"s": 3048,
"text": "More details of Twitter API and rate limits here."
},
{
"code": null,
"e": 3391,
"s": 3098,
"text": "To handle rate limits effectively, we will have 2 threads. the 1st thread will invoke friend IDs query. The 2nd thread will do users look up part. The friend finder thread will pass the user ids to the user lookup thread via a blocking queue. Basically, we use producer-consumer pattern here."
},
{
"code": null,
"e": 3447,
"s": 3391,
"text": "The following code is partial of FriendsLookupRunnable."
},
{
"code": null,
"e": 3464,
"s": 3447,
"text": "Some key points:"
},
{
"code": null,
"e": 3563,
"s": 3464,
"text": "The run method of this runnable would poll a user id from a blocking queue of user ids to process."
},
{
"code": null,
"e": 3710,
"s": 3563,
"text": "For each id, call getFriendIds method. This method returns list of friend ids. Each user id and friend id pair is inserted into User_friend table."
},
{
"code": null,
"e": 3835,
"s": 3710,
"text": "The result friend ids are also put into another blocking queue. These IDs would be retrieved by the other thread to process."
},
{
"code": null,
"e": 3998,
"s": 3835,
"text": "The getFriendIds method keeps track when was the last time it was called and make sure there is enough delay between each call (1 minute) by using Thread.sleep()."
},
{
"code": null,
"e": 4210,
"s": 3998,
"text": "Even though we do that, there are very rare cases that rate limit exceeded exception occur. So, we catch TwitterException and compare the exception status code. If rate limit did exceed, we just retry the query."
},
{
"code": null,
"e": 4332,
"s": 4210,
"text": "There are some other exceptions. For instance, when a user is protected, twitter API will give you an unauthorised error."
},
{
"code": null,
"e": 4428,
"s": 4332,
"text": "The following is the command to create User_Friend table which stores result of the 1st thread:"
},
{
"code": null,
"e": 4544,
"s": 4428,
"text": "CREATE TABLE User_Friend ( user_id INT (8), friend_id INT (8), PRIMARY KEY (user_id,friend_id));"
},
{
"code": null,
"e": 4593,
"s": 4544,
"text": "The following code is UsersLookupRunnable class."
},
{
"code": null,
"e": 4619,
"s": 4593,
"text": "Here are some key points:"
},
{
"code": null,
"e": 4758,
"s": 4619,
"text": "In the run method, there is a while loop to retrieve user ids from the queue. It then will call lookupUsers method to do the actual lookup"
},
{
"code": null,
"e": 4938,
"s": 4758,
"text": "Since Twitter lookupUsers API could handle no more than 100 user ids at a time, we will chop a user IDs array into arrays of 100 or lesser elements before calling the Twitter API."
},
{
"code": null,
"e": 5101,
"s": 4938,
"text": "The lookupUsers method keeps track when was the last time it was called and make sure there is enough delay between each call (3 seconds) by using Thread.sleep()."
},
{
"code": null,
"e": 5244,
"s": 5101,
"text": "The method returns users list which would be inserted into User table. The structure of the table should be similar to Twitter user interface."
},
{
"code": null,
"e": 5337,
"s": 5244,
"text": "The following is the command to create User table which stores the result of the 2nd thread:"
},
{
"code": null,
"e": 5892,
"s": 5337,
"text": "CREATE TABLE User ( id INT (8) PRIMARY KEY, name VARCHAR (100), screen_name VARCHAR (100), description VARCHAR (255), email VARCHAR (50), favorites_count INT, followers_count INT, friends_count INT, statuses_count INT, lang VARCHAR (10), location VARCHAR (255), url VARCHAR (255), imageurl VARCHAR (255), is_protected INT (1), is_verified INT (1), created VARCHAR (20), last_modified VARCHAR (20));"
},
{
"code": null,
"e": 5924,
"s": 5892,
"text": "The main method would do these:"
},
{
"code": null,
"e": 5950,
"s": 5924,
"text": "Setup database connection"
},
{
"code": null,
"e": 5976,
"s": 5950,
"text": "Creates 2 blocking queues"
},
{
"code": null,
"e": 6041,
"s": 5976,
"text": "Prepares the user IDs list. Adds it to the first blocking queue."
},
{
"code": null,
"e": 6075,
"s": 6041,
"text": "Creates 2 runnable and 2 threads."
},
{
"code": null,
"e": 6097,
"s": 6075,
"text": "Starts the 2 threads."
},
{
"code": null,
"e": 6180,
"s": 6097,
"text": "Adds shutdown hook. So, when the process get kill, it will interrupt both threads."
},
{
"code": null,
"e": 6214,
"s": 6180,
"text": "Wait until both 2 threads finish."
},
{
"code": null,
"e": 6235,
"s": 6214,
"text": "Cleanup the database"
},
{
"code": null,
"e": 6277,
"s": 6235,
"text": "The code should look something like this:"
},
{
"code": null,
"e": 6529,
"s": 6277,
"text": "Sometimes, we’d like to see only part of the whole data. It’s quite simple to do this because data is in SQL tables already. Let’s say we’d like to see how top 100 users with most followers in our sample tweets follow each others. Here are what to do:"
},
{
"code": null,
"e": 6602,
"s": 6529,
"text": "Create tables for storing the results. Below is the SQL statements used:"
},
{
"code": null,
"e": 6819,
"s": 6602,
"text": "CREATE TABLE Graph_Friend_Edge ( Source INT, Target INT );CREATE TABLE Graph_Friend_Node ( id INT PRIMARY KEY, label VARCHAR (50), name VARCHAR (100),);"
},
{
"code": null,
"e": 6890,
"s": 6819,
"text": "Populate the edge table with only top users. The following is the SQL:"
},
{
"code": null,
"e": 7244,
"s": 6890,
"text": "insert into graph_friend_edge(source, target)select user_id, friend_id from user_friendjoin user u1 on friend_id=u1.idjoin user u2 on user_id=u2.idwhere user_id in(select friend_id from user_friendgroup by friend_id order by count(*) desc limit 100)and friend_id in(select friend_id from user_friend group by friend_id order by count(*) desc limit 100);"
},
{
"code": null,
"e": 7289,
"s": 7244,
"text": "Then, populate the node table with this SQL:"
},
{
"code": null,
"e": 7489,
"s": 7289,
"text": "insert into graph_friend_node(id, label, name)select n.id, u.screen_name, u.namefrom(select source id from graph_friend_edgeunionselect target id from graph_friend_edge) n join user u on n.id = u.id;"
},
{
"code": null,
"e": 7557,
"s": 7489,
"text": "This part is simple. Use database tool to export data to CSV files."
},
{
"code": null,
"e": 7600,
"s": 7557,
"text": "Export user_friend table to edge CSV file."
},
{
"code": null,
"e": 7636,
"s": 7600,
"text": "Export user table to node CSV file."
},
{
"code": null,
"e": 7802,
"s": 7636,
"text": "Gephi is an open-source graph analysis and visualisation. There are many Gephi tutorials out there. Take a look here. For importing CSV files tutorial, find it here."
},
{
"code": null,
"e": 7861,
"s": 7802,
"text": "The followings are overview of steps to do in our project:"
},
{
"code": null,
"e": 7895,
"s": 7861,
"text": "Open Gephi. Create a new project."
},
{
"code": null,
"e": 7977,
"s": 7895,
"text": "Import edge and node CSV files. The initial graph may look unimpressed like this:"
},
{
"code": null,
"e": 8058,
"s": 7977,
"text": "We need to show node labels. Configure node size and colours. Apply some layout."
},
{
"code": null,
"e": 8077,
"s": 8058,
"text": "Enable node labels"
},
{
"code": null,
"e": 8165,
"s": 8077,
"text": "Configure node size and label size proportional to in-degree (number of incoming edges)"
},
{
"code": null,
"e": 8208,
"s": 8165,
"text": "Choose layout to “ForceAtlas2” and run it."
},
{
"code": null,
"e": 8242,
"s": 8208,
"text": "Run community detection algorithm"
},
{
"code": null,
"e": 8356,
"s": 8242,
"text": "Set node colour according to Modularity Class. This will colour node according to the community that it detected."
},
{
"code": null,
"e": 8411,
"s": 8356,
"text": "After these are done, the graph looks more meaningful:"
},
{
"code": null,
"e": 8455,
"s": 8411,
"text": "User’s screen names show up as node labels."
},
{
"code": null,
"e": 8510,
"s": 8455,
"text": "Nodes with more followers in this group appear bigger."
},
{
"code": null,
"e": 8561,
"s": 8510,
"text": "Edges, arrow lines, represent follow relationships"
},
{
"code": null,
"e": 8651,
"s": 8561,
"text": "Nodes with the same colours are in the same communities according to the graph algorithm."
},
{
"code": null,
"e": 8909,
"s": 8651,
"text": "We have built Java applications to collect tweets, users and friends data from Twitter and put into a relational database. We’ve done some filter on the data. Then, imported to Gephi, graph platform and visualisation tool and produce a social network graph."
}
] |
jQuery - prev( [selector] ) Method
|
The prev( [selector] ) method gets the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
Here is the simple syntax to use this method −
selector.prev( [selector] )
Here is the description of all the parameters used by this method −
selector − This is optional selector to filter the previous Elements with.
selector − This is optional selector to filter the previous Elements with.
Following is a simple example a simple showing the usage of this method. Try this example without passing selector in prev() method −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function(){
$("p").prev(".selected").addClass("hilight");
});
</script>
<style>
.hilight { background:yellow; }
</style>
</head>
<body>
<div><span>Hello</span></div>
<p class = "selected">Hello Again</p>
<p>And Again</p>
</body>
</html>
This will produce following result −
Hello Again
And Again
Following is a simple example a simple showing the usage of this method.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function(){
$("p").next(".selected").addClass("hilight");
});
</script>
<style>
.hilight { background:yellow; }
</style>
</head>
<body>
<div><span>Hello</span></div>
<p class = "hilight">Hello Again</p>
<p>And Again</p>
</body>
</html>
This will produce following result −
Hello Again
And Again
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2474,
"s": 2322,
"text": "The prev( [selector] ) method gets the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector."
},
{
"code": null,
"e": 2521,
"s": 2474,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 2550,
"s": 2521,
"text": "selector.prev( [selector] )\n"
},
{
"code": null,
"e": 2618,
"s": 2550,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2693,
"s": 2618,
"text": "selector − This is optional selector to filter the previous Elements with."
},
{
"code": null,
"e": 2768,
"s": 2693,
"text": "selector − This is optional selector to filter the previous Elements with."
},
{
"code": null,
"e": 2902,
"s": 2768,
"text": "Following is a simple example a simple showing the usage of this method. Try this example without passing selector in prev() method −"
},
{
"code": null,
"e": 3509,
"s": 2902,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function(){\n $(\"p\").prev(\".selected\").addClass(\"hilight\");\n });\n </script>\n\t\t\n <style>\n .hilight { background:yellow; }\n </style>\n </head>\n\t\n <body>\n <div><span>Hello</span></div>\n <p class = \"selected\">Hello Again</p>\n <p>And Again</p>\n </body>\n</html>"
},
{
"code": null,
"e": 3546,
"s": 3509,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3558,
"s": 3546,
"text": "Hello Again"
},
{
"code": null,
"e": 3568,
"s": 3558,
"text": "And Again"
},
{
"code": null,
"e": 3641,
"s": 3568,
"text": "Following is a simple example a simple showing the usage of this method."
},
{
"code": null,
"e": 4247,
"s": 3641,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function(){\n $(\"p\").next(\".selected\").addClass(\"hilight\");\n });\n </script>\n\t\t\n <style>\n .hilight { background:yellow; }\n </style>\n </head>\n\t\n <body>\n <div><span>Hello</span></div>\n <p class = \"hilight\">Hello Again</p>\n <p>And Again</p>\n </body>\n</html>"
},
{
"code": null,
"e": 4284,
"s": 4247,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4296,
"s": 4284,
"text": "Hello Again"
},
{
"code": null,
"e": 4306,
"s": 4296,
"text": "And Again"
},
{
"code": null,
"e": 4339,
"s": 4306,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4353,
"s": 4339,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 4388,
"s": 4353,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4402,
"s": 4388,
"text": " Pratik Singh"
},
{
"code": null,
"e": 4437,
"s": 4402,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4454,
"s": 4437,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4487,
"s": 4454,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4515,
"s": 4487,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4548,
"s": 4515,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4569,
"s": 4548,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4601,
"s": 4569,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4618,
"s": 4601,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4625,
"s": 4618,
"text": " Print"
},
{
"code": null,
"e": 4636,
"s": 4625,
"text": " Add Notes"
}
] |
PyQt5 - QClipboard
|
The QClipboard class provides access to system-wide clipboard that offers a simple mechanism to copy and paste data between applications. Its action is similar to QDrag class and uses similar data types.
QApplication class has a static method clipboard() which returns reference to clipboard object. Any type of MimeData can be copied to or pasted from the clipboard.
Following are the clipboard class methods that are commonly used −
clear()
Clears clipboard contents
setImage()
Copies QImage into clipboard
setMimeData()
Sets MIME data into clipboard
setPixmap()
Copies Pixmap object in clipboard
setText()
Copies QString in clipboard
text()
Retrieves text from clipboard
Signal associated with clipboard object is −
dataChanged()
Whenever clipboard data changes
In the following example, two TextEdit objects and two Pushbuttons are added to a top level window.
To begin with the clipboard object is instantiated. Copy() method of textedit object copies the data onto the system clipboard. When the Paste button is clicked, it fetches the clipboard data and pastes it in other textedit object.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
hbox = QVBoxLayout()
self.edit1=QTextEdit()
hbox.addWidget(self.edit1)
self.btn1=QPushButton("Copy")
hbox.addWidget(self.btn1)
self.edit2=QTextEdit()
self.btn2=QPushButton("Paste")
hbox.addWidget(self.edit2)
hbox.addWidget(self.btn2)
self.btn1.clicked.connect(self.copytext)
self.btn2.clicked.connect(self.pastetext)
self.setLayout(hbox)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Clipboard')
self.show()
def copytext(self):
#clipboard.setText(self.edit1.copy())
self.edit1.copy()
print (clipboard.text())
msg=QMessageBox()
msg.setText(clipboard.text()+" copied on clipboard")
msg.exec_()
def pastetext(self):
self.edit2.setText(clipboard.text())
app = QApplication(sys.argv)
clipboard=app.clipboard()
ex = Example()
ex.setWindowTitle("clipboard Example")
sys.exit(app.exec_())
The above code produces the following output −
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2167,
"s": 1963,
"text": "The QClipboard class provides access to system-wide clipboard that offers a simple mechanism to copy and paste data between applications. Its action is similar to QDrag class and uses similar data types."
},
{
"code": null,
"e": 2331,
"s": 2167,
"text": "QApplication class has a static method clipboard() which returns reference to clipboard object. Any type of MimeData can be copied to or pasted from the clipboard."
},
{
"code": null,
"e": 2398,
"s": 2331,
"text": "Following are the clipboard class methods that are commonly used −"
},
{
"code": null,
"e": 2406,
"s": 2398,
"text": "clear()"
},
{
"code": null,
"e": 2432,
"s": 2406,
"text": "Clears clipboard contents"
},
{
"code": null,
"e": 2443,
"s": 2432,
"text": "setImage()"
},
{
"code": null,
"e": 2472,
"s": 2443,
"text": "Copies QImage into clipboard"
},
{
"code": null,
"e": 2486,
"s": 2472,
"text": "setMimeData()"
},
{
"code": null,
"e": 2516,
"s": 2486,
"text": "Sets MIME data into clipboard"
},
{
"code": null,
"e": 2528,
"s": 2516,
"text": "setPixmap()"
},
{
"code": null,
"e": 2562,
"s": 2528,
"text": "Copies Pixmap object in clipboard"
},
{
"code": null,
"e": 2572,
"s": 2562,
"text": "setText()"
},
{
"code": null,
"e": 2600,
"s": 2572,
"text": "Copies QString in clipboard"
},
{
"code": null,
"e": 2607,
"s": 2600,
"text": "text()"
},
{
"code": null,
"e": 2637,
"s": 2607,
"text": "Retrieves text from clipboard"
},
{
"code": null,
"e": 2682,
"s": 2637,
"text": "Signal associated with clipboard object is −"
},
{
"code": null,
"e": 2696,
"s": 2682,
"text": "dataChanged()"
},
{
"code": null,
"e": 2728,
"s": 2696,
"text": "Whenever clipboard data changes"
},
{
"code": null,
"e": 2828,
"s": 2728,
"text": "In the following example, two TextEdit objects and two Pushbuttons are added to a top level window."
},
{
"code": null,
"e": 3060,
"s": 2828,
"text": "To begin with the clipboard object is instantiated. Copy() method of textedit object copies the data onto the system clipboard. When the Paste button is clicked, it fetches the clipboard data and pastes it in other textedit object."
},
{
"code": null,
"e": 4232,
"s": 3060,
"text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass Example(QWidget):\n def __init__(self):\n super(Example, self).__init__()\n\n self.initUI()\n\n def initUI(self):\n hbox = QVBoxLayout()\n self.edit1=QTextEdit()\n hbox.addWidget(self.edit1)\n self.btn1=QPushButton(\"Copy\")\n hbox.addWidget(self.btn1)\n self.edit2=QTextEdit()\n self.btn2=QPushButton(\"Paste\")\n hbox.addWidget(self.edit2)\n hbox.addWidget(self.btn2)\n self.btn1.clicked.connect(self.copytext)\n self.btn2.clicked.connect(self.pastetext)\n self.setLayout(hbox)\n \n self.setGeometry(300, 300, 300, 200)\n self.setWindowTitle('Clipboard')\n self.show()\n \n def copytext(self):\n\n #clipboard.setText(self.edit1.copy())\n self.edit1.copy()\n print (clipboard.text())\n\n msg=QMessageBox()\n msg.setText(clipboard.text()+\" copied on clipboard\")\n msg.exec_()\n\n def pastetext(self):\n self.edit2.setText(clipboard.text())\n\napp = QApplication(sys.argv)\nclipboard=app.clipboard()\nex = Example()\nex.setWindowTitle(\"clipboard Example\")\nsys.exit(app.exec_())"
},
{
"code": null,
"e": 4279,
"s": 4232,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 4316,
"s": 4279,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 4326,
"s": 4316,
"text": " ALAA EID"
},
{
"code": null,
"e": 4333,
"s": 4326,
"text": " Print"
},
{
"code": null,
"e": 4344,
"s": 4333,
"text": " Add Notes"
}
] |
Remove and update the existing record in MongoDB?
|
You can use only $pull operator that removes and updates the existing record in MongoDB. Let us first create a collection with documents −
> db.removeDemo.insertOne(
... {
... "UserName" : "Larry",
... "UserDetails" : [
... {
... "_id" : 101,
... "UserEmailId" : "976Larry@gmail.com",
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f9f88f9e6ff3eb0ce446")
}
> db.removeDemo.insertOne(
... {
... "UserName" : "Mike",
... "UserDetails" : [
... {
... "_id" : 102,
... "UserEmailId" : "Mike121@gmail.com",
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f9f98f9e6ff3eb0ce447")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.removeDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"),
"UserName" : "Larry",
"UserDetails" : [
{
"_id" : 101,
"UserEmailId" : "976Larry@gmail.com"
}
]
}
{
"_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"),
"UserName" : "Mike",
"UserDetails" : [
{
"_id" : 102,
"UserEmailId" : "Mike121@gmail.com"
}
]
}
Let us now implement the $pull query to remove and update the existing record −
> db.removeDemo.update(
... {"_id": ObjectId("5cc7f9f98f9e6ff3eb0ce447")},
... { "$pull": { "UserDetails": {"_id": 102}}}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display the documents from the collection in order to check the objects have been removed or not −
> db.removeDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"),
"UserName" : "Larry",
"UserDetails" : [
{
"_id" : 101,
"UserEmailId" : "976Larry@gmail.com"
}
]
}
{
"_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"),
"UserName" : "Mike",
"UserDetails" : [ ]
}
|
[
{
"code": null,
"e": 1201,
"s": 1062,
"text": "You can use only $pull operator that removes and updates the existing record in MongoDB. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1843,
"s": 1201,
"text": "> db.removeDemo.insertOne(\n... {\n... \"UserName\" : \"Larry\",\n... \"UserDetails\" : [\n... {\n... \"_id\" : 101,\n... \"UserEmailId\" : \"976Larry@gmail.com\",\n... }\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cc7f9f88f9e6ff3eb0ce446\")\n}\n> db.removeDemo.insertOne(\n... {\n... \"UserName\" : \"Mike\",\n... \"UserDetails\" : [\n... {\n... \"_id\" : 102,\n... \"UserEmailId\" : \"Mike121@gmail.com\",\n... }\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cc7f9f98f9e6ff3eb0ce447\")\n}"
},
{
"code": null,
"e": 1942,
"s": 1843,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1975,
"s": 1942,
"text": "> db.removeDemo.find().pretty();"
},
{
"code": null,
"e": 2016,
"s": 1975,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2390,
"s": 2016,
"text": "{\n \"_id\" : ObjectId(\"5cc7f9f88f9e6ff3eb0ce446\"),\n \"UserName\" : \"Larry\",\n \"UserDetails\" : [\n {\n \"_id\" : 101,\n \"UserEmailId\" : \"976Larry@gmail.com\"\n }\n ]\n}\n{\n \"_id\" : ObjectId(\"5cc7f9f98f9e6ff3eb0ce447\"),\n \"UserName\" : \"Mike\",\n \"UserDetails\" : [\n {\n \"_id\" : 102,\n \"UserEmailId\" : \"Mike121@gmail.com\"\n }\n ]\n}"
},
{
"code": null,
"e": 2470,
"s": 2390,
"text": "Let us now implement the $pull query to remove and update the existing record −"
},
{
"code": null,
"e": 2671,
"s": 2470,
"text": "> db.removeDemo.update(\n... {\"_id\": ObjectId(\"5cc7f9f98f9e6ff3eb0ce447\")},\n... { \"$pull\": { \"UserDetails\": {\"_id\": 102}}}\n... );\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2777,
"s": 2671,
"text": "Let us display the documents from the collection in order to check the objects have been removed or not −"
},
{
"code": null,
"e": 2810,
"s": 2777,
"text": "> db.removeDemo.find().pretty();"
},
{
"code": null,
"e": 2851,
"s": 2810,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3139,
"s": 2851,
"text": "{\n \"_id\" : ObjectId(\"5cc7f9f88f9e6ff3eb0ce446\"),\n \"UserName\" : \"Larry\",\n \"UserDetails\" : [\n {\n \"_id\" : 101,\n \"UserEmailId\" : \"976Larry@gmail.com\"\n }\n ]\n}\n{\n \"_id\" : ObjectId(\"5cc7f9f98f9e6ff3eb0ce447\"),\n \"UserName\" : \"Mike\",\n \"UserDetails\" : [ ]\n}"
}
] |
Static Positioning Using CSS
|
We can define positioning of an element in CSS as static which does not renders the element in any special way, but in a normal way. Elements with positioning as static are not affected by any of the CSS Positioning properties (left, right, top and bottom).
Let’s see an example of CSS Static Positioning Method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
p {
margin: 0;
}
div:first-child {
position: static;
background-color: orange;
text-align: center;
}
</style>
</head>
<body>
<div>Demo text</div>
<p>This is demo text wherein we are displaying an example for static positioning.</p>
<div></div>
</body>
</html>
Following is the output for the above code −
Let’s see another example of positioning method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 2px double #a43356;
margin: 5px;
padding: 5px;
}
#d1 {
position: relative;
height: 10em;
}
#d2 {
position: absolute;
width: 20%;
bottom: 10px; /*relative to parent d1*/
}
#d3 {
position: fixed;
width: 30%;
top:10em; /*relative to viewport*/
}
</style>
</head>
<body>
<div id="d1">This is demo paragraph. This is demo paragraph.
This is demo paragraph. This is demo paragraph.
This is demo paragraph. This is demo paragraph.
This is demo paragraph. This is demo paragraph.
<mark>relative</mark>
<div id="d2"><mark>absolute</mark></div>
<div id="d3"><mark>fixed</mark></div>
</div>
</body>
</html>
Following is the output for the above code −
|
[
{
"code": null,
"e": 1320,
"s": 1062,
"text": "We can define positioning of an element in CSS as static which does not renders the element in any special way, but in a normal way. Elements with positioning as static are not affected by any of the CSS Positioning properties (left, right, top and bottom)."
},
{
"code": null,
"e": 1376,
"s": 1320,
"text": "Let’s see an example of CSS Static Positioning Method −"
},
{
"code": null,
"e": 1387,
"s": 1376,
"text": " Live Demo"
},
{
"code": null,
"e": 1697,
"s": 1387,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\np {\n margin: 0;\n}\ndiv:first-child {\n position: static;\n background-color: orange;\n text-align: center;\n}\n</style>\n</head>\n<body>\n<div>Demo text</div>\n<p>This is demo text wherein we are displaying an example for static positioning.</p>\n<div></div>\n</body>\n</html>"
},
{
"code": null,
"e": 1742,
"s": 1697,
"text": "Following is the output for the above code −"
},
{
"code": null,
"e": 1792,
"s": 1742,
"text": "Let’s see another example of positioning method −"
},
{
"code": null,
"e": 1803,
"s": 1792,
"text": " Live Demo"
},
{
"code": null,
"e": 2488,
"s": 1803,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n border: 2px double #a43356;\n margin: 5px;\n padding: 5px;\n}\n#d1 {\n position: relative;\n height: 10em;\n}\n#d2 {\n position: absolute;\n width: 20%;\n bottom: 10px; /*relative to parent d1*/\n}\n#d3 {\n position: fixed;\n width: 30%;\n top:10em; /*relative to viewport*/\n}\n</style>\n</head>\n<body>\n<div id=\"d1\">This is demo paragraph. This is demo paragraph. \nThis is demo paragraph. This is demo paragraph. \nThis is demo paragraph. This is demo paragraph. \nThis is demo paragraph. This is demo paragraph. \n<mark>relative</mark>\n<div id=\"d2\"><mark>absolute</mark></div>\n<div id=\"d3\"><mark>fixed</mark></div>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 2533,
"s": 2488,
"text": "Following is the output for the above code −"
}
] |
Lines of Code (LOC) in Software Engineering - GeeksforGeeks
|
26 Apr, 2021
A line of code (LOC) is any line of text in a code that is not a comment or blank line, in any case of the number of statements or fragments of statements on the line. LOC clearly consists of all lines containing program header files, declaration of any variable, and executable and non-executable statements. As Lines of Code (LOC) only counts the volume of code, you can only use it to compare or estimate projects that use the same language and are coded using the same coding standards.
Features :
Variations such as “source lines of code”, are used to set out a codebase.
LOC is frequently used in some kinds of arguments.
They are used in assessing a project’s performance or efficiency.
Advantages :
Most used metric in cost estimation.
Its alternates have many problems as compared to this metric.
It is very easy in estimating the efforts.
Disadvantages :
Increases productivity while writing more lines of code.
Less efficient code.
It doesn’t consider complexity.
Researches have shown a rough correlation between LOC and the overall cost and length of developing a project/ product in Software Development, and between LOC and the number of defects. This means the lower your LOC measurement is, the better off you probably are in the development of your product.
Let’s take an example and check that how does the Line of code work in the simple sorting program given below:
C++
void selSort(int x[], int n) { //Below function sorts an array in ascending order int i, j, min, temp; for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) if (x[j] < x[min]) min = j; temp = x[i]; x[i] = x[min]; x[min] = temp; }}
So, now If LOC is simply a count of the numbers of lines then the above function shown contains 13 lines of code (LOC). But when comments and blank lines are ignored, the function shown above contains 12 lines of code (LOC).
Let’s take another example and check that how does the Line of code work in the given below:
C++
void main(){ int fN, sN, tN; cout << "Enter the 2 integers: "; cin >> fN >> sN; // sum of two numbers in stored in variable sum sum = fN + sN; // Prints sum cout << fN << " + " << sN << " = " << sum; return 0;}
Here also, If LOC is simply a count of the numbers of lines then the above function shown contains 11 lines of code (LOC). But when comments and blank lines are ignored, the function shown above contains 9 lines of code (LOC).
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DFD for Library Management System
What is DFD(Data Flow Diagram)?
Software Engineering | Software Design Process
Software Engineering | Black box testing
RUP and its Phases
System Testing
Software Development Life Cycle (SDLC)
Software Engineering | Seven Principles of software testing
Software Engineering | Incremental process model
Data Dictionaries in Software Engineering
|
[
{
"code": null,
"e": 24948,
"s": 24920,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 25440,
"s": 24948,
"text": "A line of code (LOC) is any line of text in a code that is not a comment or blank line, in any case of the number of statements or fragments of statements on the line. LOC clearly consists of all lines containing program header files, declaration of any variable, and executable and non-executable statements. As Lines of Code (LOC) only counts the volume of code, you can only use it to compare or estimate projects that use the same language and are coded using the same coding standards. "
},
{
"code": null,
"e": 25451,
"s": 25440,
"text": "Features :"
},
{
"code": null,
"e": 25526,
"s": 25451,
"text": "Variations such as “source lines of code”, are used to set out a codebase."
},
{
"code": null,
"e": 25577,
"s": 25526,
"text": "LOC is frequently used in some kinds of arguments."
},
{
"code": null,
"e": 25643,
"s": 25577,
"text": "They are used in assessing a project’s performance or efficiency."
},
{
"code": null,
"e": 25656,
"s": 25643,
"text": "Advantages :"
},
{
"code": null,
"e": 25693,
"s": 25656,
"text": "Most used metric in cost estimation."
},
{
"code": null,
"e": 25755,
"s": 25693,
"text": "Its alternates have many problems as compared to this metric."
},
{
"code": null,
"e": 25798,
"s": 25755,
"text": "It is very easy in estimating the efforts."
},
{
"code": null,
"e": 25815,
"s": 25798,
"text": "Disadvantages : "
},
{
"code": null,
"e": 25872,
"s": 25815,
"text": "Increases productivity while writing more lines of code."
},
{
"code": null,
"e": 25893,
"s": 25872,
"text": "Less efficient code."
},
{
"code": null,
"e": 25925,
"s": 25893,
"text": "It doesn’t consider complexity."
},
{
"code": null,
"e": 26226,
"s": 25925,
"text": "Researches have shown a rough correlation between LOC and the overall cost and length of developing a project/ product in Software Development, and between LOC and the number of defects. This means the lower your LOC measurement is, the better off you probably are in the development of your product."
},
{
"code": null,
"e": 26337,
"s": 26226,
"text": "Let’s take an example and check that how does the Line of code work in the simple sorting program given below:"
},
{
"code": null,
"e": 26341,
"s": 26337,
"text": "C++"
},
{
"code": "void selSort(int x[], int n) { //Below function sorts an array in ascending order int i, j, min, temp; for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) if (x[j] < x[min]) min = j; temp = x[i]; x[i] = x[min]; x[min] = temp; }}",
"e": 26628,
"s": 26341,
"text": null
},
{
"code": null,
"e": 26853,
"s": 26628,
"text": "So, now If LOC is simply a count of the numbers of lines then the above function shown contains 13 lines of code (LOC). But when comments and blank lines are ignored, the function shown above contains 12 lines of code (LOC)."
},
{
"code": null,
"e": 26946,
"s": 26853,
"text": "Let’s take another example and check that how does the Line of code work in the given below:"
},
{
"code": null,
"e": 26950,
"s": 26946,
"text": "C++"
},
{
"code": "void main(){ int fN, sN, tN; cout << \"Enter the 2 integers: \"; cin >> fN >> sN; // sum of two numbers in stored in variable sum sum = fN + sN; // Prints sum cout << fN << \" + \" << sN << \" = \" << sum; return 0;}",
"e": 27192,
"s": 26950,
"text": null
},
{
"code": null,
"e": 27419,
"s": 27192,
"text": "Here also, If LOC is simply a count of the numbers of lines then the above function shown contains 11 lines of code (LOC). But when comments and blank lines are ignored, the function shown above contains 9 lines of code (LOC)."
},
{
"code": null,
"e": 27436,
"s": 27419,
"text": "Software Testing"
},
{
"code": null,
"e": 27457,
"s": 27436,
"text": "Software Engineering"
},
{
"code": null,
"e": 27555,
"s": 27457,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27564,
"s": 27555,
"text": "Comments"
},
{
"code": null,
"e": 27577,
"s": 27564,
"text": "Old Comments"
},
{
"code": null,
"e": 27611,
"s": 27577,
"text": "DFD for Library Management System"
},
{
"code": null,
"e": 27643,
"s": 27611,
"text": "What is DFD(Data Flow Diagram)?"
},
{
"code": null,
"e": 27690,
"s": 27643,
"text": "Software Engineering | Software Design Process"
},
{
"code": null,
"e": 27731,
"s": 27690,
"text": "Software Engineering | Black box testing"
},
{
"code": null,
"e": 27750,
"s": 27731,
"text": "RUP and its Phases"
},
{
"code": null,
"e": 27765,
"s": 27750,
"text": "System Testing"
},
{
"code": null,
"e": 27804,
"s": 27765,
"text": "Software Development Life Cycle (SDLC)"
},
{
"code": null,
"e": 27864,
"s": 27804,
"text": "Software Engineering | Seven Principles of software testing"
},
{
"code": null,
"e": 27913,
"s": 27864,
"text": "Software Engineering | Incremental process model"
}
] |
Difference Between List and Tuple in Python
|
In this post, we will understand the differences between list and tuple in Python.
List and tuple are two different kinds of data structures used in Python. They are both used in different instances to store data of different types.
It is often referred to as a sequence. It is considered to be one of the most frequently used data type, as well as lauded for its versatility. A list can be created by placing all elements inside square brackets ([ ]) and separating the elements with commas. There can be any number of elements inside the list and they can be of different types as well (such as integer, float, string, and so on). The most important characteristic of list is that it is a mutable structure, i.e changes can be made by references the list.
Let us see how a list with heterogeneous data types can be created −
Live Demo
my_list = [1.8, 'string', 34, 'a']
print(my_list)
[1.8, 'string', 34, 'a']
There are many ways in which data within a list can be accessed.
Let us see how indexing can be used to access elements −
my_list = [1.8, ‘string’, 34, ‘a’]
print(“The second element is”)
print(my_list[1])
The second element is
string
We can also access elements from one range to another. This is known as list slicing. Let us see how that can be done −
Live Demo
my_list = [1.8, 'string', 34, 'a']
print("The elements within a certain range are")
print(my_list[1:4])
The elements within a certain range are
['string', 34, ‘a’]
We can also change the values of a list by performing indexing and assigning a new value to that index. Let us see how that can be done −
my_list = [1.8, 'string', 34, 'a']
print(“List before changes”)
print(my_list)
my_list[1] = ‘my_string’
print("List after changes")
print(my_list)
List before changes
[1.8, 'string', 34, 'a']
List after changes
[1.8, 'my_string', 34, 'a']
Now let us understand the working of a tuple structure. It is created using parenthesis, i.e. (). The important characteristic of tuple is that it is immutable, i.e. the elements one assigned inside a tuple can't be changed by accessing the tuple. There can be any number of elements inside the tuple and they can be of different types as well (such as integer, float, string, and so on).
Note: A tuple can be created without the use of parenthesis, but it is considered good practice to use parenthesis.
Let us see how a tuple with a single element can be created −
my_tuple = (“hey”,)
print(“Creating a tuple with one element”)
print(my_tuple)
("hello")
Note: Accessing the elements of the tuple, negative indexing, and list slicing are same as that of list.
If the tuple contains a list inside it, that list can be changed, but elements that are only inside the tuple, but not inside the list, can't be changed.
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "In this post, we will understand the differences between list and tuple in Python."
},
{
"code": null,
"e": 1295,
"s": 1145,
"text": "List and tuple are two different kinds of data structures used in Python. They are both used in different instances to store data of different types."
},
{
"code": null,
"e": 1821,
"s": 1295,
"text": "It is often referred to as a sequence. It is considered to be one of the most frequently used data type, as well as lauded for its versatility. A list can be created by placing all elements inside square brackets ([ ]) and separating the elements with commas. There can be any number of elements inside the list and they can be of different types as well (such as integer, float, string, and so on). The most important characteristic of list is that it is a mutable structure, i.e changes can be made by references the list. "
},
{
"code": null,
"e": 1890,
"s": 1821,
"text": "Let us see how a list with heterogeneous data types can be created −"
},
{
"code": null,
"e": 1900,
"s": 1890,
"text": "Live Demo"
},
{
"code": null,
"e": 1950,
"s": 1900,
"text": "my_list = [1.8, 'string', 34, 'a']\nprint(my_list)"
},
{
"code": null,
"e": 1975,
"s": 1950,
"text": "[1.8, 'string', 34, 'a']"
},
{
"code": null,
"e": 2040,
"s": 1975,
"text": "There are many ways in which data within a list can be accessed."
},
{
"code": null,
"e": 2097,
"s": 2040,
"text": "Let us see how indexing can be used to access elements −"
},
{
"code": null,
"e": 2181,
"s": 2097,
"text": "my_list = [1.8, ‘string’, 34, ‘a’]\nprint(“The second element is”)\nprint(my_list[1])"
},
{
"code": null,
"e": 2210,
"s": 2181,
"text": "The second element is\nstring"
},
{
"code": null,
"e": 2330,
"s": 2210,
"text": "We can also access elements from one range to another. This is known as list slicing. Let us see how that can be done −"
},
{
"code": null,
"e": 2340,
"s": 2330,
"text": "Live Demo"
},
{
"code": null,
"e": 2444,
"s": 2340,
"text": "my_list = [1.8, 'string', 34, 'a']\nprint(\"The elements within a certain range are\")\nprint(my_list[1:4])"
},
{
"code": null,
"e": 2504,
"s": 2444,
"text": "The elements within a certain range are\n['string', 34, ‘a’]"
},
{
"code": null,
"e": 2642,
"s": 2504,
"text": "We can also change the values of a list by performing indexing and assigning a new value to that index. Let us see how that can be done −"
},
{
"code": null,
"e": 2789,
"s": 2642,
"text": "my_list = [1.8, 'string', 34, 'a']\nprint(“List before changes”)\nprint(my_list)\nmy_list[1] = ‘my_string’\nprint(\"List after changes\")\nprint(my_list)"
},
{
"code": null,
"e": 2881,
"s": 2789,
"text": "List before changes\n[1.8, 'string', 34, 'a']\nList after changes\n[1.8, 'my_string', 34, 'a']"
},
{
"code": null,
"e": 3270,
"s": 2881,
"text": "Now let us understand the working of a tuple structure. It is created using parenthesis, i.e. (). The important characteristic of tuple is that it is immutable, i.e. the elements one assigned inside a tuple can't be changed by accessing the tuple. There can be any number of elements inside the tuple and they can be of different types as well (such as integer, float, string, and so on)."
},
{
"code": null,
"e": 3386,
"s": 3270,
"text": "Note: A tuple can be created without the use of parenthesis, but it is considered good practice to use parenthesis."
},
{
"code": null,
"e": 3448,
"s": 3386,
"text": "Let us see how a tuple with a single element can be created −"
},
{
"code": null,
"e": 3527,
"s": 3448,
"text": "my_tuple = (“hey”,)\nprint(“Creating a tuple with one element”)\nprint(my_tuple)"
},
{
"code": null,
"e": 3537,
"s": 3527,
"text": "(\"hello\")"
},
{
"code": null,
"e": 3642,
"s": 3537,
"text": "Note: Accessing the elements of the tuple, negative indexing, and list slicing are same as that of list."
},
{
"code": null,
"e": 3796,
"s": 3642,
"text": "If the tuple contains a list inside it, that list can be changed, but elements that are only inside the tuple, but not inside the list, can't be changed."
}
] |
A unique string in Python
|
Suppose we have a string s, we have to check whether it has all unique characters or not.
So, if the input is like "world", then the output will be True
To solve this, we will follow these steps −
set_var := a new set from all characters of s
set_var := a new set from all characters of s
return true when size of set_var is same as size of s, otherwise false
return true when size of set_var is same as size of s, otherwise false
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, s):
set_var = set(s)
return len(set_var) == len(s)
ob = Solution()
print(ob.solve('hello'))
print(ob.solve('world'))
hello
world
False
True
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "Suppose we have a string s, we have to check whether it has all unique characters or not."
},
{
"code": null,
"e": 1215,
"s": 1152,
"text": "So, if the input is like \"world\", then the output will be True"
},
{
"code": null,
"e": 1259,
"s": 1215,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1305,
"s": 1259,
"text": "set_var := a new set from all characters of s"
},
{
"code": null,
"e": 1351,
"s": 1305,
"text": "set_var := a new set from all characters of s"
},
{
"code": null,
"e": 1422,
"s": 1351,
"text": "return true when size of set_var is same as size of s, otherwise false"
},
{
"code": null,
"e": 1493,
"s": 1422,
"text": "return true when size of set_var is same as size of s, otherwise false"
},
{
"code": null,
"e": 1563,
"s": 1493,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1574,
"s": 1563,
"text": " Live Demo"
},
{
"code": null,
"e": 1738,
"s": 1574,
"text": "class Solution:\n def solve(self, s):\n set_var = set(s)\n return len(set_var) == len(s)\nob = Solution()\nprint(ob.solve('hello'))\nprint(ob.solve('world'))"
},
{
"code": null,
"e": 1750,
"s": 1738,
"text": "hello\nworld"
},
{
"code": null,
"e": 1761,
"s": 1750,
"text": "False\nTrue"
}
] |
W3Schools Code Game
|
W3Schools is optimized for learning, testing, and training.
Examples might be simplified to improve reading and basic understanding.
Tutorials, references, and examples are constantly reviewed to avoid errors,
but we cannot warrant full correctness of all content.
While using this site, you agree to have read and accepted our
terms of use,
cookie and privacy policy.
Copyright 1999-2022 by Refsnes Data.
All Rights Reserved.
|
[] |
Data Structures and Algorithms | Set 11 - GeeksforGeeks
|
07 Jul, 2021
Following questions have been asked in GATE CS 2007 exam.
1. Consider a hash table of size seven, with starting index zero, and a hash function (3x + 4)mod7. Assuming the hash table is initially empty, which of the following is the contents of the table when the sequence 1, 3, 8, 10 is inserted into the table using closed hashing? Note that ‘_’ denotes an empty location in the table. (A) 8, _, _, _, _, _, 10 (B) 1, 8, 10, _, _, _, 3 (C) 1, _, _, _, _, _,3 (D) 1, 10, 8, _, _, _, 3Answer (B) Please see http://lcm.csa.iisc.ernet.in/dsa/node38.html for closed hashing and probing.Let us put values 1, 3, 8, 10 in the hash of size 7.Initially, hash table is empty
- - - - - - -
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 1 is 0, so let us put the value at 0
1 - - - - - -
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 3 is 6, so let us put the value at 6
1 - - - - - 3
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 8 is 0, but 0 is already occupied, let us put the value(8) at next available space(1)
1 8 - - - - 3
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 10 is 6, but 6 is already occupied, let us put the value(10) at next available space(2)
1 8 10 - - - 3
0 1 2 3 4 5 6
2. In an unweighted, undirected connected graph, the shortest path from a node S to every other node is computed most efficiently, in terms of time complexity by (A) Dijkstra’s algorithm starting from S. (B) Warshall’s algorithm (C) Performing a DFS starting from S. (D) Performing a BFS starting from S.Answer(D)
* Time Complexity of the Dijkstra’s algorithm is O(|V|^2 + E)
* Time Complexity of the Warshall’s algorithm is O(|V|^3)
* DFS cannot be used for finding shortest paths
* BFS can be used for unweighted graphs. Time Complexity for BFS is O(|E| + |V|)
3. A complete n-ary tree is a tree in which each node has n children or no children. Let I be the number of internal nodes and L be the number of leaves in a complete n-ary tree. If L = 41, and I = 10, what is the value of n? (A) 3 (B) 4 (C) 5 (D) 6Answer (C) For an n-ary tree where each node has n children or no children, following relation holds
L = (n-1)*I + 1
Where L is the number of leaf nodes and I is the number of internal nodes.Let us find out the value of n for the given data.
L = 41 , I = 10
41 = 10*(n-1) + 1
(n-1) = 4
n = 5
4. In the following C function, let n >= m.
c
int gcd(n,m){ if (n%m ==0) return m; n = n%m; return gcd(m,n);}
How many recursive calls are made by this function? (A) Θ(logn)? (B) Ω(n) (C) Θ(loglogn) (D) Θ(sqrt(n))Answer (A) Above code is implementation of the Euclidean algorithm for finding Greatest Common Divisor (GCD). Please see http://mathworld.wolfram.com/EuclideanAlgorithm.html for time complexity.5. What is the time complexity of the following recursive function:
c
int DoSomething (int n){ if (n <= 2) return 1; else return (DoSomething (floor(sqrt(n))) + n);}
(A) Θ(n) (B) Θ(nlogn) (C) Θ(logn) (D) Θ(loglogn)Answer (D) Recursive relation for the DoSomething() is
T(n) = T(√n) + C1 if n > 2
We have ignored the floor() part as it doesn’t matter here if it’s a floor or ceiling.
Let n = 2^m, T(n) = T(2^m)
Let T(2^m) = S(m)
From the above two, T(n) = S(m)
S(m) = S(m/2) + C1 /* This is simply binary search recursion*/
S(m) = O(logm)
= O(loglogn) /* Since n = 2^m */
Now, let us go back to the original recursive function T(n)
T(n) = S(m)
= O(LogLogn)
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.
sumitgumber28
GATE-CS-2007
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Semaphores in Process Synchronization
Computer Networks | Set 1
Practice questions on Height balanced/AVL Tree
Computer Networks | Set 2
Operating Systems | Set 1
Database Management Systems | Set 1
|
[
{
"code": null,
"e": 24374,
"s": 24346,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 24433,
"s": 24374,
"text": "Following questions have been asked in GATE CS 2007 exam. "
},
{
"code": null,
"e": 25040,
"s": 24433,
"text": "1. Consider a hash table of size seven, with starting index zero, and a hash function (3x + 4)mod7. Assuming the hash table is initially empty, which of the following is the contents of the table when the sequence 1, 3, 8, 10 is inserted into the table using closed hashing? Note that ‘_’ denotes an empty location in the table. (A) 8, _, _, _, _, _, 10 (B) 1, 8, 10, _, _, _, 3 (C) 1, _, _, _, _, _,3 (D) 1, 10, 8, _, _, _, 3Answer (B) Please see http://lcm.csa.iisc.ernet.in/dsa/node38.html for closed hashing and probing.Let us put values 1, 3, 8, 10 in the hash of size 7.Initially, hash table is empty"
},
{
"code": null,
"e": 25103,
"s": 25040,
"text": " - - - - - - -\n 0 1 2 3 4 5 6"
},
{
"code": null,
"e": 25180,
"s": 25103,
"text": "The value of function (3x + 4)mod 7 for 1 is 0, so let us put the value at 0"
},
{
"code": null,
"e": 25243,
"s": 25180,
"text": " 1 - - - - - -\n 0 1 2 3 4 5 6"
},
{
"code": null,
"e": 25320,
"s": 25243,
"text": "The value of function (3x + 4)mod 7 for 3 is 6, so let us put the value at 6"
},
{
"code": null,
"e": 25383,
"s": 25320,
"text": " 1 - - - - - 3\n 0 1 2 3 4 5 6"
},
{
"code": null,
"e": 25509,
"s": 25383,
"text": "The value of function (3x + 4)mod 7 for 8 is 0, but 0 is already occupied, let us put the value(8) at next available space(1)"
},
{
"code": null,
"e": 25572,
"s": 25509,
"text": " 1 8 - - - - 3\n 0 1 2 3 4 5 6"
},
{
"code": null,
"e": 25700,
"s": 25572,
"text": "The value of function (3x + 4)mod 7 for 10 is 6, but 6 is already occupied, let us put the value(10) at next available space(2)"
},
{
"code": null,
"e": 25764,
"s": 25700,
"text": " 1 8 10 - - - 3\n 0 1 2 3 4 5 6"
},
{
"code": null,
"e": 26080,
"s": 25764,
"text": "2. In an unweighted, undirected connected graph, the shortest path from a node S to every other node is computed most efficiently, in terms of time complexity by (A) Dijkstra’s algorithm starting from S. (B) Warshall’s algorithm (C) Performing a DFS starting from S. (D) Performing a BFS starting from S.Answer(D) "
},
{
"code": null,
"e": 26335,
"s": 26080,
"text": " * Time Complexity of the Dijkstra’s algorithm is O(|V|^2 + E) \n * Time Complexity of the Warshall’s algorithm is O(|V|^3)\n * DFS cannot be used for finding shortest paths\n * BFS can be used for unweighted graphs. Time Complexity for BFS is O(|E| + |V|)"
},
{
"code": null,
"e": 26687,
"s": 26335,
"text": "3. A complete n-ary tree is a tree in which each node has n children or no children. Let I be the number of internal nodes and L be the number of leaves in a complete n-ary tree. If L = 41, and I = 10, what is the value of n? (A) 3 (B) 4 (C) 5 (D) 6Answer (C) For an n-ary tree where each node has n children or no children, following relation holds "
},
{
"code": null,
"e": 26707,
"s": 26687,
"text": " L = (n-1)*I + 1"
},
{
"code": null,
"e": 26834,
"s": 26707,
"text": "Where L is the number of leaf nodes and I is the number of internal nodes.Let us find out the value of n for the given data. "
},
{
"code": null,
"e": 26892,
"s": 26834,
"text": " L = 41 , I = 10\n 41 = 10*(n-1) + 1\n (n-1) = 4\n n = 5"
},
{
"code": null,
"e": 26938,
"s": 26892,
"text": "4. In the following C function, let n >= m. "
},
{
"code": null,
"e": 26940,
"s": 26938,
"text": "c"
},
{
"code": "int gcd(n,m){ if (n%m ==0) return m; n = n%m; return gcd(m,n);}",
"e": 27008,
"s": 26940,
"text": null
},
{
"code": null,
"e": 27375,
"s": 27008,
"text": "How many recursive calls are made by this function? (A) Θ(logn)? (B) Ω(n) (C) Θ(loglogn) (D) Θ(sqrt(n))Answer (A) Above code is implementation of the Euclidean algorithm for finding Greatest Common Divisor (GCD). Please see http://mathworld.wolfram.com/EuclideanAlgorithm.html for time complexity.5. What is the time complexity of the following recursive function: "
},
{
"code": null,
"e": 27377,
"s": 27375,
"text": "c"
},
{
"code": "int DoSomething (int n){ if (n <= 2) return 1; else return (DoSomething (floor(sqrt(n))) + n);}",
"e": 27482,
"s": 27377,
"text": null
},
{
"code": null,
"e": 27587,
"s": 27482,
"text": "(A) Θ(n) (B) Θ(nlogn) (C) Θ(logn) (D) Θ(loglogn)Answer (D) Recursive relation for the DoSomething() is "
},
{
"code": null,
"e": 27619,
"s": 27587,
"text": " T(n) = T(√n) + C1 if n > 2 "
},
{
"code": null,
"e": 27708,
"s": 27619,
"text": "We have ignored the floor() part as it doesn’t matter here if it’s a floor or ceiling. "
},
{
"code": null,
"e": 28034,
"s": 27708,
"text": " Let n = 2^m, T(n) = T(2^m)\n Let T(2^m) = S(m)\n\n From the above two, T(n) = S(m)\n\n S(m) = S(m/2) + C1 /* This is simply binary search recursion*/\n S(m) = O(logm) \n = O(loglogn) /* Since n = 2^m */\n \n Now, let us go back to the original recursive function T(n) \n T(n) = S(m) \n = O(LogLogn)"
},
{
"code": null,
"e": 28297,
"s": 28034,
"text": "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. "
},
{
"code": null,
"e": 28311,
"s": 28297,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28324,
"s": 28311,
"text": "GATE-CS-2007"
},
{
"code": null,
"e": 28342,
"s": 28324,
"text": "GATE-CS-DS-&-Algo"
},
{
"code": null,
"e": 28350,
"s": 28342,
"text": "GATE CS"
},
{
"code": null,
"e": 28354,
"s": 28350,
"text": "MCQ"
},
{
"code": null,
"e": 28452,
"s": 28354,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28461,
"s": 28452,
"text": "Comments"
},
{
"code": null,
"e": 28474,
"s": 28461,
"text": "Old Comments"
},
{
"code": null,
"e": 28495,
"s": 28474,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 28544,
"s": 28495,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 28576,
"s": 28544,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 28615,
"s": 28576,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 28653,
"s": 28615,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 28679,
"s": 28653,
"text": "Computer Networks | Set 1"
},
{
"code": null,
"e": 28726,
"s": 28679,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 28752,
"s": 28726,
"text": "Computer Networks | Set 2"
},
{
"code": null,
"e": 28778,
"s": 28752,
"text": "Operating Systems | Set 1"
}
] |
How can we get only unique values of a column in MySQL result set?
|
While querying data from a MySQL table, we may get duplicate values from a column. With the help of the DISTINCT clause in the SELECT statement, we can get rid of duplicate data in the result set.
SELECT DISTINCT Columns FROM Table_name WHERE conditions;
For example, we have a table named ‘tender’ having the following columns −
mysql> Select * from tender;
+----------+--------------+--------------+-------+
| clientid | client_Fname | Client_Lname | value |
+----------+--------------+--------------+-------+
| 100 | Mohan | Kumar | 60000 |
| 101 | Sohan | Singh | 50000 |
| 101 | Somil | Rattan | 55000 |
| 103 | Gaurav | Kumar | 75000 |
| 103 | Rahul | Singh | 63000 |
+----------+--------------+--------------+-------+
5 rows in set (0.00 sec)
Now, if we want to get only the unique values of the column named ‘Client_Lname’ then following would be query −
mysql> Select DISTINCT client_Lname from tender;
+--------------+
| client_Lname |
+--------------+
| Kumar |
| Singh |
| Rattan |
+--------------+
3 rows in set (0.05 sec)
The query below will do the same with a column named ‘client_Fname’.
mysql> Select DISTINCT client_Fname from tender;
+--------------+
| client_Fname |
+--------------+
| Mohan |
| Sohan |
| Somil |
| Gaurav |
| Rahul |
+--------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1259,
"s": 1062,
"text": "While querying data from a MySQL table, we may get duplicate values from a column. With the help of the DISTINCT clause in the SELECT statement, we can get rid of duplicate data in the result set."
},
{
"code": null,
"e": 1317,
"s": 1259,
"text": "SELECT DISTINCT Columns FROM Table_name WHERE conditions;"
},
{
"code": null,
"e": 1392,
"s": 1317,
"text": "For example, we have a table named ‘tender’ having the following columns −"
},
{
"code": null,
"e": 1905,
"s": 1392,
"text": "mysql> Select * from tender;\n+----------+--------------+--------------+-------+\n| clientid | client_Fname | Client_Lname | value |\n+----------+--------------+--------------+-------+\n| 100 | Mohan | Kumar | 60000 |\n| 101 | Sohan | Singh | 50000 |\n| 101 | Somil | Rattan | 55000 |\n| 103 | Gaurav | Kumar | 75000 |\n| 103 | Rahul | Singh | 63000 |\n+----------+--------------+--------------+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2018,
"s": 1905,
"text": "Now, if we want to get only the unique values of the column named ‘Client_Lname’ then following would be query −"
},
{
"code": null,
"e": 2211,
"s": 2018,
"text": "mysql> Select DISTINCT client_Lname from tender;\n+--------------+\n| client_Lname |\n+--------------+\n| Kumar |\n| Singh |\n| Rattan |\n+--------------+\n3 rows in set (0.05 sec)"
},
{
"code": null,
"e": 2280,
"s": 2211,
"text": "The query below will do the same with a column named ‘client_Fname’."
},
{
"code": null,
"e": 2507,
"s": 2280,
"text": "mysql> Select DISTINCT client_Fname from tender;\n+--------------+\n| client_Fname |\n+--------------+\n| Mohan |\n| Sohan |\n| Somil |\n| Gaurav |\n| Rahul |\n+--------------+\n5 rows in set (0.00 sec)"
}
] |
Font Size in CSS
|
The CSS font-size property is used to set the size of font. We can specify the value in percentages, units like pixels, cm, points, em, etc. and absolute keyword. Relative values maximize accessibility. The default font-size is 16px or 12pt.
The syntax of CSS font-size property is as follows −
Selector {
font-size: /*value*/
}
The following examples illustrate CSS font-size property −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: auto;
padding: 10px;
text-align: center;
width: 50%;
border: 2px solid;
border-radius: 15%;
font-size: 1.4em;
}
</style>
</head>
<body>
<div>
one
<div>two
<div>three</div>
</div>
</div>
</body>
</html>
This gives the following output −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
p {
font-size: smaller;
}
#demo {
font-size: initial;
}
p:last-of-type {
font-size: 200%;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is demo text 1.</p>
<p id="demo">This is demo text 2. </p>
<p>This is demo text 3.</p>
</body>
</html>
This gives the following output −
|
[
{
"code": null,
"e": 1304,
"s": 1062,
"text": "The CSS font-size property is used to set the size of font. We can specify the value in percentages, units like pixels, cm, points, em, etc. and absolute keyword. Relative values maximize accessibility. The default font-size is 16px or 12pt."
},
{
"code": null,
"e": 1357,
"s": 1304,
"text": "The syntax of CSS font-size property is as follows −"
},
{
"code": null,
"e": 1394,
"s": 1357,
"text": "Selector {\n font-size: /*value*/\n}"
},
{
"code": null,
"e": 1453,
"s": 1394,
"text": "The following examples illustrate CSS font-size property −"
},
{
"code": null,
"e": 1464,
"s": 1453,
"text": " Live Demo"
},
{
"code": null,
"e": 1739,
"s": 1464,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n margin: auto;\n padding: 10px;\n text-align: center;\n width: 50%;\n border: 2px solid;\n border-radius: 15%;\n font-size: 1.4em;\n}\n</style>\n</head>\n<body>\n<div>\none\n<div>two\n<div>three</div>\n</div>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 1773,
"s": 1739,
"text": "This gives the following output −"
},
{
"code": null,
"e": 1784,
"s": 1773,
"text": " Live Demo"
},
{
"code": null,
"e": 2080,
"s": 1784,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\np {\n font-size: smaller;\n}\n#demo {\n font-size: initial;\n}\np:last-of-type {\n font-size: 200%;\n}\n</style>\n</head>\n<body>\n<h2>Demo Heading</h2>\n<p>This is demo text 1.</p>\n<p id=\"demo\">This is demo text 2. </p>\n<p>This is demo text 3.</p>\n</body>\n</html>"
},
{
"code": null,
"e": 2114,
"s": 2080,
"text": "This gives the following output −"
}
] |
Array creation using Comprehensions and Generators in Julia - GeeksforGeeks
|
17 May, 2020
Julia is a language designed for high-level performance and can support interactive use as well. It has many descriptive datatypes and type-declarations can be used to solidify the programs. Julia is slowly climbing the ladder and gaining the interest of many Data Scientists and machine learning scientists today. It is comparatively faster than Python as it is designed to implement the math concepts like linear algebra and matrix representations. Excellent for numerical computation, this language has multiple dispatches for defining data types like numbers and arrays.
Julia arrays use square brackets([ ]) for list comprehensions just like Python or MATLAB. It consists of three kinds of arrays. Array comprehension is a very powerful way to construct an array. The resulting array depends on the type of data used while construction.Syntax:
[expression for element = iterable]
For 1-D Arrays:
# Julia array using for looptwice = []for i in 1:5 push!(twice, 2i)
can also be written and will give the same output as
# Using Comprehensiontwice = [2x for x=1:5]
For 2-D Arrays:
# Creating 2D array using comprehension u = [x + 2y for x in 1:5, y in 0:1]
For 3-D Arrays:
# Creating 3D arrays using comprehension p = [x + 2y + 3z for x in 1:4, y in 0:1, z in 1:3]
This does not exactly return an array type data structure but a generator type data structure. It uses parentheses ‘( )’ instead of the square brackets as in list comprehensions. The syntax else is very similar to that of the above.The object can be iterated to produce values when needed instead of allocating an array and storing them in advance. The series of data below are not allocated any memory unlike the examples above.
Syntax:
(expression for element = iterable)
For 1-D Arrays:
# Creating 1D Array using Generators j = (2x for x = 1:5)
For 2-D Arrays:
# Creating 2D Arrays using Generatorsu = (x + 2y for x in 1:5, y in 0:1)
For 3-D Arrays:
# Creating 3D arrays using Generators p = (x + 2y + 3z for x in 1:4, y in 0:1, z in 1:3)
julia-array
Picked
Julia
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Formatting of Strings in Julia
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
|
[
{
"code": null,
"e": 25521,
"s": 25493,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 26096,
"s": 25521,
"text": "Julia is a language designed for high-level performance and can support interactive use as well. It has many descriptive datatypes and type-declarations can be used to solidify the programs. Julia is slowly climbing the ladder and gaining the interest of many Data Scientists and machine learning scientists today. It is comparatively faster than Python as it is designed to implement the math concepts like linear algebra and matrix representations. Excellent for numerical computation, this language has multiple dispatches for defining data types like numbers and arrays."
},
{
"code": null,
"e": 26370,
"s": 26096,
"text": "Julia arrays use square brackets([ ]) for list comprehensions just like Python or MATLAB. It consists of three kinds of arrays. Array comprehension is a very powerful way to construct an array. The resulting array depends on the type of data used while construction.Syntax:"
},
{
"code": null,
"e": 26406,
"s": 26370,
"text": "[expression for element = iterable]"
},
{
"code": null,
"e": 26423,
"s": 26406,
"text": " For 1-D Arrays:"
},
{
"code": "# Julia array using for looptwice = []for i in 1:5 push!(twice, 2i)",
"e": 26494,
"s": 26423,
"text": null
},
{
"code": null,
"e": 26547,
"s": 26494,
"text": "can also be written and will give the same output as"
},
{
"code": "# Using Comprehensiontwice = [2x for x=1:5]",
"e": 26591,
"s": 26547,
"text": null
},
{
"code": null,
"e": 26608,
"s": 26591,
"text": " For 2-D Arrays:"
},
{
"code": "# Creating 2D array using comprehension u = [x + 2y for x in 1:5, y in 0:1]",
"e": 26685,
"s": 26608,
"text": null
},
{
"code": null,
"e": 26702,
"s": 26685,
"text": " For 3-D Arrays:"
},
{
"code": "# Creating 3D arrays using comprehension p = [x + 2y + 3z for x in 1:4, y in 0:1, z in 1:3]",
"e": 26795,
"s": 26702,
"text": null
},
{
"code": null,
"e": 27225,
"s": 26795,
"text": "This does not exactly return an array type data structure but a generator type data structure. It uses parentheses ‘( )’ instead of the square brackets as in list comprehensions. The syntax else is very similar to that of the above.The object can be iterated to produce values when needed instead of allocating an array and storing them in advance. The series of data below are not allocated any memory unlike the examples above."
},
{
"code": null,
"e": 27233,
"s": 27225,
"text": "Syntax:"
},
{
"code": null,
"e": 27269,
"s": 27233,
"text": "(expression for element = iterable)"
},
{
"code": null,
"e": 27286,
"s": 27269,
"text": " For 1-D Arrays:"
},
{
"code": "# Creating 1D Array using Generators j = (2x for x = 1:5)",
"e": 27345,
"s": 27286,
"text": null
},
{
"code": null,
"e": 27362,
"s": 27345,
"text": " For 2-D Arrays:"
},
{
"code": "# Creating 2D Arrays using Generatorsu = (x + 2y for x in 1:5, y in 0:1)",
"e": 27435,
"s": 27362,
"text": null
},
{
"code": null,
"e": 27452,
"s": 27435,
"text": " For 3-D Arrays:"
},
{
"code": "# Creating 3D arrays using Generators p = (x + 2y + 3z for x in 1:4, y in 0:1, z in 1:3)",
"e": 27542,
"s": 27452,
"text": null
},
{
"code": null,
"e": 27554,
"s": 27542,
"text": "julia-array"
},
{
"code": null,
"e": 27561,
"s": 27554,
"text": "Picked"
},
{
"code": null,
"e": 27567,
"s": 27561,
"text": "Julia"
},
{
"code": null,
"e": 27583,
"s": 27567,
"text": "Write From Home"
},
{
"code": null,
"e": 27681,
"s": 27583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27698,
"s": 27681,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 27758,
"s": 27698,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 27831,
"s": 27758,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 27865,
"s": 27831,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 27896,
"s": 27865,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 27932,
"s": 27896,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27968,
"s": 27932,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 28029,
"s": 27968,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28045,
"s": 28029,
"text": "Python infinity"
}
] |
Vim - Quick Guide
|
Vim editor is one of the more popular text editors we use today. It is a clone of the Vi editor and is written by Bram Moolenaar. It is cross platform editor and available on most popular platforms like Windows, Linux, Mac and other UNIX variants. In this chapter, we will discuss following items −
Introduction
Features of Vim
Why Vim was created?
Vim is acronym for Vi IMproved. It is free and open source text editor written by Bram Moolenaar. It was first released in 1991 for UNIX variants and its main goal was to provide enhancement to the Vi editor, which was released way back in 1976.
Vim is considered as clone Vi editor. Like Vi, it is also command centric editor. One of the advantage of learning Vim is – it is available everywhere. Take any UNIX variant like Linux, Mac, HP-UX, AIX and many more, Vim is there by default. Vim traditionally does not have GUI but now there is separate installer called gVim which provides GUI.
This section discusses some of the important features of Vim −
Its memory footprint is very low
Its memory footprint is very low
It is command centric. You can perform complex text related task with few commands
It is command centric. You can perform complex text related task with few commands
It is highly configurable and uses simple text file to store its configuration
It is highly configurable and uses simple text file to store its configuration
There are many plug-in available for Vim. Its functionality can be extended in great manner using these plug-in
There are many plug-in available for Vim. Its functionality can be extended in great manner using these plug-in
It supports multiple windows. Using this feature screen can be split into multiple windows
It supports multiple windows. Using this feature screen can be split into multiple windows
Same as multiple windows, it also supports multiple buffers
Same as multiple windows, it also supports multiple buffers
It supports multiple tabs which allows to work on multiple files
It supports multiple tabs which allows to work on multiple files
It supports recording features which allows to record and play Vim commands in repeated manner
It supports recording features which allows to record and play Vim commands in repeated manner
Vim is based on original Vi editor, which was created by Bill Joy in 1976. During 90’s Vi was lacking behind in-the so called the editor war existed between the Vi and Emacs editor. So Bram implemented a lots of missing features that the Emacs community used as argument for why Emacs was better that Vi/Vim.
Vim is lightweight package and its installation is really simple. In this chapter, we will discuss following items −
Installation on Windows platform
Installation on Debian based Linux
Installation on RPM based Linux
Vim doesn’t have any specific requirements. It is simple software bundle which provides all dependencies.
To download Vim visit vim.org
To download Vim visit vim.org
Click on Download option from left pane
Click on Download option from left pane
Click on PC - MS-DOS and MS-Windows option
Click on PC - MS-DOS and MS-Windows option
Download .exe installer from this page. At the time of writing this tutorial installer name was gvim80.exe
Download .exe installer from this page. At the time of writing this tutorial installer name was gvim80.exe
Double click on installer and follow on screen instructions to complete installation
Double click on installer and follow on screen instructions to complete installation
Vim stores its configuration in simple text file namely _vimrc and it is located under home directory of user.
To find current user’s home directory execute below command in terminal −
To find current user’s home directory execute below command in terminal −
$ echo %userprofile%
Navigate to home directory and create a new file namely _vimrc. Ensure that this file doesn’t have any extension.
Navigate to home directory and create a new file namely _vimrc. Ensure that this file doesn’t have any extension.
Open this file in text editor, enter following text and save it −
Open this file in text editor, enter following text and save it −
set nu
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
Installation on Linux platform is quite simple as compared to Windows. This section describes installation and configuration on Debian based Linux.
Execute below command in terminal −
Execute below command in terminal −
$ sudo apt-get update
$ sudo apt-get install vim
To ensure Vim is correctly installed execute below command −
To ensure Vim is correctly installed execute below command −
$ which vim
It should print the location of Vim binary. In my case it was −
It should print the location of Vim binary. In my case it was −
/usr/bin/vim
Vim stores its configuration in simple text file namely .vimrc and it is located under home directory of user.
To find current user’s home directory execute below command in terminal −
To find current user’s home directory execute below command in terminal −
$ echo $HOME
Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension.
Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension.
Open this file in text editor, enter following text and save it −
Open this file in text editor, enter following text and save it −
set nu
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
This section describes installation and configuration on RPM based Linux.
Execute below command in terminal −
Execute below command in terminal −
$ su -
$ yum install vim
To ensure Vim is correctly installed execute below command −
To ensure Vim is correctly installed execute below command −
$ which vim
It should print the location of Vim binary. In my case it was −
It should print the location of Vim binary. In my case it was −
/usr/bin/vim
Vim stores its configuration in simple text file namely .vimrc and it is located under home directory of user.
To find current user’s home directory execute below command in terminal −
To find current user’s home directory execute below command in terminal −
$ echo $HOME
Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension.
Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension.
Open this file in text editor, enter following text and save it −
Open this file in text editor, enter following text and save it −
set nu
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on.
Vim is clone of original Vi editor. In this chapter, we will discuss about other Vi clones. Main purpose of this chapter to know other clones and its compatibility with original Vi editor.
In this chapter, we will discuss following items −
Vi
Stevie
Elvis
nvi
vile
Compatibility with original Vi
Vi is acronym for Visual. It is screen-oriented text editor originally created for UNIX. The original code for Vi was written by Bill Joy in 1976 and first released on BSD platform. Vi was extension of ed editor which was most common at that time.
Vim was the first editor to introduce multiple modes. There is a separate mode for editing text, selecting text and executing command. Vim editor supports all these modes. Later sections of this tutorial describe these modes.
Stevie editor was developed for Atari ST platform. It was released in 1987 it is an abbreviation for ST Editor for VI enthusiastic.
It was very simple and provided only very small subset of the original Vi editor. However, it provided familiar environment to user moving on Atari ST platform.
Elvis’s main intention was to remove Stevie editor limitation. Stevie used to load entire file in RAM, Elvis removed this limitation by introducing buffers. Also it added some functionality into it like syntax highlighting, multiple window support, networking support and simple GUI.
nvi stands for new Vi. It was a result of license dispute between AT & T lab and Computer Science Research Group(CSRC) at university of California, Berkeley. Vi was based on ed editor and was under license of AT & T which restricted them to distribute Vi with BDS. Hence they rewrote Vi and released it under BSD license.
Vim is improved version of Vi and it added many features where Vi was lagging. It added many useful features like −
Multiple windows/tabs/buffers
Introduction of Vim scripting language
Syntax highlighting for more than 200 languages
Integration with compilers, interpreters and debuggers
Vile is an abbreviation which stands for Vi like Emacs and it was an attempt to bring popular features from both editor and combine it into one. Few popular features of Vile are −
One editing mode for each file type
Introduction of Vile procedural language
Named functions to bound keys according to user choice
Though above discussed editors are considered as Vi clones they are not 100% compatible with original Vi. Below table shows more details about their compatibility −
Beginning with this section we will get our hands dirty with Vim. In this chapter, we will discuss following items −
Start Vim
Start Vim
Vim modes
Vim modes
Create new file
Create new file
View file in read-only mode
View file in read-only mode
Edit existing file
Edit existing file
Vim is little bit different than today’s GUI based editor. It can be started and used from GUI as well as terminal.
To start Vim from graphical launcher just double click on gVim icon. It will open editor window as follows −
To start Vim from graphical launcher just double click on gVim icon. It will open editor window as follows −
Using Vim from terminal will be identical on Windows as well as Linux platform. Perform following steps to start and quit Vim from terminal −
Open terminal and enter vim command as follows −
Open terminal and enter vim command as follows −
$ vim
It will open Vim in terminal as follows −
It will open Vim in terminal as follows −
To close this, press Esc key followed by colon(:) and q. In Vim q command stands for quit. This command will be shown in bottom left corner of editor itself −
To close this, press Esc key followed by colon(:) and q. In Vim q command stands for quit. This command will be shown in bottom left corner of editor itself −
Vim supports multiple modes. This section discusses some of the important modes which will be used on day-to-day basis.
This is the default mode in which Vim starts. We can enter editor commands in this mode. We can use variety of commands in this mode like copy, paste, delete, replace and many more. We’ll discuss these commands in later sections.
NOTE − Here onwards, any Vim command without colon indicates that we are executing that command in command mode.
You can use this mode to enter/edit text. To switch from default command to insert mode press i key. It will show current mode in bottom left corner of editor.
We can enter any text once we are in insert mode. Below image shows this −
Use Escape key to switch back to command mode from this mode.
This mode is also used to enter commands. Commands in this mode starts with colon(:). For instance, in previous section quit command was entered in this mode. We can go to this mode either from command or insert mode.
To switch from command mode to this mode just type colon
To switch from command mode to this mode just type colon
To switch from insert mode to this mode press Escape and type colon
To switch from insert mode to this mode press Escape and type colon
In below image colon at bottom left indicates line mode.
NOTE − Here onwards, any Vim command starting with colon indicates that we are executing that command in command line mode.
In this mode we can visually select text and run commands on selected sections.
To switch from command mode to visual mode type v
To switch from command mode to visual mode type v
To switch from any other mode to visual mode first switch back to command mode by pressing Escape, then type v to switch to visual mode
To switch from any other mode to visual mode first switch back to command mode by pressing Escape, then type v to switch to visual mode
In below image bottom left corner shows visual mode.
Perform below steps to create and save new file −
Execute following command to open Vim
Execute following command to open Vim
$ vim
Type following command in Vim
Type following command in Vim
:edit message.txt
It will reload file if, it exist already
Switch to insert mode
Switch to insert mode
i
Enter some text
Enter some text
Switch back to command mode
Switch back to command mode
Esc
Save changes to file
Save changes to file
:w
Now message.txt file will be created.
Quit Vim
Quit Vim
:q
Use –R option to open file in read-only mode
$ vim -R message.txt
In below image bottom left corner shows read-only mode −
Alternatively you can use view command to achieve same result.
$ view message.txt
Perform below steps to edit existing file −
Open file using Vim
Open file using Vim
$ vim message.txt
Switch to insert mode and enter some text there.
Switch to insert mode and enter some text there.
i
Quit editor without saving changes
Quit editor without saving changes
:q!
OR
Save changes and quit editor using following command −
Save changes and quit editor using following command −
:wq
Vim is feature rich editor hence remembering everything about it will be difficult. But there is no need to worry, we can always ask for help. Fortunately this help is provided by Vim itself.
In this chapter, we will discuss following items −
Access help manual
Help on specific topic
Search help phrase in manual
Access online help
Help manual is shipped with Vim editor itself and it is really comprehensive. To access help execute below command −
:help
Help manual will show entire help about Vim. But what if, we are only interested in certain topic. Vim provides command for that as well with following syntax
:help <topic-name>
In above command replace <topic-name> with topic in which you are interested. Forinstance to access help about vim mode, execute following command
:help modes
You can search specific topic only if you know its name. But what if, you don’t know the exact name of help topic. In that case you can use below command −
:helpgrep <phrase>
For instance, to access help about navigation in Vim execute below command
:helpgrep navigation
Vim also provides online help. To access online help −
Visit vim-help URL
Visit vim-help URL
Additionally you can also refer vim-docs documentation
Additionally you can also refer vim-docs documentation
Vim provides many commands which make editing functionality really powerful. In this chapter, we will discuss following items −
Insert
Append
Open new line
Substitute
Change
Replace
Join
To insert text before cursor perform following steps −
To insert text before cursor perform following steps
Switch to insert mode
i
Let us suppose you are in the middle of line and you want to insert text at the beginning of current line then perform following steps −
Switch to command mode
Esc
Activate insert mode
I
This action will move cursor to the beginning of current line and switch Vim in insert mode
To append text after cursor perform following steps
Switch to command mode and move cursor to appropriate position
Esc
Switch to insert mode
a
This action will move cursor next by one position and switch Vim in insert mode.
Let us suppose you are in the middle of line and you want to append text at the end of current line then perform following steps −
Switch to command mode
Esc
Switch to insert mode
A
This action will move cursor to the end of line and switch Vim in insert mode
Let us suppose you are in the middle of line and you want to open new line below current line then perform following steps −
Switch to command mode
Esc
Switch to insert mode
o
This action will insert blank line below current line and switch Vim in insert mode
Let us suppose you are in the middle of line and you want to open new line above current line then perform following steps −
Switch to command mode
Esc
Switch to insert mode
o
This action will insert blank line above current line and switch Vim in insert mode
Let us suppose you want to substitute single character then perform following steps −
Switch to command mode
Esc
Move cursor to appropriate position
Switch to insert mode
s
This action will delete character under cursor and switch Vim in insert mode To substitute entire line use −
s
This action will delete entire line and switch Vim in insert mode.
Let us suppose you want to change text in current line then perform following steps −
Switch to command mode
Esc
Execute following command −
cc
This is similar to substitute action using S
To change text from current cursor position, execute following command
C
This action will delete text after current cursor position and switch Vim in insert mode.
To replace single character perform following steps −
Switch to command mode
Esc
Move cursor to appropriate position
Execute following command −
r
Enter character to be substituted.
Note that this command will not switch Vim in insert mode
To replace entire line execute −
R
It will switch Vim in replace mode as shown in below image −
To join two lines perform following steps −
Switch to command mode
Esc
Move cursor to appropriate line
Execute following command −
J
Vim has great support for advanced navigation. In this chapter, we’ll discuss some of the popular navigation techniques which help to improve productivity.
In basic navigation we can navigate to left, right, up and down by position. Below commands can be used for this −
Move cursor to left by one position
Move cursor to right by one position
Move cursor to upward direction by one line
Move cursor to downward direction by one line
To perform multi-position navigation use number with these commands. For instance to navigate cursor 10 line below from current line, execute following command −
10j
You can use numbers with remaining commands as well.
In addition to this, below commands also perform some useful navigation.
Move cursor to the beginning of current line
Move cursor to the end of current line
Scroll down entire page
Scroll up entire page
Below command can be used to navigate to specific line −
Jump to the nth line
Jump to the start of file
Jump to the end of file
We can use following commands for word navigation −
Move cursor to the beginning of the next word
Move cursor to the end of the current word
Move cursor to the beginning of the previous word
Vim keeps track of your navigation using a jump list. You can go backward and forward through that list.
The jump list keeps tracks of all the places you’ve been to by tracking file name, line number and column number.
To view jump list execute following command −
:jumps
Following command are based on jump list −
Jump back to the previous position
Jump to the next position
We have seen basic editing earlier. Let us understand some other editing features of Vim. In this section, we will discuss following items −
Buffer
Swap files
Cut, copy, delete, paste actions
Undo and redo actions
Buffer is temporary memory used by Vim. When we open a file in editor, Vim loads its contents from disk drive. These contents are stored in memory (RAM) whenever we edit a file we are actually editing file from buffer. Once we finish editing and save file that time only buffer contents are transferred to appropriate file.
Swap area is a file created by Vim to store buffer contents periodically. While editing file our changes may be lost because of any reasons and Vim provides swap files to provide data recovery.
To get actual name of swap file execute following command −
:swapname
For instance in my case name was message.txt.swp as show in below image −
We often perform cut, copy and paste actions on text. Vim provides following commands to perform these actions (y stands for yank and p stands for paste action) −
Delete character from cursor position
Delete previous character from cursor position
Copy single character from cursor position
Paste character after cursor position
Paste character before cursor position
We can use cut, copy and paste commands with words and sentences as well. Below table shows this −
Delete word from cursor position
Delete entire line from cursor position
Delete entire line
Copies entire line
Copies entire line
To perform multi-line/multi-word actions just use numbers with command. You can use this syntax with other commands as well. For instance, to delete 3 words use −
3dw
We can undo single or multiple actions. To perform one time undo action execute −
u
To perform multiple undo action, use number with same command. For instance, below command will undo last 3 actions −
3u
In addition to this, to undo all execute following command −
U
Redo is apposite action of undo. Execute any of the command to perform redo action.
Ctrl + r
OR
: red
Search is very common action and it is one of the actions we use most of the time. In this chapter we will see some command which will allow performing these actions effectively.
In this chapter, we will discuss following items −
Search settings
Search in current file
Search in multiple files
Search in help files
To perform incremental search execute following command −
:set incsearch
To highlight search execute following command −
:set hlsearch
This command will automatically highlight current matches. For instance in below image
fox word is highlighted −
To disable incremental and highlighted search execute following commands −
:set noincsearch
:set nohlsearch
Use following commands to perform search in forward direction −
Search expression in forward direction
Find next occurrence. This is same and find next
Find previous occurrence. This is same as find previous
Repeat previous forward search
Use following commands to perform search in backward direction
Search expression in backward direction
Find previous occurrence. This is same and find previous
Find next occurrence. This is same as find next
Repeat previous backward search
Place cursor under any word and execute following commands to perform search operation −
Search next occurrence of current word
Search previous occurrence of current word
Using vimgrep command we can search <expression> in multiple files. For instance below command searches string - Jarvis in all text files.
:vimgrep Jarvis *.txt
Note that to go to next and previous occurrence we have to use following commands −
Go to next occurrence of expression
Go to previous occurrence of expression
Vim is very powerful editor. It supports many advanced features to work with multiple files, buffer and windows. In this section, we will discuss following items −
Multiple files
Multiple buffers
Multiple tabs
Multiple windows
Let us suppose you are editing a file and you want to open another file in same Vim session. In that case, you can use Vim’s edit command. Below table shows these commands
Load new file in buffer for editing
Same as :e
List the files for editing from current directory
Same as :e <tab>
We have already seen what Vim buffers are. Vim supports multiple buffers. Below commands will be useful will working with buffers −
Add file into new buffer
Switch to Nth buffer. For instance to switch to 3rd buffer use :b3
Move to the next buffer in buffer list
Move to the previous buffer in buffer list
List all buffers
Move to the first buffer
Move to the last buffer
Load all buffers
For instance, below command adds new file to buffer −
Now, there are two files in buffer. Execute below command to show this −
:buffers
It will show following output −
Like other editors we can also open multiple tabs in Vim. Below table describes tab related commands −
Open new tab
Open new file in tab
Close current tab
Move to the next tab
Move to the previous tab
Move to the first tab
Move to the last tab
For instance, below images shows multiple tabs
In Vim we can create new window using following commands −
Open new window
Open file in new window
In below image, we can see that current Vim window is split into 2 parts after executing following commands −
$vim message.txt
:new
Vim supports bookmark feature. Using this feature we can make navigation within file really faster. In this chapter, we will discuss following items −
Create bookmark
Jump to bookmark
List all bookmarks
Delete bookmarks
Local bookmarks
Global bookmarks
To create bookmark execute following command −
m{bookmark-name}
In above example bookmark-name is single alphabetical character. For instance, below command creates bookmark of name a.
ma
Once bookmark is created we can jump there. Following command can be use to jump to bookmark −
Move to the exact location of bookmark. Please note that this character is back quote
Jump to the beginning of bookmark line. Please note that this character is single quote
To list all bookmarks execute following command −
:marks
In below image it show list of bookmarks for current file
To delete bookmarks execute following command −
:delmarks {bookmark-name}
For instance, below command delete bookmark with name a.
:delmarks a
When you have multiple files open and if you want to go to a particular position in any one of the open files, then you can use global mark feature of Vim.
If the bookmark name is an upper case letter, then that is a global Bookmark. Above discussed commands are applicable for both local and global bookmarks.
Macro is record and play feature. When this is combined with Vim commands it becomes really powerful combination. In this section, we will discuss following items −
Start recording
Perform Vim actions
Stop recording
Play recording
To start recording press q followed by any lower case letter as a macro name. For instance in below example I have used “a” as a macro name
In this step you can perform any Vim actions like: cut, copy, delete, replace and so on.You can see these actions by executing following command −
:registers
For instance, below command shows that yank and delete actions were performed −
Once you are done with actions, press q again to stop recording. Now recording mode will disappear as shown below −
To play execute below command −
@{macro-name}
For instance to execute macro “a”, execute below command −
@a
To play same macro multiple times use numbers with it. For instance, to execute same macro 10 times execute following command −
10@a
Vim provides many registers. We can use these registers as multiple clipboards. This feature is really useful while working with multiple files. In this chapter, we will discuss following items −
Copy text in register
Paste text from register
List available registers
Register types
For copying, we can use normal yank command i.e. yy and to store it in register we can use following syntax −
“<register-name><command>
For instance, to copy text in register “a” use following command −
“ayy
To paste text from register use −
“<register-name>p
For instance, below command copies text from register “a” −
“ap
To list all available registers use following command
:registers
Vim supports following types of registers −
Unnamed register is denoted by “”. Vim stores deleted or copied text in this register
We can use 26 named registers; we can use a-z or A-Z. By default vim doesn’t uses these registers.
If we use lower case register name then contents will be overwritten and if we use uppercase name then contents will be appended in that register.
We can use 0 to 9 named registers. Vim fills these registers with text from yank and delete command.
Numbered register 0 contains the text from the most recent yank command.
Numbered register 1 contains the text deleted by the most recent delete or change command
Following are the default registers −
Name of the current file
Name of the alternate file for the current window
Most recently executed command
Contains the last inserted text
Last used register
Fold functionality will be useful when file contents large text. Using this feature we can only show selected potion of file. This feature is particularly useful while working with programming languages. In this chapter, we will discuss following items −
Activate and deactivate fold functionality
Various fold actions
To activate fold use following command −
:set foldenable
:set foldmethod = indent
To deactivate fold use following command
:set nofoldenable
To fold code, go to any method and execute following command −
zc
For example below image shows the result of this action −
To open fold use following command −
zo
Below image shows the result of this action −
To close all folds execute following command
zM
Below image shows the result of this action
To unfold all execute following −
zR
Below image shows the result of this action −
Similar to UNIX diff command we can use Vim to show diff in much better manner. It will show diff in colorful manner. In this chapter, we will discuss following items −
Show differences between files
Activate and deactivate diff mode
Navigation in diff mode
Applying changes from diff window
To show differences between files execute below command −
$ vimdiff <file> <file>
OR
$ vim –d <file> <file>
For instance below command shows differences −
In above image, text highlighted in magenta color is common. Remaining text is highlighted in red color which indicates that there are some differences after common text.
If you are already in vim and you want to perform diff action, then use one of the following command −
Use below command to perform horizontal split −
:diffsplit filename
Above images shows that we are comparing two files namely message-1.txt and message-2.txt.
To perform vertical split use following command −
:vert diffsplit <filename>
It opens following window −
Above images shows that we are comparing two files namely message-1.txt and message-2.txt.
Navigation in diff mode is little bit different. For instance, when you scroll text from one window then text from adjacent window also scrolled. This is called scrollbind. To enable this use −
:set scrollbind
To disable this use −
:set noscrollbind
If you edit file in this mode then use following command to update diff −
:diffupdate
To switch between diff windows execute following command −
Ctrl + w Ctrl + w
Please note that, we have to press Ctrl + w 2 times.
In diff window, execute following command to jump to previous change −
[c
In diff window, execute following command to jump to next change −
]c
To apply change from adjacent diff window to current diff windows execute −
:diffget
For instance, if you are in left window and you want to take change from right window to current window then you will execute above command.
To apply change from current diff window to adjacent diff window execute −
:diffput
For instance, if you are in left window and you want apply change from current window to right window then you will execute above command.
Using plug-ins, we can extends the functionality of Vim. Vim supports many plug-ins and most of them are available freely. This chapter is about Vim plug-ins and we will discuss following items −
Plug-in management
Some useful plug-ins
This section discusses plug-in management. Vim provides various plug-ins managers but we won’t be using any plug-in manager, instead we’ll be doing all these steps manually for better understanding. Once you understand these steps, you can go with plug-in manager.
To install any plug-in perform following steps −
Create .vim/bundle directory in user’s home directory
Copy plug-in inside this directory
Set runtimepath in vim
Let us install badwolf plug-in in Vim. It is a color scheme for vim.
$ mkdir -p ~/.vim/bundle
$ cd ~/.vim/bundle/
$ git clone https://github.com/sjl/badwolf.git
$ echo "set runtimepath^ = ~/.vim/bundle/badwolf" > ~/.vimrc
Now plug-in is installed, so we can use badwold color scheme as follows −
:colorscheme badwolf
If we observe carefully, plug-in is a just collection of files and if we want to update that plug-in then just update appropriate plug-in directory from ~/.vim/bundle.
Removing plug-in in Vim is really simple. To remove plug-in perform following steps −
Remove plug-in directory from ~/.vim/bundle
Modify runtimepath appropriately
Below is list of some useful Vim plug-ins
Disassemble C/C++ code
Indenting for AWK script
Vim package manager
Automatically save and load vim session based on switching of git branch
Provide liniting for python files
We can configure Vim to use it as an IDE. In this section, we will discuss following items
Syntax highlighting
Smart indentation
Bounce
Execute shell commands
Configuring ctags and csope
Auto-completion and auto-suggestion
Syntax highlighting is one of the important features of IDE. To enable syntax highlighting use −
:syntax on
For instance, below image show syntax highlighting for C code −
To disable syntax highlighting use −
:syntax off
When syntax highlighting is disabled, it will show following output −
To perform auto and smart indentation use following commands −
: set autoindent
: set smartindent
In addition to this you can use below command to auto-indent C code −
: set cindent
If you are using programming language which uses curly braces to combine multiple statements then % key will be your friend. This key will jump between start and end of curly braces quickly.
For instance, you are at line 11 and execute % command then it will move cursor the line 4. Below image shows this −
To execute single command from Vim editor user −
:!<command>
For instance, to execute pwd command use following syntax −
:!pwd
However, if you want to multiple shell commands then execute following command −
:shell
Above command will give you terminal access, where you can execute multiple commands. Once you are done with it, just type exit command which will return back to Vim session.
Combination of ctags and csope provides many useful features like go to function definition, go to function declaration, find function calls, search file, and many more. Perform below steps to configure these tool −
Generate tags using following command −
$ ctags <file>
This command will generate new file namely tags
Provide tag file to vim using following command −
:set tags = tag
Now move your cursor under function name and press Ctrl + ] to go to function definition.
Use Ctrl + t to come back to previous position.
To install and configure cscope perform following steps −
Install cscope
$ sudo apt-get install cscope
Generate ctags and launch main window
$ cscope –R
User Ctrl + d to close cscope window
We can use following commands for auto-completion −
Word completion
Line completion
File name completion
Note that we have to use these commands in insert mode.
Many times we need to work with remote servers. And often we edit files from those remote servers. One of the obvious solution to edit those files is to log in to the remote sever and edit files. But sometimes it is convenient to edit those files from local machine because we might have installed and configured various plug-in on our local system. In this chapter, we will discuss following items −
Access remote files
Understand netread and netwrite
Other supported protocol
Vim supports remote file editing using following syntax −
$vim scp://user@server.com/filepath
In above example vim will recognize that it has to use scp protocol and it will access file using that protocol. For instance −
$ vim scp://jarvis@remote-server.com//tmp/message.txt
Above command will open /tmp/message.txt file from remote-server. It will use SCP protocol and jarvis user’s credentials for authentication.
Vim supports nread and nwrite functionality which stands for net read and net write respectively. Previous section shows method to access remote file while launching Vim. But what if you are already in Vim? Then you can use following commands −
:Nread scp://jarvis@localhost//tmp/message.txt
In addition to reading we can also modify file on remote server directly. In that case use Nwrite command as follows −
:Nwrite scp://jarvis@localhost//tmp/message.txt
Once file is opened, you can use regular Vim commands.
In addition to SCP, Vim supports following protocols −
FTP
SFTP
HTTP (read-only)
rsync
Now we got fair idea about Vim. Let us discuss few tips and tricks of Vim to improve productivity. In this section, we will discuss following items −
Convert spaces to tabs and vice-versa
Highlight miss-spelled words
Word completion
Copy line character by character
Indent code
Change file format
If you are editing a file and you want to convert entered tab character to spaces then execute following command −
:set expandtab
Note that, this command will not change existing tabs to spaces. To achieve this execute following command −
:set tabstop = 4 shiftwidth = 4 expandtab
:retab
In above command we are instructing Vim to convert tabs into 4 spaces
To convert spaces to tabs execute below command −
:set noexpandtab :retab!
We can instruct Vim to highlight miss-spelled words. To do this execute following command −
:set spell
Below image highlights misspelled word in Vim −
Vim also provides word completion. For this execute following command in insert mode −
Ctrl + p
Use following command to copy and paste line character by character −
Copy and paste text located above the cursor
Copy and paste text located below the cursor
Note the we have to use these commands in insert mode.
If you have un-indented code to indent it execute following command −
=%
For instance, if you have un-indented code like this −
Then go to line 4 and execute =% command. It will indent code like this −
To change file format to UNIX execute following command −
:set ff = unix
To change file format to DOS execute following command −
:set ff = dos
We can personalize Vim according to our requirement. In this section, we will discuss following items −
Configuration files
Changing fonts
Changing color scheme
Personal highlighting
Status line
For Vim configuration files can be at user level or global level. User specific settings will be stored in user level files while global settings will be stored in global level files.
Global vimrc
To find out global vimrc file execute following command in editor
:echo $VIM
OR
:echo \%VIM\%
On Linux this file will be located under /usr/share/vim directory while on Window it will be under C:\Program Files\Vim folder
Local vimrc
Local vimrc will be located under user’s home directory. For instance, on Linux it will be under /home/<USER> directory while on Windows it will be under C:\Documents and Setting\<USER>/ folder
Note that, on Windows file name will be _vimrc whereas on Linux it will be .vimrc.
Global gvimrc
On Linux this file will be located under /usr/share/gvim directory while on Window it will be under C:\Program Files\Vim folder
Local gvimrc
Local gvimrc will be located under user’s home directory. For instance, on Linux it will be under /home/<USER> directory while on Windows it will be under C:\Documents and Setting\<USER>/ folder
Note that, on Windows file name will be _gvimrc whereas on Linux it will be 55 .gvimrc.
exrc files are used for backward compatibility. These files are ignored if either vimrc or gvimrc file is present.
Global exrc
On Linux this file will be located under /usr/share/vim directory while on Window it will be under C:\Program Files\Vim folder
Local exrc
Local exrc will be located under user’s home directory. For instance, on Linux it will be under /home/<USER> directory while on Windows it will be under C:\Documents and Setting\<USER>/_exrc folder
To change font execute following command in gVim −
:set guifont = courier
Above command will change font to courier.
To change color scheme execute following command −
:colorscheme <tab>
When you press tab character, it will show available color schemes for Vim.
Execute below command to highlight columns greater than 73 −
:match ErrorMsg /\%>73v.\+/
Below image shows this −
Below is description of this command −
Match after column
This is column number
It should work for virtual columns only
Match one or more characters
To add line number execute following command −
:set number
To disable this execute following command −
:set nonumber
To set number width execute following command −
:set numberwidth = <num>
To enable spell check execute following command −
:set spell
And to set spell language execute following command −
:set spelllang = <language>
For example to set German use following comman −
:set spelllang = de
Using abbreviation we can create shortcuts for long string. For instance below command creates abbreviation namely “quick”.
:abbr quick the quick brown fox
If you type “quick” and press tab then it will be replaced by “the quick brown fox” string
We can use this to correct some typos. For instance below command does this −
:abr teh the
Status line is shown at the bottom of editor. To enable status line execute following command −
:set laststatus = 2
To remove this for current session execute following command −
:set laststatus = 0
Vim is really powerful editor and now you can get your hands dirty with it. Mastering Vim will really improve your productively. Using Vim you can solve many complex tasks with few commands. You can refer following documentation to know more about Vim.
You can access Vim’s official documentation from following website −
https://www.vim.org/
You can enhance vim further by writing scripts to it. It has its own scripting language. To know more about it, visit following link −
https://vim.sourceforge.io/scripts/index.php
Vim plug-ins further extend its functionality and makes you more productive. You can install, configure and even write plug-ins for Vim. You can refer documentation regarding this from their official website.
46 Lectures
5.5 hours
Jason Cannon
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2269,
"s": 1970,
"text": "Vim editor is one of the more popular text editors we use today. It is a clone of the Vi editor and is written by Bram Moolenaar. It is cross platform editor and available on most popular platforms like Windows, Linux, Mac and other UNIX variants. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 2282,
"s": 2269,
"text": "Introduction"
},
{
"code": null,
"e": 2298,
"s": 2282,
"text": "Features of Vim"
},
{
"code": null,
"e": 2319,
"s": 2298,
"text": "Why Vim was created?"
},
{
"code": null,
"e": 2565,
"s": 2319,
"text": "Vim is acronym for Vi IMproved. It is free and open source text editor written by Bram Moolenaar. It was first released in 1991 for UNIX variants and its main goal was to provide enhancement to the Vi editor, which was released way back in 1976."
},
{
"code": null,
"e": 2911,
"s": 2565,
"text": "Vim is considered as clone Vi editor. Like Vi, it is also command centric editor. One of the advantage of learning Vim is – it is available everywhere. Take any UNIX variant like Linux, Mac, HP-UX, AIX and many more, Vim is there by default. Vim traditionally does not have GUI but now there is separate installer called gVim which provides GUI."
},
{
"code": null,
"e": 2974,
"s": 2911,
"text": "This section discusses some of the important features of Vim −"
},
{
"code": null,
"e": 3007,
"s": 2974,
"text": "Its memory footprint is very low"
},
{
"code": null,
"e": 3040,
"s": 3007,
"text": "Its memory footprint is very low"
},
{
"code": null,
"e": 3123,
"s": 3040,
"text": "It is command centric. You can perform complex text related task with few commands"
},
{
"code": null,
"e": 3206,
"s": 3123,
"text": "It is command centric. You can perform complex text related task with few commands"
},
{
"code": null,
"e": 3285,
"s": 3206,
"text": "It is highly configurable and uses simple text file to store its configuration"
},
{
"code": null,
"e": 3364,
"s": 3285,
"text": "It is highly configurable and uses simple text file to store its configuration"
},
{
"code": null,
"e": 3476,
"s": 3364,
"text": "There are many plug-in available for Vim. Its functionality can be extended in great manner using these plug-in"
},
{
"code": null,
"e": 3588,
"s": 3476,
"text": "There are many plug-in available for Vim. Its functionality can be extended in great manner using these plug-in"
},
{
"code": null,
"e": 3679,
"s": 3588,
"text": "It supports multiple windows. Using this feature screen can be split into multiple windows"
},
{
"code": null,
"e": 3770,
"s": 3679,
"text": "It supports multiple windows. Using this feature screen can be split into multiple windows"
},
{
"code": null,
"e": 3830,
"s": 3770,
"text": "Same as multiple windows, it also supports multiple buffers"
},
{
"code": null,
"e": 3890,
"s": 3830,
"text": "Same as multiple windows, it also supports multiple buffers"
},
{
"code": null,
"e": 3955,
"s": 3890,
"text": "It supports multiple tabs which allows to work on multiple files"
},
{
"code": null,
"e": 4020,
"s": 3955,
"text": "It supports multiple tabs which allows to work on multiple files"
},
{
"code": null,
"e": 4115,
"s": 4020,
"text": "It supports recording features which allows to record and play Vim commands in repeated manner"
},
{
"code": null,
"e": 4210,
"s": 4115,
"text": "It supports recording features which allows to record and play Vim commands in repeated manner"
},
{
"code": null,
"e": 4519,
"s": 4210,
"text": "Vim is based on original Vi editor, which was created by Bill Joy in 1976. During 90’s Vi was lacking behind in-the so called the editor war existed between the Vi and Emacs editor. So Bram implemented a lots of missing features that the Emacs community used as argument for why Emacs was better that Vi/Vim."
},
{
"code": null,
"e": 4636,
"s": 4519,
"text": "Vim is lightweight package and its installation is really simple. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 4669,
"s": 4636,
"text": "Installation on Windows platform"
},
{
"code": null,
"e": 4704,
"s": 4669,
"text": "Installation on Debian based Linux"
},
{
"code": null,
"e": 4736,
"s": 4704,
"text": "Installation on RPM based Linux"
},
{
"code": null,
"e": 4842,
"s": 4736,
"text": "Vim doesn’t have any specific requirements. It is simple software bundle which provides all dependencies."
},
{
"code": null,
"e": 4872,
"s": 4842,
"text": "To download Vim visit vim.org"
},
{
"code": null,
"e": 4902,
"s": 4872,
"text": "To download Vim visit vim.org"
},
{
"code": null,
"e": 4942,
"s": 4902,
"text": "Click on Download option from left pane"
},
{
"code": null,
"e": 4982,
"s": 4942,
"text": "Click on Download option from left pane"
},
{
"code": null,
"e": 5025,
"s": 4982,
"text": "Click on PC - MS-DOS and MS-Windows option"
},
{
"code": null,
"e": 5068,
"s": 5025,
"text": "Click on PC - MS-DOS and MS-Windows option"
},
{
"code": null,
"e": 5175,
"s": 5068,
"text": "Download .exe installer from this page. At the time of writing this tutorial installer name was gvim80.exe"
},
{
"code": null,
"e": 5282,
"s": 5175,
"text": "Download .exe installer from this page. At the time of writing this tutorial installer name was gvim80.exe"
},
{
"code": null,
"e": 5367,
"s": 5282,
"text": "Double click on installer and follow on screen instructions to complete installation"
},
{
"code": null,
"e": 5452,
"s": 5367,
"text": "Double click on installer and follow on screen instructions to complete installation"
},
{
"code": null,
"e": 5563,
"s": 5452,
"text": "Vim stores its configuration in simple text file namely _vimrc and it is located under home directory of user."
},
{
"code": null,
"e": 5637,
"s": 5563,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 5711,
"s": 5637,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 5733,
"s": 5711,
"text": "$ echo %userprofile%\n"
},
{
"code": null,
"e": 5847,
"s": 5733,
"text": "Navigate to home directory and create a new file namely _vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 5961,
"s": 5847,
"text": "Navigate to home directory and create a new file namely _vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 6027,
"s": 5961,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 6093,
"s": 6027,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 6101,
"s": 6093,
"text": "set nu\n"
},
{
"code": null,
"e": 6200,
"s": 6101,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 6299,
"s": 6200,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 6447,
"s": 6299,
"text": "Installation on Linux platform is quite simple as compared to Windows. This section describes installation and configuration on Debian based Linux."
},
{
"code": null,
"e": 6483,
"s": 6447,
"text": "Execute below command in terminal −"
},
{
"code": null,
"e": 6519,
"s": 6483,
"text": "Execute below command in terminal −"
},
{
"code": null,
"e": 6570,
"s": 6519,
"text": "$ sudo apt-get update \n$ sudo apt-get install vim\n"
},
{
"code": null,
"e": 6631,
"s": 6570,
"text": "To ensure Vim is correctly installed execute below command −"
},
{
"code": null,
"e": 6692,
"s": 6631,
"text": "To ensure Vim is correctly installed execute below command −"
},
{
"code": null,
"e": 6705,
"s": 6692,
"text": "$ which vim\n"
},
{
"code": null,
"e": 6769,
"s": 6705,
"text": "It should print the location of Vim binary. In my case it was −"
},
{
"code": null,
"e": 6833,
"s": 6769,
"text": "It should print the location of Vim binary. In my case it was −"
},
{
"code": null,
"e": 6847,
"s": 6833,
"text": "/usr/bin/vim\n"
},
{
"code": null,
"e": 6958,
"s": 6847,
"text": "Vim stores its configuration in simple text file namely .vimrc and it is located under home directory of user."
},
{
"code": null,
"e": 7032,
"s": 6958,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 7106,
"s": 7032,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 7120,
"s": 7106,
"text": "$ echo $HOME\n"
},
{
"code": null,
"e": 7234,
"s": 7120,
"text": "Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 7348,
"s": 7234,
"text": "Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 7414,
"s": 7348,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 7480,
"s": 7414,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 7488,
"s": 7480,
"text": "set nu\n"
},
{
"code": null,
"e": 7587,
"s": 7488,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 7686,
"s": 7587,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 7760,
"s": 7686,
"text": "This section describes installation and configuration on RPM based Linux."
},
{
"code": null,
"e": 7796,
"s": 7760,
"text": "Execute below command in terminal −"
},
{
"code": null,
"e": 7832,
"s": 7796,
"text": "Execute below command in terminal −"
},
{
"code": null,
"e": 7859,
"s": 7832,
"text": "$ su - \n$ yum install vim\n"
},
{
"code": null,
"e": 7920,
"s": 7859,
"text": "To ensure Vim is correctly installed execute below command −"
},
{
"code": null,
"e": 7981,
"s": 7920,
"text": "To ensure Vim is correctly installed execute below command −"
},
{
"code": null,
"e": 7994,
"s": 7981,
"text": "$ which vim\n"
},
{
"code": null,
"e": 8058,
"s": 7994,
"text": "It should print the location of Vim binary. In my case it was −"
},
{
"code": null,
"e": 8122,
"s": 8058,
"text": "It should print the location of Vim binary. In my case it was −"
},
{
"code": null,
"e": 8136,
"s": 8122,
"text": "/usr/bin/vim\n"
},
{
"code": null,
"e": 8247,
"s": 8136,
"text": "Vim stores its configuration in simple text file namely .vimrc and it is located under home directory of user."
},
{
"code": null,
"e": 8321,
"s": 8247,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 8395,
"s": 8321,
"text": "To find current user’s home directory execute below command in terminal −"
},
{
"code": null,
"e": 8409,
"s": 8395,
"text": "$ echo $HOME\n"
},
{
"code": null,
"e": 8523,
"s": 8409,
"text": "Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 8637,
"s": 8523,
"text": "Navigate to home directory and create a new file namely .vimrc. Ensure that this file doesn’t have any extension."
},
{
"code": null,
"e": 8703,
"s": 8637,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 8769,
"s": 8703,
"text": "Open this file in text editor, enter following text and save it −"
},
{
"code": null,
"e": 8777,
"s": 8769,
"text": "set nu\n"
},
{
"code": null,
"e": 8876,
"s": 8777,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 8975,
"s": 8876,
"text": "Now Vim will show line numbers when file is opened. We’ll add more options to this file latter on."
},
{
"code": null,
"e": 9164,
"s": 8975,
"text": "Vim is clone of original Vi editor. In this chapter, we will discuss about other Vi clones. Main purpose of this chapter to know other clones and its compatibility with original Vi editor."
},
{
"code": null,
"e": 9215,
"s": 9164,
"text": "In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 9218,
"s": 9215,
"text": "Vi"
},
{
"code": null,
"e": 9225,
"s": 9218,
"text": "Stevie"
},
{
"code": null,
"e": 9231,
"s": 9225,
"text": "Elvis"
},
{
"code": null,
"e": 9235,
"s": 9231,
"text": "nvi"
},
{
"code": null,
"e": 9240,
"s": 9235,
"text": "vile"
},
{
"code": null,
"e": 9271,
"s": 9240,
"text": "Compatibility with original Vi"
},
{
"code": null,
"e": 9519,
"s": 9271,
"text": "Vi is acronym for Visual. It is screen-oriented text editor originally created for UNIX. The original code for Vi was written by Bill Joy in 1976 and first released on BSD platform. Vi was extension of ed editor which was most common at that time."
},
{
"code": null,
"e": 9745,
"s": 9519,
"text": "Vim was the first editor to introduce multiple modes. There is a separate mode for editing text, selecting text and executing command. Vim editor supports all these modes. Later sections of this tutorial describe these modes."
},
{
"code": null,
"e": 9877,
"s": 9745,
"text": "Stevie editor was developed for Atari ST platform. It was released in 1987 it is an abbreviation for ST Editor for VI enthusiastic."
},
{
"code": null,
"e": 10038,
"s": 9877,
"text": "It was very simple and provided only very small subset of the original Vi editor. However, it provided familiar environment to user moving on Atari ST platform."
},
{
"code": null,
"e": 10322,
"s": 10038,
"text": "Elvis’s main intention was to remove Stevie editor limitation. Stevie used to load entire file in RAM, Elvis removed this limitation by introducing buffers. Also it added some functionality into it like syntax highlighting, multiple window support, networking support and simple GUI."
},
{
"code": null,
"e": 10644,
"s": 10322,
"text": "nvi stands for new Vi. It was a result of license dispute between AT & T lab and Computer Science Research Group(CSRC) at university of California, Berkeley. Vi was based on ed editor and was under license of AT & T which restricted them to distribute Vi with BDS. Hence they rewrote Vi and released it under BSD license."
},
{
"code": null,
"e": 10760,
"s": 10644,
"text": "Vim is improved version of Vi and it added many features where Vi was lagging. It added many useful features like −"
},
{
"code": null,
"e": 10790,
"s": 10760,
"text": "Multiple windows/tabs/buffers"
},
{
"code": null,
"e": 10829,
"s": 10790,
"text": "Introduction of Vim scripting language"
},
{
"code": null,
"e": 10877,
"s": 10829,
"text": "Syntax highlighting for more than 200 languages"
},
{
"code": null,
"e": 10932,
"s": 10877,
"text": "Integration with compilers, interpreters and debuggers"
},
{
"code": null,
"e": 11112,
"s": 10932,
"text": "Vile is an abbreviation which stands for Vi like Emacs and it was an attempt to bring popular features from both editor and combine it into one. Few popular features of Vile are −"
},
{
"code": null,
"e": 11148,
"s": 11112,
"text": "One editing mode for each file type"
},
{
"code": null,
"e": 11189,
"s": 11148,
"text": "Introduction of Vile procedural language"
},
{
"code": null,
"e": 11244,
"s": 11189,
"text": "Named functions to bound keys according to user choice"
},
{
"code": null,
"e": 11409,
"s": 11244,
"text": "Though above discussed editors are considered as Vi clones they are not 100% compatible with original Vi. Below table shows more details about their compatibility −"
},
{
"code": null,
"e": 11526,
"s": 11409,
"text": "Beginning with this section we will get our hands dirty with Vim. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 11536,
"s": 11526,
"text": "Start Vim"
},
{
"code": null,
"e": 11546,
"s": 11536,
"text": "Start Vim"
},
{
"code": null,
"e": 11556,
"s": 11546,
"text": "Vim modes"
},
{
"code": null,
"e": 11566,
"s": 11556,
"text": "Vim modes"
},
{
"code": null,
"e": 11582,
"s": 11566,
"text": "Create new file"
},
{
"code": null,
"e": 11598,
"s": 11582,
"text": "Create new file"
},
{
"code": null,
"e": 11626,
"s": 11598,
"text": "View file in read-only mode"
},
{
"code": null,
"e": 11654,
"s": 11626,
"text": "View file in read-only mode"
},
{
"code": null,
"e": 11673,
"s": 11654,
"text": "Edit existing file"
},
{
"code": null,
"e": 11692,
"s": 11673,
"text": "Edit existing file"
},
{
"code": null,
"e": 11808,
"s": 11692,
"text": "Vim is little bit different than today’s GUI based editor. It can be started and used from GUI as well as terminal."
},
{
"code": null,
"e": 11917,
"s": 11808,
"text": "To start Vim from graphical launcher just double click on gVim icon. It will open editor window as follows −"
},
{
"code": null,
"e": 12026,
"s": 11917,
"text": "To start Vim from graphical launcher just double click on gVim icon. It will open editor window as follows −"
},
{
"code": null,
"e": 12168,
"s": 12026,
"text": "Using Vim from terminal will be identical on Windows as well as Linux platform. Perform following steps to start and quit Vim from terminal −"
},
{
"code": null,
"e": 12217,
"s": 12168,
"text": "Open terminal and enter vim command as follows −"
},
{
"code": null,
"e": 12266,
"s": 12217,
"text": "Open terminal and enter vim command as follows −"
},
{
"code": null,
"e": 12273,
"s": 12266,
"text": "$ vim\n"
},
{
"code": null,
"e": 12315,
"s": 12273,
"text": "It will open Vim in terminal as follows −"
},
{
"code": null,
"e": 12357,
"s": 12315,
"text": "It will open Vim in terminal as follows −"
},
{
"code": null,
"e": 12516,
"s": 12357,
"text": "To close this, press Esc key followed by colon(:) and q. In Vim q command stands for quit. This command will be shown in bottom left corner of editor itself −"
},
{
"code": null,
"e": 12675,
"s": 12516,
"text": "To close this, press Esc key followed by colon(:) and q. In Vim q command stands for quit. This command will be shown in bottom left corner of editor itself −"
},
{
"code": null,
"e": 12795,
"s": 12675,
"text": "Vim supports multiple modes. This section discusses some of the important modes which will be used on day-to-day basis."
},
{
"code": null,
"e": 13025,
"s": 12795,
"text": "This is the default mode in which Vim starts. We can enter editor commands in this mode. We can use variety of commands in this mode like copy, paste, delete, replace and many more. We’ll discuss these commands in later sections."
},
{
"code": null,
"e": 13138,
"s": 13025,
"text": "NOTE − Here onwards, any Vim command without colon indicates that we are executing that command in command mode."
},
{
"code": null,
"e": 13298,
"s": 13138,
"text": "You can use this mode to enter/edit text. To switch from default command to insert mode press i key. It will show current mode in bottom left corner of editor."
},
{
"code": null,
"e": 13373,
"s": 13298,
"text": "We can enter any text once we are in insert mode. Below image shows this −"
},
{
"code": null,
"e": 13435,
"s": 13373,
"text": "Use Escape key to switch back to command mode from this mode."
},
{
"code": null,
"e": 13653,
"s": 13435,
"text": "This mode is also used to enter commands. Commands in this mode starts with colon(:). For instance, in previous section quit command was entered in this mode. We can go to this mode either from command or insert mode."
},
{
"code": null,
"e": 13710,
"s": 13653,
"text": "To switch from command mode to this mode just type colon"
},
{
"code": null,
"e": 13767,
"s": 13710,
"text": "To switch from command mode to this mode just type colon"
},
{
"code": null,
"e": 13835,
"s": 13767,
"text": "To switch from insert mode to this mode press Escape and type colon"
},
{
"code": null,
"e": 13903,
"s": 13835,
"text": "To switch from insert mode to this mode press Escape and type colon"
},
{
"code": null,
"e": 13960,
"s": 13903,
"text": "In below image colon at bottom left indicates line mode."
},
{
"code": null,
"e": 14084,
"s": 13960,
"text": "NOTE − Here onwards, any Vim command starting with colon indicates that we are executing that command in command line mode."
},
{
"code": null,
"e": 14164,
"s": 14084,
"text": "In this mode we can visually select text and run commands on selected sections."
},
{
"code": null,
"e": 14214,
"s": 14164,
"text": "To switch from command mode to visual mode type v"
},
{
"code": null,
"e": 14264,
"s": 14214,
"text": "To switch from command mode to visual mode type v"
},
{
"code": null,
"e": 14400,
"s": 14264,
"text": "To switch from any other mode to visual mode first switch back to command mode by pressing Escape, then type v to switch to visual mode"
},
{
"code": null,
"e": 14536,
"s": 14400,
"text": "To switch from any other mode to visual mode first switch back to command mode by pressing Escape, then type v to switch to visual mode"
},
{
"code": null,
"e": 14589,
"s": 14536,
"text": "In below image bottom left corner shows visual mode."
},
{
"code": null,
"e": 14639,
"s": 14589,
"text": "Perform below steps to create and save new file −"
},
{
"code": null,
"e": 14677,
"s": 14639,
"text": "Execute following command to open Vim"
},
{
"code": null,
"e": 14715,
"s": 14677,
"text": "Execute following command to open Vim"
},
{
"code": null,
"e": 14722,
"s": 14715,
"text": "$ vim\n"
},
{
"code": null,
"e": 14752,
"s": 14722,
"text": "Type following command in Vim"
},
{
"code": null,
"e": 14782,
"s": 14752,
"text": "Type following command in Vim"
},
{
"code": null,
"e": 14801,
"s": 14782,
"text": ":edit message.txt\n"
},
{
"code": null,
"e": 14842,
"s": 14801,
"text": "It will reload file if, it exist already"
},
{
"code": null,
"e": 14864,
"s": 14842,
"text": "Switch to insert mode"
},
{
"code": null,
"e": 14886,
"s": 14864,
"text": "Switch to insert mode"
},
{
"code": null,
"e": 14889,
"s": 14886,
"text": "i\n"
},
{
"code": null,
"e": 14905,
"s": 14889,
"text": "Enter some text"
},
{
"code": null,
"e": 14921,
"s": 14905,
"text": "Enter some text"
},
{
"code": null,
"e": 14949,
"s": 14921,
"text": "Switch back to command mode"
},
{
"code": null,
"e": 14977,
"s": 14949,
"text": "Switch back to command mode"
},
{
"code": null,
"e": 14982,
"s": 14977,
"text": "Esc\n"
},
{
"code": null,
"e": 15003,
"s": 14982,
"text": "Save changes to file"
},
{
"code": null,
"e": 15024,
"s": 15003,
"text": "Save changes to file"
},
{
"code": null,
"e": 15028,
"s": 15024,
"text": ":w\n"
},
{
"code": null,
"e": 15066,
"s": 15028,
"text": "Now message.txt file will be created."
},
{
"code": null,
"e": 15075,
"s": 15066,
"text": "Quit Vim"
},
{
"code": null,
"e": 15084,
"s": 15075,
"text": "Quit Vim"
},
{
"code": null,
"e": 15088,
"s": 15084,
"text": ":q\n"
},
{
"code": null,
"e": 15133,
"s": 15088,
"text": "Use –R option to open file in read-only mode"
},
{
"code": null,
"e": 15155,
"s": 15133,
"text": "$ vim -R message.txt\n"
},
{
"code": null,
"e": 15212,
"s": 15155,
"text": "In below image bottom left corner shows read-only mode −"
},
{
"code": null,
"e": 15275,
"s": 15212,
"text": "Alternatively you can use view command to achieve same result."
},
{
"code": null,
"e": 15295,
"s": 15275,
"text": "$ view message.txt\n"
},
{
"code": null,
"e": 15339,
"s": 15295,
"text": "Perform below steps to edit existing file −"
},
{
"code": null,
"e": 15359,
"s": 15339,
"text": "Open file using Vim"
},
{
"code": null,
"e": 15379,
"s": 15359,
"text": "Open file using Vim"
},
{
"code": null,
"e": 15398,
"s": 15379,
"text": "$ vim message.txt\n"
},
{
"code": null,
"e": 15447,
"s": 15398,
"text": "Switch to insert mode and enter some text there."
},
{
"code": null,
"e": 15496,
"s": 15447,
"text": "Switch to insert mode and enter some text there."
},
{
"code": null,
"e": 15499,
"s": 15496,
"text": "i\n"
},
{
"code": null,
"e": 15534,
"s": 15499,
"text": "Quit editor without saving changes"
},
{
"code": null,
"e": 15569,
"s": 15534,
"text": "Quit editor without saving changes"
},
{
"code": null,
"e": 15574,
"s": 15569,
"text": ":q!\n"
},
{
"code": null,
"e": 15577,
"s": 15574,
"text": "OR"
},
{
"code": null,
"e": 15632,
"s": 15577,
"text": "Save changes and quit editor using following command −"
},
{
"code": null,
"e": 15687,
"s": 15632,
"text": "Save changes and quit editor using following command −"
},
{
"code": null,
"e": 15692,
"s": 15687,
"text": ":wq\n"
},
{
"code": null,
"e": 15884,
"s": 15692,
"text": "Vim is feature rich editor hence remembering everything about it will be difficult. But there is no need to worry, we can always ask for help. Fortunately this help is provided by Vim itself."
},
{
"code": null,
"e": 15935,
"s": 15884,
"text": "In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 15954,
"s": 15935,
"text": "Access help manual"
},
{
"code": null,
"e": 15977,
"s": 15954,
"text": "Help on specific topic"
},
{
"code": null,
"e": 16006,
"s": 15977,
"text": "Search help phrase in manual"
},
{
"code": null,
"e": 16025,
"s": 16006,
"text": "Access online help"
},
{
"code": null,
"e": 16142,
"s": 16025,
"text": "Help manual is shipped with Vim editor itself and it is really comprehensive. To access help execute below command −"
},
{
"code": null,
"e": 16149,
"s": 16142,
"text": ":help\n"
},
{
"code": null,
"e": 16308,
"s": 16149,
"text": "Help manual will show entire help about Vim. But what if, we are only interested in certain topic. Vim provides command for that as well with following syntax"
},
{
"code": null,
"e": 16328,
"s": 16308,
"text": ":help <topic-name>\n"
},
{
"code": null,
"e": 16475,
"s": 16328,
"text": "In above command replace <topic-name> with topic in which you are interested. Forinstance to access help about vim mode, execute following command"
},
{
"code": null,
"e": 16488,
"s": 16475,
"text": ":help modes\n"
},
{
"code": null,
"e": 16644,
"s": 16488,
"text": "You can search specific topic only if you know its name. But what if, you don’t know the exact name of help topic. In that case you can use below command −"
},
{
"code": null,
"e": 16664,
"s": 16644,
"text": ":helpgrep <phrase>\n"
},
{
"code": null,
"e": 16739,
"s": 16664,
"text": "For instance, to access help about navigation in Vim execute below command"
},
{
"code": null,
"e": 16761,
"s": 16739,
"text": ":helpgrep navigation\n"
},
{
"code": null,
"e": 16816,
"s": 16761,
"text": "Vim also provides online help. To access online help −"
},
{
"code": null,
"e": 16835,
"s": 16816,
"text": "Visit vim-help URL"
},
{
"code": null,
"e": 16854,
"s": 16835,
"text": "Visit vim-help URL"
},
{
"code": null,
"e": 16909,
"s": 16854,
"text": "Additionally you can also refer vim-docs documentation"
},
{
"code": null,
"e": 16964,
"s": 16909,
"text": "Additionally you can also refer vim-docs documentation"
},
{
"code": null,
"e": 17092,
"s": 16964,
"text": "Vim provides many commands which make editing functionality really powerful. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 17099,
"s": 17092,
"text": "Insert"
},
{
"code": null,
"e": 17106,
"s": 17099,
"text": "Append"
},
{
"code": null,
"e": 17120,
"s": 17106,
"text": "Open new line"
},
{
"code": null,
"e": 17131,
"s": 17120,
"text": "Substitute"
},
{
"code": null,
"e": 17138,
"s": 17131,
"text": "Change"
},
{
"code": null,
"e": 17146,
"s": 17138,
"text": "Replace"
},
{
"code": null,
"e": 17151,
"s": 17146,
"text": "Join"
},
{
"code": null,
"e": 17206,
"s": 17151,
"text": "To insert text before cursor perform following steps −"
},
{
"code": null,
"e": 17259,
"s": 17206,
"text": "To insert text before cursor perform following steps"
},
{
"code": null,
"e": 17281,
"s": 17259,
"text": "Switch to insert mode"
},
{
"code": null,
"e": 17284,
"s": 17281,
"text": "i\n"
},
{
"code": null,
"e": 17421,
"s": 17284,
"text": "Let us suppose you are in the middle of line and you want to insert text at the beginning of current line then perform following steps −"
},
{
"code": null,
"e": 17444,
"s": 17421,
"text": "Switch to command mode"
},
{
"code": null,
"e": 17449,
"s": 17444,
"text": "Esc\n"
},
{
"code": null,
"e": 17470,
"s": 17449,
"text": "Activate insert mode"
},
{
"code": null,
"e": 17473,
"s": 17470,
"text": "I\n"
},
{
"code": null,
"e": 17565,
"s": 17473,
"text": "This action will move cursor to the beginning of current line and switch Vim in insert mode"
},
{
"code": null,
"e": 17617,
"s": 17565,
"text": "To append text after cursor perform following steps"
},
{
"code": null,
"e": 17680,
"s": 17617,
"text": "Switch to command mode and move cursor to appropriate position"
},
{
"code": null,
"e": 17685,
"s": 17680,
"text": "Esc\n"
},
{
"code": null,
"e": 17707,
"s": 17685,
"text": "Switch to insert mode"
},
{
"code": null,
"e": 17710,
"s": 17707,
"text": "a\n"
},
{
"code": null,
"e": 17791,
"s": 17710,
"text": "This action will move cursor next by one position and switch Vim in insert mode."
},
{
"code": null,
"e": 17922,
"s": 17791,
"text": "Let us suppose you are in the middle of line and you want to append text at the end of current line then perform following steps −"
},
{
"code": null,
"e": 17945,
"s": 17922,
"text": "Switch to command mode"
},
{
"code": null,
"e": 17950,
"s": 17945,
"text": "Esc\n"
},
{
"code": null,
"e": 17972,
"s": 17950,
"text": "Switch to insert mode"
},
{
"code": null,
"e": 17975,
"s": 17972,
"text": "A\n"
},
{
"code": null,
"e": 18053,
"s": 17975,
"text": "This action will move cursor to the end of line and switch Vim in insert mode"
},
{
"code": null,
"e": 18178,
"s": 18053,
"text": "Let us suppose you are in the middle of line and you want to open new line below current line then perform following steps −"
},
{
"code": null,
"e": 18201,
"s": 18178,
"text": "Switch to command mode"
},
{
"code": null,
"e": 18206,
"s": 18201,
"text": "Esc\n"
},
{
"code": null,
"e": 18228,
"s": 18206,
"text": "Switch to insert mode"
},
{
"code": null,
"e": 18231,
"s": 18228,
"text": "o\n"
},
{
"code": null,
"e": 18315,
"s": 18231,
"text": "This action will insert blank line below current line and switch Vim in insert mode"
},
{
"code": null,
"e": 18440,
"s": 18315,
"text": "Let us suppose you are in the middle of line and you want to open new line above current line then perform following steps −"
},
{
"code": null,
"e": 18463,
"s": 18440,
"text": "Switch to command mode"
},
{
"code": null,
"e": 18468,
"s": 18463,
"text": "Esc\n"
},
{
"code": null,
"e": 18490,
"s": 18468,
"text": "Switch to insert mode"
},
{
"code": null,
"e": 18493,
"s": 18490,
"text": "o\n"
},
{
"code": null,
"e": 18577,
"s": 18493,
"text": "This action will insert blank line above current line and switch Vim in insert mode"
},
{
"code": null,
"e": 18663,
"s": 18577,
"text": "Let us suppose you want to substitute single character then perform following steps −"
},
{
"code": null,
"e": 18686,
"s": 18663,
"text": "Switch to command mode"
},
{
"code": null,
"e": 18691,
"s": 18686,
"text": "Esc\n"
},
{
"code": null,
"e": 18727,
"s": 18691,
"text": "Move cursor to appropriate position"
},
{
"code": null,
"e": 18749,
"s": 18727,
"text": "Switch to insert mode"
},
{
"code": null,
"e": 18752,
"s": 18749,
"text": "s\n"
},
{
"code": null,
"e": 18861,
"s": 18752,
"text": "This action will delete character under cursor and switch Vim in insert mode To substitute entire line use −"
},
{
"code": null,
"e": 18864,
"s": 18861,
"text": "s\n"
},
{
"code": null,
"e": 18931,
"s": 18864,
"text": "This action will delete entire line and switch Vim in insert mode."
},
{
"code": null,
"e": 19017,
"s": 18931,
"text": "Let us suppose you want to change text in current line then perform following steps −"
},
{
"code": null,
"e": 19040,
"s": 19017,
"text": "Switch to command mode"
},
{
"code": null,
"e": 19045,
"s": 19040,
"text": "Esc\n"
},
{
"code": null,
"e": 19073,
"s": 19045,
"text": "Execute following command −"
},
{
"code": null,
"e": 19077,
"s": 19073,
"text": "cc\n"
},
{
"code": null,
"e": 19122,
"s": 19077,
"text": "This is similar to substitute action using S"
},
{
"code": null,
"e": 19193,
"s": 19122,
"text": "To change text from current cursor position, execute following command"
},
{
"code": null,
"e": 19196,
"s": 19193,
"text": "C\n"
},
{
"code": null,
"e": 19286,
"s": 19196,
"text": "This action will delete text after current cursor position and switch Vim in insert mode."
},
{
"code": null,
"e": 19340,
"s": 19286,
"text": "To replace single character perform following steps −"
},
{
"code": null,
"e": 19363,
"s": 19340,
"text": "Switch to command mode"
},
{
"code": null,
"e": 19368,
"s": 19363,
"text": "Esc\n"
},
{
"code": null,
"e": 19404,
"s": 19368,
"text": "Move cursor to appropriate position"
},
{
"code": null,
"e": 19432,
"s": 19404,
"text": "Execute following command −"
},
{
"code": null,
"e": 19435,
"s": 19432,
"text": "r\n"
},
{
"code": null,
"e": 19470,
"s": 19435,
"text": "Enter character to be substituted."
},
{
"code": null,
"e": 19528,
"s": 19470,
"text": "Note that this command will not switch Vim in insert mode"
},
{
"code": null,
"e": 19561,
"s": 19528,
"text": "To replace entire line execute −"
},
{
"code": null,
"e": 19564,
"s": 19561,
"text": "R\n"
},
{
"code": null,
"e": 19625,
"s": 19564,
"text": "It will switch Vim in replace mode as shown in below image −"
},
{
"code": null,
"e": 19669,
"s": 19625,
"text": "To join two lines perform following steps −"
},
{
"code": null,
"e": 19692,
"s": 19669,
"text": "Switch to command mode"
},
{
"code": null,
"e": 19697,
"s": 19692,
"text": "Esc\n"
},
{
"code": null,
"e": 19729,
"s": 19697,
"text": "Move cursor to appropriate line"
},
{
"code": null,
"e": 19757,
"s": 19729,
"text": "Execute following command −"
},
{
"code": null,
"e": 19760,
"s": 19757,
"text": "J\n"
},
{
"code": null,
"e": 19916,
"s": 19760,
"text": "Vim has great support for advanced navigation. In this chapter, we’ll discuss some of the popular navigation techniques which help to improve productivity."
},
{
"code": null,
"e": 20031,
"s": 19916,
"text": "In basic navigation we can navigate to left, right, up and down by position. Below commands can be used for this −"
},
{
"code": null,
"e": 20067,
"s": 20031,
"text": "Move cursor to left by one position"
},
{
"code": null,
"e": 20104,
"s": 20067,
"text": "Move cursor to right by one position"
},
{
"code": null,
"e": 20148,
"s": 20104,
"text": "Move cursor to upward direction by one line"
},
{
"code": null,
"e": 20194,
"s": 20148,
"text": "Move cursor to downward direction by one line"
},
{
"code": null,
"e": 20356,
"s": 20194,
"text": "To perform multi-position navigation use number with these commands. For instance to navigate cursor 10 line below from current line, execute following command −"
},
{
"code": null,
"e": 20361,
"s": 20356,
"text": "10j\n"
},
{
"code": null,
"e": 20414,
"s": 20361,
"text": "You can use numbers with remaining commands as well."
},
{
"code": null,
"e": 20487,
"s": 20414,
"text": "In addition to this, below commands also perform some useful navigation."
},
{
"code": null,
"e": 20532,
"s": 20487,
"text": "Move cursor to the beginning of current line"
},
{
"code": null,
"e": 20571,
"s": 20532,
"text": "Move cursor to the end of current line"
},
{
"code": null,
"e": 20595,
"s": 20571,
"text": "Scroll down entire page"
},
{
"code": null,
"e": 20617,
"s": 20595,
"text": "Scroll up entire page"
},
{
"code": null,
"e": 20674,
"s": 20617,
"text": "Below command can be used to navigate to specific line −"
},
{
"code": null,
"e": 20695,
"s": 20674,
"text": "Jump to the nth line"
},
{
"code": null,
"e": 20721,
"s": 20695,
"text": "Jump to the start of file"
},
{
"code": null,
"e": 20745,
"s": 20721,
"text": "Jump to the end of file"
},
{
"code": null,
"e": 20797,
"s": 20745,
"text": "We can use following commands for word navigation −"
},
{
"code": null,
"e": 20843,
"s": 20797,
"text": "Move cursor to the beginning of the next word"
},
{
"code": null,
"e": 20886,
"s": 20843,
"text": "Move cursor to the end of the current word"
},
{
"code": null,
"e": 20936,
"s": 20886,
"text": "Move cursor to the beginning of the previous word"
},
{
"code": null,
"e": 21041,
"s": 20936,
"text": "Vim keeps track of your navigation using a jump list. You can go backward and forward through that list."
},
{
"code": null,
"e": 21155,
"s": 21041,
"text": "The jump list keeps tracks of all the places you’ve been to by tracking file name, line number and column number."
},
{
"code": null,
"e": 21201,
"s": 21155,
"text": "To view jump list execute following command −"
},
{
"code": null,
"e": 21209,
"s": 21201,
"text": ":jumps\n"
},
{
"code": null,
"e": 21252,
"s": 21209,
"text": "Following command are based on jump list −"
},
{
"code": null,
"e": 21287,
"s": 21252,
"text": "Jump back to the previous position"
},
{
"code": null,
"e": 21313,
"s": 21287,
"text": "Jump to the next position"
},
{
"code": null,
"e": 21454,
"s": 21313,
"text": "We have seen basic editing earlier. Let us understand some other editing features of Vim. In this section, we will discuss following items −"
},
{
"code": null,
"e": 21461,
"s": 21454,
"text": "Buffer"
},
{
"code": null,
"e": 21472,
"s": 21461,
"text": "Swap files"
},
{
"code": null,
"e": 21505,
"s": 21472,
"text": "Cut, copy, delete, paste actions"
},
{
"code": null,
"e": 21527,
"s": 21505,
"text": "Undo and redo actions"
},
{
"code": null,
"e": 21851,
"s": 21527,
"text": "Buffer is temporary memory used by Vim. When we open a file in editor, Vim loads its contents from disk drive. These contents are stored in memory (RAM) whenever we edit a file we are actually editing file from buffer. Once we finish editing and save file that time only buffer contents are transferred to appropriate file."
},
{
"code": null,
"e": 22045,
"s": 21851,
"text": "Swap area is a file created by Vim to store buffer contents periodically. While editing file our changes may be lost because of any reasons and Vim provides swap files to provide data recovery."
},
{
"code": null,
"e": 22105,
"s": 22045,
"text": "To get actual name of swap file execute following command −"
},
{
"code": null,
"e": 22116,
"s": 22105,
"text": ":swapname\n"
},
{
"code": null,
"e": 22190,
"s": 22116,
"text": "For instance in my case name was message.txt.swp as show in below image −"
},
{
"code": null,
"e": 22353,
"s": 22190,
"text": "We often perform cut, copy and paste actions on text. Vim provides following commands to perform these actions (y stands for yank and p stands for paste action) −"
},
{
"code": null,
"e": 22391,
"s": 22353,
"text": "Delete character from cursor position"
},
{
"code": null,
"e": 22438,
"s": 22391,
"text": "Delete previous character from cursor position"
},
{
"code": null,
"e": 22481,
"s": 22438,
"text": "Copy single character from cursor position"
},
{
"code": null,
"e": 22519,
"s": 22481,
"text": "Paste character after cursor position"
},
{
"code": null,
"e": 22558,
"s": 22519,
"text": "Paste character before cursor position"
},
{
"code": null,
"e": 22657,
"s": 22558,
"text": "We can use cut, copy and paste commands with words and sentences as well. Below table shows this −"
},
{
"code": null,
"e": 22690,
"s": 22657,
"text": "Delete word from cursor position"
},
{
"code": null,
"e": 22730,
"s": 22690,
"text": "Delete entire line from cursor position"
},
{
"code": null,
"e": 22749,
"s": 22730,
"text": "Delete entire line"
},
{
"code": null,
"e": 22768,
"s": 22749,
"text": "Copies entire line"
},
{
"code": null,
"e": 22787,
"s": 22768,
"text": "Copies entire line"
},
{
"code": null,
"e": 22950,
"s": 22787,
"text": "To perform multi-line/multi-word actions just use numbers with command. You can use this syntax with other commands as well. For instance, to delete 3 words use −"
},
{
"code": null,
"e": 22955,
"s": 22950,
"text": "3dw\n"
},
{
"code": null,
"e": 23037,
"s": 22955,
"text": "We can undo single or multiple actions. To perform one time undo action execute −"
},
{
"code": null,
"e": 23040,
"s": 23037,
"text": "u\n"
},
{
"code": null,
"e": 23158,
"s": 23040,
"text": "To perform multiple undo action, use number with same command. For instance, below command will undo last 3 actions −"
},
{
"code": null,
"e": 23162,
"s": 23158,
"text": "3u\n"
},
{
"code": null,
"e": 23223,
"s": 23162,
"text": "In addition to this, to undo all execute following command −"
},
{
"code": null,
"e": 23226,
"s": 23223,
"text": "U\n"
},
{
"code": null,
"e": 23310,
"s": 23226,
"text": "Redo is apposite action of undo. Execute any of the command to perform redo action."
},
{
"code": null,
"e": 23329,
"s": 23310,
"text": "Ctrl + r\nOR\n: red\n"
},
{
"code": null,
"e": 23508,
"s": 23329,
"text": "Search is very common action and it is one of the actions we use most of the time. In this chapter we will see some command which will allow performing these actions effectively."
},
{
"code": null,
"e": 23559,
"s": 23508,
"text": "In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 23575,
"s": 23559,
"text": "Search settings"
},
{
"code": null,
"e": 23598,
"s": 23575,
"text": "Search in current file"
},
{
"code": null,
"e": 23623,
"s": 23598,
"text": "Search in multiple files"
},
{
"code": null,
"e": 23644,
"s": 23623,
"text": "Search in help files"
},
{
"code": null,
"e": 23702,
"s": 23644,
"text": "To perform incremental search execute following command −"
},
{
"code": null,
"e": 23718,
"s": 23702,
"text": ":set incsearch\n"
},
{
"code": null,
"e": 23766,
"s": 23718,
"text": "To highlight search execute following command −"
},
{
"code": null,
"e": 23781,
"s": 23766,
"text": ":set hlsearch\n"
},
{
"code": null,
"e": 23894,
"s": 23781,
"text": "This command will automatically highlight current matches. For instance in below image\nfox word is highlighted −"
},
{
"code": null,
"e": 23969,
"s": 23894,
"text": "To disable incremental and highlighted search execute following commands −"
},
{
"code": null,
"e": 24003,
"s": 23969,
"text": ":set noincsearch\n:set nohlsearch\n"
},
{
"code": null,
"e": 24067,
"s": 24003,
"text": "Use following commands to perform search in forward direction −"
},
{
"code": null,
"e": 24106,
"s": 24067,
"text": "Search expression in forward direction"
},
{
"code": null,
"e": 24155,
"s": 24106,
"text": "Find next occurrence. This is same and find next"
},
{
"code": null,
"e": 24211,
"s": 24155,
"text": "Find previous occurrence. This is same as find previous"
},
{
"code": null,
"e": 24242,
"s": 24211,
"text": "Repeat previous forward search"
},
{
"code": null,
"e": 24305,
"s": 24242,
"text": "Use following commands to perform search in backward direction"
},
{
"code": null,
"e": 24345,
"s": 24305,
"text": "Search expression in backward direction"
},
{
"code": null,
"e": 24402,
"s": 24345,
"text": "Find previous occurrence. This is same and find previous"
},
{
"code": null,
"e": 24450,
"s": 24402,
"text": "Find next occurrence. This is same as find next"
},
{
"code": null,
"e": 24482,
"s": 24450,
"text": "Repeat previous backward search"
},
{
"code": null,
"e": 24571,
"s": 24482,
"text": "Place cursor under any word and execute following commands to perform search operation −"
},
{
"code": null,
"e": 24610,
"s": 24571,
"text": "Search next occurrence of current word"
},
{
"code": null,
"e": 24653,
"s": 24610,
"text": "Search previous occurrence of current word"
},
{
"code": null,
"e": 24792,
"s": 24653,
"text": "Using vimgrep command we can search <expression> in multiple files. For instance below command searches string - Jarvis in all text files."
},
{
"code": null,
"e": 24815,
"s": 24792,
"text": ":vimgrep Jarvis *.txt\n"
},
{
"code": null,
"e": 24899,
"s": 24815,
"text": "Note that to go to next and previous occurrence we have to use following commands −"
},
{
"code": null,
"e": 24935,
"s": 24899,
"text": "Go to next occurrence of expression"
},
{
"code": null,
"e": 24975,
"s": 24935,
"text": "Go to previous occurrence of expression"
},
{
"code": null,
"e": 25139,
"s": 24975,
"text": "Vim is very powerful editor. It supports many advanced features to work with multiple files, buffer and windows. In this section, we will discuss following items −"
},
{
"code": null,
"e": 25154,
"s": 25139,
"text": "Multiple files"
},
{
"code": null,
"e": 25171,
"s": 25154,
"text": "Multiple buffers"
},
{
"code": null,
"e": 25185,
"s": 25171,
"text": "Multiple tabs"
},
{
"code": null,
"e": 25202,
"s": 25185,
"text": "Multiple windows"
},
{
"code": null,
"e": 25374,
"s": 25202,
"text": "Let us suppose you are editing a file and you want to open another file in same Vim session. In that case, you can use Vim’s edit command. Below table shows these commands"
},
{
"code": null,
"e": 25410,
"s": 25374,
"text": "Load new file in buffer for editing"
},
{
"code": null,
"e": 25421,
"s": 25410,
"text": "Same as :e"
},
{
"code": null,
"e": 25471,
"s": 25421,
"text": "List the files for editing from current directory"
},
{
"code": null,
"e": 25488,
"s": 25471,
"text": "Same as :e <tab>"
},
{
"code": null,
"e": 25620,
"s": 25488,
"text": "We have already seen what Vim buffers are. Vim supports multiple buffers. Below commands will be useful will working with buffers −"
},
{
"code": null,
"e": 25645,
"s": 25620,
"text": "Add file into new buffer"
},
{
"code": null,
"e": 25712,
"s": 25645,
"text": "Switch to Nth buffer. For instance to switch to 3rd buffer use :b3"
},
{
"code": null,
"e": 25751,
"s": 25712,
"text": "Move to the next buffer in buffer list"
},
{
"code": null,
"e": 25794,
"s": 25751,
"text": "Move to the previous buffer in buffer list"
},
{
"code": null,
"e": 25811,
"s": 25794,
"text": "List all buffers"
},
{
"code": null,
"e": 25836,
"s": 25811,
"text": "Move to the first buffer"
},
{
"code": null,
"e": 25860,
"s": 25836,
"text": "Move to the last buffer"
},
{
"code": null,
"e": 25877,
"s": 25860,
"text": "Load all buffers"
},
{
"code": null,
"e": 25931,
"s": 25877,
"text": "For instance, below command adds new file to buffer −"
},
{
"code": null,
"e": 26004,
"s": 25931,
"text": "Now, there are two files in buffer. Execute below command to show this −"
},
{
"code": null,
"e": 26014,
"s": 26004,
"text": ":buffers\n"
},
{
"code": null,
"e": 26046,
"s": 26014,
"text": "It will show following output −"
},
{
"code": null,
"e": 26149,
"s": 26046,
"text": "Like other editors we can also open multiple tabs in Vim. Below table describes tab related commands −"
},
{
"code": null,
"e": 26162,
"s": 26149,
"text": "Open new tab"
},
{
"code": null,
"e": 26183,
"s": 26162,
"text": "Open new file in tab"
},
{
"code": null,
"e": 26201,
"s": 26183,
"text": "Close current tab"
},
{
"code": null,
"e": 26222,
"s": 26201,
"text": "Move to the next tab"
},
{
"code": null,
"e": 26247,
"s": 26222,
"text": "Move to the previous tab"
},
{
"code": null,
"e": 26269,
"s": 26247,
"text": "Move to the first tab"
},
{
"code": null,
"e": 26290,
"s": 26269,
"text": "Move to the last tab"
},
{
"code": null,
"e": 26337,
"s": 26290,
"text": "For instance, below images shows multiple tabs"
},
{
"code": null,
"e": 26396,
"s": 26337,
"text": "In Vim we can create new window using following commands −"
},
{
"code": null,
"e": 26412,
"s": 26396,
"text": "Open new window"
},
{
"code": null,
"e": 26436,
"s": 26412,
"text": "Open file in new window"
},
{
"code": null,
"e": 26546,
"s": 26436,
"text": "In below image, we can see that current Vim window is split into 2 parts after executing following commands −"
},
{
"code": null,
"e": 26569,
"s": 26546,
"text": "$vim message.txt\n:new\n"
},
{
"code": null,
"e": 26720,
"s": 26569,
"text": "Vim supports bookmark feature. Using this feature we can make navigation within file really faster. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 26736,
"s": 26720,
"text": "Create bookmark"
},
{
"code": null,
"e": 26753,
"s": 26736,
"text": "Jump to bookmark"
},
{
"code": null,
"e": 26772,
"s": 26753,
"text": "List all bookmarks"
},
{
"code": null,
"e": 26789,
"s": 26772,
"text": "Delete bookmarks"
},
{
"code": null,
"e": 26805,
"s": 26789,
"text": "Local bookmarks"
},
{
"code": null,
"e": 26822,
"s": 26805,
"text": "Global bookmarks"
},
{
"code": null,
"e": 26869,
"s": 26822,
"text": "To create bookmark execute following command −"
},
{
"code": null,
"e": 26887,
"s": 26869,
"text": "m{bookmark-name}\n"
},
{
"code": null,
"e": 27008,
"s": 26887,
"text": "In above example bookmark-name is single alphabetical character. For instance, below command creates bookmark of name a."
},
{
"code": null,
"e": 27012,
"s": 27008,
"text": "ma\n"
},
{
"code": null,
"e": 27107,
"s": 27012,
"text": "Once bookmark is created we can jump there. Following command can be use to jump to bookmark −"
},
{
"code": null,
"e": 27193,
"s": 27107,
"text": "Move to the exact location of bookmark. Please note that this character is back quote"
},
{
"code": null,
"e": 27281,
"s": 27193,
"text": "Jump to the beginning of bookmark line. Please note that this character is single quote"
},
{
"code": null,
"e": 27331,
"s": 27281,
"text": "To list all bookmarks execute following command −"
},
{
"code": null,
"e": 27339,
"s": 27331,
"text": ":marks\n"
},
{
"code": null,
"e": 27397,
"s": 27339,
"text": "In below image it show list of bookmarks for current file"
},
{
"code": null,
"e": 27445,
"s": 27397,
"text": "To delete bookmarks execute following command −"
},
{
"code": null,
"e": 27472,
"s": 27445,
"text": ":delmarks {bookmark-name}\n"
},
{
"code": null,
"e": 27529,
"s": 27472,
"text": "For instance, below command delete bookmark with name a."
},
{
"code": null,
"e": 27542,
"s": 27529,
"text": ":delmarks a\n"
},
{
"code": null,
"e": 27698,
"s": 27542,
"text": "When you have multiple files open and if you want to go to a particular position in any one of the open files, then you can use global mark feature of Vim."
},
{
"code": null,
"e": 27853,
"s": 27698,
"text": "If the bookmark name is an upper case letter, then that is a global Bookmark. Above discussed commands are applicable for both local and global bookmarks."
},
{
"code": null,
"e": 28018,
"s": 27853,
"text": "Macro is record and play feature. When this is combined with Vim commands it becomes really powerful combination. In this section, we will discuss following items −"
},
{
"code": null,
"e": 28034,
"s": 28018,
"text": "Start recording"
},
{
"code": null,
"e": 28054,
"s": 28034,
"text": "Perform Vim actions"
},
{
"code": null,
"e": 28069,
"s": 28054,
"text": "Stop recording"
},
{
"code": null,
"e": 28084,
"s": 28069,
"text": "Play recording"
},
{
"code": null,
"e": 28224,
"s": 28084,
"text": "To start recording press q followed by any lower case letter as a macro name. For instance in below example I have used “a” as a macro name"
},
{
"code": null,
"e": 28371,
"s": 28224,
"text": "In this step you can perform any Vim actions like: cut, copy, delete, replace and so on.You can see these actions by executing following command −"
},
{
"code": null,
"e": 28383,
"s": 28371,
"text": ":registers\n"
},
{
"code": null,
"e": 28463,
"s": 28383,
"text": "For instance, below command shows that yank and delete actions were performed −"
},
{
"code": null,
"e": 28579,
"s": 28463,
"text": "Once you are done with actions, press q again to stop recording. Now recording mode will disappear as shown below −"
},
{
"code": null,
"e": 28611,
"s": 28579,
"text": "To play execute below command −"
},
{
"code": null,
"e": 28626,
"s": 28611,
"text": "@{macro-name}\n"
},
{
"code": null,
"e": 28685,
"s": 28626,
"text": "For instance to execute macro “a”, execute below command −"
},
{
"code": null,
"e": 28689,
"s": 28685,
"text": "@a\n"
},
{
"code": null,
"e": 28817,
"s": 28689,
"text": "To play same macro multiple times use numbers with it. For instance, to execute same macro 10 times execute following command −"
},
{
"code": null,
"e": 28823,
"s": 28817,
"text": "10@a\n"
},
{
"code": null,
"e": 29019,
"s": 28823,
"text": "Vim provides many registers. We can use these registers as multiple clipboards. This feature is really useful while working with multiple files. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 29041,
"s": 29019,
"text": "Copy text in register"
},
{
"code": null,
"e": 29066,
"s": 29041,
"text": "Paste text from register"
},
{
"code": null,
"e": 29091,
"s": 29066,
"text": "List available registers"
},
{
"code": null,
"e": 29106,
"s": 29091,
"text": "Register types"
},
{
"code": null,
"e": 29216,
"s": 29106,
"text": "For copying, we can use normal yank command i.e. yy and to store it in register we can use following syntax −"
},
{
"code": null,
"e": 29243,
"s": 29216,
"text": "“<register-name><command>\n"
},
{
"code": null,
"e": 29310,
"s": 29243,
"text": "For instance, to copy text in register “a” use following command −"
},
{
"code": null,
"e": 29316,
"s": 29310,
"text": "“ayy\n"
},
{
"code": null,
"e": 29350,
"s": 29316,
"text": "To paste text from register use −"
},
{
"code": null,
"e": 29369,
"s": 29350,
"text": "“<register-name>p\n"
},
{
"code": null,
"e": 29429,
"s": 29369,
"text": "For instance, below command copies text from register “a” −"
},
{
"code": null,
"e": 29434,
"s": 29429,
"text": "“ap\n"
},
{
"code": null,
"e": 29488,
"s": 29434,
"text": "To list all available registers use following command"
},
{
"code": null,
"e": 29500,
"s": 29488,
"text": ":registers\n"
},
{
"code": null,
"e": 29544,
"s": 29500,
"text": "Vim supports following types of registers −"
},
{
"code": null,
"e": 29630,
"s": 29544,
"text": "Unnamed register is denoted by “”. Vim stores deleted or copied text in this register"
},
{
"code": null,
"e": 29729,
"s": 29630,
"text": "We can use 26 named registers; we can use a-z or A-Z. By default vim doesn’t uses these registers."
},
{
"code": null,
"e": 29876,
"s": 29729,
"text": "If we use lower case register name then contents will be overwritten and if we use uppercase name then contents will be appended in that register."
},
{
"code": null,
"e": 29977,
"s": 29876,
"text": "We can use 0 to 9 named registers. Vim fills these registers with text from yank and delete command."
},
{
"code": null,
"e": 30050,
"s": 29977,
"text": "Numbered register 0 contains the text from the most recent yank command."
},
{
"code": null,
"e": 30140,
"s": 30050,
"text": "Numbered register 1 contains the text deleted by the most recent delete or change command"
},
{
"code": null,
"e": 30178,
"s": 30140,
"text": "Following are the default registers −"
},
{
"code": null,
"e": 30203,
"s": 30178,
"text": "Name of the current file"
},
{
"code": null,
"e": 30253,
"s": 30203,
"text": "Name of the alternate file for the current window"
},
{
"code": null,
"e": 30284,
"s": 30253,
"text": "Most recently executed command"
},
{
"code": null,
"e": 30316,
"s": 30284,
"text": "Contains the last inserted text"
},
{
"code": null,
"e": 30335,
"s": 30316,
"text": "Last used register"
},
{
"code": null,
"e": 30590,
"s": 30335,
"text": "Fold functionality will be useful when file contents large text. Using this feature we can only show selected potion of file. This feature is particularly useful while working with programming languages. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 30633,
"s": 30590,
"text": "Activate and deactivate fold functionality"
},
{
"code": null,
"e": 30654,
"s": 30633,
"text": "Various fold actions"
},
{
"code": null,
"e": 30695,
"s": 30654,
"text": "To activate fold use following command −"
},
{
"code": null,
"e": 30738,
"s": 30695,
"text": ":set foldenable \n:set foldmethod = indent\n"
},
{
"code": null,
"e": 30779,
"s": 30738,
"text": "To deactivate fold use following command"
},
{
"code": null,
"e": 30798,
"s": 30779,
"text": ":set nofoldenable\n"
},
{
"code": null,
"e": 30861,
"s": 30798,
"text": "To fold code, go to any method and execute following command −"
},
{
"code": null,
"e": 30865,
"s": 30861,
"text": "zc\n"
},
{
"code": null,
"e": 30923,
"s": 30865,
"text": "For example below image shows the result of this action −"
},
{
"code": null,
"e": 30960,
"s": 30923,
"text": "To open fold use following command −"
},
{
"code": null,
"e": 30964,
"s": 30960,
"text": "zo\n"
},
{
"code": null,
"e": 31010,
"s": 30964,
"text": "Below image shows the result of this action −"
},
{
"code": null,
"e": 31055,
"s": 31010,
"text": "To close all folds execute following command"
},
{
"code": null,
"e": 31059,
"s": 31055,
"text": "zM\n"
},
{
"code": null,
"e": 31103,
"s": 31059,
"text": "Below image shows the result of this action"
},
{
"code": null,
"e": 31137,
"s": 31103,
"text": "To unfold all execute following −"
},
{
"code": null,
"e": 31141,
"s": 31137,
"text": "zR\n"
},
{
"code": null,
"e": 31187,
"s": 31141,
"text": "Below image shows the result of this action −"
},
{
"code": null,
"e": 31356,
"s": 31187,
"text": "Similar to UNIX diff command we can use Vim to show diff in much better manner. It will show diff in colorful manner. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 31387,
"s": 31356,
"text": "Show differences between files"
},
{
"code": null,
"e": 31421,
"s": 31387,
"text": "Activate and deactivate diff mode"
},
{
"code": null,
"e": 31445,
"s": 31421,
"text": "Navigation in diff mode"
},
{
"code": null,
"e": 31479,
"s": 31445,
"text": "Applying changes from diff window"
},
{
"code": null,
"e": 31537,
"s": 31479,
"text": "To show differences between files execute below command −"
},
{
"code": null,
"e": 31590,
"s": 31537,
"text": "$ vimdiff <file> <file> \nOR \n$ vim –d <file> <file>\n"
},
{
"code": null,
"e": 31637,
"s": 31590,
"text": "For instance below command shows differences −"
},
{
"code": null,
"e": 31808,
"s": 31637,
"text": "In above image, text highlighted in magenta color is common. Remaining text is highlighted in red color which indicates that there are some differences after common text."
},
{
"code": null,
"e": 31911,
"s": 31808,
"text": "If you are already in vim and you want to perform diff action, then use one of the following command −"
},
{
"code": null,
"e": 31959,
"s": 31911,
"text": "Use below command to perform horizontal split −"
},
{
"code": null,
"e": 31980,
"s": 31959,
"text": ":diffsplit filename\n"
},
{
"code": null,
"e": 32071,
"s": 31980,
"text": "Above images shows that we are comparing two files namely message-1.txt and message-2.txt."
},
{
"code": null,
"e": 32121,
"s": 32071,
"text": "To perform vertical split use following command −"
},
{
"code": null,
"e": 32149,
"s": 32121,
"text": ":vert diffsplit <filename>\n"
},
{
"code": null,
"e": 32177,
"s": 32149,
"text": "It opens following window −"
},
{
"code": null,
"e": 32268,
"s": 32177,
"text": "Above images shows that we are comparing two files namely message-1.txt and message-2.txt."
},
{
"code": null,
"e": 32462,
"s": 32268,
"text": "Navigation in diff mode is little bit different. For instance, when you scroll text from one window then text from adjacent window also scrolled. This is called scrollbind. To enable this use −"
},
{
"code": null,
"e": 32479,
"s": 32462,
"text": ":set scrollbind\n"
},
{
"code": null,
"e": 32501,
"s": 32479,
"text": "To disable this use −"
},
{
"code": null,
"e": 32520,
"s": 32501,
"text": ":set noscrollbind\n"
},
{
"code": null,
"e": 32594,
"s": 32520,
"text": "If you edit file in this mode then use following command to update diff −"
},
{
"code": null,
"e": 32607,
"s": 32594,
"text": ":diffupdate\n"
},
{
"code": null,
"e": 32666,
"s": 32607,
"text": "To switch between diff windows execute following command −"
},
{
"code": null,
"e": 32685,
"s": 32666,
"text": "Ctrl + w Ctrl + w\n"
},
{
"code": null,
"e": 32738,
"s": 32685,
"text": "Please note that, we have to press Ctrl + w 2 times."
},
{
"code": null,
"e": 32809,
"s": 32738,
"text": "In diff window, execute following command to jump to previous change −"
},
{
"code": null,
"e": 32813,
"s": 32809,
"text": "[c\n"
},
{
"code": null,
"e": 32880,
"s": 32813,
"text": "In diff window, execute following command to jump to next change −"
},
{
"code": null,
"e": 32884,
"s": 32880,
"text": "]c\n"
},
{
"code": null,
"e": 32960,
"s": 32884,
"text": "To apply change from adjacent diff window to current diff windows execute −"
},
{
"code": null,
"e": 32970,
"s": 32960,
"text": ":diffget\n"
},
{
"code": null,
"e": 33111,
"s": 32970,
"text": "For instance, if you are in left window and you want to take change from right window to current window then you will execute above command."
},
{
"code": null,
"e": 33186,
"s": 33111,
"text": "To apply change from current diff window to adjacent diff window execute −"
},
{
"code": null,
"e": 33196,
"s": 33186,
"text": ":diffput\n"
},
{
"code": null,
"e": 33335,
"s": 33196,
"text": "For instance, if you are in left window and you want apply change from current window to right window then you will execute above command."
},
{
"code": null,
"e": 33531,
"s": 33335,
"text": "Using plug-ins, we can extends the functionality of Vim. Vim supports many plug-ins and most of them are available freely. This chapter is about Vim plug-ins and we will discuss following items −"
},
{
"code": null,
"e": 33550,
"s": 33531,
"text": "Plug-in management"
},
{
"code": null,
"e": 33571,
"s": 33550,
"text": "Some useful plug-ins"
},
{
"code": null,
"e": 33836,
"s": 33571,
"text": "This section discusses plug-in management. Vim provides various plug-ins managers but we won’t be using any plug-in manager, instead we’ll be doing all these steps manually for better understanding. Once you understand these steps, you can go with plug-in manager."
},
{
"code": null,
"e": 33885,
"s": 33836,
"text": "To install any plug-in perform following steps −"
},
{
"code": null,
"e": 33939,
"s": 33885,
"text": "Create .vim/bundle directory in user’s home directory"
},
{
"code": null,
"e": 33974,
"s": 33939,
"text": "Copy plug-in inside this directory"
},
{
"code": null,
"e": 33997,
"s": 33974,
"text": "Set runtimepath in vim"
},
{
"code": null,
"e": 34066,
"s": 33997,
"text": "Let us install badwolf plug-in in Vim. It is a color scheme for vim."
},
{
"code": null,
"e": 34223,
"s": 34066,
"text": "$ mkdir -p ~/.vim/bundle \n$ cd ~/.vim/bundle/ \n$ git clone https://github.com/sjl/badwolf.git \n$ echo \"set runtimepath^ = ~/.vim/bundle/badwolf\" > ~/.vimrc\n"
},
{
"code": null,
"e": 34297,
"s": 34223,
"text": "Now plug-in is installed, so we can use badwold color scheme as follows −"
},
{
"code": null,
"e": 34319,
"s": 34297,
"text": ":colorscheme badwolf\n"
},
{
"code": null,
"e": 34487,
"s": 34319,
"text": "If we observe carefully, plug-in is a just collection of files and if we want to update that plug-in then just update appropriate plug-in directory from ~/.vim/bundle."
},
{
"code": null,
"e": 34573,
"s": 34487,
"text": "Removing plug-in in Vim is really simple. To remove plug-in perform following steps −"
},
{
"code": null,
"e": 34617,
"s": 34573,
"text": "Remove plug-in directory from ~/.vim/bundle"
},
{
"code": null,
"e": 34650,
"s": 34617,
"text": "Modify runtimepath appropriately"
},
{
"code": null,
"e": 34692,
"s": 34650,
"text": "Below is list of some useful Vim plug-ins"
},
{
"code": null,
"e": 34715,
"s": 34692,
"text": "Disassemble C/C++ code"
},
{
"code": null,
"e": 34740,
"s": 34715,
"text": "Indenting for AWK script"
},
{
"code": null,
"e": 34760,
"s": 34740,
"text": "Vim package manager"
},
{
"code": null,
"e": 34833,
"s": 34760,
"text": "Automatically save and load vim session based on switching of git branch"
},
{
"code": null,
"e": 34867,
"s": 34833,
"text": "Provide liniting for python files"
},
{
"code": null,
"e": 34958,
"s": 34867,
"text": "We can configure Vim to use it as an IDE. In this section, we will discuss following items"
},
{
"code": null,
"e": 34978,
"s": 34958,
"text": "Syntax highlighting"
},
{
"code": null,
"e": 34996,
"s": 34978,
"text": "Smart indentation"
},
{
"code": null,
"e": 35003,
"s": 34996,
"text": "Bounce"
},
{
"code": null,
"e": 35026,
"s": 35003,
"text": "Execute shell commands"
},
{
"code": null,
"e": 35054,
"s": 35026,
"text": "Configuring ctags and csope"
},
{
"code": null,
"e": 35090,
"s": 35054,
"text": "Auto-completion and auto-suggestion"
},
{
"code": null,
"e": 35187,
"s": 35090,
"text": "Syntax highlighting is one of the important features of IDE. To enable syntax highlighting use −"
},
{
"code": null,
"e": 35199,
"s": 35187,
"text": ":syntax on\n"
},
{
"code": null,
"e": 35263,
"s": 35199,
"text": "For instance, below image show syntax highlighting for C code −"
},
{
"code": null,
"e": 35300,
"s": 35263,
"text": "To disable syntax highlighting use −"
},
{
"code": null,
"e": 35313,
"s": 35300,
"text": ":syntax off\n"
},
{
"code": null,
"e": 35383,
"s": 35313,
"text": "When syntax highlighting is disabled, it will show following output −"
},
{
"code": null,
"e": 35446,
"s": 35383,
"text": "To perform auto and smart indentation use following commands −"
},
{
"code": null,
"e": 35483,
"s": 35446,
"text": ": set autoindent \n: set smartindent\n"
},
{
"code": null,
"e": 35553,
"s": 35483,
"text": "In addition to this you can use below command to auto-indent C code −"
},
{
"code": null,
"e": 35568,
"s": 35553,
"text": ": set cindent\n"
},
{
"code": null,
"e": 35759,
"s": 35568,
"text": "If you are using programming language which uses curly braces to combine multiple statements then % key will be your friend. This key will jump between start and end of curly braces quickly."
},
{
"code": null,
"e": 35876,
"s": 35759,
"text": "For instance, you are at line 11 and execute % command then it will move cursor the line 4. Below image shows this −"
},
{
"code": null,
"e": 35925,
"s": 35876,
"text": "To execute single command from Vim editor user −"
},
{
"code": null,
"e": 35938,
"s": 35925,
"text": ":!<command>\n"
},
{
"code": null,
"e": 35998,
"s": 35938,
"text": "For instance, to execute pwd command use following syntax −"
},
{
"code": null,
"e": 36005,
"s": 35998,
"text": ":!pwd\n"
},
{
"code": null,
"e": 36086,
"s": 36005,
"text": "However, if you want to multiple shell commands then execute following command −"
},
{
"code": null,
"e": 36094,
"s": 36086,
"text": ":shell\n"
},
{
"code": null,
"e": 36269,
"s": 36094,
"text": "Above command will give you terminal access, where you can execute multiple commands. Once you are done with it, just type exit command which will return back to Vim session."
},
{
"code": null,
"e": 36485,
"s": 36269,
"text": "Combination of ctags and csope provides many useful features like go to function definition, go to function declaration, find function calls, search file, and many more. Perform below steps to configure these tool −"
},
{
"code": null,
"e": 36525,
"s": 36485,
"text": "Generate tags using following command −"
},
{
"code": null,
"e": 36541,
"s": 36525,
"text": "$ ctags <file>\n"
},
{
"code": null,
"e": 36589,
"s": 36541,
"text": "This command will generate new file namely tags"
},
{
"code": null,
"e": 36639,
"s": 36589,
"text": "Provide tag file to vim using following command −"
},
{
"code": null,
"e": 36656,
"s": 36639,
"text": ":set tags = tag\n"
},
{
"code": null,
"e": 36746,
"s": 36656,
"text": "Now move your cursor under function name and press Ctrl + ] to go to function definition."
},
{
"code": null,
"e": 36794,
"s": 36746,
"text": "Use Ctrl + t to come back to previous position."
},
{
"code": null,
"e": 36852,
"s": 36794,
"text": "To install and configure cscope perform following steps −"
},
{
"code": null,
"e": 36867,
"s": 36852,
"text": "Install cscope"
},
{
"code": null,
"e": 36898,
"s": 36867,
"text": "$ sudo apt-get install cscope\n"
},
{
"code": null,
"e": 36936,
"s": 36898,
"text": "Generate ctags and launch main window"
},
{
"code": null,
"e": 36949,
"s": 36936,
"text": "$ cscope –R\n"
},
{
"code": null,
"e": 36986,
"s": 36949,
"text": "User Ctrl + d to close cscope window"
},
{
"code": null,
"e": 37038,
"s": 36986,
"text": "We can use following commands for auto-completion −"
},
{
"code": null,
"e": 37054,
"s": 37038,
"text": "Word completion"
},
{
"code": null,
"e": 37070,
"s": 37054,
"text": "Line completion"
},
{
"code": null,
"e": 37091,
"s": 37070,
"text": "File name completion"
},
{
"code": null,
"e": 37147,
"s": 37091,
"text": "Note that we have to use these commands in insert mode."
},
{
"code": null,
"e": 37548,
"s": 37147,
"text": "Many times we need to work with remote servers. And often we edit files from those remote servers. One of the obvious solution to edit those files is to log in to the remote sever and edit files. But sometimes it is convenient to edit those files from local machine because we might have installed and configured various plug-in on our local system. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 37568,
"s": 37548,
"text": "Access remote files"
},
{
"code": null,
"e": 37600,
"s": 37568,
"text": "Understand netread and netwrite"
},
{
"code": null,
"e": 37625,
"s": 37600,
"text": "Other supported protocol"
},
{
"code": null,
"e": 37683,
"s": 37625,
"text": "Vim supports remote file editing using following syntax −"
},
{
"code": null,
"e": 37720,
"s": 37683,
"text": "$vim scp://user@server.com/filepath\n"
},
{
"code": null,
"e": 37848,
"s": 37720,
"text": "In above example vim will recognize that it has to use scp protocol and it will access file using that protocol. For instance −"
},
{
"code": null,
"e": 37903,
"s": 37848,
"text": "$ vim scp://jarvis@remote-server.com//tmp/message.txt\n"
},
{
"code": null,
"e": 38044,
"s": 37903,
"text": "Above command will open /tmp/message.txt file from remote-server. It will use SCP protocol and jarvis user’s credentials for authentication."
},
{
"code": null,
"e": 38289,
"s": 38044,
"text": "Vim supports nread and nwrite functionality which stands for net read and net write respectively. Previous section shows method to access remote file while launching Vim. But what if you are already in Vim? Then you can use following commands −"
},
{
"code": null,
"e": 38337,
"s": 38289,
"text": ":Nread scp://jarvis@localhost//tmp/message.txt\n"
},
{
"code": null,
"e": 38456,
"s": 38337,
"text": "In addition to reading we can also modify file on remote server directly. In that case use Nwrite command as follows −"
},
{
"code": null,
"e": 38505,
"s": 38456,
"text": ":Nwrite scp://jarvis@localhost//tmp/message.txt\n"
},
{
"code": null,
"e": 38560,
"s": 38505,
"text": "Once file is opened, you can use regular Vim commands."
},
{
"code": null,
"e": 38615,
"s": 38560,
"text": "In addition to SCP, Vim supports following protocols −"
},
{
"code": null,
"e": 38619,
"s": 38615,
"text": "FTP"
},
{
"code": null,
"e": 38624,
"s": 38619,
"text": "SFTP"
},
{
"code": null,
"e": 38641,
"s": 38624,
"text": "HTTP (read-only)"
},
{
"code": null,
"e": 38647,
"s": 38641,
"text": "rsync"
},
{
"code": null,
"e": 38797,
"s": 38647,
"text": "Now we got fair idea about Vim. Let us discuss few tips and tricks of Vim to improve productivity. In this section, we will discuss following items −"
},
{
"code": null,
"e": 38835,
"s": 38797,
"text": "Convert spaces to tabs and vice-versa"
},
{
"code": null,
"e": 38864,
"s": 38835,
"text": "Highlight miss-spelled words"
},
{
"code": null,
"e": 38880,
"s": 38864,
"text": "Word completion"
},
{
"code": null,
"e": 38913,
"s": 38880,
"text": "Copy line character by character"
},
{
"code": null,
"e": 38925,
"s": 38913,
"text": "Indent code"
},
{
"code": null,
"e": 38944,
"s": 38925,
"text": "Change file format"
},
{
"code": null,
"e": 39059,
"s": 38944,
"text": "If you are editing a file and you want to convert entered tab character to spaces then execute following command −"
},
{
"code": null,
"e": 39075,
"s": 39059,
"text": ":set expandtab\n"
},
{
"code": null,
"e": 39184,
"s": 39075,
"text": "Note that, this command will not change existing tabs to spaces. To achieve this execute following command −"
},
{
"code": null,
"e": 39235,
"s": 39184,
"text": ":set tabstop = 4 shiftwidth = 4 expandtab \n:retab\n"
},
{
"code": null,
"e": 39305,
"s": 39235,
"text": "In above command we are instructing Vim to convert tabs into 4 spaces"
},
{
"code": null,
"e": 39355,
"s": 39305,
"text": "To convert spaces to tabs execute below command −"
},
{
"code": null,
"e": 39381,
"s": 39355,
"text": ":set noexpandtab :retab!\n"
},
{
"code": null,
"e": 39473,
"s": 39381,
"text": "We can instruct Vim to highlight miss-spelled words. To do this execute following command −"
},
{
"code": null,
"e": 39485,
"s": 39473,
"text": ":set spell\n"
},
{
"code": null,
"e": 39533,
"s": 39485,
"text": "Below image highlights misspelled word in Vim −"
},
{
"code": null,
"e": 39620,
"s": 39533,
"text": "Vim also provides word completion. For this execute following command in insert mode −"
},
{
"code": null,
"e": 39630,
"s": 39620,
"text": "Ctrl + p\n"
},
{
"code": null,
"e": 39700,
"s": 39630,
"text": "Use following command to copy and paste line character by character −"
},
{
"code": null,
"e": 39745,
"s": 39700,
"text": "Copy and paste text located above the cursor"
},
{
"code": null,
"e": 39790,
"s": 39745,
"text": "Copy and paste text located below the cursor"
},
{
"code": null,
"e": 39845,
"s": 39790,
"text": "Note the we have to use these commands in insert mode."
},
{
"code": null,
"e": 39915,
"s": 39845,
"text": "If you have un-indented code to indent it execute following command −"
},
{
"code": null,
"e": 39919,
"s": 39915,
"text": "=%\n"
},
{
"code": null,
"e": 39974,
"s": 39919,
"text": "For instance, if you have un-indented code like this −"
},
{
"code": null,
"e": 40048,
"s": 39974,
"text": "Then go to line 4 and execute =% command. It will indent code like this −"
},
{
"code": null,
"e": 40106,
"s": 40048,
"text": "To change file format to UNIX execute following command −"
},
{
"code": null,
"e": 40122,
"s": 40106,
"text": ":set ff = unix\n"
},
{
"code": null,
"e": 40179,
"s": 40122,
"text": "To change file format to DOS execute following command −"
},
{
"code": null,
"e": 40194,
"s": 40179,
"text": ":set ff = dos\n"
},
{
"code": null,
"e": 40298,
"s": 40194,
"text": "We can personalize Vim according to our requirement. In this section, we will discuss following items −"
},
{
"code": null,
"e": 40318,
"s": 40298,
"text": "Configuration files"
},
{
"code": null,
"e": 40333,
"s": 40318,
"text": "Changing fonts"
},
{
"code": null,
"e": 40355,
"s": 40333,
"text": "Changing color scheme"
},
{
"code": null,
"e": 40377,
"s": 40355,
"text": "Personal highlighting"
},
{
"code": null,
"e": 40389,
"s": 40377,
"text": "Status line"
},
{
"code": null,
"e": 40573,
"s": 40389,
"text": "For Vim configuration files can be at user level or global level. User specific settings will be stored in user level files while global settings will be stored in global level files."
},
{
"code": null,
"e": 40586,
"s": 40573,
"text": "Global vimrc"
},
{
"code": null,
"e": 40652,
"s": 40586,
"text": "To find out global vimrc file execute following command in editor"
},
{
"code": null,
"e": 40664,
"s": 40652,
"text": ":echo $VIM\n"
},
{
"code": null,
"e": 40667,
"s": 40664,
"text": "OR"
},
{
"code": null,
"e": 40682,
"s": 40667,
"text": ":echo \\%VIM\\%\n"
},
{
"code": null,
"e": 40809,
"s": 40682,
"text": "On Linux this file will be located under /usr/share/vim directory while on Window it will be under C:\\Program Files\\Vim folder"
},
{
"code": null,
"e": 40821,
"s": 40809,
"text": "Local vimrc"
},
{
"code": null,
"e": 41015,
"s": 40821,
"text": "Local vimrc will be located under user’s home directory. For instance, on Linux it will be under /home/<USER> directory while on Windows it will be under C:\\Documents and Setting\\<USER>/ folder"
},
{
"code": null,
"e": 41098,
"s": 41015,
"text": "Note that, on Windows file name will be _vimrc whereas on Linux it will be .vimrc."
},
{
"code": null,
"e": 41112,
"s": 41098,
"text": "Global gvimrc"
},
{
"code": null,
"e": 41240,
"s": 41112,
"text": "On Linux this file will be located under /usr/share/gvim directory while on Window it will be under C:\\Program Files\\Vim folder"
},
{
"code": null,
"e": 41253,
"s": 41240,
"text": "Local gvimrc"
},
{
"code": null,
"e": 41448,
"s": 41253,
"text": "Local gvimrc will be located under user’s home directory. For instance, on Linux it will be under /home/<USER> directory while on Windows it will be under C:\\Documents and Setting\\<USER>/ folder"
},
{
"code": null,
"e": 41536,
"s": 41448,
"text": "Note that, on Windows file name will be _gvimrc whereas on Linux it will be 55 .gvimrc."
},
{
"code": null,
"e": 41651,
"s": 41536,
"text": "exrc files are used for backward compatibility. These files are ignored if either vimrc or gvimrc file is present."
},
{
"code": null,
"e": 41663,
"s": 41651,
"text": "Global exrc"
},
{
"code": null,
"e": 41790,
"s": 41663,
"text": "On Linux this file will be located under /usr/share/vim directory while on Window it will be under C:\\Program Files\\Vim folder"
},
{
"code": null,
"e": 41801,
"s": 41790,
"text": "Local exrc"
},
{
"code": null,
"e": 41999,
"s": 41801,
"text": "Local exrc will be located under user’s home directory. For instance, on Linux it will be under /home/<USER> directory while on Windows it will be under C:\\Documents and Setting\\<USER>/_exrc folder"
},
{
"code": null,
"e": 42050,
"s": 41999,
"text": "To change font execute following command in gVim −"
},
{
"code": null,
"e": 42074,
"s": 42050,
"text": ":set guifont = courier\n"
},
{
"code": null,
"e": 42117,
"s": 42074,
"text": "Above command will change font to courier."
},
{
"code": null,
"e": 42168,
"s": 42117,
"text": "To change color scheme execute following command −"
},
{
"code": null,
"e": 42188,
"s": 42168,
"text": ":colorscheme <tab>\n"
},
{
"code": null,
"e": 42264,
"s": 42188,
"text": "When you press tab character, it will show available color schemes for Vim."
},
{
"code": null,
"e": 42325,
"s": 42264,
"text": "Execute below command to highlight columns greater than 73 −"
},
{
"code": null,
"e": 42354,
"s": 42325,
"text": ":match ErrorMsg /\\%>73v.\\+/\n"
},
{
"code": null,
"e": 42379,
"s": 42354,
"text": "Below image shows this −"
},
{
"code": null,
"e": 42418,
"s": 42379,
"text": "Below is description of this command −"
},
{
"code": null,
"e": 42437,
"s": 42418,
"text": "Match after column"
},
{
"code": null,
"e": 42459,
"s": 42437,
"text": "This is column number"
},
{
"code": null,
"e": 42499,
"s": 42459,
"text": "It should work for virtual columns only"
},
{
"code": null,
"e": 42528,
"s": 42499,
"text": "Match one or more characters"
},
{
"code": null,
"e": 42575,
"s": 42528,
"text": "To add line number execute following command −"
},
{
"code": null,
"e": 42588,
"s": 42575,
"text": ":set number\n"
},
{
"code": null,
"e": 42632,
"s": 42588,
"text": "To disable this execute following command −"
},
{
"code": null,
"e": 42647,
"s": 42632,
"text": ":set nonumber\n"
},
{
"code": null,
"e": 42695,
"s": 42647,
"text": "To set number width execute following command −"
},
{
"code": null,
"e": 42721,
"s": 42695,
"text": ":set numberwidth = <num>\n"
},
{
"code": null,
"e": 42771,
"s": 42721,
"text": "To enable spell check execute following command −"
},
{
"code": null,
"e": 42783,
"s": 42771,
"text": ":set spell\n"
},
{
"code": null,
"e": 42837,
"s": 42783,
"text": "And to set spell language execute following command −"
},
{
"code": null,
"e": 42866,
"s": 42837,
"text": ":set spelllang = <language>\n"
},
{
"code": null,
"e": 42915,
"s": 42866,
"text": "For example to set German use following comman −"
},
{
"code": null,
"e": 42936,
"s": 42915,
"text": ":set spelllang = de\n"
},
{
"code": null,
"e": 43060,
"s": 42936,
"text": "Using abbreviation we can create shortcuts for long string. For instance below command creates abbreviation namely “quick”."
},
{
"code": null,
"e": 43093,
"s": 43060,
"text": ":abbr quick the quick brown fox\n"
},
{
"code": null,
"e": 43184,
"s": 43093,
"text": "If you type “quick” and press tab then it will be replaced by “the quick brown fox” string"
},
{
"code": null,
"e": 43262,
"s": 43184,
"text": "We can use this to correct some typos. For instance below command does this −"
},
{
"code": null,
"e": 43276,
"s": 43262,
"text": ":abr teh the\n"
},
{
"code": null,
"e": 43372,
"s": 43276,
"text": "Status line is shown at the bottom of editor. To enable status line execute following command −"
},
{
"code": null,
"e": 43393,
"s": 43372,
"text": ":set laststatus = 2\n"
},
{
"code": null,
"e": 43456,
"s": 43393,
"text": "To remove this for current session execute following command −"
},
{
"code": null,
"e": 43477,
"s": 43456,
"text": ":set laststatus = 0\n"
},
{
"code": null,
"e": 43730,
"s": 43477,
"text": "Vim is really powerful editor and now you can get your hands dirty with it. Mastering Vim will really improve your productively. Using Vim you can solve many complex tasks with few commands. You can refer following documentation to know more about Vim."
},
{
"code": null,
"e": 43799,
"s": 43730,
"text": "You can access Vim’s official documentation from following website −"
},
{
"code": null,
"e": 43820,
"s": 43799,
"text": "https://www.vim.org/"
},
{
"code": null,
"e": 43955,
"s": 43820,
"text": "You can enhance vim further by writing scripts to it. It has its own scripting language. To know more about it, visit following link −"
},
{
"code": null,
"e": 44000,
"s": 43955,
"text": "https://vim.sourceforge.io/scripts/index.php"
},
{
"code": null,
"e": 44209,
"s": 44000,
"text": "Vim plug-ins further extend its functionality and makes you more productive. You can install, configure and even write plug-ins for Vim. You can refer documentation regarding this from their official website."
},
{
"code": null,
"e": 44244,
"s": 44209,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 44258,
"s": 44244,
"text": " Jason Cannon"
},
{
"code": null,
"e": 44265,
"s": 44258,
"text": " Print"
},
{
"code": null,
"e": 44276,
"s": 44265,
"text": " Add Notes"
}
] |
Logistic Regression — Detailed Overview | by Saishruthi Swaminathan | Towards Data Science
|
Logistic Regression was used in the biological sciences in early twentieth century. It was then used in many social science applications. Logistic Regression is used when the dependent variable(target) is categorical.
For example,
To predict whether an email is spam (1) or (0)
Whether the tumor is malignant (1) or not (0)
Consider a scenario where we need to classify whether an email is spam or not. If we use linear regression for this problem, there is a need for setting up a threshold based on which classification can be done. Say if the actual class is malignant, predicted continuous value 0.4 and the threshold value is 0.5, the data point will be classified as not malignant which can lead to serious consequence in real time.
From this example, it can be inferred that linear regression is not suitable for classification problem. Linear regression is unbounded, and this brings logistic regression into picture. Their value strictly ranges from 0 to 1.
Simple Logistic Regression
(Full Source code: https://github.com/SSaishruthi/LogisticRegression_Vectorized_Implementation/blob/master/Logistic_Regression.ipynb)
Model
Output = 0 or 1
Hypothesis => Z = WX + B
hΘ(x) = sigmoid (Z)
Sigmoid Function
If ‘Z’ goes to infinity, Y(predicted) will become 1 and if ‘Z’ goes to negative infinity, Y(predicted) will become 0.
Analysis of the hypothesis
The output from the hypothesis is the estimated probability. This is used to infer how confident can predicted value be actual value when given an input X. Consider the below example,
X = [x0 x1] = [1 IP-Address]
Based on the x1 value, let’s say we obtained the estimated probability to be 0.8. This tells that there is 80% chance that an email will be spam.
Mathematically this can be written as,
This justifies the name ‘logistic regression’. Data is fit into linear regression model, which then be acted upon by a logistic function predicting the target categorical dependent variable.
Types of Logistic Regression
1. Binary Logistic Regression
The categorical response has only two 2 possible outcomes. Example: Spam or Not
2. Multinomial Logistic Regression
Three or more categories without ordering. Example: Predicting which food is preferred more (Veg, Non-Veg, Vegan)
3. Ordinal Logistic Regression
Three or more categories with ordering. Example: Movie rating from 1 to 5
Decision Boundary
To predict which class a data belongs, a threshold can be set. Based upon this threshold, the obtained estimated probability is classified into classes.
Say, if predicted_value ≥ 0.5, then classify email as spam else as not spam.
Decision boundary can be linear or non-linear. Polynomial order can be increased to get complex decision boundary.
Cost Function
Why cost function which has been used for linear can not be used for logistic?
Linear regression uses mean squared error as its cost function. If this is used for logistic regression, then it will be a non-convex function of parameters (theta). Gradient descent will converge into global minimum only if the function is convex.
Cost function explanation
Simplified cost function
Why this cost function?
This negative function is because when we train, we need to maximize the probability by minimizing loss function. Decreasing the cost will increase the maximum likelihood assuming that samples are drawn from an identically independent distribution.
Deriving the formula for Gradient Descent Algorithm
Python Implementation
def weightInitialization(n_features): w = np.zeros((1,n_features)) b = 0 return w,bdef sigmoid_activation(result): final_result = 1/(1+np.exp(-result)) return final_resultdef model_optimize(w, b, X, Y): m = X.shape[0] #Prediction final_result = sigmoid_activation(np.dot(w,X.T)+b) Y_T = Y.T cost = (-1/m)*(np.sum((Y_T*np.log(final_result)) + ((1-Y_T)*(np.log(1-final_result))))) # #Gradient calculation dw = (1/m)*(np.dot(X.T, (final_result-Y.T).T)) db = (1/m)*(np.sum(final_result-Y.T)) grads = {"dw": dw, "db": db} return grads, costdef model_predict(w, b, X, Y, learning_rate, no_iterations): costs = [] for i in range(no_iterations): # grads, cost = model_optimize(w,b,X,Y) # dw = grads["dw"] db = grads["db"] #weight update w = w - (learning_rate * (dw.T)) b = b - (learning_rate * db) # if (i % 100 == 0): costs.append(cost) #print("Cost after %i iteration is %f" %(i, cost)) #final parameters coeff = {"w": w, "b": b} gradient = {"dw": dw, "db": db} return coeff, gradient, costsdef predict(final_pred, m): y_pred = np.zeros((1,m)) for i in range(final_pred.shape[1]): if final_pred[0][i] > 0.5: y_pred[0][i] = 1 return y_pred
Cost vs Number_of_Iterations
Train and test accuracy of the system is 100 %
This implementation is for binary logistic regression. For data with more than 2 classes, softmax regression has to be used.
This is an educational post and inspired from Prof. Andrew Ng’s deep learning course.
Full code : https://github.com/SSaishruthi/LogisticRegression_Vectorized_Implementation/blob/master/Logistic_Regression.ipynb
|
[
{
"code": null,
"e": 390,
"s": 172,
"text": "Logistic Regression was used in the biological sciences in early twentieth century. It was then used in many social science applications. Logistic Regression is used when the dependent variable(target) is categorical."
},
{
"code": null,
"e": 403,
"s": 390,
"text": "For example,"
},
{
"code": null,
"e": 450,
"s": 403,
"text": "To predict whether an email is spam (1) or (0)"
},
{
"code": null,
"e": 496,
"s": 450,
"text": "Whether the tumor is malignant (1) or not (0)"
},
{
"code": null,
"e": 911,
"s": 496,
"text": "Consider a scenario where we need to classify whether an email is spam or not. If we use linear regression for this problem, there is a need for setting up a threshold based on which classification can be done. Say if the actual class is malignant, predicted continuous value 0.4 and the threshold value is 0.5, the data point will be classified as not malignant which can lead to serious consequence in real time."
},
{
"code": null,
"e": 1139,
"s": 911,
"text": "From this example, it can be inferred that linear regression is not suitable for classification problem. Linear regression is unbounded, and this brings logistic regression into picture. Their value strictly ranges from 0 to 1."
},
{
"code": null,
"e": 1166,
"s": 1139,
"text": "Simple Logistic Regression"
},
{
"code": null,
"e": 1300,
"s": 1166,
"text": "(Full Source code: https://github.com/SSaishruthi/LogisticRegression_Vectorized_Implementation/blob/master/Logistic_Regression.ipynb)"
},
{
"code": null,
"e": 1306,
"s": 1300,
"text": "Model"
},
{
"code": null,
"e": 1322,
"s": 1306,
"text": "Output = 0 or 1"
},
{
"code": null,
"e": 1347,
"s": 1322,
"text": "Hypothesis => Z = WX + B"
},
{
"code": null,
"e": 1367,
"s": 1347,
"text": "hΘ(x) = sigmoid (Z)"
},
{
"code": null,
"e": 1384,
"s": 1367,
"text": "Sigmoid Function"
},
{
"code": null,
"e": 1502,
"s": 1384,
"text": "If ‘Z’ goes to infinity, Y(predicted) will become 1 and if ‘Z’ goes to negative infinity, Y(predicted) will become 0."
},
{
"code": null,
"e": 1529,
"s": 1502,
"text": "Analysis of the hypothesis"
},
{
"code": null,
"e": 1713,
"s": 1529,
"text": "The output from the hypothesis is the estimated probability. This is used to infer how confident can predicted value be actual value when given an input X. Consider the below example,"
},
{
"code": null,
"e": 1742,
"s": 1713,
"text": "X = [x0 x1] = [1 IP-Address]"
},
{
"code": null,
"e": 1888,
"s": 1742,
"text": "Based on the x1 value, let’s say we obtained the estimated probability to be 0.8. This tells that there is 80% chance that an email will be spam."
},
{
"code": null,
"e": 1927,
"s": 1888,
"text": "Mathematically this can be written as,"
},
{
"code": null,
"e": 2118,
"s": 1927,
"text": "This justifies the name ‘logistic regression’. Data is fit into linear regression model, which then be acted upon by a logistic function predicting the target categorical dependent variable."
},
{
"code": null,
"e": 2147,
"s": 2118,
"text": "Types of Logistic Regression"
},
{
"code": null,
"e": 2177,
"s": 2147,
"text": "1. Binary Logistic Regression"
},
{
"code": null,
"e": 2257,
"s": 2177,
"text": "The categorical response has only two 2 possible outcomes. Example: Spam or Not"
},
{
"code": null,
"e": 2292,
"s": 2257,
"text": "2. Multinomial Logistic Regression"
},
{
"code": null,
"e": 2406,
"s": 2292,
"text": "Three or more categories without ordering. Example: Predicting which food is preferred more (Veg, Non-Veg, Vegan)"
},
{
"code": null,
"e": 2437,
"s": 2406,
"text": "3. Ordinal Logistic Regression"
},
{
"code": null,
"e": 2511,
"s": 2437,
"text": "Three or more categories with ordering. Example: Movie rating from 1 to 5"
},
{
"code": null,
"e": 2529,
"s": 2511,
"text": "Decision Boundary"
},
{
"code": null,
"e": 2682,
"s": 2529,
"text": "To predict which class a data belongs, a threshold can be set. Based upon this threshold, the obtained estimated probability is classified into classes."
},
{
"code": null,
"e": 2759,
"s": 2682,
"text": "Say, if predicted_value ≥ 0.5, then classify email as spam else as not spam."
},
{
"code": null,
"e": 2874,
"s": 2759,
"text": "Decision boundary can be linear or non-linear. Polynomial order can be increased to get complex decision boundary."
},
{
"code": null,
"e": 2888,
"s": 2874,
"text": "Cost Function"
},
{
"code": null,
"e": 2967,
"s": 2888,
"text": "Why cost function which has been used for linear can not be used for logistic?"
},
{
"code": null,
"e": 3216,
"s": 2967,
"text": "Linear regression uses mean squared error as its cost function. If this is used for logistic regression, then it will be a non-convex function of parameters (theta). Gradient descent will converge into global minimum only if the function is convex."
},
{
"code": null,
"e": 3242,
"s": 3216,
"text": "Cost function explanation"
},
{
"code": null,
"e": 3267,
"s": 3242,
"text": "Simplified cost function"
},
{
"code": null,
"e": 3291,
"s": 3267,
"text": "Why this cost function?"
},
{
"code": null,
"e": 3540,
"s": 3291,
"text": "This negative function is because when we train, we need to maximize the probability by minimizing loss function. Decreasing the cost will increase the maximum likelihood assuming that samples are drawn from an identically independent distribution."
},
{
"code": null,
"e": 3592,
"s": 3540,
"text": "Deriving the formula for Gradient Descent Algorithm"
},
{
"code": null,
"e": 3614,
"s": 3592,
"text": "Python Implementation"
},
{
"code": null,
"e": 4965,
"s": 3614,
"text": "def weightInitialization(n_features): w = np.zeros((1,n_features)) b = 0 return w,bdef sigmoid_activation(result): final_result = 1/(1+np.exp(-result)) return final_resultdef model_optimize(w, b, X, Y): m = X.shape[0] #Prediction final_result = sigmoid_activation(np.dot(w,X.T)+b) Y_T = Y.T cost = (-1/m)*(np.sum((Y_T*np.log(final_result)) + ((1-Y_T)*(np.log(1-final_result))))) # #Gradient calculation dw = (1/m)*(np.dot(X.T, (final_result-Y.T).T)) db = (1/m)*(np.sum(final_result-Y.T)) grads = {\"dw\": dw, \"db\": db} return grads, costdef model_predict(w, b, X, Y, learning_rate, no_iterations): costs = [] for i in range(no_iterations): # grads, cost = model_optimize(w,b,X,Y) # dw = grads[\"dw\"] db = grads[\"db\"] #weight update w = w - (learning_rate * (dw.T)) b = b - (learning_rate * db) # if (i % 100 == 0): costs.append(cost) #print(\"Cost after %i iteration is %f\" %(i, cost)) #final parameters coeff = {\"w\": w, \"b\": b} gradient = {\"dw\": dw, \"db\": db} return coeff, gradient, costsdef predict(final_pred, m): y_pred = np.zeros((1,m)) for i in range(final_pred.shape[1]): if final_pred[0][i] > 0.5: y_pred[0][i] = 1 return y_pred"
},
{
"code": null,
"e": 4994,
"s": 4965,
"text": "Cost vs Number_of_Iterations"
},
{
"code": null,
"e": 5041,
"s": 4994,
"text": "Train and test accuracy of the system is 100 %"
},
{
"code": null,
"e": 5166,
"s": 5041,
"text": "This implementation is for binary logistic regression. For data with more than 2 classes, softmax regression has to be used."
},
{
"code": null,
"e": 5252,
"s": 5166,
"text": "This is an educational post and inspired from Prof. Andrew Ng’s deep learning course."
}
] |
Image-to-Image Translation using Pix2Pix - GeeksforGeeks
|
27 Jan, 2022
pix2pix was proposed by researchers at UC Berkeley in 2017. It uses conditional Generative Adversarial Network to perform the image-to-image translation task (i.e. converting one image to another, such facades to buildings and Google Maps to Google Earth, etc.
The pix2pix uses conditional generative adversarial networks (conditional-GAN) in its architecture. The reason for that is that even if we trained a model with a simple L1/L2 loss function for a particular image-to-image translation task, this might not understand the nuances of the images.
Generator:
U-Net architecture
The architecture used in the generator was U-Net architecture. It is similar to Encoder-Decoder architecture except for the use of skip-connections in the encoder-decoder architecture. The use of skip-connection makes this
Encoder Architecture: The Encoder network of the Generator network has seven convolutional blocks. Each convolutional block has a convolutional layer, followed by a LeakyRelu activation function (with a slope of 0.2 in the paper). Each convolutional block also has a batch normalization layer except the first convolutional layer.
Decoder Architecture: The Decoder network of the Generator network has seven Transpose convolutional block. Each upsampling convolutional block (Dconv) has an upsampling layer, followed by a convolutional layer, a batch normalization layer, and a ReLU activation function.
The generator architecture contains skip connections between each layer i and layer n − i, where n is the total number of layers. Each skip connection simply concatenates all channels at layer i with those at layer n − i.
Discriminator:
Patch GAN discriminator
The discriminator use Patch GAN architecture, which is also used Style GAN architecture. This PatchGAN architecture contains a number of Transpose convolutional blocks. This PatchGAN architecture takes an NxN part of the image and tries to find whether it is real and fake. This discriminator is applied convolutionally across the whole image, averaging it to generate the result of the discriminator D.
Each block of the discriminator contains a convolution layer, batch norm layer, and LeakyReLU. This discriminator receives two inputs:
The input image and Target Image (which discriminator should classify as real)
The input image and Generated Image (which discriminator should classify as fake).
THe PatchGAN is used because the author argues that it will be able to preserve high-frequency details in the image, with low-frequency details that can be focused by L1-loss.
Generator Loss:
The generator loss used in the paper is the linear combination of L1- loss between generated image, target image, and GAN loss as we define above.
Our generated loss will be:
Therefore, our total loss for generator
Discriminator Loss
The discriminator loss takes two inputs real image and generated image:
real_loss is a sigmoid cross-entropy loss of the real images and an array of ones(since these are the real images).
generated_loss is a sigmoid cross-entropy loss of the generated images and an array of zeros(since these are the fake images)
The total loss is the sum of the real_loss and generated_loss.
Implementation:
First, we download and preprocess the image dataset. We will use the CMP Facade dataset that was provided Czech Technical University and processed by the authors of the pix2pix paper. We will preprocess the dataset before training.
Code:
python3
# import necessary packagesimport tensorflow as tf import osimport time from matplotlib import pyplot as pltfrom IPython import display# install tensorboard ! pip install -U tensorboard # download datasetURL = "https://people.eecs.berkeley.edu/~tinghuiz / projects / pix2pix / datasets / facades.tar.gz" path_to_zip = tf.keras.utils.get_file('facades.tar.gz', origin = URL, extract = True) PATH = os.path.join(os.path.dirname(path_to_zip), 'facades/') # Define Training variableBUFFER_SIZE = 400BATCH_SIZE = 1IMG_WIDTH = 256IMG_HEIGHT = 256 # load the images from datasetdef load(image_file): image = tf.io.read_file(image_file) image = tf.image.decode_jpeg(image) w = tf.shape(image)[1] w = w // 2 real_image = image[:, :w, :] input_image = image[:, w:, :] input_image = tf.cast(input_image, tf.float32) real_image = tf.cast(real_image, tf.float32) return input_image, real_image # resize the images to provided width and heightdef resize(input_image, real_image, height, width): input_image = tf.image.resize(input_image, [height, width], method = tf.image.ResizeMethod.NEAREST_NEIGHBOR) real_image = tf.image.resize(real_image, [height, width], method = tf.image.ResizeMethod.NEAREST_NEIGHBOR) return input_image, real_image """function to stack (input, real) images and apply random crop on them to cropto (256, 256)"""def random_crop(input_image, real_image): stacked_image = tf.stack([input_image, real_image], axis = 0) cropped_image = tf.image.random_crop( stacked_image, size =[2, IMG_HEIGHT, IMG_WIDTH, 3]) return cropped_image[0], cropped_image[1] """Before training, we need to perform random jittering on the datasetAccording to the paper, this random jittering contains 3 steps --> Resize the image to bigger size --> Random crop the image to target size of model --> Random Flip on the images """ @tf.function()def random_jitter(input_image, real_image): # resizing to 286 x 286 x 3 input_image, real_image = resize(input_image, real_image, 286, 286) # randomly cropping to 256 x 256 x 3 input_image, real_image = random_crop(input_image, real_image) if tf.random.uniform(()) > 0.5: # random mirroring input_image = tf.image.flip_left_right(input_image) real_image = tf.image.flip_left_right(real_image) return input_image, real_image
Now, we load train and test data using the function we defined above.
Code:
python3
# function to Load image from train data"""On train data, we performed random jitter and normalize,but since we don't need any augmentation on test_data, we just resize it"""def load_image_train(image_file): input_image, real_image = load(image_file) input_image, real_image = random_jitter(input_image, real_image) input_image, real_image = normalize(input_image, real_image) return input_image, real_image# function to Load images from test datadef load_image_test(image_file): input_image, real_image = load(image_file) input_image, real_image = resize(input_image, real_image, IMG_HEIGHT, IMG_WIDTH) input_image, real_image = normalize(input_image, real_image) return input_image, real_image # apply the above load_images_train function on train datatrain_dataset = tf.data.Dataset.list_files(PATH+'train/*.jpg')train_dataset = train_dataset.map(load_image_train, num_parallel_calls = tf.data.experimental.AUTOTUNE)train_dataset = train_dataset.shuffle(BUFFER_SIZE)train_dataset = train_dataset.batch(BATCH_SIZE) # apply the above load_images_test function on test datatest_dataset = tf.data.Dataset.list_files(PATH+'test/*.jpg')test_dataset = test_dataset.map(load_image_test)test_dataset = test_dataset.batch(BATCH_SIZE)
After performing data processing, Now, we write the code for generator architecture. This generator block contains 2 parts encoder block and decoder block. The encoder block contains a downsampling convolution block and the decoder block contains an upsampling transpose convolution block.
Generator architecture
Now we define our architecture for the discriminator. The discriminator architecture uses a PatchGAN model. For this architecture, we can use the above downsampling convolution block we defined. The loss of the discriminator is the sum of real loss (sigmoid cross-entropy b/w real image and array of 1s) and generated loss (sigmoid cross-entropy b/w generated image and an array of 0s).
Code:
python3
# code for discriminator architecture"""FOr more details look into architecture section"""def Discriminator(): initializer = tf.random_normal_initializer(0., 0.02) inp = tf.keras.layers.Input(shape =[256, 256, 3], name ='input_image') tar = tf.keras.layers.Input(shape =[256, 256, 3], name ='target_image') x = tf.keras.layers.concatenate([inp, tar]) # (batch_size, 256, 256, channels * 2) down1 = downsample(64, 4, False)(x) # (batch_size, 128, 128, 64) down2 = downsample(128, 4)(down1) # (batch_size, 64, 64, 128) down3 = downsample(256, 4)(down2) # (batch_size, 32, 32, 256) zero_pad1 = tf.keras.layers.ZeroPadding2D()(down3) # (batch_size, 34, 34, 256) conv = tf.keras.layers.Conv2D(512, 4, strides = 1, kernel_initializer = initializer, use_bias = False)(zero_pad1) # (batch_size, 31, 31, 512) batchnorm1 = tf.keras.layers.BatchNormalization()(conv) leaky_relu = tf.keras.layers.LeakyReLU()(batchnorm1) zero_pad2 = tf.keras.layers.ZeroPadding2D()(leaky_relu) # (batch_size, 33, 33, 512) last = tf.keras.layers.Conv2D(1, 4, strides = 1, kernel_initializer = initializer)(zero_pad2) # (batch_size, 30, 30, 1) return tf.keras.Model(inputs =[inp, tar], outputs = last) # define discriminator loss functiondisc_ce_loss = tf.keras.losses.BinaryCrossentropy(from_logits = True)def discriminator_loss(disc_real_output, disc_generated_output): real_loss = disc_ce_loss(tf.ones_like(disc_real_output), disc_real_output) generated_loss = disc_ce_loss(tf.zeros_like(disc_generated_output), disc_generated_output) total_disc_loss = real_loss + generated_loss return total_disc_loss discriminator = Discriminator()tf.keras.utils.plot_model(discriminator, show_shapes = True)
Discriminator Architecture
In this step, we define optimizers and checkpoints. We will use Adam optimizer in both generator discriminator.
Code:
python3
# define generator and discriminator architecturegenerator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1 = 0.5)discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1 = 0.5) # Create the model checkpointcheckpoint_dir = './train_checkpoints'checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")checkpoint = tf.train.Checkpoint(generator_optimizer = generator_optimizer, discriminator_optimizer = discriminator_optimizer, generator = generator, discriminator = discriminator)
Now, we define the training procedure. The training procedure consists of the following steps:For each example input, we passed the image as input to the generator to get the generated image.The discriminator receives the input_image and the generated image as the first input. The second input is the input_image and the target_image.Next, we calculate the generator and the discriminator loss.Then, we calculate the gradients of loss with respect to both the generator and the discriminator variables(inputs) and apply those to the optimizer.
For each example input, we passed the image as input to the generator to get the generated image.
The discriminator receives the input_image and the generated image as the first input. The second input is the input_image and the target_image.
Next, we calculate the generator and the discriminator loss.
Then, we calculate the gradients of loss with respect to both the generator and the discriminator variables(inputs) and apply those to the optimizer.
Code:
python3
# Define training procedureEPOCHS = 30 import datetimelog_dir ="logs/" summary_writer = tf.summary.create_file_writer( log_dir + "fit/" + datetime.datetime.now().strftime("% Y % m % d-% H % M % S")) @tf.functiondef train_step(input_image, target, epoch): with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: gen_output = generator(input_image, training = True) disc_real_output = discriminator([input_image, target], training = True) disc_generated_output = discriminator([input_image, gen_output], training = True) gen_total_loss, gen_gan_loss, gen_l1_loss = generator_loss(disc_generated_output, gen_output, target) disc_loss = discriminator_loss(disc_real_output, disc_generated_output) generator_gradients = gen_tape.gradient(gen_total_loss, generator.trainable_variables) discriminator_gradients = disc_tape.gradient(disc_loss, discriminator.trainable_variables) generator_optimizer.apply_gradients(zip(generator_gradients, generator.trainable_variables)) discriminator_optimizer.apply_gradients(zip(discriminator_gradients, discriminator.trainable_variables)) with summary_writer.as_default(): tf.summary.scalar('gen_total_loss', gen_total_loss, step = epoch) tf.summary.scalar('gen_gan_loss', gen_gan_loss, step = epoch) tf.summary.scalar('gen_l1_loss', gen_l1_loss, step = epoch) tf.summary.scalar('disc_loss', disc_loss, step = epoch) def fit(train_ds, epochs, test_ds): for epoch in range(epochs): % time for example_input, example_target in test_ds.take(1): generate_images(generator, example_input, example_target) print("Epoch: ", epoch) # Train for n, (input_image, target) in train_ds.enumerate(): train_step(input_image, target, epoch) print() # saving (checkpoint) the model every 10 epochs if (epoch + 1) % 10 == 0: checkpoint.save(file_prefix = checkpoint_prefix) checkpoint.save(file_prefix = checkpoint_prefix)fit(train_dataset, EPOCHS, test_dataset)
Now, we use the generator of the trained model on test data to generate the images.
Code:
python3
# code to plot resultsdef generate_images(model, test_input, tar): prediction = model(test_input, training = True) plt.figure(figsize =(15, 15)) display_list = [test_input[0], tar[0], prediction[0]] title = ['Input Image', 'Ground Truth', 'Predicted Image'] for i in range(3): plt.subplot(1, 3, i + 1) plt.title(title[i]) # getting the pixel values between [0, 1] to plot it. plt.imshow(display_list[i] * 0.5 + 0.5) plt.axis('off') plt.show() for inputs, tar in test_dataset.take(5): generate_images(generator, inputs, tar)
Results
References:
Pix2Pix paper
TensorFlow implementation on Pix2pix
clintra
simmytarika5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Reinforcement learning
Decision Tree Introduction with example
Python | Decision tree implementation
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": 26149,
"s": 26121,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 26411,
"s": 26149,
"text": "pix2pix was proposed by researchers at UC Berkeley in 2017. It uses conditional Generative Adversarial Network to perform the image-to-image translation task (i.e. converting one image to another, such facades to buildings and Google Maps to Google Earth, etc. "
},
{
"code": null,
"e": 26703,
"s": 26411,
"text": "The pix2pix uses conditional generative adversarial networks (conditional-GAN) in its architecture. The reason for that is that even if we trained a model with a simple L1/L2 loss function for a particular image-to-image translation task, this might not understand the nuances of the images."
},
{
"code": null,
"e": 26714,
"s": 26703,
"text": "Generator:"
},
{
"code": null,
"e": 26733,
"s": 26714,
"text": "U-Net architecture"
},
{
"code": null,
"e": 26957,
"s": 26733,
"text": "The architecture used in the generator was U-Net architecture. It is similar to Encoder-Decoder architecture except for the use of skip-connections in the encoder-decoder architecture. The use of skip-connection makes this "
},
{
"code": null,
"e": 27288,
"s": 26957,
"text": "Encoder Architecture: The Encoder network of the Generator network has seven convolutional blocks. Each convolutional block has a convolutional layer, followed by a LeakyRelu activation function (with a slope of 0.2 in the paper). Each convolutional block also has a batch normalization layer except the first convolutional layer."
},
{
"code": null,
"e": 27561,
"s": 27288,
"text": "Decoder Architecture: The Decoder network of the Generator network has seven Transpose convolutional block. Each upsampling convolutional block (Dconv) has an upsampling layer, followed by a convolutional layer, a batch normalization layer, and a ReLU activation function."
},
{
"code": null,
"e": 27783,
"s": 27561,
"text": "The generator architecture contains skip connections between each layer i and layer n − i, where n is the total number of layers. Each skip connection simply concatenates all channels at layer i with those at layer n − i."
},
{
"code": null,
"e": 27798,
"s": 27783,
"text": "Discriminator:"
},
{
"code": null,
"e": 27822,
"s": 27798,
"text": "Patch GAN discriminator"
},
{
"code": null,
"e": 28226,
"s": 27822,
"text": "The discriminator use Patch GAN architecture, which is also used Style GAN architecture. This PatchGAN architecture contains a number of Transpose convolutional blocks. This PatchGAN architecture takes an NxN part of the image and tries to find whether it is real and fake. This discriminator is applied convolutionally across the whole image, averaging it to generate the result of the discriminator D."
},
{
"code": null,
"e": 28361,
"s": 28226,
"text": "Each block of the discriminator contains a convolution layer, batch norm layer, and LeakyReLU. This discriminator receives two inputs:"
},
{
"code": null,
"e": 28440,
"s": 28361,
"text": "The input image and Target Image (which discriminator should classify as real)"
},
{
"code": null,
"e": 28523,
"s": 28440,
"text": "The input image and Generated Image (which discriminator should classify as fake)."
},
{
"code": null,
"e": 28699,
"s": 28523,
"text": "THe PatchGAN is used because the author argues that it will be able to preserve high-frequency details in the image, with low-frequency details that can be focused by L1-loss."
},
{
"code": null,
"e": 28715,
"s": 28699,
"text": "Generator Loss:"
},
{
"code": null,
"e": 28864,
"s": 28715,
"text": "The generator loss used in the paper is the linear combination of L1- loss between generated image, target image, and GAN loss as we define above. "
},
{
"code": null,
"e": 28894,
"s": 28866,
"text": "Our generated loss will be:"
},
{
"code": null,
"e": 28936,
"s": 28896,
"text": "Therefore, our total loss for generator"
},
{
"code": null,
"e": 28957,
"s": 28938,
"text": "Discriminator Loss"
},
{
"code": null,
"e": 29031,
"s": 28959,
"text": "The discriminator loss takes two inputs real image and generated image:"
},
{
"code": null,
"e": 29149,
"s": 29033,
"text": "real_loss is a sigmoid cross-entropy loss of the real images and an array of ones(since these are the real images)."
},
{
"code": null,
"e": 29275,
"s": 29149,
"text": "generated_loss is a sigmoid cross-entropy loss of the generated images and an array of zeros(since these are the fake images)"
},
{
"code": null,
"e": 29338,
"s": 29275,
"text": "The total loss is the sum of the real_loss and generated_loss."
},
{
"code": null,
"e": 29356,
"s": 29340,
"text": "Implementation:"
},
{
"code": null,
"e": 29590,
"s": 29358,
"text": "First, we download and preprocess the image dataset. We will use the CMP Facade dataset that was provided Czech Technical University and processed by the authors of the pix2pix paper. We will preprocess the dataset before training."
},
{
"code": null,
"e": 29597,
"s": 29590,
"text": "Code: "
},
{
"code": null,
"e": 29605,
"s": 29597,
"text": "python3"
},
{
"code": "# import necessary packagesimport tensorflow as tf import osimport time from matplotlib import pyplot as pltfrom IPython import display# install tensorboard ! pip install -U tensorboard # download datasetURL = \"https://people.eecs.berkeley.edu/~tinghuiz / projects / pix2pix / datasets / facades.tar.gz\" path_to_zip = tf.keras.utils.get_file('facades.tar.gz', origin = URL, extract = True) PATH = os.path.join(os.path.dirname(path_to_zip), 'facades/') # Define Training variableBUFFER_SIZE = 400BATCH_SIZE = 1IMG_WIDTH = 256IMG_HEIGHT = 256 # load the images from datasetdef load(image_file): image = tf.io.read_file(image_file) image = tf.image.decode_jpeg(image) w = tf.shape(image)[1] w = w // 2 real_image = image[:, :w, :] input_image = image[:, w:, :] input_image = tf.cast(input_image, tf.float32) real_image = tf.cast(real_image, tf.float32) return input_image, real_image # resize the images to provided width and heightdef resize(input_image, real_image, height, width): input_image = tf.image.resize(input_image, [height, width], method = tf.image.ResizeMethod.NEAREST_NEIGHBOR) real_image = tf.image.resize(real_image, [height, width], method = tf.image.ResizeMethod.NEAREST_NEIGHBOR) return input_image, real_image \"\"\"function to stack (input, real) images and apply random crop on them to cropto (256, 256)\"\"\"def random_crop(input_image, real_image): stacked_image = tf.stack([input_image, real_image], axis = 0) cropped_image = tf.image.random_crop( stacked_image, size =[2, IMG_HEIGHT, IMG_WIDTH, 3]) return cropped_image[0], cropped_image[1] \"\"\"Before training, we need to perform random jittering on the datasetAccording to the paper, this random jittering contains 3 steps --> Resize the image to bigger size --> Random crop the image to target size of model --> Random Flip on the images \"\"\" @tf.function()def random_jitter(input_image, real_image): # resizing to 286 x 286 x 3 input_image, real_image = resize(input_image, real_image, 286, 286) # randomly cropping to 256 x 256 x 3 input_image, real_image = random_crop(input_image, real_image) if tf.random.uniform(()) > 0.5: # random mirroring input_image = tf.image.flip_left_right(input_image) real_image = tf.image.flip_left_right(real_image) return input_image, real_image",
"e": 32033,
"s": 29605,
"text": null
},
{
"code": null,
"e": 32103,
"s": 32033,
"text": "Now, we load train and test data using the function we defined above."
},
{
"code": null,
"e": 32110,
"s": 32103,
"text": "Code: "
},
{
"code": null,
"e": 32118,
"s": 32110,
"text": "python3"
},
{
"code": "# function to Load image from train data\"\"\"On train data, we performed random jitter and normalize,but since we don't need any augmentation on test_data, we just resize it\"\"\"def load_image_train(image_file): input_image, real_image = load(image_file) input_image, real_image = random_jitter(input_image, real_image) input_image, real_image = normalize(input_image, real_image) return input_image, real_image# function to Load images from test datadef load_image_test(image_file): input_image, real_image = load(image_file) input_image, real_image = resize(input_image, real_image, IMG_HEIGHT, IMG_WIDTH) input_image, real_image = normalize(input_image, real_image) return input_image, real_image # apply the above load_images_train function on train datatrain_dataset = tf.data.Dataset.list_files(PATH+'train/*.jpg')train_dataset = train_dataset.map(load_image_train, num_parallel_calls = tf.data.experimental.AUTOTUNE)train_dataset = train_dataset.shuffle(BUFFER_SIZE)train_dataset = train_dataset.batch(BATCH_SIZE) # apply the above load_images_test function on test datatest_dataset = tf.data.Dataset.list_files(PATH+'test/*.jpg')test_dataset = test_dataset.map(load_image_test)test_dataset = test_dataset.batch(BATCH_SIZE)",
"e": 33422,
"s": 32118,
"text": null
},
{
"code": null,
"e": 33712,
"s": 33422,
"text": "After performing data processing, Now, we write the code for generator architecture. This generator block contains 2 parts encoder block and decoder block. The encoder block contains a downsampling convolution block and the decoder block contains an upsampling transpose convolution block."
},
{
"code": null,
"e": 33735,
"s": 33712,
"text": "Generator architecture"
},
{
"code": null,
"e": 34122,
"s": 33735,
"text": "Now we define our architecture for the discriminator. The discriminator architecture uses a PatchGAN model. For this architecture, we can use the above downsampling convolution block we defined. The loss of the discriminator is the sum of real loss (sigmoid cross-entropy b/w real image and array of 1s) and generated loss (sigmoid cross-entropy b/w generated image and an array of 0s)."
},
{
"code": null,
"e": 34129,
"s": 34122,
"text": "Code: "
},
{
"code": null,
"e": 34137,
"s": 34129,
"text": "python3"
},
{
"code": "# code for discriminator architecture\"\"\"FOr more details look into architecture section\"\"\"def Discriminator(): initializer = tf.random_normal_initializer(0., 0.02) inp = tf.keras.layers.Input(shape =[256, 256, 3], name ='input_image') tar = tf.keras.layers.Input(shape =[256, 256, 3], name ='target_image') x = tf.keras.layers.concatenate([inp, tar]) # (batch_size, 256, 256, channels * 2) down1 = downsample(64, 4, False)(x) # (batch_size, 128, 128, 64) down2 = downsample(128, 4)(down1) # (batch_size, 64, 64, 128) down3 = downsample(256, 4)(down2) # (batch_size, 32, 32, 256) zero_pad1 = tf.keras.layers.ZeroPadding2D()(down3) # (batch_size, 34, 34, 256) conv = tf.keras.layers.Conv2D(512, 4, strides = 1, kernel_initializer = initializer, use_bias = False)(zero_pad1) # (batch_size, 31, 31, 512) batchnorm1 = tf.keras.layers.BatchNormalization()(conv) leaky_relu = tf.keras.layers.LeakyReLU()(batchnorm1) zero_pad2 = tf.keras.layers.ZeroPadding2D()(leaky_relu) # (batch_size, 33, 33, 512) last = tf.keras.layers.Conv2D(1, 4, strides = 1, kernel_initializer = initializer)(zero_pad2) # (batch_size, 30, 30, 1) return tf.keras.Model(inputs =[inp, tar], outputs = last) # define discriminator loss functiondisc_ce_loss = tf.keras.losses.BinaryCrossentropy(from_logits = True)def discriminator_loss(disc_real_output, disc_generated_output): real_loss = disc_ce_loss(tf.ones_like(disc_real_output), disc_real_output) generated_loss = disc_ce_loss(tf.zeros_like(disc_generated_output), disc_generated_output) total_disc_loss = real_loss + generated_loss return total_disc_loss discriminator = Discriminator()tf.keras.utils.plot_model(discriminator, show_shapes = True)",
"e": 35927,
"s": 34137,
"text": null
},
{
"code": null,
"e": 35954,
"s": 35927,
"text": "Discriminator Architecture"
},
{
"code": null,
"e": 36066,
"s": 35954,
"text": "In this step, we define optimizers and checkpoints. We will use Adam optimizer in both generator discriminator."
},
{
"code": null,
"e": 36073,
"s": 36066,
"text": "Code: "
},
{
"code": null,
"e": 36081,
"s": 36073,
"text": "python3"
},
{
"code": "# define generator and discriminator architecturegenerator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1 = 0.5)discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1 = 0.5) # Create the model checkpointcheckpoint_dir = './train_checkpoints'checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")checkpoint = tf.train.Checkpoint(generator_optimizer = generator_optimizer, discriminator_optimizer = discriminator_optimizer, generator = generator, discriminator = discriminator)",
"e": 36667,
"s": 36081,
"text": null
},
{
"code": null,
"e": 37212,
"s": 36667,
"text": "Now, we define the training procedure. The training procedure consists of the following steps:For each example input, we passed the image as input to the generator to get the generated image.The discriminator receives the input_image and the generated image as the first input. The second input is the input_image and the target_image.Next, we calculate the generator and the discriminator loss.Then, we calculate the gradients of loss with respect to both the generator and the discriminator variables(inputs) and apply those to the optimizer."
},
{
"code": null,
"e": 37310,
"s": 37212,
"text": "For each example input, we passed the image as input to the generator to get the generated image."
},
{
"code": null,
"e": 37455,
"s": 37310,
"text": "The discriminator receives the input_image and the generated image as the first input. The second input is the input_image and the target_image."
},
{
"code": null,
"e": 37516,
"s": 37455,
"text": "Next, we calculate the generator and the discriminator loss."
},
{
"code": null,
"e": 37666,
"s": 37516,
"text": "Then, we calculate the gradients of loss with respect to both the generator and the discriminator variables(inputs) and apply those to the optimizer."
},
{
"code": null,
"e": 37673,
"s": 37666,
"text": "Code: "
},
{
"code": null,
"e": 37681,
"s": 37673,
"text": "python3"
},
{
"code": "# Define training procedureEPOCHS = 30 import datetimelog_dir =\"logs/\" summary_writer = tf.summary.create_file_writer( log_dir + \"fit/\" + datetime.datetime.now().strftime(\"% Y % m % d-% H % M % S\")) @tf.functiondef train_step(input_image, target, epoch): with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: gen_output = generator(input_image, training = True) disc_real_output = discriminator([input_image, target], training = True) disc_generated_output = discriminator([input_image, gen_output], training = True) gen_total_loss, gen_gan_loss, gen_l1_loss = generator_loss(disc_generated_output, gen_output, target) disc_loss = discriminator_loss(disc_real_output, disc_generated_output) generator_gradients = gen_tape.gradient(gen_total_loss, generator.trainable_variables) discriminator_gradients = disc_tape.gradient(disc_loss, discriminator.trainable_variables) generator_optimizer.apply_gradients(zip(generator_gradients, generator.trainable_variables)) discriminator_optimizer.apply_gradients(zip(discriminator_gradients, discriminator.trainable_variables)) with summary_writer.as_default(): tf.summary.scalar('gen_total_loss', gen_total_loss, step = epoch) tf.summary.scalar('gen_gan_loss', gen_gan_loss, step = epoch) tf.summary.scalar('gen_l1_loss', gen_l1_loss, step = epoch) tf.summary.scalar('disc_loss', disc_loss, step = epoch) def fit(train_ds, epochs, test_ds): for epoch in range(epochs): % time for example_input, example_target in test_ds.take(1): generate_images(generator, example_input, example_target) print(\"Epoch: \", epoch) # Train for n, (input_image, target) in train_ds.enumerate(): train_step(input_image, target, epoch) print() # saving (checkpoint) the model every 10 epochs if (epoch + 1) % 10 == 0: checkpoint.save(file_prefix = checkpoint_prefix) checkpoint.save(file_prefix = checkpoint_prefix)fit(train_dataset, EPOCHS, test_dataset)",
"e": 39833,
"s": 37681,
"text": null
},
{
"code": null,
"e": 39917,
"s": 39833,
"text": "Now, we use the generator of the trained model on test data to generate the images."
},
{
"code": null,
"e": 39924,
"s": 39917,
"text": "Code: "
},
{
"code": null,
"e": 39932,
"s": 39924,
"text": "python3"
},
{
"code": "# code to plot resultsdef generate_images(model, test_input, tar): prediction = model(test_input, training = True) plt.figure(figsize =(15, 15)) display_list = [test_input[0], tar[0], prediction[0]] title = ['Input Image', 'Ground Truth', 'Predicted Image'] for i in range(3): plt.subplot(1, 3, i + 1) plt.title(title[i]) # getting the pixel values between [0, 1] to plot it. plt.imshow(display_list[i] * 0.5 + 0.5) plt.axis('off') plt.show() for inputs, tar in test_dataset.take(5): generate_images(generator, inputs, tar)",
"e": 40482,
"s": 39932,
"text": null
},
{
"code": null,
"e": 40490,
"s": 40482,
"text": "Results"
},
{
"code": null,
"e": 40502,
"s": 40490,
"text": "References:"
},
{
"code": null,
"e": 40516,
"s": 40502,
"text": "Pix2Pix paper"
},
{
"code": null,
"e": 40553,
"s": 40516,
"text": "TensorFlow implementation on Pix2pix"
},
{
"code": null,
"e": 40561,
"s": 40553,
"text": "clintra"
},
{
"code": null,
"e": 40574,
"s": 40561,
"text": "simmytarika5"
},
{
"code": null,
"e": 40591,
"s": 40574,
"text": "Machine Learning"
},
{
"code": null,
"e": 40598,
"s": 40591,
"text": "Python"
},
{
"code": null,
"e": 40615,
"s": 40598,
"text": "Machine Learning"
},
{
"code": null,
"e": 40713,
"s": 40615,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40736,
"s": 40713,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 40750,
"s": 40736,
"text": "Decision Tree"
},
{
"code": null,
"e": 40773,
"s": 40750,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 40813,
"s": 40773,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 40851,
"s": 40813,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 40879,
"s": 40851,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 40929,
"s": 40879,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 40951,
"s": 40929,
"text": "Python map() function"
}
] |
How to define a variable in HTML5 ? - GeeksforGeeks
|
05 Jun, 2020
In this article, we define a variable in the HTML by using the <var> tag in the document. It is a phrase tag and used to specify the variable in a mathematical equation or in the computer program. The content of this tag is displayed in an italic format in most of the browsers.
Syntax:
<var> Contents... </var>
Example:
<!DOCTYPE html><html> <head> <title> How to define a variable in HTML5? </title> <style> body { text-align: center; } .gfg { font-size: 40px; font-weight: bold; color: green; } .geeks { font-size: 25px; font-weight: bold; } </style></head> <body> <div class="gfg">GeeksForGeeks</div> <h2> <var> HTML5: How to define a variable? </var> </h2> <var>GeeksforGeeks Variable</var></body> </html>
Output:
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
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.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction)
|
[
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 25655,
"s": 25376,
"text": "In this article, we define a variable in the HTML by using the <var> tag in the document. It is a phrase tag and used to specify the variable in a mathematical equation or in the computer program. The content of this tag is displayed in an italic format in most of the browsers."
},
{
"code": null,
"e": 25663,
"s": 25655,
"text": "Syntax:"
},
{
"code": null,
"e": 25688,
"s": 25663,
"text": "<var> Contents... </var>"
},
{
"code": null,
"e": 25697,
"s": 25688,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to define a variable in HTML5? </title> <style> body { text-align: center; } .gfg { font-size: 40px; font-weight: bold; color: green; } .geeks { font-size: 25px; font-weight: bold; } </style></head> <body> <div class=\"gfg\">GeeksForGeeks</div> <h2> <var> HTML5: How to define a variable? </var> </h2> <var>GeeksforGeeks Variable</var></body> </html>",
"e": 26271,
"s": 25697,
"text": null
},
{
"code": null,
"e": 26279,
"s": 26271,
"text": "Output:"
},
{
"code": null,
"e": 26316,
"s": 26279,
"text": "Supported Browsers are listed below:"
},
{
"code": null,
"e": 26330,
"s": 26316,
"text": "Google Chrome"
},
{
"code": null,
"e": 26348,
"s": 26330,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26356,
"s": 26348,
"text": "Firefox"
},
{
"code": null,
"e": 26362,
"s": 26356,
"text": "Opera"
},
{
"code": null,
"e": 26369,
"s": 26362,
"text": "Safari"
},
{
"code": null,
"e": 26506,
"s": 26369,
"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": 26515,
"s": 26506,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26525,
"s": 26515,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26529,
"s": 26525,
"text": "CSS"
},
{
"code": null,
"e": 26534,
"s": 26529,
"text": "HTML"
},
{
"code": null,
"e": 26551,
"s": 26534,
"text": "Web Technologies"
},
{
"code": null,
"e": 26578,
"s": 26551,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26583,
"s": 26578,
"text": "HTML"
},
{
"code": null,
"e": 26681,
"s": 26583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26690,
"s": 26681,
"text": "Comments"
},
{
"code": null,
"e": 26703,
"s": 26690,
"text": "Old Comments"
},
{
"code": null,
"e": 26740,
"s": 26703,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26769,
"s": 26740,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26808,
"s": 26769,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 26850,
"s": 26808,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 26885,
"s": 26850,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 26945,
"s": 26885,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27006,
"s": 26945,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27056,
"s": 27006,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27109,
"s": 27056,
"text": "Hide or show elements in HTML using display property"
}
] |
Check if a Queen can attack a given cell on chessboard - GeeksforGeeks
|
05 May, 2021
Given the position of the queen (qX, qY) and the opponent (oX, oY) on a chessboard. The task is to determine whether the queen can attack the opponent or not. Note that the queen can attack in the same row, same column and diagonally.Example:
Input: qX = 4, qY = 5, oX = 6, oY = 7 Output: Yes The queen can attack diagonally.Input: qX = 1, qY = 1, oX = 3, oY = 2 Output: No
Approach:
If qR = oR, it means that both the queen and the opponent are in the same row and the queen can attack the opponent.
Similarly, if qC = oC then also the queen can attack the opponent as they both are in the same column.
And for diagonals, if abs(qR – oR) = abs(qC – oC) i.e. queen can attack the opponent diagonally.
If all of the above conditions fail then the opponent is safe from the queen.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function that returns true if the queen// can attack the opponentbool canQueenAttack(int qR, int qC, int oR, int oC){ // If queen and the opponent are in the same row if (qR == oR) return true; // If queen and the opponent are in the same column if (qC == oC) return true; // If queen can attack diagonally if (abs(qR - oR) == abs(qC - oC)) return true; // Opponent is safe return false;} // Driver codeint main(){ int qR = 1, qC = 1; int oR = 3, oC = 2; if (canQueenAttack(qR, qC, oR, oC)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachclass GFG{ // Function that returns true if the queen// can attack the opponentstatic boolean canQueenAttack(int qR, int qC, int oR, int oC){ // If queen and the opponent // are in the same row if (qR == oR) return true; // If queen and the opponent // are in the same column if (qC == oC) return true; // If queen can attack diagonally if (Math.abs(qR - oR) == Math.abs(qC - oC)) return true; // Opponent is safe return false;} // Driver codepublic static void main(String[] args){ int qR = 1, qC = 1; int oR = 3, oC = 2; if (canQueenAttack(qR, qC, oR, oC)) System.out.println("Yes"); else System.out.println("No");}} // This code is Contributed by Code_Mech.
# Python3 implementation of the approach # Function that returns True if the# queen can attack the opponentdef canQueenAttack(qR, qC, oR, oC): # If queen and the opponent are # in the same row if qR == oR: return True # If queen and the opponent are # in the same column if qC == oC: return True # If queen can attack diagonally if abs(qR - oR) == abs(qC - oC): return True # Opponent is safe return False # Driver codeif __name__ == "__main__": qR, qC = 1, 1 oR, oC = 3, 2 if canQueenAttack(qR, qC, oR, oC): print("Yes") else: print("No") # This code is contributed# by Rituraj Jain
// C# implementation of the approachusing System;class GFG{ // Function that returns true if the queen// can attack the opponentstatic bool canQueenAttack(int qR, int qC, int oR, int oC){ // If queen and the opponent // are in the same row if (qR == oR) return true; // If queen and the opponent // are in the same column if (qC == oC) return true; // If queen can attack diagonally if (Math.Abs(qR - oR) == Math.Abs(qC - oC)) return true; // Opponent is safe return false;} // Driver codepublic static void Main(){ int qR = 1, qC = 1; int oR = 3, oC = 2; if (canQueenAttack(qR, qC, oR, oC)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is Contributed by Code_Mech.
<?php// PHP implementation of the approach // Function that returns true if the// queen can attack the opponentfunction canQueenAttack($qR, $qC, $oR, $oC){ // If queen and the opponent are // in the same row if ($qR == $oR) return true; // If queen and the opponent are // in the same column if ($qC == $oC) return true; // If queen can attack diagonally if (abs($qR - $oR) == abs($qC - $oC)) return true; // Opponent is safe return false;} // Driver code$qR = 1; $qC = 1;$oR = 3; $oC = 2; if (canQueenAttack($qR, $qC, $oR, $oC)) echo "Yes";else echo "No"; // This code is contributed// by Akanksha Rai?>
<script> // JavaScript implementation of the approach // Function that returns true if the queen// can attack the opponentfunction canQueenAttack(qR, qC, oR, oC){ // If queen and the opponent are in the same row if (qR == oR) return true; // If queen and the opponent are in the same column if (qC == oC) return true; // If queen can attack diagonally if (Math.abs(qR - oR) == Math.abs(qC - oC)) return true; // Opponent is safe return false;} // Driver code var qR = 1, qC = 1; var oR = 3, oC = 2; if (canQueenAttack(qR, qC, oR, oC)) document.write("Yes"); else document.write("No"); // This Code is Contributed by Harshit Srivastava </script>
No
rituraj_jain
Akanksha_Rai
Code_Mech
srivastavaharshit848
chessboard-problems
Cisco
Competitive Programming
Cisco
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Formatted output in Java
Breadth First Traversal ( BFS ) on a 2D array
What is Competitive Programming and How to Prepare for It?
Understanding The Coin Change Problem With Dynamic Programming
Use of FLAG in programming
Shortest path in a directed graph by Dijkstra’s algorithm
Setting up Sublime Text for C++ Competitive Programming Environment
Fast I/O in Java in Competitive Programming
Runtime Errors
How to overcome Time Limit Exceed(TLE)?
|
[
{
"code": null,
"e": 25028,
"s": 25000,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 25273,
"s": 25028,
"text": "Given the position of the queen (qX, qY) and the opponent (oX, oY) on a chessboard. The task is to determine whether the queen can attack the opponent or not. Note that the queen can attack in the same row, same column and diagonally.Example: "
},
{
"code": null,
"e": 25406,
"s": 25273,
"text": "Input: qX = 4, qY = 5, oX = 6, oY = 7 Output: Yes The queen can attack diagonally.Input: qX = 1, qY = 1, oX = 3, oY = 2 Output: No "
},
{
"code": null,
"e": 25420,
"s": 25408,
"text": "Approach: "
},
{
"code": null,
"e": 25537,
"s": 25420,
"text": "If qR = oR, it means that both the queen and the opponent are in the same row and the queen can attack the opponent."
},
{
"code": null,
"e": 25640,
"s": 25537,
"text": "Similarly, if qC = oC then also the queen can attack the opponent as they both are in the same column."
},
{
"code": null,
"e": 25737,
"s": 25640,
"text": "And for diagonals, if abs(qR – oR) = abs(qC – oC) i.e. queen can attack the opponent diagonally."
},
{
"code": null,
"e": 25866,
"s": 25737,
"text": "If all of the above conditions fail then the opponent is safe from the queen.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25870,
"s": 25866,
"text": "C++"
},
{
"code": null,
"e": 25875,
"s": 25870,
"text": "Java"
},
{
"code": null,
"e": 25883,
"s": 25875,
"text": "Python3"
},
{
"code": null,
"e": 25886,
"s": 25883,
"text": "C#"
},
{
"code": null,
"e": 25890,
"s": 25886,
"text": "PHP"
},
{
"code": null,
"e": 25901,
"s": 25890,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function that returns true if the queen// can attack the opponentbool canQueenAttack(int qR, int qC, int oR, int oC){ // If queen and the opponent are in the same row if (qR == oR) return true; // If queen and the opponent are in the same column if (qC == oC) return true; // If queen can attack diagonally if (abs(qR - oR) == abs(qC - oC)) return true; // Opponent is safe return false;} // Driver codeint main(){ int qR = 1, qC = 1; int oR = 3, oC = 2; if (canQueenAttack(qR, qC, oR, oC)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26595,
"s": 25901,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function that returns true if the queen// can attack the opponentstatic boolean canQueenAttack(int qR, int qC, int oR, int oC){ // If queen and the opponent // are in the same row if (qR == oR) return true; // If queen and the opponent // are in the same column if (qC == oC) return true; // If queen can attack diagonally if (Math.abs(qR - oR) == Math.abs(qC - oC)) return true; // Opponent is safe return false;} // Driver codepublic static void main(String[] args){ int qR = 1, qC = 1; int oR = 3, oC = 2; if (canQueenAttack(qR, qC, oR, oC)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is Contributed by Code_Mech.",
"e": 27409,
"s": 26595,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function that returns True if the# queen can attack the opponentdef canQueenAttack(qR, qC, oR, oC): # If queen and the opponent are # in the same row if qR == oR: return True # If queen and the opponent are # in the same column if qC == oC: return True # If queen can attack diagonally if abs(qR - oR) == abs(qC - oC): return True # Opponent is safe return False # Driver codeif __name__ == \"__main__\": qR, qC = 1, 1 oR, oC = 3, 2 if canQueenAttack(qR, qC, oR, oC): print(\"Yes\") else: print(\"No\") # This code is contributed# by Rituraj Jain",
"e": 28079,
"s": 27409,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG{ // Function that returns true if the queen// can attack the opponentstatic bool canQueenAttack(int qR, int qC, int oR, int oC){ // If queen and the opponent // are in the same row if (qR == oR) return true; // If queen and the opponent // are in the same column if (qC == oC) return true; // If queen can attack diagonally if (Math.Abs(qR - oR) == Math.Abs(qC - oC)) return true; // Opponent is safe return false;} // Driver codepublic static void Main(){ int qR = 1, qC = 1; int oR = 3, oC = 2; if (canQueenAttack(qR, qC, oR, oC)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is Contributed by Code_Mech.",
"e": 28886,
"s": 28079,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function that returns true if the// queen can attack the opponentfunction canQueenAttack($qR, $qC, $oR, $oC){ // If queen and the opponent are // in the same row if ($qR == $oR) return true; // If queen and the opponent are // in the same column if ($qC == $oC) return true; // If queen can attack diagonally if (abs($qR - $oR) == abs($qC - $oC)) return true; // Opponent is safe return false;} // Driver code$qR = 1; $qC = 1;$oR = 3; $oC = 2; if (canQueenAttack($qR, $qC, $oR, $oC)) echo \"Yes\";else echo \"No\"; // This code is contributed// by Akanksha Rai?>",
"e": 29551,
"s": 28886,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function that returns true if the queen// can attack the opponentfunction canQueenAttack(qR, qC, oR, oC){ // If queen and the opponent are in the same row if (qR == oR) return true; // If queen and the opponent are in the same column if (qC == oC) return true; // If queen can attack diagonally if (Math.abs(qR - oR) == Math.abs(qC - oC)) return true; // Opponent is safe return false;} // Driver code var qR = 1, qC = 1; var oR = 3, oC = 2; if (canQueenAttack(qR, qC, oR, oC)) document.write(\"Yes\"); else document.write(\"No\"); // This Code is Contributed by Harshit Srivastava </script>",
"e": 30304,
"s": 29551,
"text": null
},
{
"code": null,
"e": 30307,
"s": 30304,
"text": "No"
},
{
"code": null,
"e": 30322,
"s": 30309,
"text": "rituraj_jain"
},
{
"code": null,
"e": 30335,
"s": 30322,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30345,
"s": 30335,
"text": "Code_Mech"
},
{
"code": null,
"e": 30366,
"s": 30345,
"text": "srivastavaharshit848"
},
{
"code": null,
"e": 30386,
"s": 30366,
"text": "chessboard-problems"
},
{
"code": null,
"e": 30392,
"s": 30386,
"text": "Cisco"
},
{
"code": null,
"e": 30416,
"s": 30392,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30422,
"s": 30416,
"text": "Cisco"
},
{
"code": null,
"e": 30520,
"s": 30422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30545,
"s": 30520,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 30591,
"s": 30545,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 30650,
"s": 30591,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 30713,
"s": 30650,
"text": "Understanding The Coin Change Problem With Dynamic Programming"
},
{
"code": null,
"e": 30740,
"s": 30713,
"text": "Use of FLAG in programming"
},
{
"code": null,
"e": 30798,
"s": 30740,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 30866,
"s": 30798,
"text": "Setting up Sublime Text for C++ Competitive Programming Environment"
},
{
"code": null,
"e": 30910,
"s": 30866,
"text": "Fast I/O in Java in Competitive Programming"
},
{
"code": null,
"e": 30925,
"s": 30910,
"text": "Runtime Errors"
}
] |
Apache Derby - Where Clause
|
The WHERE clause is used in the SELECT, DELETE or, UPDATE statements to specify the rows on which the operation needs to be carried out. Usually, this clause is followed by a condition or expression which returns a Boolean value, the Select, delete or, update operations are performed only on the rows which satisfy the given condition.
ij> SELECT * from table_name WHERE condition;
or,
ij> DELETE from table_name WHERE condition;
or,
ij> UPDATE table_name SET column_name = value WHERE condition;
The WHERE clause can use the comparison operators such as =,!=, <, >, <=, and >=, as well as the BETWEEN and LIKE operators.
Let us assume we have a table named Employees in the database with 7 records as shown below −
ID |NAME |SALARY |LOCATION
-----------------------------------------------------------------------------
1 |Amit |30000 |Hyderabad
2 |Kalyan |40000 |Vishakhapatnam
3 |Renuka |50000 |Delhi
4 |Archana |15000 |Mumbai
5 |Trupthi |45000 |Kochin
6 |Suchatra|33000 |Pune
7 |Rahul |39000 |Lucknow
The following SQL DELETE statement fetches the records of the employees whose salary is more than 35000 −
ij> SELECT * FROM Employees WHERE Salary>35000;
This will produce the following output −
ID |NAME |SALARY |LOCATION
---------------------------------------------------
2 |Kalyan |40000 |Vishakhapatnam
3 |Renuka |50000 |Delhi
5 |Trupthi|45000 |Kochin
7 |Rahul |39000 |Lucknow
4 rows selected
Similarly, you can also delete and update records using this clause.
Following example updates the location of those whose salary is less than 30000.
ij> UPDATE Employees SET Location = 'Vijayawada' WHERE Salary<35000;
3 rows inserted/updated/deleted
If you verify the contents of the table, you can see the updated table as shown below −
ij> SELECT * FROM Employees;
ID |NAME |SALARY |LOCATION
------------------------------------------------------------------------------
1 |Amit |30000 |Vijayawada
2 |Kalyan |40000 |Vishakhapatnam
3 |Renuka |50000 |Delhi
4 |Archana |15000 |Vijayawada
5 |Trupthi |45000 |Kochin
6 |Suchatra|33000 |Vijayawada
7 |Rahul |39000 |Lucknow
7 rows selected
This section teaches you how to use WHERE clause and perform CURD operations on a table in Apache Derby database using JDBC application.
If you want to request the Derby network server using network client, make sure that the server is up and running. The class name for the Network client driver is org.apache.derby.jdbc.ClientDriver and the URL is jdbc:derby://localhost:1527/DATABASE_NAME;create=true;user=USER_NAME; password=PASSWORD".
Follow the steps given below to use WHERE clause and perform CURD operations on a table in Apache Derby
To communicate with the database, first of all, you need to register the driver. The forName() method of the class Class accepts a String value representing a class name loads it in to the memory, which automatically registers it. Register the driver using this method
In general, the first step we do to communicate to the database is to connect with it. The Connection class represents the physical connection with a database server. You can create a connection object by invoking the getConnection() method of the DriverManager class. Create a connection using this method.
You need to create a Statement or PreparedStatement or, CallableStatement objects to send SQL statements to the database. You can create these using the methods createStatement(), prepareStatement() and, prepareCall() respectively. Create either of these objects using the appropriate method.
After creating a statement, you need to execute it. The Statement class provides various methods to execute a query like the execute() method to execute a statement that returns more than one result set. The executeUpdate() method executes queries like INSERT, UPDATE, DELETE. The executeQuery() method results that returns data. Use either of these methods and execute the statement created previously.
Following JDBC example demonstrates how to use WHERE clause and perform CURD operations on a table in Apache Derby using JDBC program. Here, we are connecting to a database named sampleDB (will create if it does not exist) using the embedded driver.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
public class WhereClauseExample {
public static void main(String args[]) throws Exception {
//Registering the driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Getting the Connection object
String URL = "jdbc:derby:sampleDB;create=true";
Connection conn = DriverManager.getConnection(URL);
//Creating the Statement object
Statement stmt = conn.createStatement();
//Creating a table and populating it
String query = "CREATE TABLE Employees("
+ "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+ "Name VARCHAR(255), Salary INT NOT NULL, "
+ "Location VARCHAR(255), "
+ "PRIMARY KEY (Id))";
String query = "INSERT INTO Employees("
+ "Name, Salary, Location) VALUES "
+ "('Amit', 30000, 'Hyderabad'), "
+ "('Kalyan', 40000, 'Vishakhapatnam'), "
+ "('Renuka', 50000, 'Delhi'), "
+ "('Archana', 15000, 'Mumbai'), "
+ "('Trupthi', 45000, 'Kochin'), "
+ "('Suchatra', 33000, 'Pune'), "
+ "('Rahul', 39000, 'Lucknow'), "
+ "('Trupti', 45000, 'Kochin')";
//Executing the query
String query = "SELECT * FROM Employees WHERE Salary>35000";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
System.out.println("Id: "+rs.getString("Id"));
System.out.println("Name: "+rs.getString("Name"));
System.out.println("Salary: "+rs.getString("Salary"));
System.out.println("Location: "+rs.getString("Location"));
System.out.println(" ");
}
}
}
On executing the above program, you will get the following output −
Id: 2
Name: Kalyan
Salary: 43000
Location: Chennai
Id: 3
Name: Renuka
Salary: 50000
Location: Delhi
Id: 5
Name: Trupthi
Salary: 45000
Location: Kochin
Id: 7
Name: Rahul
Salary: 39000
Location: Lucknow
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2517,
"s": 2180,
"text": "The WHERE clause is used in the SELECT, DELETE or, UPDATE statements to specify the rows on which the operation needs to be carried out. Usually, this clause is followed by a condition or expression which returns a Boolean value, the Select, delete or, update operations are performed only on the rows which satisfy the given condition."
},
{
"code": null,
"e": 2679,
"s": 2517,
"text": "ij> SELECT * from table_name WHERE condition;\nor,\nij> DELETE from table_name WHERE condition;\nor,\nij> UPDATE table_name SET column_name = value WHERE condition;\n"
},
{
"code": null,
"e": 2804,
"s": 2679,
"text": "The WHERE clause can use the comparison operators such as =,!=, <, >, <=, and >=, as well as the BETWEEN and LIKE operators."
},
{
"code": null,
"e": 2898,
"s": 2804,
"text": "Let us assume we have a table named Employees in the database with 7 records as shown below −"
},
{
"code": null,
"e": 3213,
"s": 2898,
"text": "ID |NAME |SALARY |LOCATION\n-----------------------------------------------------------------------------\n1 |Amit |30000 |Hyderabad\n2 |Kalyan |40000 |Vishakhapatnam\n3 |Renuka |50000 |Delhi\n4 |Archana |15000 |Mumbai\n5 |Trupthi |45000 |Kochin\n6 |Suchatra|33000 |Pune\n7 |Rahul |39000 |Lucknow \n"
},
{
"code": null,
"e": 3319,
"s": 3213,
"text": "The following SQL DELETE statement fetches the records of the employees whose salary is more than 35000 −"
},
{
"code": null,
"e": 3367,
"s": 3319,
"text": "ij> SELECT * FROM Employees WHERE Salary>35000;"
},
{
"code": null,
"e": 3408,
"s": 3367,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3623,
"s": 3408,
"text": "ID |NAME |SALARY |LOCATION \n---------------------------------------------------\n2 |Kalyan |40000 |Vishakhapatnam\n3 |Renuka |50000 |Delhi\n5 |Trupthi|45000 |Kochin\n7 |Rahul |39000 |Lucknow\n4 rows selected\n"
},
{
"code": null,
"e": 3692,
"s": 3623,
"text": "Similarly, you can also delete and update records using this clause."
},
{
"code": null,
"e": 3773,
"s": 3692,
"text": "Following example updates the location of those whose salary is less than 30000."
},
{
"code": null,
"e": 3874,
"s": 3773,
"text": "ij> UPDATE Employees SET Location = 'Vijayawada' WHERE Salary<35000;\n3 rows inserted/updated/deleted"
},
{
"code": null,
"e": 3962,
"s": 3874,
"text": "If you verify the contents of the table, you can see the updated table as shown below −"
},
{
"code": null,
"e": 4333,
"s": 3962,
"text": "ij> SELECT * FROM Employees;\nID |NAME |SALARY |LOCATION\n------------------------------------------------------------------------------\n1 |Amit |30000 |Vijayawada\n2 |Kalyan |40000 |Vishakhapatnam\n3 |Renuka |50000 |Delhi\n4 |Archana |15000 |Vijayawada\n5 |Trupthi |45000 |Kochin\n6 |Suchatra|33000 |Vijayawada\n7 |Rahul |39000 |Lucknow\n7 rows selected\n"
},
{
"code": null,
"e": 4470,
"s": 4333,
"text": "This section teaches you how to use WHERE clause and perform CURD operations on a table in Apache Derby database using JDBC application."
},
{
"code": null,
"e": 4773,
"s": 4470,
"text": "If you want to request the Derby network server using network client, make sure that the server is up and running. The class name for the Network client driver is org.apache.derby.jdbc.ClientDriver and the URL is jdbc:derby://localhost:1527/DATABASE_NAME;create=true;user=USER_NAME; password=PASSWORD\"."
},
{
"code": null,
"e": 4877,
"s": 4773,
"text": "Follow the steps given below to use WHERE clause and perform CURD operations on a table in Apache Derby"
},
{
"code": null,
"e": 5146,
"s": 4877,
"text": "To communicate with the database, first of all, you need to register the driver. The forName() method of the class Class accepts a String value representing a class name loads it in to the memory, which automatically registers it. Register the driver using this method"
},
{
"code": null,
"e": 5454,
"s": 5146,
"text": "In general, the first step we do to communicate to the database is to connect with it. The Connection class represents the physical connection with a database server. You can create a connection object by invoking the getConnection() method of the DriverManager class. Create a connection using this method."
},
{
"code": null,
"e": 5747,
"s": 5454,
"text": "You need to create a Statement or PreparedStatement or, CallableStatement objects to send SQL statements to the database. You can create these using the methods createStatement(), prepareStatement() and, prepareCall() respectively. Create either of these objects using the appropriate method."
},
{
"code": null,
"e": 6151,
"s": 5747,
"text": "After creating a statement, you need to execute it. The Statement class provides various methods to execute a query like the execute() method to execute a statement that returns more than one result set. The executeUpdate() method executes queries like INSERT, UPDATE, DELETE. The executeQuery() method results that returns data. Use either of these methods and execute the statement created previously."
},
{
"code": null,
"e": 6401,
"s": 6151,
"text": "Following JDBC example demonstrates how to use WHERE clause and perform CURD operations on a table in Apache Derby using JDBC program. Here, we are connecting to a database named sampleDB (will create if it does not exist) using the embedded driver."
},
{
"code": null,
"e": 8119,
"s": 6401,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Statement;\nimport java.sql.ResultSet;\npublic class WhereClauseExample {\n public static void main(String args[]) throws Exception {\n //Registering the driver\n Class.forName(\"org.apache.derby.jdbc.EmbeddedDriver\");\n //Getting the Connection object\n String URL = \"jdbc:derby:sampleDB;create=true\";\n Connection conn = DriverManager.getConnection(URL);\n\n //Creating the Statement object\n Statement stmt = conn.createStatement();\n\n //Creating a table and populating it\n String query = \"CREATE TABLE Employees(\"\n + \"Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, \"\n + \"Name VARCHAR(255), Salary INT NOT NULL, \"\n + \"Location VARCHAR(255), \"\n + \"PRIMARY KEY (Id))\";\n String query = \"INSERT INTO Employees(\"\n + \"Name, Salary, Location) VALUES \"\n + \"('Amit', 30000, 'Hyderabad'), \"\n + \"('Kalyan', 40000, 'Vishakhapatnam'), \"\n + \"('Renuka', 50000, 'Delhi'), \"\n + \"('Archana', 15000, 'Mumbai'), \"\n + \"('Trupthi', 45000, 'Kochin'), \"\n + \"('Suchatra', 33000, 'Pune'), \"\n + \"('Rahul', 39000, 'Lucknow'), \"\n + \"('Trupti', 45000, 'Kochin')\";\n //Executing the query\n String query = \"SELECT * FROM Employees WHERE Salary>35000\";\n ResultSet rs = stmt.executeQuery(query);\n while(rs.next()) {\n System.out.println(\"Id: \"+rs.getString(\"Id\"));\n System.out.println(\"Name: \"+rs.getString(\"Name\"));\n System.out.println(\"Salary: \"+rs.getString(\"Salary\"));\n System.out.println(\"Location: \"+rs.getString(\"Location\"));\n System.out.println(\" \");\n }\n }\n}"
},
{
"code": null,
"e": 8187,
"s": 8119,
"text": "On executing the above program, you will get the following output −"
},
{
"code": null,
"e": 8392,
"s": 8187,
"text": "Id: 2\nName: Kalyan\nSalary: 43000\nLocation: Chennai\n\nId: 3\nName: Renuka\nSalary: 50000\nLocation: Delhi\n\nId: 5\nName: Trupthi\nSalary: 45000\nLocation: Kochin\n\nId: 7\nName: Rahul\nSalary: 39000\nLocation: Lucknow\n"
},
{
"code": null,
"e": 8427,
"s": 8392,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8446,
"s": 8427,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8481,
"s": 8446,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8502,
"s": 8481,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 8535,
"s": 8502,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8548,
"s": 8535,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 8583,
"s": 8548,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8601,
"s": 8583,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 8634,
"s": 8601,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8652,
"s": 8634,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 8685,
"s": 8652,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8703,
"s": 8685,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 8710,
"s": 8703,
"text": " Print"
},
{
"code": null,
"e": 8721,
"s": 8710,
"text": " Add Notes"
}
] |
SaltStack - Configuration Management
|
Configuration management is one of the most significant concept in SaltStack. It is used to create a reusable configuration template, called a state. The state describes everything required to put a system component or an application into a known configuration.
Salt state is a reusable configuration for a specific part of a system. States are easier to understand and described using a simple YAML.
Salt states are easy to create. Let us create a simple state in this chapter. Move to the directory “salt-vagrant-demo/saltstack/salt/” and create a file named samples.sls and add the following lines in it.
samples.sls
install_network_packages:
pkg.installed:
- pkgs:
- rsync
- lftp
- curl
Now, save the file and run the following command in the Salt master.
root@saltmaster:/home/vagrant# salt 'minion1’ state.apply samples
Here, we installed rsync, lftp and curl through the pkg.installed module using the Salt state in a salt minion, minion1. If it works properly, you could see the response as shown below.
It will produce the following output −
minion1:
----------
ID: install_network_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 08:08:48.612336
Duration: 545.385 ms
Changes:
Summary for minion1
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 545.385 ms
Now that we have created a state using the ‘.sls’ file and applied it by specifically calling it. Salt has a default state file called as the top.sls file. The top file is used to apply multiple state files to Salt minions. The top file describes where states should be applied. Well, States and the Top file work together to create the core of SaltStack’s configuration management capability.
Let us now create a simple top.sls file in the directory saltstack/salt and add the following.
top.sls
base:
'*':
- common
'minion1':
- samples
Here, the state, commonly applies to all system state, samples applies to minion1.
Next, run the Salt master and apply the state as shown below.
root@saltmaster:/home/vagrant# salt '*' state.apply
It will produce the following output −
minion1:
----------
ID: common_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 09:33:35.642355
Duration: 588.21 ms
Changes:
Summary for minion1
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 588.210 ms
minion2:
----------
ID: common_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 09:33:35.890331
Duration: 602.79 ms
Changes:
Summary for minion2
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 602.790 ms
If you have a large number of connected minions, then you can limit how many systems are updated at once. It is performed by using the –batch-size option, which is defined below.
root@saltmaster:/home/vagrant# salt --batch-size 5 '*' state.apply
It will produce the following output −
Executing run on ['minion2', 'minion1']
jid:
20170314094638482664
minion1:
----------
ID: common_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 09:46:41.228519
Duration: 582.24 ms
Changes:
Summary for minion1
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 582.240 ms
retcode:
0
jid:
20170314094638482664
minion2:
----------
ID: common_packages
Function: pkg.installed
Result: True
Comment: All specified packages are already installed
Started: 09:46:41.153609
Duration: 605.235 ms
Changes:
Summary for minion2
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 605.235 ms
retcode:
0
Salt state functions are used to install and configure applications on your remote system. Let us install a “Vim” package using the Salt state function.
Create a file named “sample.sls” under the directory “salt-vagrant-demo/saltstack/salt/sample.sls” and add the following −
sample.sls
install vim:
pkg.installed:
- name: vim
Once, Vagrant environment is up, run the salt master and apply the sample.sls by running the following command.
root@saltmaster:/home/vagrant# sudo salt 'minion2’ state.apply sample
It will produce the following output −
minion2:
----------
ID: install vim
Function: pkg.installed
Name: vim
Result: True
Comment: Package vim is installed
Started: 15:07:45.752764
Duration: 553.506 ms
Changes:
Summary for minion2
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 553.506 ms
Now, we have added a package “Vim”. Let us now test the package using the Salt testing method.
The test run is mandated by adding the “test = True” option to the states. The return information will show states that will be applied in yellow and the result is reported as ‘None’.
The following command is used to test the state −
root@saltmaster:/home/vagrant# sudo salt 'minion2’ state.apply sample test = True
It will produce the following output −
minion2:
----------
ID: install vim
Function: pkg.installed
Name: vim
Result: True
Comment: Package vim is already installed
Started: 15:07:45.752764
Duration: 553.506 ms
Changes:
Summary for minion2
------------
Succeeded: 1
Failed: 0
------------
Total states run: 1
Total run time: 553.506 ms
Pillar is an essential component to make Salt states reusable. It is used to define secure data for minions assigned using targets. Salt pillar data stores values such as ports, file paths, configuration parameters and passwords.
The configuration for the pillar_roots in the master config file is shown below −
pillar_roots:
base:
- /srv/pillar
Here, the file is in the “/srv/pillar” directory.
Consider, the top file located in /srv/pillar/top.sls has the following structure −
base:
'*':
- default
Now, move to the default.sls file located in /srv/pillar/default.sls and add the following code.
# Default pillar values
apache
git
After saving the file, refresh the pillar to update all the changes.
You can refresh the pillar using the following command.
root@saltmaster:/home/vagrant# salt '*' saltutil.refresh_pillar
The above command is used to refresh the Salt pillar data on all the minions.
To list out the pillar data, you can use the command given below.
root@saltmaster:/home/vagrant# salt '*' pillar.ls
It will produce the following output −
minion2:
- apache
- git
minion1:
- apache
- git
Once the pillar is setup, the data can be viewed on the minion via the pillar module. It can be accessed through the function pillar.items, which is defined below.
root@saltmaster:/home/vagrant# salt '*' pillar.items
It will produce the following output −
minion2:
----------
apache:
httpd
git:
git
minion1:
----------
apache:
httpd
git:
git
The ‘Include’ component is used to define the same configuration task in multiple places. It is easy to perform. At the top of your state file, add an include using the following format −
include:
- state file 1
- state file 2
Here, state file 1 and state file 2 are the names of the SLS files that you want to include. No need to include the .sls extension. The Included Salt states are inserted at the top of the current file.
You can include subdirectory state file using a dot (.). It acts as a directory separator.
include:
- dir.sls1
Grains is an interface used to derive the information about the underlying system. Grains are collected for the operating system, domain name, IP address, kernel, OS type, memory and many other system properties.
Grain data can be used when targeting minions, which is defined in the following code block.
root@saltmaster:/home/vagrant# salt -G 'os:Ubuntu' test.ping
It will produce the following output −
minion1:
True
minion2:
True
Grains can be listed by using the ‘grains.ls’ module, which is defined below.
root@saltmaster:/home/vagrant# salt '*' grains.ls
Like Pillar, Grains data can also be listed by using the 'grains.items’.
root@saltmaster:/home/vagrant# salt '*' grains.items
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2469,
"s": 2207,
"text": "Configuration management is one of the most significant concept in SaltStack. It is used to create a reusable configuration template, called a state. The state describes everything required to put a system component or an application into a known configuration."
},
{
"code": null,
"e": 2608,
"s": 2469,
"text": "Salt state is a reusable configuration for a specific part of a system. States are easier to understand and described using a simple YAML."
},
{
"code": null,
"e": 2815,
"s": 2608,
"text": "Salt states are easy to create. Let us create a simple state in this chapter. Move to the directory “salt-vagrant-demo/saltstack/salt/” and create a file named samples.sls and add the following lines in it."
},
{
"code": null,
"e": 2827,
"s": 2815,
"text": "samples.sls"
},
{
"code": null,
"e": 2935,
"s": 2827,
"text": "install_network_packages:\n pkg.installed:\n - pkgs:\n - rsync\n - lftp\n - curl\n"
},
{
"code": null,
"e": 3004,
"s": 2935,
"text": "Now, save the file and run the following command in the Salt master."
},
{
"code": null,
"e": 3071,
"s": 3004,
"text": "root@saltmaster:/home/vagrant# salt 'minion1’ state.apply samples\n"
},
{
"code": null,
"e": 3257,
"s": 3071,
"text": "Here, we installed rsync, lftp and curl through the pkg.installed module using the Salt state in a salt minion, minion1. If it works properly, you could see the response as shown below."
},
{
"code": null,
"e": 3296,
"s": 3257,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3637,
"s": 3296,
"text": "minion1:\n----------\n ID: install_network_packages\n Function: pkg.installed\n Result: True\n Comment: All specified packages are already installed\n Started: 08:08:48.612336\n Duration: 545.385 ms\n Changes:\n\nSummary for minion1\n------------\nSucceeded: 1\nFailed: 0\n------------\nTotal states run: 1\nTotal run time: 545.385 ms\n"
},
{
"code": null,
"e": 4031,
"s": 3637,
"text": "Now that we have created a state using the ‘.sls’ file and applied it by specifically calling it. Salt has a default state file called as the top.sls file. The top file is used to apply multiple state files to Salt minions. The top file describes where states should be applied. Well, States and the Top file work together to create the core of SaltStack’s configuration management capability."
},
{
"code": null,
"e": 4126,
"s": 4031,
"text": "Let us now create a simple top.sls file in the directory saltstack/salt and add the following."
},
{
"code": null,
"e": 4134,
"s": 4126,
"text": "top.sls"
},
{
"code": null,
"e": 4193,
"s": 4134,
"text": "base:\n '*':\n - common\n 'minion1':\n - samples\n"
},
{
"code": null,
"e": 4276,
"s": 4193,
"text": "Here, the state, commonly applies to all system state, samples applies to minion1."
},
{
"code": null,
"e": 4338,
"s": 4276,
"text": "Next, run the Salt master and apply the state as shown below."
},
{
"code": null,
"e": 4390,
"s": 4338,
"text": "root@saltmaster:/home/vagrant# salt '*' state.apply"
},
{
"code": null,
"e": 4429,
"s": 4390,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 5090,
"s": 4429,
"text": "minion1:\n----------\n ID: common_packages\n Function: pkg.installed\n Result: True\n Comment: All specified packages are already installed\n Started: 09:33:35.642355\n Duration: 588.21 ms\n Changes:\n\nSummary for minion1\n------------\nSucceeded: 1\nFailed: 0\n------------\nTotal states run: 1\nTotal run time: 588.210 ms\nminion2:\n----------\n ID: common_packages\n Function: pkg.installed\n Result: True\n Comment: All specified packages are already installed\n Started: 09:33:35.890331\n Duration: 602.79 ms\n Changes:\n\nSummary for minion2\n------------\nSucceeded: 1\nFailed: 0\n------------\nTotal states run: 1\nTotal run time: 602.790 ms\n"
},
{
"code": null,
"e": 5269,
"s": 5090,
"text": "If you have a large number of connected minions, then you can limit how many systems are updated at once. It is performed by using the –batch-size option, which is defined below."
},
{
"code": null,
"e": 5336,
"s": 5269,
"text": "root@saltmaster:/home/vagrant# salt --batch-size 5 '*' state.apply"
},
{
"code": null,
"e": 5375,
"s": 5336,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 6163,
"s": 5375,
"text": "Executing run on ['minion2', 'minion1']\njid:\n 20170314094638482664\nminion1:\n----------\n ID: common_packages\n Function: pkg.installed\n Result: True\n Comment: All specified packages are already installed\n Started: 09:46:41.228519\n Duration: 582.24 ms\n Changes:\n\nSummary for minion1\n------------\nSucceeded: 1\nFailed: 0\n------------\nTotal states run: 1\nTotal run time: 582.240 ms\nretcode:\n 0\njid:\n 20170314094638482664\nminion2:\n----------\n ID: common_packages\n Function: pkg.installed\n Result: True\n Comment: All specified packages are already installed\n Started: 09:46:41.153609\n Duration: 605.235 ms\n Changes:\n\nSummary for minion2\n------------\nSucceeded: 1\nFailed: 0\n------------\nTotal states run: 1\nTotal run time: 605.235 ms\nretcode:\n 0\n"
},
{
"code": null,
"e": 6316,
"s": 6163,
"text": "Salt state functions are used to install and configure applications on your remote system. Let us install a “Vim” package using the Salt state function."
},
{
"code": null,
"e": 6439,
"s": 6316,
"text": "Create a file named “sample.sls” under the directory “salt-vagrant-demo/saltstack/salt/sample.sls” and add the following −"
},
{
"code": null,
"e": 6450,
"s": 6439,
"text": "sample.sls"
},
{
"code": null,
"e": 6500,
"s": 6450,
"text": "install vim:\n pkg.installed:\n - name: vim\n"
},
{
"code": null,
"e": 6612,
"s": 6500,
"text": "Once, Vagrant environment is up, run the salt master and apply the sample.sls by running the following command."
},
{
"code": null,
"e": 6682,
"s": 6612,
"text": "root@saltmaster:/home/vagrant# sudo salt 'minion2’ state.apply sample"
},
{
"code": null,
"e": 6721,
"s": 6682,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 7042,
"s": 6721,
"text": "minion2:\n----------\n ID: install vim\n Function: pkg.installed\n Name: vim\n Result: True\n Comment: Package vim is installed\n Started: 15:07:45.752764\n Duration: 553.506 ms\n Changes:\n\nSummary for minion2\n------------\nSucceeded: 1\nFailed: 0\n------------\nTotal states run: 1\nTotal run time: 553.506 ms\n"
},
{
"code": null,
"e": 7137,
"s": 7042,
"text": "Now, we have added a package “Vim”. Let us now test the package using the Salt testing method."
},
{
"code": null,
"e": 7321,
"s": 7137,
"text": "The test run is mandated by adding the “test = True” option to the states. The return information will show states that will be applied in yellow and the result is reported as ‘None’."
},
{
"code": null,
"e": 7371,
"s": 7321,
"text": "The following command is used to test the state −"
},
{
"code": null,
"e": 7454,
"s": 7371,
"text": "root@saltmaster:/home/vagrant# sudo salt 'minion2’ state.apply sample test = True\n"
},
{
"code": null,
"e": 7493,
"s": 7454,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 7822,
"s": 7493,
"text": "minion2:\n----------\n ID: install vim\n Function: pkg.installed\n Name: vim\n Result: True\n Comment: Package vim is already installed\n Started: 15:07:45.752764\n Duration: 553.506 ms\n Changes:\n\nSummary for minion2\n------------\nSucceeded: 1\nFailed: 0\n------------\nTotal states run: 1\nTotal run time: 553.506 ms\n"
},
{
"code": null,
"e": 8052,
"s": 7822,
"text": "Pillar is an essential component to make Salt states reusable. It is used to define secure data for minions assigned using targets. Salt pillar data stores values such as ports, file paths, configuration parameters and passwords."
},
{
"code": null,
"e": 8134,
"s": 8052,
"text": "The configuration for the pillar_roots in the master config file is shown below −"
},
{
"code": null,
"e": 8178,
"s": 8134,
"text": "pillar_roots:\n base:\n - /srv/pillar\n"
},
{
"code": null,
"e": 8228,
"s": 8178,
"text": "Here, the file is in the “/srv/pillar” directory."
},
{
"code": null,
"e": 8312,
"s": 8228,
"text": "Consider, the top file located in /srv/pillar/top.sls has the following structure −"
},
{
"code": null,
"e": 8343,
"s": 8312,
"text": "base:\n '*':\n - default\n"
},
{
"code": null,
"e": 8440,
"s": 8343,
"text": "Now, move to the default.sls file located in /srv/pillar/default.sls and add the following code."
},
{
"code": null,
"e": 8476,
"s": 8440,
"text": "# Default pillar values\napache\ngit\n"
},
{
"code": null,
"e": 8545,
"s": 8476,
"text": "After saving the file, refresh the pillar to update all the changes."
},
{
"code": null,
"e": 8601,
"s": 8545,
"text": "You can refresh the pillar using the following command."
},
{
"code": null,
"e": 8666,
"s": 8601,
"text": "root@saltmaster:/home/vagrant# salt '*' saltutil.refresh_pillar\n"
},
{
"code": null,
"e": 8744,
"s": 8666,
"text": "The above command is used to refresh the Salt pillar data on all the minions."
},
{
"code": null,
"e": 8810,
"s": 8744,
"text": "To list out the pillar data, you can use the command given below."
},
{
"code": null,
"e": 8860,
"s": 8810,
"text": "root@saltmaster:/home/vagrant# salt '*' pillar.ls"
},
{
"code": null,
"e": 8899,
"s": 8860,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 8960,
"s": 8899,
"text": "minion2:\n - apache\n - git\nminion1:\n - apache\n - git\n"
},
{
"code": null,
"e": 9124,
"s": 8960,
"text": "Once the pillar is setup, the data can be viewed on the minion via the pillar module. It can be accessed through the function pillar.items, which is defined below."
},
{
"code": null,
"e": 9177,
"s": 9124,
"text": "root@saltmaster:/home/vagrant# salt '*' pillar.items"
},
{
"code": null,
"e": 9216,
"s": 9177,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 9345,
"s": 9216,
"text": "minion2:\n ----------\n apache:\n httpd\n git:\n git\nminion1:\n ----------\n apache:\n httpd\n git:\n git\n"
},
{
"code": null,
"e": 9533,
"s": 9345,
"text": "The ‘Include’ component is used to define the same configuration task in multiple places. It is easy to perform. At the top of your state file, add an include using the following format −"
},
{
"code": null,
"e": 9580,
"s": 9533,
"text": "include:\n - state file 1 \n - state file 2\n"
},
{
"code": null,
"e": 9782,
"s": 9580,
"text": "Here, state file 1 and state file 2 are the names of the SLS files that you want to include. No need to include the .sls extension. The Included Salt states are inserted at the top of the current file."
},
{
"code": null,
"e": 9873,
"s": 9782,
"text": "You can include subdirectory state file using a dot (.). It acts as a directory separator."
},
{
"code": null,
"e": 9898,
"s": 9873,
"text": "include:\n - dir.sls1 \n"
},
{
"code": null,
"e": 10111,
"s": 9898,
"text": "Grains is an interface used to derive the information about the underlying system. Grains are collected for the operating system, domain name, IP address, kernel, OS type, memory and many other system properties."
},
{
"code": null,
"e": 10204,
"s": 10111,
"text": "Grain data can be used when targeting minions, which is defined in the following code block."
},
{
"code": null,
"e": 10266,
"s": 10204,
"text": "root@saltmaster:/home/vagrant# salt -G 'os:Ubuntu' test.ping\n"
},
{
"code": null,
"e": 10305,
"s": 10266,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 10340,
"s": 10305,
"text": "minion1:\n True\nminion2:\n True\n"
},
{
"code": null,
"e": 10418,
"s": 10340,
"text": "Grains can be listed by using the ‘grains.ls’ module, which is defined below."
},
{
"code": null,
"e": 10469,
"s": 10418,
"text": "root@saltmaster:/home/vagrant# salt '*' grains.ls\n"
},
{
"code": null,
"e": 10542,
"s": 10469,
"text": "Like Pillar, Grains data can also be listed by using the 'grains.items’."
},
{
"code": null,
"e": 10596,
"s": 10542,
"text": "root@saltmaster:/home/vagrant# salt '*' grains.items\n"
},
{
"code": null,
"e": 10603,
"s": 10596,
"text": " Print"
},
{
"code": null,
"e": 10614,
"s": 10603,
"text": " Add Notes"
}
] |
Introduction to Dart Programming Language - GeeksforGeeks
|
11 Jun, 2020
Dart is the open-source programming language originally developed by Google. It is meant for both server side as well as the user side. The Dart SDK comes with its compiler – the Dart VM and a utility dart2js which is meant for generating Javascript equivalent of a Dart Script so that it can be run on those sites also which don’t support Dart.
Dart is Object-oriented language and is quite similar to that of Java Programming. Dart is extensively use to create single-page websites and web-applications. Best example of dart application is Gmail.
You can install Dart SDK from their official website or download the installer from this site.
For Windows OS:
To install dart in window system we will be using Chocolatey.
To install Dart:
C:\> choco install dart-sdk
To Update Dart:
C:\> choco upgrade dart-sdk
For Linux OS:
If you’re using Debian/Ubuntu on AMD64 (64-bit Intel), you can choose one of the following options, both of which can update the SDK automatically when new versions are released.
Install using apt-get
Install a Debian package
Perform the following one-time setup:
$ sudo apt-get update
$ sudo apt-get install apt-transport-https
$ sudo sh -c 'wget -qO- https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -'
$ sudo sh -c 'wget -qO- https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list'
Then install the Dart SDK:
$ sudo apt-get update
$ sudo apt-get install dart
Download Dart SDK as Debian package in the .deb package format.
Modify PATH for access to all Dart binaries
After installing the SDK, add its bin directory to your PATH. For example, use the following command to change PATH in your active terminal session:
$ export PATH="$PATH:/usr/lib/dart/bin"
To change the PATH for future terminal sessions, use a command like this:
$ echo 'export PATH="$PATH:/usr/lib/dart/bin"' >> ~/.profile
For Mac OS: Install Homebrew , and then run the following commands:
$ brew tap dart-lang/dart
$ brew install dart
To upgrade when a new release of Dart is available:
$ brew upgrade dart
First Code in Dart: In dart main() function is predefined method and acts as the entry point to the application. A dart script needs the main() method for execution of the code. The program code goes like this:
Dart
main() { print("Welcome to GeeksForGeeks");}
Output:
Welcome to GeeksForGeeks
The print() command is predefined function that prints the specific string or value to the standard input.
Execution of program:
Online Compiler: The online compiler which support Dart is Dart Pad.IDE: The IDEs which support Dart are WebStorm, Intellij, Eclipse, etc. Among them WebStorm from Jetbrains is available for Mac OS, Windows and Linux.The dart program can also be compile through terminal by executing the code dart file_name.dart.
Online Compiler: The online compiler which support Dart is Dart Pad.
IDE: The IDEs which support Dart are WebStorm, Intellij, Eclipse, etc. Among them WebStorm from Jetbrains is available for Mac OS, Windows and Linux.
The dart program can also be compile through terminal by executing the code dart file_name.dart.
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - BoxShadow Widget
Flutter - Checkbox Widget
Dart Tutorial
How to Append or Concatenate Strings in Dart?
Android Studio Setup for Flutter Development
Flutter - Flexible Widget
Flutter - Carousel Slider
|
[
{
"code": null,
"e": 24118,
"s": 24090,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 24465,
"s": 24118,
"text": "Dart is the open-source programming language originally developed by Google. It is meant for both server side as well as the user side. The Dart SDK comes with its compiler – the Dart VM and a utility dart2js which is meant for generating Javascript equivalent of a Dart Script so that it can be run on those sites also which don’t support Dart. "
},
{
"code": null,
"e": 24668,
"s": 24465,
"text": "Dart is Object-oriented language and is quite similar to that of Java Programming. Dart is extensively use to create single-page websites and web-applications. Best example of dart application is Gmail."
},
{
"code": null,
"e": 24763,
"s": 24668,
"text": "You can install Dart SDK from their official website or download the installer from this site."
},
{
"code": null,
"e": 24780,
"s": 24763,
"text": "For Windows OS: "
},
{
"code": null,
"e": 24842,
"s": 24780,
"text": "To install dart in window system we will be using Chocolatey."
},
{
"code": null,
"e": 24859,
"s": 24842,
"text": "To install Dart:"
},
{
"code": null,
"e": 24888,
"s": 24859,
"text": "C:\\> choco install dart-sdk\n"
},
{
"code": null,
"e": 24904,
"s": 24888,
"text": "To Update Dart:"
},
{
"code": null,
"e": 24933,
"s": 24904,
"text": "C:\\> choco upgrade dart-sdk\n"
},
{
"code": null,
"e": 24947,
"s": 24933,
"text": "For Linux OS:"
},
{
"code": null,
"e": 25127,
"s": 24947,
"text": " If you’re using Debian/Ubuntu on AMD64 (64-bit Intel), you can choose one of the following options, both of which can update the SDK automatically when new versions are released."
},
{
"code": null,
"e": 25149,
"s": 25127,
"text": "Install using apt-get"
},
{
"code": null,
"e": 25174,
"s": 25149,
"text": "Install a Debian package"
},
{
"code": null,
"e": 25212,
"s": 25174,
"text": "Perform the following one-time setup:"
},
{
"code": null,
"e": 25524,
"s": 25212,
"text": "$ sudo apt-get update\n$ sudo apt-get install apt-transport-https\n$ sudo sh -c 'wget -qO- https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -'\n$ sudo sh -c 'wget -qO- https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list'\n"
},
{
"code": null,
"e": 25552,
"s": 25524,
"text": " Then install the Dart SDK:"
},
{
"code": null,
"e": 25603,
"s": 25552,
"text": "$ sudo apt-get update\n$ sudo apt-get install dart\n"
},
{
"code": null,
"e": 25667,
"s": 25603,
"text": "Download Dart SDK as Debian package in the .deb package format."
},
{
"code": null,
"e": 25711,
"s": 25667,
"text": "Modify PATH for access to all Dart binaries"
},
{
"code": null,
"e": 25860,
"s": 25711,
"text": "After installing the SDK, add its bin directory to your PATH. For example, use the following command to change PATH in your active terminal session:"
},
{
"code": null,
"e": 25901,
"s": 25860,
"text": "$ export PATH=\"$PATH:/usr/lib/dart/bin\"\n"
},
{
"code": null,
"e": 25975,
"s": 25901,
"text": "To change the PATH for future terminal sessions, use a command like this:"
},
{
"code": null,
"e": 26037,
"s": 25975,
"text": "$ echo 'export PATH=\"$PATH:/usr/lib/dart/bin\"' >> ~/.profile\n"
},
{
"code": null,
"e": 26105,
"s": 26037,
"text": "For Mac OS: Install Homebrew , and then run the following commands:"
},
{
"code": null,
"e": 26152,
"s": 26105,
"text": "$ brew tap dart-lang/dart\n$ brew install dart\n"
},
{
"code": null,
"e": 26204,
"s": 26152,
"text": "To upgrade when a new release of Dart is available:"
},
{
"code": null,
"e": 26225,
"s": 26204,
"text": "$ brew upgrade dart\n"
},
{
"code": null,
"e": 26438,
"s": 26225,
"text": "First Code in Dart: In dart main() function is predefined method and acts as the entry point to the application. A dart script needs the main() method for execution of the code. The program code goes like this: "
},
{
"code": null,
"e": 26443,
"s": 26438,
"text": "Dart"
},
{
"code": "main() { print(\"Welcome to GeeksForGeeks\");}",
"e": 26491,
"s": 26443,
"text": null
},
{
"code": null,
"e": 26499,
"s": 26491,
"text": "Output:"
},
{
"code": null,
"e": 26525,
"s": 26499,
"text": "Welcome to GeeksForGeeks\n"
},
{
"code": null,
"e": 26632,
"s": 26525,
"text": "The print() command is predefined function that prints the specific string or value to the standard input."
},
{
"code": null,
"e": 26654,
"s": 26632,
"text": "Execution of program:"
},
{
"code": null,
"e": 26968,
"s": 26654,
"text": "Online Compiler: The online compiler which support Dart is Dart Pad.IDE: The IDEs which support Dart are WebStorm, Intellij, Eclipse, etc. Among them WebStorm from Jetbrains is available for Mac OS, Windows and Linux.The dart program can also be compile through terminal by executing the code dart file_name.dart."
},
{
"code": null,
"e": 27037,
"s": 26968,
"text": "Online Compiler: The online compiler which support Dart is Dart Pad."
},
{
"code": null,
"e": 27187,
"s": 27037,
"text": "IDE: The IDEs which support Dart are WebStorm, Intellij, Eclipse, etc. Among them WebStorm from Jetbrains is available for Mac OS, Windows and Linux."
},
{
"code": null,
"e": 27284,
"s": 27187,
"text": "The dart program can also be compile through terminal by executing the code dart file_name.dart."
},
{
"code": null,
"e": 27291,
"s": 27286,
"text": "Dart"
},
{
"code": null,
"e": 27389,
"s": 27291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27398,
"s": 27389,
"text": "Comments"
},
{
"code": null,
"e": 27411,
"s": 27398,
"text": "Old Comments"
},
{
"code": null,
"e": 27443,
"s": 27411,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 27482,
"s": 27443,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 27508,
"s": 27482,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 27535,
"s": 27508,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 27561,
"s": 27535,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 27575,
"s": 27561,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 27621,
"s": 27575,
"text": "How to Append or Concatenate Strings in Dart?"
},
{
"code": null,
"e": 27666,
"s": 27621,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 27692,
"s": 27666,
"text": "Flutter - Flexible Widget"
}
] |
Lexicographically smallest subsequence possible by removing a character from given string - GeeksforGeeks
|
19 Feb, 2022
Given a string S of length N, the task is to find the lexicographically smallest subsequence of length (N – 1), i.e. by removing a single character from the given string.
Examples:
Input: S = “geeksforgeeks”Output: “eeksforgeeks”Explanation: Lexicographically smallest subsequence possible is “eeksforgeeks”.
Input: S = “zxvsjas”Output: “xvsjas”Explanation: Lexicographically smallest subsequence possible is “xvsjas”.
Naive Approach: The simplest approach is to generate all possible subsequences of length (N – 1) from the given string and store all subsequences in an array. Now, sort the array and print the string at 0th position for the smallest lexicographically subsequence.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the lexicographically// smallest subsequence of length N-1void firstSubsequence(string s){ vector<string> allsubseq; string k; // Generate all subsequence of // length N-1 for (int i = 0; i < s.length(); i++) { // Store main value of string str k = s; // Erasing element at position i k.erase(i, 1); allsubseq.push_back(k); } // Sort the vector sort(allsubseq.begin(), allsubseq.end()); // Print first element of vector cout << allsubseq[0];} // Driver Codeint main(){ // Given string S string S = "geeksforgeeks"; // Function Call firstSubsequence(S); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(String s){ Vector<String> allsubseq = new Vector<>(); // Generate all subsequence of // length N-1 for(int i = 0; i < s.length(); i++) { String k = ""; // Store main value of String str for(int j = 0; j < s.length(); j++) { if (i != j) { k += s.charAt(j); } } allsubseq.add(k); } // Sort the vector Collections.sort(allsubseq); // Print first element of vector System.out.print(allsubseq.get(0));} // Driver Codepublic static void main(String[] args){ // Given String S String S = "geeksforgeeks"; // Function Call firstSubsequence(S);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to find the lexicographically# smallest subsequence of length N-1def firstSubsequence(s): allsubseq = [] k = [] # Generate all subsequence of # length N-1 for i in range(len(s)): # Store main value of string str k = [i for i in s] # Erasing element at position i del k[i] allsubseq.append("".join(k)) # Sort the vector allsubseq = sorted(allsubseq) # Print first element of vector print(allsubseq[0]) # Driver Codeif __name__ == '__main__': # Given string S S = "geeksforgeeks" # Function Call firstSubsequence(S) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(string s){ List<string> allsubseq = new List<string>(); // Generate all subsequence of // length N-1 for(int i = 0; i < s.Length; i++) { string k = ""; // Store main value of string str for(int j = 0; j < s.Length; j++) { if (i != j) { k += s[j]; } } allsubseq.Add(k); } // Sort the vector allsubseq.Sort(); // Print first element of vector Console.WriteLine(allsubseq[0]);} // Driver Codepublic static void Main(){ // Given string S string S = "geeksforgeeks"; // Function Call firstSubsequence(S);}} // This code is contributed by ipg2016107
<script>// Javascript program for the above approach // Function to find the lexicographically// smallest subsequence of length N-1function firstSubsequence(s){ let allsubseq = []; // Generate all subsequence of // length N-1 for(let i = 0; i < s.length; i++) { let k = ""; // Store main value of String str for(let j = 0; j < s.length; j++) { if (i != j) { k += s[j]; } } allsubseq.push(k); } // Sort the vector (allsubseq).sort(); // Print first element of vector document.write(allsubseq[0]);} // Driver Code // Given String Slet S = "geeksforgeeks"; // Function CallfirstSubsequence(S); // This code is contributed by patel2127</script>
Output:
eeksforgeeks
Time Complexity: O(N *N)Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to iterate over the string and check if the ith character is greater that (i + 1)th character, then simply remove the ith character and print the remaining string. Otherwise, remove the last element and print the desired subsequence.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the lexicographically// smallest subsequence of length N-1void firstSubsequence(string s){ // Store index of character // to be deleted int isMax = -1; // Traverse the string for (int i = 0; i < s.length() - 1; i++) { // If ith character > (i + 1)th // character then store it if (s[i] > s[i + 1]) { isMax = i; break; } } // If any character found in non // alphabetical order then remove it if (isMax >= 0) { s.erase(isMax, 1); } // Otherwise remove last character else { s.erase(s.length() - 1, 1); } // Print the resultant subsequence cout << s;} // Driver Codeint main(){ // Given string S string S = "geeksforgeeks"; // Function Call firstSubsequence(S); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(String s){ // Store index of character // to be deleted int isMax = -1; // Traverse the String for(int i = 0; i < s.length() - 1; i++) { // If ith character > (i + 1)th // character then store it if (s.charAt(i) > s.charAt(i + 1)) { isMax = i; break; } } // If any character found in non // alphabetical order then remove it if (isMax >= 0) { s = s.substring(0, isMax) + s.substring(isMax + 1); // s.rerase(isMax, 1); } // Otherwise remove last character else { //s.erase(s.length() - 1, 1); s = s.substring(0, s.length() - 1); } // Print the resultant subsequence System.out.print(s);} // Driver Codepublic static void main(String[] args){ // Given String S String S = "geeksforgeeks"; // Function Call firstSubsequence(S);}} // This code is contributed by Princi Singh
# Python3 program for the above approach # Function to find the lexicographically# smallest subsequence of length N-1def firstSubsequence(s): # Store index of character # to be deleted isMax = -1 # Traverse the String for i in range(len(s)): # If ith character > (i + 1)th # character then store it if (s[i] > s[i + 1]): isMax = i break # If any character found in non # alphabetical order then remove it if (isMax >= 0): s = s[0 : isMax] + s[isMax + 1 : len(s)] # s.rerase(isMax, 1); # Otherwise remove last character else: # s.erase(s.length() - 1, 1); s = s[0: s.length() - 1] # Print the resultant subsequence print(s) # Driver Codeif __name__ == '__main__': # Given String S S = "geeksforgeeks" # Function Call firstSubsequence(S) # This code is contributed by Princi Singh
// C# program for the above approachusing System; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(String s){ // Store index of character // to be deleted int isMax = -1; // Traverse the String for(int i = 0; i < s.Length - 1; i++) { // If ith character > (i + 1)th // character then store it if (s[i] > s[i + 1]) { isMax = i; break; } } // If any character found in non // alphabetical order then remove it if (isMax >= 0) { s = s.Substring(0, isMax) + s.Substring(isMax + 1); // s.rerase(isMax, 1); } // Otherwise remove last character else { //s.erase(s.Length - 1, 1); s = s.Substring(0, s.Length - 1); } // Print the resultant subsequence Console.Write(s);} // Driver Codepublic static void Main(String[] args){ // Given String S String S = "geeksforgeeks"; // Function Call firstSubsequence(S);}} // This code is contributed by Amit Katiyar
<script>// Javascript program for the above approach // Function to find the lexicographically// smallest subsequence of length N-1function firstSubsequence(s){ // Store index of character // to be deleted let isMax = -1; // Traverse the String for(let i = 0; i < s.length - 1; i++) { // If ith character > (i + 1)th // character then store it if (s[i] > s[i + 1]) { isMax = i; break; } } // If any character found in non // alphabetical order then remove it if (isMax >= 0) { s = s.substring(0, isMax) + s.substring(isMax + 1); // s.rerase(isMax, 1); } // Otherwise remove last character else { //s.erase(s.length() - 1, 1); s = s.substring(0, s.length - 1); } // Print the resultant subsequence document.write(s);} // Driver Code// Given String Slet S = "geeksforgeeks"; // Function CallfirstSubsequence(S); // This code is contributed by unknown2108</script>
Output:
eeksforgeeks
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
amit143katiyar
ipg2016107
princi singh
patel2127
unknown2108
sunnykr2
lexicographic-ordering
subsequence
Combinatorial
Sorting
Strings
Strings
Sorting
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Combinational Sum
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Print all possible strings of length k that can be formed from a set of n characters
Print all subsets of given size of a set
|
[
{
"code": null,
"e": 25689,
"s": 25661,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 25860,
"s": 25689,
"text": "Given a string S of length N, the task is to find the lexicographically smallest subsequence of length (N – 1), i.e. by removing a single character from the given string."
},
{
"code": null,
"e": 25870,
"s": 25860,
"text": "Examples:"
},
{
"code": null,
"e": 25998,
"s": 25870,
"text": "Input: S = “geeksforgeeks”Output: “eeksforgeeks”Explanation: Lexicographically smallest subsequence possible is “eeksforgeeks”."
},
{
"code": null,
"e": 26108,
"s": 25998,
"text": "Input: S = “zxvsjas”Output: “xvsjas”Explanation: Lexicographically smallest subsequence possible is “xvsjas”."
},
{
"code": null,
"e": 26372,
"s": 26108,
"text": "Naive Approach: The simplest approach is to generate all possible subsequences of length (N – 1) from the given string and store all subsequences in an array. Now, sort the array and print the string at 0th position for the smallest lexicographically subsequence."
},
{
"code": null,
"e": 26423,
"s": 26372,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26427,
"s": 26423,
"text": "C++"
},
{
"code": null,
"e": 26432,
"s": 26427,
"text": "Java"
},
{
"code": null,
"e": 26440,
"s": 26432,
"text": "Python3"
},
{
"code": null,
"e": 26443,
"s": 26440,
"text": "C#"
},
{
"code": null,
"e": 26454,
"s": 26443,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the lexicographically// smallest subsequence of length N-1void firstSubsequence(string s){ vector<string> allsubseq; string k; // Generate all subsequence of // length N-1 for (int i = 0; i < s.length(); i++) { // Store main value of string str k = s; // Erasing element at position i k.erase(i, 1); allsubseq.push_back(k); } // Sort the vector sort(allsubseq.begin(), allsubseq.end()); // Print first element of vector cout << allsubseq[0];} // Driver Codeint main(){ // Given string S string S = \"geeksforgeeks\"; // Function Call firstSubsequence(S); return 0;}",
"e": 27217,
"s": 26454,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(String s){ Vector<String> allsubseq = new Vector<>(); // Generate all subsequence of // length N-1 for(int i = 0; i < s.length(); i++) { String k = \"\"; // Store main value of String str for(int j = 0; j < s.length(); j++) { if (i != j) { k += s.charAt(j); } } allsubseq.add(k); } // Sort the vector Collections.sort(allsubseq); // Print first element of vector System.out.print(allsubseq.get(0));} // Driver Codepublic static void main(String[] args){ // Given String S String S = \"geeksforgeeks\"; // Function Call firstSubsequence(S);}} // This code is contributed by Amit Katiyar",
"e": 28129,
"s": 27217,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the lexicographically# smallest subsequence of length N-1def firstSubsequence(s): allsubseq = [] k = [] # Generate all subsequence of # length N-1 for i in range(len(s)): # Store main value of string str k = [i for i in s] # Erasing element at position i del k[i] allsubseq.append(\"\".join(k)) # Sort the vector allsubseq = sorted(allsubseq) # Print first element of vector print(allsubseq[0]) # Driver Codeif __name__ == '__main__': # Given string S S = \"geeksforgeeks\" # Function Call firstSubsequence(S) # This code is contributed by mohit kumar 29",
"e": 28827,
"s": 28129,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(string s){ List<string> allsubseq = new List<string>(); // Generate all subsequence of // length N-1 for(int i = 0; i < s.Length; i++) { string k = \"\"; // Store main value of string str for(int j = 0; j < s.Length; j++) { if (i != j) { k += s[j]; } } allsubseq.Add(k); } // Sort the vector allsubseq.Sort(); // Print first element of vector Console.WriteLine(allsubseq[0]);} // Driver Codepublic static void Main(){ // Given string S string S = \"geeksforgeeks\"; // Function Call firstSubsequence(S);}} // This code is contributed by ipg2016107",
"e": 29726,
"s": 28827,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to find the lexicographically// smallest subsequence of length N-1function firstSubsequence(s){ let allsubseq = []; // Generate all subsequence of // length N-1 for(let i = 0; i < s.length; i++) { let k = \"\"; // Store main value of String str for(let j = 0; j < s.length; j++) { if (i != j) { k += s[j]; } } allsubseq.push(k); } // Sort the vector (allsubseq).sort(); // Print first element of vector document.write(allsubseq[0]);} // Driver Code // Given String Slet S = \"geeksforgeeks\"; // Function CallfirstSubsequence(S); // This code is contributed by patel2127</script>",
"e": 30508,
"s": 29726,
"text": null
},
{
"code": null,
"e": 30516,
"s": 30508,
"text": "Output:"
},
{
"code": null,
"e": 30529,
"s": 30516,
"text": "eeksforgeeks"
},
{
"code": null,
"e": 30575,
"s": 30529,
"text": "Time Complexity: O(N *N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 30873,
"s": 30575,
"text": "Efficient Approach: To optimize the above approach, the idea is to iterate over the string and check if the ith character is greater that (i + 1)th character, then simply remove the ith character and print the remaining string. Otherwise, remove the last element and print the desired subsequence."
},
{
"code": null,
"e": 30924,
"s": 30873,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 30928,
"s": 30924,
"text": "C++"
},
{
"code": null,
"e": 30933,
"s": 30928,
"text": "Java"
},
{
"code": null,
"e": 30941,
"s": 30933,
"text": "Python3"
},
{
"code": null,
"e": 30944,
"s": 30941,
"text": "C#"
},
{
"code": null,
"e": 30955,
"s": 30944,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the lexicographically// smallest subsequence of length N-1void firstSubsequence(string s){ // Store index of character // to be deleted int isMax = -1; // Traverse the string for (int i = 0; i < s.length() - 1; i++) { // If ith character > (i + 1)th // character then store it if (s[i] > s[i + 1]) { isMax = i; break; } } // If any character found in non // alphabetical order then remove it if (isMax >= 0) { s.erase(isMax, 1); } // Otherwise remove last character else { s.erase(s.length() - 1, 1); } // Print the resultant subsequence cout << s;} // Driver Codeint main(){ // Given string S string S = \"geeksforgeeks\"; // Function Call firstSubsequence(S); return 0;}",
"e": 31868,
"s": 30955,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(String s){ // Store index of character // to be deleted int isMax = -1; // Traverse the String for(int i = 0; i < s.length() - 1; i++) { // If ith character > (i + 1)th // character then store it if (s.charAt(i) > s.charAt(i + 1)) { isMax = i; break; } } // If any character found in non // alphabetical order then remove it if (isMax >= 0) { s = s.substring(0, isMax) + s.substring(isMax + 1); // s.rerase(isMax, 1); } // Otherwise remove last character else { //s.erase(s.length() - 1, 1); s = s.substring(0, s.length() - 1); } // Print the resultant subsequence System.out.print(s);} // Driver Codepublic static void main(String[] args){ // Given String S String S = \"geeksforgeeks\"; // Function Call firstSubsequence(S);}} // This code is contributed by Princi Singh",
"e": 33010,
"s": 31868,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the lexicographically# smallest subsequence of length N-1def firstSubsequence(s): # Store index of character # to be deleted isMax = -1 # Traverse the String for i in range(len(s)): # If ith character > (i + 1)th # character then store it if (s[i] > s[i + 1]): isMax = i break # If any character found in non # alphabetical order then remove it if (isMax >= 0): s = s[0 : isMax] + s[isMax + 1 : len(s)] # s.rerase(isMax, 1); # Otherwise remove last character else: # s.erase(s.length() - 1, 1); s = s[0: s.length() - 1] # Print the resultant subsequence print(s) # Driver Codeif __name__ == '__main__': # Given String S S = \"geeksforgeeks\" # Function Call firstSubsequence(S) # This code is contributed by Princi Singh",
"e": 33934,
"s": 33010,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(String s){ // Store index of character // to be deleted int isMax = -1; // Traverse the String for(int i = 0; i < s.Length - 1; i++) { // If ith character > (i + 1)th // character then store it if (s[i] > s[i + 1]) { isMax = i; break; } } // If any character found in non // alphabetical order then remove it if (isMax >= 0) { s = s.Substring(0, isMax) + s.Substring(isMax + 1); // s.rerase(isMax, 1); } // Otherwise remove last character else { //s.erase(s.Length - 1, 1); s = s.Substring(0, s.Length - 1); } // Print the resultant subsequence Console.Write(s);} // Driver Codepublic static void Main(String[] args){ // Given String S String S = \"geeksforgeeks\"; // Function Call firstSubsequence(S);}} // This code is contributed by Amit Katiyar",
"e": 35045,
"s": 33934,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to find the lexicographically// smallest subsequence of length N-1function firstSubsequence(s){ // Store index of character // to be deleted let isMax = -1; // Traverse the String for(let i = 0; i < s.length - 1; i++) { // If ith character > (i + 1)th // character then store it if (s[i] > s[i + 1]) { isMax = i; break; } } // If any character found in non // alphabetical order then remove it if (isMax >= 0) { s = s.substring(0, isMax) + s.substring(isMax + 1); // s.rerase(isMax, 1); } // Otherwise remove last character else { //s.erase(s.length() - 1, 1); s = s.substring(0, s.length - 1); } // Print the resultant subsequence document.write(s);} // Driver Code// Given String Slet S = \"geeksforgeeks\"; // Function CallfirstSubsequence(S); // This code is contributed by unknown2108</script>",
"e": 36085,
"s": 35045,
"text": null
},
{
"code": null,
"e": 36094,
"s": 36085,
"text": "Output: "
},
{
"code": null,
"e": 36107,
"s": 36094,
"text": "eeksforgeeks"
},
{
"code": null,
"e": 36150,
"s": 36107,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 36165,
"s": 36150,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 36180,
"s": 36165,
"text": "amit143katiyar"
},
{
"code": null,
"e": 36191,
"s": 36180,
"text": "ipg2016107"
},
{
"code": null,
"e": 36204,
"s": 36191,
"text": "princi singh"
},
{
"code": null,
"e": 36214,
"s": 36204,
"text": "patel2127"
},
{
"code": null,
"e": 36226,
"s": 36214,
"text": "unknown2108"
},
{
"code": null,
"e": 36235,
"s": 36226,
"text": "sunnykr2"
},
{
"code": null,
"e": 36258,
"s": 36235,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 36270,
"s": 36258,
"text": "subsequence"
},
{
"code": null,
"e": 36284,
"s": 36270,
"text": "Combinatorial"
},
{
"code": null,
"e": 36292,
"s": 36284,
"text": "Sorting"
},
{
"code": null,
"e": 36300,
"s": 36292,
"text": "Strings"
},
{
"code": null,
"e": 36308,
"s": 36300,
"text": "Strings"
},
{
"code": null,
"e": 36316,
"s": 36308,
"text": "Sorting"
},
{
"code": null,
"e": 36330,
"s": 36316,
"text": "Combinatorial"
},
{
"code": null,
"e": 36428,
"s": 36330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36437,
"s": 36428,
"text": "Comments"
},
{
"code": null,
"e": 36450,
"s": 36437,
"text": "Old Comments"
},
{
"code": null,
"e": 36468,
"s": 36450,
"text": "Combinational Sum"
},
{
"code": null,
"e": 36505,
"s": 36468,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 36562,
"s": 36505,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 36647,
"s": 36562,
"text": "Print all possible strings of length k that can be formed from a set of n characters"
}
] |
VBScript StrReverse Function
|
The StrReverse Function reverses the specified string.
StrReverse(string)
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
document.write("Line 1 : " & StrReverse("VBSCRIPT") & "<br />")
document.write("Line 2 : " & StrReverse("My First VBScript") & "<br />")
document.write("Line 3 : " & StrReverse("123.45") & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 : TPIRCSBV
Line 2 : tpircSBV tsriF yM
Line 3 : 54.321
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2135,
"s": 2080,
"text": "The StrReverse Function reverses the specified string."
},
{
"code": null,
"e": 2156,
"s": 2135,
"text": "StrReverse(string) \n"
},
{
"code": null,
"e": 2511,
"s": 2156,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n document.write(\"Line 1 : \" & StrReverse(\"VBSCRIPT\") & \"<br />\")\n document.write(\"Line 2 : \" & StrReverse(\"My First VBScript\") & \"<br />\")\n document.write(\"Line 3 : \" & StrReverse(\"123.45\") & \"<br />\")\n\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2632,
"s": 2511,
"text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −"
},
{
"code": null,
"e": 2694,
"s": 2632,
"text": "Line 1 : TPIRCSBV\nLine 2 : tpircSBV tsriF yM\nLine 3 : 54.321\n"
},
{
"code": null,
"e": 2727,
"s": 2694,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2744,
"s": 2727,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 2751,
"s": 2744,
"text": " Print"
},
{
"code": null,
"e": 2762,
"s": 2751,
"text": " Add Notes"
}
] |
HTML | <body> background Attribute - GeeksforGeeks
|
28 Mar, 2022
The HTML <body> background Attribute is used to specify the background-image for the document. Note: It is not supported by HTML5 Instead of using this attribute we use CSS background property.
Syntax:
<body background="URL">
Attribute Values: It contains the value i.e URL Which specify the address of the background Image.
Absolute URL: It points to another website.
Relative URL: It points to a file within a website.
Example:
html
<!DOCTYPE html><html> <head> <title> HTML body Background Attribute </title></head> <!-- body tag starts here --><body background="https://media.geeksforgeeks.org/wp-content/uploads/rk.png"> <center> <h1>GeeksforGeeks</h1> <h2>HTML <body> background Attribute</h2> <a href="#"> It is a Computer Science portal For Geeks </a> </center></body><!-- body tag ends here --> </html>
Output:
Supported Browsers: The browser supported by <body> background Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
ManasChhabra2
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 25184,
"s": 25156,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 25379,
"s": 25184,
"text": "The HTML <body> background Attribute is used to specify the background-image for the document. Note: It is not supported by HTML5 Instead of using this attribute we use CSS background property. "
},
{
"code": null,
"e": 25388,
"s": 25379,
"text": "Syntax: "
},
{
"code": null,
"e": 25412,
"s": 25388,
"text": "<body background=\"URL\">"
},
{
"code": null,
"e": 25513,
"s": 25412,
"text": "Attribute Values: It contains the value i.e URL Which specify the address of the background Image. "
},
{
"code": null,
"e": 25557,
"s": 25513,
"text": "Absolute URL: It points to another website."
},
{
"code": null,
"e": 25609,
"s": 25557,
"text": "Relative URL: It points to a file within a website."
},
{
"code": null,
"e": 25620,
"s": 25609,
"text": "Example: "
},
{
"code": null,
"e": 25625,
"s": 25620,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML body Background Attribute </title></head> <!-- body tag starts here --><body background=\"https://media.geeksforgeeks.org/wp-content/uploads/rk.png\"> <center> <h1>GeeksforGeeks</h1> <h2>HTML <body> background Attribute</h2> <a href=\"#\"> It is a Computer Science portal For Geeks </a> </center></body><!-- body tag ends here --> </html>",
"e": 26074,
"s": 25625,
"text": null
},
{
"code": null,
"e": 26084,
"s": 26074,
"text": "Output: "
},
{
"code": null,
"e": 26177,
"s": 26084,
"text": "Supported Browsers: The browser supported by <body> background Attribute are listed below: "
},
{
"code": null,
"e": 26191,
"s": 26177,
"text": "Google Chrome"
},
{
"code": null,
"e": 26209,
"s": 26191,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26217,
"s": 26209,
"text": "Firefox"
},
{
"code": null,
"e": 26224,
"s": 26217,
"text": "Safari"
},
{
"code": null,
"e": 26230,
"s": 26224,
"text": "Opera"
},
{
"code": null,
"e": 26369,
"s": 26232,
"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": 26383,
"s": 26369,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 26397,
"s": 26383,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 26413,
"s": 26397,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26418,
"s": 26413,
"text": "HTML"
},
{
"code": null,
"e": 26435,
"s": 26418,
"text": "Web Technologies"
},
{
"code": null,
"e": 26440,
"s": 26435,
"text": "HTML"
},
{
"code": null,
"e": 26538,
"s": 26440,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26547,
"s": 26538,
"text": "Comments"
},
{
"code": null,
"e": 26560,
"s": 26547,
"text": "Old Comments"
},
{
"code": null,
"e": 26608,
"s": 26560,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26658,
"s": 26608,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26682,
"s": 26658,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26732,
"s": 26682,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26774,
"s": 26732,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 26816,
"s": 26774,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26849,
"s": 26816,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26892,
"s": 26849,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26937,
"s": 26892,
"text": "Convert a string to an integer in JavaScript"
}
] |
Web Services - Examples
|
Based on the web service architecture, we create the following two components as a part of web services implementation −
This is the provider of the web service. The service provider implements the service and makes it available on the Internet or intranet.
We will write and publish a simple web service using .NET SDK.
This is any consumer of the web service. The requestor utilizes an existing web service by opening a network connection and sending an XML request.
We will also write two web service requestors: one web-based consumer (ASP.NET application) and another Windows application-based consumer.
Given below is our first web service example which works as a service provider and exposes two methods (add and SayHello) as the web services to be used by applications. This is a standard template for a web service. .NET web services use the .asmx extension. Note that a method exposed as a web service has the WebMethod attribute. Save this file as FirstService.asmx in the IIS virtual directory (as explained in configuring IIS; for example, c:\MyWebSerces).
FirstService.asmx
<%@ WebService language = "C#" class = "FirstService" %>
using System;
using System.Web.Services;
using System.Xml.Serialization;
[WebService(Namespace = "http://localhost/MyWebServices/")]
public class FirstService : WebService{
[WebMethod]
public int Add(int a, int b) {
return a + b;
}
[WebMethod]
public String SayHello() {
return "Hello World";
}
}
To test a web service, it must be published. A web service can be published either on an intranet or the Internet. We will publish this web service on IIS running on a local machine. Let us start with configuring the IIS.
Open Start → Settings → Control Panel → Administrative tools → Internet Services Manager.
Open Start → Settings → Control Panel → Administrative tools → Internet Services Manager.
Expand and right-click on the default web site; select New &#rarr; Virtual Directory. The Virtual Directory Creation Wizard opens. Click Next.
Expand and right-click on the default web site; select New &#rarr; Virtual Directory. The Virtual Directory Creation Wizard opens. Click Next.
The "Virtual Directory Alias" screen opens. Type the virtual directory name. For example, MyWebServices. Click Next.
The "Virtual Directory Alias" screen opens. Type the virtual directory name. For example, MyWebServices. Click Next.
The "Web Site Content Directory" screen opens.
The "Web Site Content Directory" screen opens.
Enter the directory path name for the virtual directory. For example, c:\MyWebServices. Click Next.
Enter the directory path name for the virtual directory. For example, c:\MyWebServices. Click Next.
The "Access Permission" screen opens. Change the settings as per your requirements. Let us keep the default settings for this exercise.
The "Access Permission" screen opens. Change the settings as per your requirements. Let us keep the default settings for this exercise.
Click the Next button. It completes the IIS configuration.
Click the Next button. It completes the IIS configuration.
Click Finish to complete the configuration.
Click Finish to complete the configuration.
To test whether the IIS has been configured properly, copy an HTML file (For example, x.html) in the virtual directory (C:\MyWebServices) created above. Now, open Internet Explorer and type http://localhost/MyWebServices/x.html. It should open the x.html file.
Note − If it does not work, try replacing the localhost with the IP address of your machine. If it still does not work, check whether IIS is running; you may need to reconfigure the IIS and the Virtual Directory.
To test this web service, copy FirstService.asmx in the IIS virtual directory created above (C:\MyWebServices). Open the web service in Internet Explorer (http://localhost/MyWebServices/FirstService.asmx). It should open your web service page. The page should have links to two methods exposed as web services by our application. Congratulations! You have written your first web service!
As we have just seen, writing web services is easy in the .NET Framework. Writing web service consumers is also easy in the .NET framework; however, it is a bit more involved. As said earlier, we will write two types of service consumers, one web-based and another Windows application-based consumer. Let us write our first web service consumer.
Write a web-based consumer as given below. Call it WebApp.aspx. Note that it is an ASP.NET application. Save this in the virtual directory of the web service (c:\MyWebServices\WebApp.axpx).
This application has two text fields that are used to get numbers from the user to be added. It has one button, Execute, that when clicked gets the Add and SayHello web services.
WebApp.aspx
<%@ Page Language = "C#" %>
<script runat = "server">
void runSrvice_Click(Object sender, EventArgs e) {
FirstService mySvc = new FirstService();
Label1.Text = mySvc.SayHello();
Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)).ToString();
}
</script>
<html>
<head> </head>
<body>
<form runat = "server">
<p>
<em>First Number to Add </em>:
<asp:TextBox id = "txtNum1" runat = "server" Width = "43px">4< /asp:TextBox>
</p>
<p>
<em>Second Number To Add </em>:
<asp:TextBox id = "txtNum2" runat = "server" Width = "44px">5</asp:TextBox>
</p>
<p>
<strong><u>Web Service Result -</u></strong>
</p>
<p>
<em>Hello world Service</em> :
<asp:Label id = "Label1" runat = "server" Font-Underline = "True">Label< /asp:Label>
</p>
<p>
<em>Add Service</em> :
& <asp:Label id = "Label2" runat = "server" Font-Underline = "True">Label</asp:Label>
</p>
<p align = "left">
<asp:Button id = "runSrvice" onclick = "runSrvice_Click" runat = "server" Text = "Execute"></asp:Button>
</p>
</form>
</body>
</html>
After the consumer is created, we need to create a proxy for the web service to be consumed. This work is done automatically by Visual Studio .NET for us when referencing a web service that has been added. Here are the steps to be followed −
Create a proxy for the Web Service to be consumed. The proxy is created using the WSDL utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. The proxy is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. Visual Studio .NET creates a proxy automatically for you when the Web Service reference is added. Create a proxy for the Web Service using the WSDL utility supplied with the .NET SDK. It will create FirstSevice.cs file in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service.
Create a proxy for the Web Service to be consumed. The proxy is created using the WSDL utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. The proxy is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. Visual Studio .NET creates a proxy automatically for you when the Web Service reference is added. Create a proxy for the Web Service using the WSDL utility supplied with the .NET SDK. It will create FirstSevice.cs file in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service.
c:> WSDL http://localhost/MyWebServices/FirstService.asmx?WSDL
c:> csc /t:library FirstService.cs
Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\MyWebServices\bin). Internet Information Services (IIS) looks for the proxy in this directory.
Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\MyWebServices\bin). Internet Information Services (IIS) looks for the proxy in this directory.
Create the service consumer, in the same way we already did. Note that an object of the Web Service proxy is instantiated in the consumer. This proxy takes care of interacting with the service.
Create the service consumer, in the same way we already did. Note that an object of the Web Service proxy is instantiated in the consumer. This proxy takes care of interacting with the service.
Type the URL of the consumer in IE to test it (for example, http://localhost/MyWebServices/WebApp.aspx).
Type the URL of the consumer in IE to test it (for example, http://localhost/MyWebServices/WebApp.aspx).
Writing a Windows application-based web service consumer is the same as writing any other Windows application. You only need to create the proxy (which we have already done) and reference this proxy when compiling the application. Following is our Windows application that uses the web service. This application creates a web service object (of course, proxy) and calls the SayHello, and Add methods on it.
WinApp.cs
using System;
using System.IO;
namespace SvcConsumer {
class SvcEater {
public static void Main(String[] args) {
FirstService mySvc = new FirstService();
Console.WriteLine("Calling Hello World Service: " + mySvc.SayHello());
Console.WriteLine("Calling Add(2, 3) Service: " + mySvc.Add(2, 3).ToString());
}
}
}
Compile it using c:\>csc /r:FirstService.dll WinApp.cs. It will create WinApp.exe. Run it to test the application and the web service.
Now, the question arises: How can you be sure that this application is actually calling the web service?
It is simple to test. Stop your web server so that the web service cannot be contacted. Now, run the WinApp application. It will fire a runtime exception. Now, start the web server again. It should work.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1978,
"s": 1857,
"text": "Based on the web service architecture, we create the following two components as a part of web services implementation −"
},
{
"code": null,
"e": 2115,
"s": 1978,
"text": "This is the provider of the web service. The service provider implements the service and makes it available on the Internet or intranet."
},
{
"code": null,
"e": 2178,
"s": 2115,
"text": "We will write and publish a simple web service using .NET SDK."
},
{
"code": null,
"e": 2326,
"s": 2178,
"text": "This is any consumer of the web service. The requestor utilizes an existing web service by opening a network connection and sending an XML request."
},
{
"code": null,
"e": 2466,
"s": 2326,
"text": "We will also write two web service requestors: one web-based consumer (ASP.NET application) and another Windows application-based consumer."
},
{
"code": null,
"e": 2928,
"s": 2466,
"text": "Given below is our first web service example which works as a service provider and exposes two methods (add and SayHello) as the web services to be used by applications. This is a standard template for a web service. .NET web services use the .asmx extension. Note that a method exposed as a web service has the WebMethod attribute. Save this file as FirstService.asmx in the IIS virtual directory (as explained in configuring IIS; for example, c:\\MyWebSerces)."
},
{
"code": null,
"e": 3333,
"s": 2928,
"text": "FirstService.asmx\n<%@ WebService language = \"C#\" class = \"FirstService\" %>\n\nusing System;\nusing System.Web.Services;\nusing System.Xml.Serialization;\n\n[WebService(Namespace = \"http://localhost/MyWebServices/\")]\npublic class FirstService : WebService{\n [WebMethod]\n public int Add(int a, int b) {\n return a + b;\n }\n\n [WebMethod]\n public String SayHello() {\n return \"Hello World\";\n }\n}"
},
{
"code": null,
"e": 3555,
"s": 3333,
"text": "To test a web service, it must be published. A web service can be published either on an intranet or the Internet. We will publish this web service on IIS running on a local machine. Let us start with configuring the IIS."
},
{
"code": null,
"e": 3645,
"s": 3555,
"text": "Open Start → Settings → Control Panel → Administrative tools → Internet Services Manager."
},
{
"code": null,
"e": 3735,
"s": 3645,
"text": "Open Start → Settings → Control Panel → Administrative tools → Internet Services Manager."
},
{
"code": null,
"e": 3878,
"s": 3735,
"text": "Expand and right-click on the default web site; select New &#rarr; Virtual Directory. The Virtual Directory Creation Wizard opens. Click Next."
},
{
"code": null,
"e": 4021,
"s": 3878,
"text": "Expand and right-click on the default web site; select New &#rarr; Virtual Directory. The Virtual Directory Creation Wizard opens. Click Next."
},
{
"code": null,
"e": 4138,
"s": 4021,
"text": "The \"Virtual Directory Alias\" screen opens. Type the virtual directory name. For example, MyWebServices. Click Next."
},
{
"code": null,
"e": 4255,
"s": 4138,
"text": "The \"Virtual Directory Alias\" screen opens. Type the virtual directory name. For example, MyWebServices. Click Next."
},
{
"code": null,
"e": 4302,
"s": 4255,
"text": "The \"Web Site Content Directory\" screen opens."
},
{
"code": null,
"e": 4349,
"s": 4302,
"text": "The \"Web Site Content Directory\" screen opens."
},
{
"code": null,
"e": 4449,
"s": 4349,
"text": "Enter the directory path name for the virtual directory. For example, c:\\MyWebServices. Click Next."
},
{
"code": null,
"e": 4549,
"s": 4449,
"text": "Enter the directory path name for the virtual directory. For example, c:\\MyWebServices. Click Next."
},
{
"code": null,
"e": 4685,
"s": 4549,
"text": "The \"Access Permission\" screen opens. Change the settings as per your requirements. Let us keep the default settings for this exercise."
},
{
"code": null,
"e": 4821,
"s": 4685,
"text": "The \"Access Permission\" screen opens. Change the settings as per your requirements. Let us keep the default settings for this exercise."
},
{
"code": null,
"e": 4880,
"s": 4821,
"text": "Click the Next button. It completes the IIS configuration."
},
{
"code": null,
"e": 4939,
"s": 4880,
"text": "Click the Next button. It completes the IIS configuration."
},
{
"code": null,
"e": 4983,
"s": 4939,
"text": "Click Finish to complete the configuration."
},
{
"code": null,
"e": 5027,
"s": 4983,
"text": "Click Finish to complete the configuration."
},
{
"code": null,
"e": 5288,
"s": 5027,
"text": "To test whether the IIS has been configured properly, copy an HTML file (For example, x.html) in the virtual directory (C:\\MyWebServices) created above. Now, open Internet Explorer and type http://localhost/MyWebServices/x.html. It should open the x.html file."
},
{
"code": null,
"e": 5501,
"s": 5288,
"text": "Note − If it does not work, try replacing the localhost with the IP address of your machine. If it still does not work, check whether IIS is running; you may need to reconfigure the IIS and the Virtual Directory."
},
{
"code": null,
"e": 5889,
"s": 5501,
"text": "To test this web service, copy FirstService.asmx in the IIS virtual directory created above (C:\\MyWebServices). Open the web service in Internet Explorer (http://localhost/MyWebServices/FirstService.asmx). It should open your web service page. The page should have links to two methods exposed as web services by our application. Congratulations! You have written your first web service!"
},
{
"code": null,
"e": 6235,
"s": 5889,
"text": "As we have just seen, writing web services is easy in the .NET Framework. Writing web service consumers is also easy in the .NET framework; however, it is a bit more involved. As said earlier, we will write two types of service consumers, one web-based and another Windows application-based consumer. Let us write our first web service consumer."
},
{
"code": null,
"e": 6425,
"s": 6235,
"text": "Write a web-based consumer as given below. Call it WebApp.aspx. Note that it is an ASP.NET application. Save this in the virtual directory of the web service (c:\\MyWebServices\\WebApp.axpx)."
},
{
"code": null,
"e": 6604,
"s": 6425,
"text": "This application has two text fields that are used to get numbers from the user to be added. It has one button, Execute, that when clicked gets the Add and SayHello web services."
},
{
"code": null,
"e": 7930,
"s": 6604,
"text": "WebApp.aspx\n<%@ Page Language = \"C#\" %>\n<script runat = \"server\">\n void runSrvice_Click(Object sender, EventArgs e) {\n FirstService mySvc = new FirstService();\n Label1.Text = mySvc.SayHello();\n Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)).ToString();\n }\n</script>\n\n<html>\n <head> </head>\n \n <body>\n <form runat = \"server\">\n <p>\n <em>First Number to Add </em>:\n <asp:TextBox id = \"txtNum1\" runat = \"server\" Width = \"43px\">4< /asp:TextBox>\n </p>\n\t\t\t\n <p>\n <em>Second Number To Add </em>:\n <asp:TextBox id = \"txtNum2\" runat = \"server\" Width = \"44px\">5</asp:TextBox>\n </p>\n\t\t\t\n <p>\n <strong><u>Web Service Result -</u></strong>\n </p>\n\t\t\t\n <p>\n <em>Hello world Service</em> :\n <asp:Label id = \"Label1\" runat = \"server\" Font-Underline = \"True\">Label< /asp:Label>\n </p>\n\n <p>\n <em>Add Service</em> :\n & <asp:Label id = \"Label2\" runat = \"server\" Font-Underline = \"True\">Label</asp:Label>\n </p>\n\t\t\t\n <p align = \"left\">\n <asp:Button id = \"runSrvice\" onclick = \"runSrvice_Click\" runat = \"server\" Text = \"Execute\"></asp:Button>\n </p>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 8172,
"s": 7930,
"text": "After the consumer is created, we need to create a proxy for the web service to be consumed. This work is done automatically by Visual Studio .NET for us when referencing a web service that has been added. Here are the steps to be followed −"
},
{
"code": null,
"e": 8844,
"s": 8172,
"text": "Create a proxy for the Web Service to be consumed. The proxy is created using the WSDL utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. The proxy is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. Visual Studio .NET creates a proxy automatically for you when the Web Service reference is added. Create a proxy for the Web Service using the WSDL utility supplied with the .NET SDK. It will create FirstSevice.cs file in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service."
},
{
"code": null,
"e": 9516,
"s": 8844,
"text": "Create a proxy for the Web Service to be consumed. The proxy is created using the WSDL utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. The proxy is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. Visual Studio .NET creates a proxy automatically for you when the Web Service reference is added. Create a proxy for the Web Service using the WSDL utility supplied with the .NET SDK. It will create FirstSevice.cs file in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service."
},
{
"code": null,
"e": 9615,
"s": 9516,
"text": "c:> WSDL http://localhost/MyWebServices/FirstService.asmx?WSDL\nc:> csc /t:library FirstService.cs\n"
},
{
"code": null,
"e": 9802,
"s": 9615,
"text": "Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\\MyWebServices\\bin). Internet Information Services (IIS) looks for the proxy in this directory."
},
{
"code": null,
"e": 9989,
"s": 9802,
"text": "Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\\MyWebServices\\bin). Internet Information Services (IIS) looks for the proxy in this directory."
},
{
"code": null,
"e": 10183,
"s": 9989,
"text": "Create the service consumer, in the same way we already did. Note that an object of the Web Service proxy is instantiated in the consumer. This proxy takes care of interacting with the service."
},
{
"code": null,
"e": 10377,
"s": 10183,
"text": "Create the service consumer, in the same way we already did. Note that an object of the Web Service proxy is instantiated in the consumer. This proxy takes care of interacting with the service."
},
{
"code": null,
"e": 10482,
"s": 10377,
"text": "Type the URL of the consumer in IE to test it (for example, http://localhost/MyWebServices/WebApp.aspx)."
},
{
"code": null,
"e": 10587,
"s": 10482,
"text": "Type the URL of the consumer in IE to test it (for example, http://localhost/MyWebServices/WebApp.aspx)."
},
{
"code": null,
"e": 10994,
"s": 10587,
"text": "Writing a Windows application-based web service consumer is the same as writing any other Windows application. You only need to create the proxy (which we have already done) and reference this proxy when compiling the application. Following is our Windows application that uses the web service. This application creates a web service object (of course, proxy) and calls the SayHello, and Add methods on it."
},
{
"code": null,
"e": 11361,
"s": 10994,
"text": "WinApp.cs\n\nusing System;\nusing System.IO;\n\nnamespace SvcConsumer {\n class SvcEater {\n public static void Main(String[] args) {\n FirstService mySvc = new FirstService();\n Console.WriteLine(\"Calling Hello World Service: \" + mySvc.SayHello());\n Console.WriteLine(\"Calling Add(2, 3) Service: \" + mySvc.Add(2, 3).ToString());\n }\n }\n}"
},
{
"code": null,
"e": 11496,
"s": 11361,
"text": "Compile it using c:\\>csc /r:FirstService.dll WinApp.cs. It will create WinApp.exe. Run it to test the application and the web service."
},
{
"code": null,
"e": 11601,
"s": 11496,
"text": "Now, the question arises: How can you be sure that this application is actually calling the web service?"
},
{
"code": null,
"e": 11805,
"s": 11601,
"text": "It is simple to test. Stop your web server so that the web service cannot be contacted. Now, run the WinApp application. It will fire a runtime exception. Now, start the web server again. It should work."
},
{
"code": null,
"e": 11812,
"s": 11805,
"text": " Print"
},
{
"code": null,
"e": 11823,
"s": 11812,
"text": " Add Notes"
}
] |
How to turn your webcam into a Motion Detect controller | by Benson Ruan | Towards Data Science
|
Have you ever played Xbox games with a motion sensor? It feel so cool to just swing your arms to hit the tennis ball in the video game. Motion detection is the technique that make this magic happened, it can detect a change in the position of an object relative to its surroundings.
In this article, let’s have some fun. I am going to build a Virtual Drums Playground which will let you play the drums by just waving your hands in the air. And it don’t need any motion sensor, all it need is to turn on the webcam on your PC or Mobile.
Here it is the demo of the Virtual Drums Playground. As you can see, the drum and cymbal is played when it detects significant movement in that area.
Try it yourself in the link below :
bensonruan.com
Did you have fun and kept playing the drums like a rock star? Are you curious about how this magic happened? I was first inspired by the xylophone version of this, and then built my drum version above. Follow me below for the journey of implementing this Virtual Drum Playground.
To stream your webcam into the browser, I utilize the JavaScript library navigator.mediaDevices.getUserMedia. To find out more details about that, please refer to my previous blog :
medium.com
Overlay the webcam with the images of drums and cymbals. This is to set the target areas in the webcam, so that whenever in those areas detected a significant movement, it triggers the effect of playing the gear.
HTML
JavaScript
Store the location of the gears by their (x, y, width, height), please note that the width and height need to be calculated by the ratio between the full screen camera size and the blended canvas size.
For the purpose of playing the drums and cymbals, we need to load the audio sound track files for those music instruments.
Here is the most important part that doing the motion detection. It is using a technique call Blend Mode Difference.
First, let me explain the concept of Blend Mode Difference. Imagine you take one picture, then another one after half second, if there is nothing moved in that half second, those two pictures would be exactly the same. When you subtract the pixel values of those 2 pictures, it would be all 0, the blended images would be completely black. If there is movement in certain areas, the blended image would high light the differences.
For more details, please refer to the article below:
www.adobe.com
We are repeatedly calling below functions for each frame of the webcam video for motion detection.
function update() { drawVideo(); blend(); checkAreas(); window.requestAnimationFrame(update);}
Within the drums and cymbals’ areas, if it detects a significant difference between frames, it indicate that there is movement in that area. Then we play the effect and sound of the corresponding gear.
while (i < (blendedData.data.length * 0.25)) { average += (blendedData.data[i*4] + blendedData.data[i*4+1] + blendedData.data[i*4+2]) / 3; ++i;}average = Math.round(average / (blendedData.data.length * 0.25));if (average > 20) { //over a threshold, means significant movement playHover(drum); }
That’s pretty much for the code. Let’s enjoy and play some crazy drums!
You can download the complete code of the above demo in the link below:
github.com
Nowadays, motion detection had been applied in many areas, e.g. Security alarms, Automatic gates... Some works with sensors, others might be based on computer vision object detection. After all, I hope you find this Virtual Drum Playground funny, and piqued your interest in the latest technology.
Thank you for reading. If you like this article, feel free to share on LinkedIn or Twitter. Let me know in the comment if you have any questions. Follow me on GitHub and Linkedin.
|
[
{
"code": null,
"e": 455,
"s": 172,
"text": "Have you ever played Xbox games with a motion sensor? It feel so cool to just swing your arms to hit the tennis ball in the video game. Motion detection is the technique that make this magic happened, it can detect a change in the position of an object relative to its surroundings."
},
{
"code": null,
"e": 708,
"s": 455,
"text": "In this article, let’s have some fun. I am going to build a Virtual Drums Playground which will let you play the drums by just waving your hands in the air. And it don’t need any motion sensor, all it need is to turn on the webcam on your PC or Mobile."
},
{
"code": null,
"e": 858,
"s": 708,
"text": "Here it is the demo of the Virtual Drums Playground. As you can see, the drum and cymbal is played when it detects significant movement in that area."
},
{
"code": null,
"e": 894,
"s": 858,
"text": "Try it yourself in the link below :"
},
{
"code": null,
"e": 909,
"s": 894,
"text": "bensonruan.com"
},
{
"code": null,
"e": 1189,
"s": 909,
"text": "Did you have fun and kept playing the drums like a rock star? Are you curious about how this magic happened? I was first inspired by the xylophone version of this, and then built my drum version above. Follow me below for the journey of implementing this Virtual Drum Playground."
},
{
"code": null,
"e": 1371,
"s": 1189,
"text": "To stream your webcam into the browser, I utilize the JavaScript library navigator.mediaDevices.getUserMedia. To find out more details about that, please refer to my previous blog :"
},
{
"code": null,
"e": 1382,
"s": 1371,
"text": "medium.com"
},
{
"code": null,
"e": 1595,
"s": 1382,
"text": "Overlay the webcam with the images of drums and cymbals. This is to set the target areas in the webcam, so that whenever in those areas detected a significant movement, it triggers the effect of playing the gear."
},
{
"code": null,
"e": 1600,
"s": 1595,
"text": "HTML"
},
{
"code": null,
"e": 1611,
"s": 1600,
"text": "JavaScript"
},
{
"code": null,
"e": 1813,
"s": 1611,
"text": "Store the location of the gears by their (x, y, width, height), please note that the width and height need to be calculated by the ratio between the full screen camera size and the blended canvas size."
},
{
"code": null,
"e": 1936,
"s": 1813,
"text": "For the purpose of playing the drums and cymbals, we need to load the audio sound track files for those music instruments."
},
{
"code": null,
"e": 2053,
"s": 1936,
"text": "Here is the most important part that doing the motion detection. It is using a technique call Blend Mode Difference."
},
{
"code": null,
"e": 2484,
"s": 2053,
"text": "First, let me explain the concept of Blend Mode Difference. Imagine you take one picture, then another one after half second, if there is nothing moved in that half second, those two pictures would be exactly the same. When you subtract the pixel values of those 2 pictures, it would be all 0, the blended images would be completely black. If there is movement in certain areas, the blended image would high light the differences."
},
{
"code": null,
"e": 2537,
"s": 2484,
"text": "For more details, please refer to the article below:"
},
{
"code": null,
"e": 2551,
"s": 2537,
"text": "www.adobe.com"
},
{
"code": null,
"e": 2650,
"s": 2551,
"text": "We are repeatedly calling below functions for each frame of the webcam video for motion detection."
},
{
"code": null,
"e": 2749,
"s": 2650,
"text": "function update() { drawVideo(); blend(); checkAreas(); window.requestAnimationFrame(update);}"
},
{
"code": null,
"e": 2951,
"s": 2749,
"text": "Within the drums and cymbals’ areas, if it detects a significant difference between frames, it indicate that there is movement in that area. Then we play the effect and sound of the corresponding gear."
},
{
"code": null,
"e": 3258,
"s": 2951,
"text": "while (i < (blendedData.data.length * 0.25)) { average += (blendedData.data[i*4] + blendedData.data[i*4+1] + blendedData.data[i*4+2]) / 3; ++i;}average = Math.round(average / (blendedData.data.length * 0.25));if (average > 20) { //over a threshold, means significant movement playHover(drum); }"
},
{
"code": null,
"e": 3330,
"s": 3258,
"text": "That’s pretty much for the code. Let’s enjoy and play some crazy drums!"
},
{
"code": null,
"e": 3402,
"s": 3330,
"text": "You can download the complete code of the above demo in the link below:"
},
{
"code": null,
"e": 3413,
"s": 3402,
"text": "github.com"
},
{
"code": null,
"e": 3711,
"s": 3413,
"text": "Nowadays, motion detection had been applied in many areas, e.g. Security alarms, Automatic gates... Some works with sensors, others might be based on computer vision object detection. After all, I hope you find this Virtual Drum Playground funny, and piqued your interest in the latest technology."
}
] |
The "\" escape character in C#
|
The "#", "0", ".", ",", "%", and "‰" symbols in a format string are interpreted as format specifiers.
Prevent a character from being interpreted as a format specifier, by preceding it with an escape character i.e. backslash.
To prevent interpreting as an escape character, use escape character for #", "0", and "\" characters.
Let us see an example −
Here, we are displaying #, by preceding it with an escape character i.e. backslash.
Live Demo
using System;
using System.Globalization;
class Demo {
static void Main() {
int num = 20;
Console.WriteLine(num.ToString("\\#\\# ##0 Rank"));
}
}
## 20 Rank
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "The \"#\", \"0\", \".\", \",\", \"%\", and \"‰\" symbols in a format string are interpreted as format specifiers."
},
{
"code": null,
"e": 1287,
"s": 1164,
"text": "Prevent a character from being interpreted as a format specifier, by preceding it with an escape character i.e. backslash."
},
{
"code": null,
"e": 1389,
"s": 1287,
"text": "To prevent interpreting as an escape character, use escape character for #\", \"0\", and \"\\\" characters."
},
{
"code": null,
"e": 1413,
"s": 1389,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1497,
"s": 1413,
"text": "Here, we are displaying #, by preceding it with an escape character i.e. backslash."
},
{
"code": null,
"e": 1508,
"s": 1497,
"text": " Live Demo"
},
{
"code": null,
"e": 1672,
"s": 1508,
"text": "using System;\nusing System.Globalization;\nclass Demo {\n static void Main() {\n int num = 20;\n Console.WriteLine(num.ToString(\"\\\\#\\\\# ##0 Rank\"));\n }\n}"
},
{
"code": null,
"e": 1683,
"s": 1672,
"text": "## 20 Rank"
}
] |
F# - Tuples
|
A tuple is a comma-separated collection of values. These are used for creating ad hoc data structures, which group together related values.
For example, (“Zara Ali”, “Hyderabad”, 10) is a 3-tuple with two string values and an int value, it has the type (string * string * int).
Tuples could be pairs, triples, and so on, of the same or different types.
Some examples are provided here −
// Tuple of two integers.
( 4, 5 )
// Triple of strings.
( "one", "two", "three" )
// Tuple of unknown types.
( a, b )
// Tuple that has mixed types.
( "Absolute Classes", 1, 2.0 )
// Tuple of integer expressions.
( a * 4, b + 7)
This program has a function that takes a tuple of four float values and returns the average −
let averageFour (a, b, c, d) =
let sum = a + b + c + d
sum / 4.0
let avg:float = averageFour (4.0, 5.1, 8.0, 12.0)
printfn "Avg of four numbers: %f" avg
When you compile and execute the program, it yields the following output −
Avg of four numbers: 7.275000
The individual members of a tuple could be assessed and printed using pattern matching.
The following example illustrates the concept −
let display tuple1 =
match tuple1 with
| (a, b, c) -> printfn "Detail Info: %A %A %A" a b c
display ("Zara Ali", "Hyderabad", 10 )
When you compile and execute the program, it yields the following output −
Detail Info: "Zara Ali" "Hyderabad" 10
F# has two built-in functions, fst and snd, which return the first and second items in a 2-tuple.
The following example illustrates the concept −
printfn "First member: %A" (fst(23, 30))
printfn "Second member: %A" (snd(23, 30))
printfn "First member: %A" (fst("Hello", "World!"))
printfn "Second member: %A" (snd("Hello", "World!"))
let nameTuple = ("Zara", "Ali")
printfn "First Name: %A" (fst nameTuple)
printfn "Second Name: %A" (snd nameTuple)
When you compile and execute the program, it yields the following output −
First member: 23
Second member: 30
First member: "Hello"
Second member: "World!"
First Name: "Zara"
Second Name: "Ali"
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2301,
"s": 2161,
"text": "A tuple is a comma-separated collection of values. These are used for creating ad hoc data structures, which group together related values."
},
{
"code": null,
"e": 2439,
"s": 2301,
"text": "For example, (“Zara Ali”, “Hyderabad”, 10) is a 3-tuple with two string values and an int value, it has the type (string * string * int)."
},
{
"code": null,
"e": 2514,
"s": 2439,
"text": "Tuples could be pairs, triples, and so on, of the same or different types."
},
{
"code": null,
"e": 2548,
"s": 2514,
"text": "Some examples are provided here −"
},
{
"code": null,
"e": 2783,
"s": 2548,
"text": "// Tuple of two integers.\n( 4, 5 )\n\n// Triple of strings.\n( \"one\", \"two\", \"three\" )\n\n// Tuple of unknown types.\n( a, b )\n\n// Tuple that has mixed types.\n( \"Absolute Classes\", 1, 2.0 )\n\n// Tuple of integer expressions.\n( a * 4, b + 7)\n"
},
{
"code": null,
"e": 2877,
"s": 2783,
"text": "This program has a function that takes a tuple of four float values and returns the average −"
},
{
"code": null,
"e": 3037,
"s": 2877,
"text": "let averageFour (a, b, c, d) =\n let sum = a + b + c + d\n sum / 4.0\n\nlet avg:float = averageFour (4.0, 5.1, 8.0, 12.0)\nprintfn \"Avg of four numbers: %f\" avg"
},
{
"code": null,
"e": 3112,
"s": 3037,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 3143,
"s": 3112,
"text": "Avg of four numbers: 7.275000\n"
},
{
"code": null,
"e": 3231,
"s": 3143,
"text": "The individual members of a tuple could be assessed and printed using pattern matching."
},
{
"code": null,
"e": 3279,
"s": 3231,
"text": "The following example illustrates the concept −"
},
{
"code": null,
"e": 3417,
"s": 3279,
"text": "let display tuple1 =\n match tuple1 with\n | (a, b, c) -> printfn \"Detail Info: %A %A %A\" a b c\n\ndisplay (\"Zara Ali\", \"Hyderabad\", 10 )"
},
{
"code": null,
"e": 3492,
"s": 3417,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 3532,
"s": 3492,
"text": "Detail Info: \"Zara Ali\" \"Hyderabad\" 10\n"
},
{
"code": null,
"e": 3630,
"s": 3532,
"text": "F# has two built-in functions, fst and snd, which return the first and second items in a 2-tuple."
},
{
"code": null,
"e": 3678,
"s": 3630,
"text": "The following example illustrates the concept −"
},
{
"code": null,
"e": 3984,
"s": 3678,
"text": "printfn \"First member: %A\" (fst(23, 30))\nprintfn \"Second member: %A\" (snd(23, 30))\n\nprintfn \"First member: %A\" (fst(\"Hello\", \"World!\"))\nprintfn \"Second member: %A\" (snd(\"Hello\", \"World!\"))\n\nlet nameTuple = (\"Zara\", \"Ali\")\n\nprintfn \"First Name: %A\" (fst nameTuple)\nprintfn \"Second Name: %A\" (snd nameTuple)"
},
{
"code": null,
"e": 4059,
"s": 3984,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 4179,
"s": 4059,
"text": "First member: 23\nSecond member: 30\nFirst member: \"Hello\"\nSecond member: \"World!\"\nFirst Name: \"Zara\"\nSecond Name: \"Ali\"\n"
},
{
"code": null,
"e": 4186,
"s": 4179,
"text": " Print"
},
{
"code": null,
"e": 4197,
"s": 4186,
"text": " Add Notes"
}
] |
How can I play a sound when a Tkinter button is pushed?
|
Python has many inbuilt libraries and modules that are used for building various application interfaces and components. Pygame is one of the python modules which is used to design and build video games and music. It provides a mixture to handle all sound related activities. Using music sub-module, you can stream mp3, ogg, and other variety of sounds.
To create an application that plays some sound on clicking a button, we have to follow these steps,
Make sure that Pygame is installed in your local machine. You can install pygame using pip install pygame command.
Make sure that Pygame is installed in your local machine. You can install pygame using pip install pygame command.
Initialize Pygame mixture by using pygame.mixture.init()
Initialize Pygame mixture by using pygame.mixture.init()
Create a button widget which is used further to play the music.
Create a button widget which is used further to play the music.
Define a function play_sound() and load the music by specifying the location of the file in mixture.load.music(filename).
Define a function play_sound() and load the music by specifying the location of the file in mixture.load.music(filename).
Add mixture.music.play() to play the music.
Add mixture.music.play() to play the music.
# Import the required libraries
from tkinter import *
import pygame
from PIL import Image, ImageTk
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x500")
# Add a background image
bg = ImageTk.PhotoImage(file="music.jpg")
label = Label(win, image=bg)
label.place(x=0, y=0)
# Initialize mixer module in pygame
pygame.mixer.init()
# Define a function to play the music
def play_sound():
pygame.mixer.music.load("sample1.mp3")
pygame.mixer.music.play()
# Add a Button widget
b1 = Button(win, text="Play Music", command=play_sound)
b1.pack(pady=60)
win.mainloop()
If we run the above code, it will display a window with a button in it. Now, add music location in the given function to play some music in the application.
|
[
{
"code": null,
"e": 1415,
"s": 1062,
"text": "Python has many inbuilt libraries and modules that are used for building various application interfaces and components. Pygame is one of the python modules which is used to design and build video games and music. It provides a mixture to handle all sound related activities. Using music sub-module, you can stream mp3, ogg, and other variety of sounds."
},
{
"code": null,
"e": 1515,
"s": 1415,
"text": "To create an application that plays some sound on clicking a button, we have to follow these steps,"
},
{
"code": null,
"e": 1630,
"s": 1515,
"text": "Make sure that Pygame is installed in your local machine. You can install pygame using pip install pygame command."
},
{
"code": null,
"e": 1745,
"s": 1630,
"text": "Make sure that Pygame is installed in your local machine. You can install pygame using pip install pygame command."
},
{
"code": null,
"e": 1802,
"s": 1745,
"text": "Initialize Pygame mixture by using pygame.mixture.init()"
},
{
"code": null,
"e": 1859,
"s": 1802,
"text": "Initialize Pygame mixture by using pygame.mixture.init()"
},
{
"code": null,
"e": 1923,
"s": 1859,
"text": "Create a button widget which is used further to play the music."
},
{
"code": null,
"e": 1987,
"s": 1923,
"text": "Create a button widget which is used further to play the music."
},
{
"code": null,
"e": 2109,
"s": 1987,
"text": "Define a function play_sound() and load the music by specifying the location of the file in mixture.load.music(filename)."
},
{
"code": null,
"e": 2231,
"s": 2109,
"text": "Define a function play_sound() and load the music by specifying the location of the file in mixture.load.music(filename)."
},
{
"code": null,
"e": 2275,
"s": 2231,
"text": "Add mixture.music.play() to play the music."
},
{
"code": null,
"e": 2319,
"s": 2275,
"text": "Add mixture.music.play() to play the music."
},
{
"code": null,
"e": 2949,
"s": 2319,
"text": "# Import the required libraries\nfrom tkinter import *\nimport pygame\nfrom PIL import Image, ImageTk\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x500\")\n\n# Add a background image\nbg = ImageTk.PhotoImage(file=\"music.jpg\")\n\nlabel = Label(win, image=bg)\nlabel.place(x=0, y=0)\n\n# Initialize mixer module in pygame\npygame.mixer.init()\n\n# Define a function to play the music\ndef play_sound():\n pygame.mixer.music.load(\"sample1.mp3\")\n pygame.mixer.music.play()\n\n# Add a Button widget\nb1 = Button(win, text=\"Play Music\", command=play_sound)\nb1.pack(pady=60)\n\nwin.mainloop()"
},
{
"code": null,
"e": 3106,
"s": 2949,
"text": "If we run the above code, it will display a window with a button in it. Now, add music location in the given function to play some music in the application."
}
] |
Java program to expand a String if range is given?
|
To expand a String if range is given, the Java code is as follows −
Live Demo
public class Demo {
public static void expand_range(String word) {
StringBuilder my_sb = new StringBuilder();
String[] str_arr = word.split(", ");
for (int i = 0; i < str_arr.length; i++){
String[] split_str = str_arr[i].split("-");
if (split_str.length == 2){
int low = Integer.parseInt(split_str[0]);
int high = Integer.parseInt(split_str[split_str.length - 1]);
while (low <= high){
my_sb.append(low + " ");
low++;
}
} else {
my_sb.append(str_arr[i] + " ");
}
}
System.out.println(my_sb.toString());
}
public static void main(String args[]){
String my_str = "1-4, 56-57, 99-101, 0-1";
System.out.println("The expanded range of given numbers is ");
expand_range(my_str);
}
}
The expanded range of given numbers is
1 2 3 4 56 57 99 100 101 0 1
A class named Demo contains a function named ‘expand_range’, that splits the string basedon
commas, and iterates through the string and splits the numbers and increments 1 every time. This is displayed on the console. In the main function, the string is defined, and the function is called by passing this function as a parameter. Relevant message is displayed on the console.
|
[
{
"code": null,
"e": 1130,
"s": 1062,
"text": "To expand a String if range is given, the Java code is as follows −"
},
{
"code": null,
"e": 1141,
"s": 1130,
"text": " Live Demo"
},
{
"code": null,
"e": 2004,
"s": 1141,
"text": "public class Demo {\n public static void expand_range(String word) {\n StringBuilder my_sb = new StringBuilder();\n String[] str_arr = word.split(\", \");\n for (int i = 0; i < str_arr.length; i++){\n String[] split_str = str_arr[i].split(\"-\");\n if (split_str.length == 2){\n int low = Integer.parseInt(split_str[0]);\n int high = Integer.parseInt(split_str[split_str.length - 1]);\n while (low <= high){\n my_sb.append(low + \" \");\n low++;\n }\n } else {\n my_sb.append(str_arr[i] + \" \");\n }\n }\n System.out.println(my_sb.toString());\n }\n public static void main(String args[]){\n String my_str = \"1-4, 56-57, 99-101, 0-1\";\n System.out.println(\"The expanded range of given numbers is \");\n expand_range(my_str);\n }\n}"
},
{
"code": null,
"e": 2072,
"s": 2004,
"text": "The expanded range of given numbers is\n1 2 3 4 56 57 99 100 101 0 1"
},
{
"code": null,
"e": 2449,
"s": 2072,
"text": "A class named Demo contains a function named ‘expand_range’, that splits the string basedon\ncommas, and iterates through the string and splits the numbers and increments 1 every time. This is displayed on the console. In the main function, the string is defined, and the function is called by passing this function as a parameter. Relevant message is displayed on the console."
}
] |
How to set new value for an attribute using jQuery?
|
The jQuery attr() method is used to get the value of an attribute. It can also be used to set new value. We will set new value of attribute href to tutorialspoint.com/html5 from tutorialspoint.com/css.
You can try to run the following code to learn how to set new value for an attribute in jQuery −
Live Demo
<html>
<head>
<title>Selector Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#tpoint").attr("href", "https://www.tutorialspoint.com/html5");
});
});
</script>
</head>
<body>
<p><a href="https://www.tutorialspoint.com/css" id="tpoint">Tutorialspoint</a></p>
<button>Set new value</button>
<p>The value of above link will change on clicking the above button. This will set a new value for the attribute. Check before and after button click.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1264,
"s": 1062,
"text": "The jQuery attr() method is used to get the value of an attribute. It can also be used to set new value. We will set new value of attribute href to tutorialspoint.com/html5 from tutorialspoint.com/css."
},
{
"code": null,
"e": 1361,
"s": 1264,
"text": "You can try to run the following code to learn how to set new value for an attribute in jQuery −"
},
{
"code": null,
"e": 1371,
"s": 1361,
"text": "Live Demo"
},
{
"code": null,
"e": 2073,
"s": 1371,
"text": "<html>\n <head>\n <title>Selector Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\"button\").click(function(){\n $(\"#tpoint\").attr(\"href\", \"https://www.tutorialspoint.com/html5\");\n });\n });\n </script>\n </head>\n <body>\n <p><a href=\"https://www.tutorialspoint.com/css\" id=\"tpoint\">Tutorialspoint</a></p>\n <button>Set new value</button>\n <p>The value of above link will change on clicking the above button. This will set a new value for the attribute. Check before and after button click.</p>\n </body>\n</html>"
}
] |
postmap - Unix, Linux Command
|
makemap file_type file_name < file_name
If the result files do not exist they will be created with the
same group and other read permissions as the source file.
While the table update is in progress, signal delivery is
postponed, and an exclusive, advisory, lock is placed on the
entire table, in order to avoid surprises in spectator
programs.
key whitespace value
By default the lookup key is mapped to lowercase to make
the lookups case insensitive; as of Postfix 2.3 this case
folding happens only with tables whose lookup keys are
fixed-case strings such as btree:, dbm: or hash:. With
earlier versions, the lookup key is folded even with tables
where a lookup field can match both upper and lower case
text, such as regexp: and pcre:. This resulted in loss of
information with $number substitutions.
If a key value of - is specified, the program reads key
values from the standard input stream. The exit status is zero
when at least one of the requested keys was found.
If a key value of - is specified, the program reads key
values from the standard input stream and writes one line of
key value output for each key that was found. The exit
status is zero when at least one of the requested keys was found.
The postmap(1) command can query any supported file type,
but it can create only the following file types:
postmap(1) terminates with zero exit status in case of success
(including successful "postmap -q" lookup) and terminates
with non-zero exit status in case of failure.
postalias(1), create/update/query alias database
postconf(1), supported database types
postconf(5), configuration parameters
syslogd(8), system logging
DATABASE_README, Postfix lookup table overview
Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA
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": 10622,
"s": 10577,
"text": "\n makemap file_type file_name < file_name\n"
},
{
"code": null,
"e": 10745,
"s": 10622,
"text": "\nIf the result files do not exist they will be created with the\nsame group and other read permissions as the source file.\n"
},
{
"code": null,
"e": 10931,
"s": 10745,
"text": "\nWhile the table update is in progress, signal delivery is\npostponed, and an exclusive, advisory, lock is placed on the\nentire table, in order to avoid surprises in spectator\nprograms.\n"
},
{
"code": null,
"e": 10959,
"s": 10933,
"text": "\n key whitespace value\n"
},
{
"code": null,
"e": 11401,
"s": 10959,
"text": "\nBy default the lookup key is mapped to lowercase to make\nthe lookups case insensitive; as of Postfix 2.3 this case\nfolding happens only with tables whose lookup keys are\nfixed-case strings such as btree:, dbm: or hash:. With\nearlier versions, the lookup key is folded even with tables\nwhere a lookup field can match both upper and lower case\ntext, such as regexp: and pcre:. This resulted in loss of\ninformation with $number substitutions.\n"
},
{
"code": null,
"e": 11575,
"s": 11403,
"text": "\nIf a key value of - is specified, the program reads key\nvalues from the standard input stream. The exit status is zero\nwhen at least one of the requested keys was found.\n"
},
{
"code": null,
"e": 11815,
"s": 11575,
"text": "\nIf a key value of - is specified, the program reads key\nvalues from the standard input stream and writes one line of\nkey value output for each key that was found. The exit\nstatus is zero when at least one of the requested keys was found.\n"
},
{
"code": null,
"e": 11924,
"s": 11815,
"text": "\nThe postmap(1) command can query any supported file type,\nbut it can create only the following file types:\n"
},
{
"code": null,
"e": 12093,
"s": 11924,
"text": "\npostmap(1) terminates with zero exit status in case of success\n(including successful \"postmap -q\" lookup) and terminates\nwith non-zero exit status in case of failure.\n"
},
{
"code": null,
"e": 12250,
"s": 12097,
"text": "postalias(1), create/update/query alias database\npostconf(1), supported database types\npostconf(5), configuration parameters\nsyslogd(8), system logging\n"
},
{
"code": null,
"e": 12300,
"s": 12252,
"text": "DATABASE_README, Postfix lookup table overview\n"
},
{
"code": null,
"e": 12387,
"s": 12302,
"text": "Wietse Venema\nIBM T.J. Watson Research\nP.O. Box 704\nYorktown Heights, NY 10598, USA\n"
},
{
"code": null,
"e": 12404,
"s": 12387,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 12439,
"s": 12404,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12467,
"s": 12439,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12501,
"s": 12467,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12518,
"s": 12501,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12551,
"s": 12518,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12562,
"s": 12551,
"text": " Pradeep D"
},
{
"code": null,
"e": 12597,
"s": 12562,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12613,
"s": 12597,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12646,
"s": 12613,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12658,
"s": 12646,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12690,
"s": 12658,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12698,
"s": 12690,
"text": " Uplatz"
},
{
"code": null,
"e": 12705,
"s": 12698,
"text": " Print"
},
{
"code": null,
"e": 12716,
"s": 12705,
"text": " Add Notes"
}
] |
Sarcasm Detection: Step towards Sentiment Analysis | by DIGVIJAY SINGH | Towards Data Science
|
Humans have a social nature. Social nature means that we interact with each other in positive, friendly ways, and it also means that we know how to manipulate others in a very negative way.
Sarcasm, which is both positively funny and negatively nasty, plays an important part in human social interaction.
But sometimes it is difficult to detect whether someone is making fun of us with some irony. So to make it easy we built something which helps you in detecting sarcastic text, but before getting into much more detail, let’s define sarcasm:-
Sarcasm is “a sharp, bitter, or cutting expression or remark”. The use of irony to mock or convey contempt.
So now it’s time to charge up and start the journey of sarcasm detection.
Let’s start by defining the problem:-
Problem description:-
We have given the News Headlines Dataset and our goal is to predict whether a given text is sarcastic or not.
This News Headlines Dataset for Sarcasm Detection is collected from The Onion website which aims at producing sarcastic versions of current events and HuffPost website which collects real news headlines.
You can get this Dataset easily from the amazing website Kaggle, here is the link below:-
Click here to download dataset
Our dataset has three columns, where the
article_link (type: Object): contains links to the news articles.
headline (type: Object): contains headlines of the news articles.
is_sarcastic (type: int64): contains 0(for nonsarcastic text) and 1(for sarcastic text).
Source Code(Python):-
This sarcasm detector was built-in Python language, so it’s time to import essential libraries and modules and don’t worry if you don’t know about these modules, we will learn about these as we will move ahead:-
import pandas as pd, numpy as np, re, timefrom nltk.stem.porter import PorterStemmer
Now it’s time to get our models and some dependencies:-
from sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrixfrom sklearn.svm import LinearSVCfrom sklearn.model_selection import cross_val_scorefrom sklearn.naive_bayes import GaussianNBfrom sklearn.linear_model import LogisticRegressionfrom sklearn.ensemble import RandomForestClassifier
and don’t worry, if you don’t have any of the modules, you can use:-
pip install <module/library Name>
to install any of the dependencies.
After getting all the dependencies it’s time to load our dataset into Pandas Dataframe.
# Loading data from json filedata = pd.read_json(‘Sarcasm_Headlines_Dataset.json’, lines = True)
Now let’s see the first five rows of our dataset using data.head() method of Pandas Dataframe.
It is always better to check the null values in the dataset first.
print(data.isnull().any(axis = 0))# Output :-# ----------------------# article_link False# headline False# is_sarcastic False# dtype: bool# ----------------------
Since our dataset doesn’t have any null value. So, we can proceed to clean the data.
Cleaning the data:-
Although, it looks that our data is clean but the headline column has some special symbols that have to be eliminated.
So, we are using Regular Expression to eliminate special symbols.
# Relacing special symbols and digits in headline column# re stands for Regular Expressiondata['headline'] = data['headline'].apply(lambda s : re.sub('[^a-zA-Z]', ' ', s))
Feature and label extraction:-
It’s time to extract features and labels out of our data. It seems that we may consider article_link and headline as features. But, article_link doesn’t play an important role in predicting the label. So, the only feature that we have is the headline column. And is_sarcastic is the only label.
# getting features and labelsfeatures = data['headline']labels = data['is_sarcastic']
Stemming of features:-
Stemming is the process of reducing a word to its word stem that affixes to suffixes and prefixes or the roots of words known as a lemma. Stemming is important in natural language understanding (NLU) and natural language processing (NLP).
for example:-
original word: “reading” and “reader”.
after stemming: read (for all the above two words).
# Stemming our dataps = PorterStemmer()features = features.apply(lambda x: x.split())features = features.apply(lambda x : ‘ ‘.join([ps.stem(word) for word in x]))
Vectorization of features using TF-IDF Vectorizer:-
TF-IDF is an abbreviation for Term Frequency-Inverse Document Frequency and is a very common algorithm to transform the text into a meaningful representation of numbers. The technique is widely used to extract features across various NLP applications.
# vectorizing the data with maximum of 5000 featuresfrom sklearn.feature_extraction.text import TfidfVectorizertv = TfidfVectorizer(max_features = 5000)features = list(features)features = tv.fit_transform(features).toarray()
Training and Testing data:-
After all the important stuff, it’s time to split our data into training and testing chunks.
# getting training and testing datafeatures_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size = .05, random_state = 0)
Training and testing of models:-
Now it’s showtime, we are going to train our model using different Machine Learning algorithms.
# model 1:-# Using linear support vector classifierlsvc = LinearSVC()# training the modellsvc.fit(features_train, labels_train)# getting the score of train and test dataprint(lsvc.score(features_train, labels_train)) # 90.93print(lsvc.score(features_test, labels_test)) # 83.75# model 2:-# Using Gaussuan Naive Bayesgnb = GaussianNB()gnb.fit(features_train, labels_train)print(gnb.score(features_train, labels_train)) # 78.86print(gnb.score(features_test, labels_test)) # 73.80# model 3:-# Logistic Regressionlr = LogisticRegression()lr.fit(features_train, labels_train)print(lr.score(features_train, labels_train)) # 88.16print(lr.score(features_test, labels_test)) # 83.08# model 4:-# Random Forest Classifierrfc = RandomForestClassifier(n_estimators = 10, random_state = 0)rfc.fit(features_train, labels_train)print(rfc.score(features_train, labels_train)) # 98.82print(rfc.score(features_test, labels_test)) # 79.71
After applying all the above models, the score is as follows:-
It can be seen that the best scorer is the Linear Support Vector Classifier with an accuracy of 83.75%. And remaining models have accuracies nearer to Linear Support Vector Classifier. Therefore, we have chosen the best one.
User-Interface:-
For making it user-friendly, we also built a user-interface using HTML, CSS, and Bootstrap, which is supported by The Flask.
This is how our user interface looks like:-
Based on the input text, our model predicts it to be sarcastic or not.
Summary:-
It can be seen that how well we can use the power of Machine Learning algorithms to make this sentiment analysis an easier task.
Special Thanks:-
The realization of this project was done at Forsk-Labs under the direction of amazing mentors, who helped us a lot in building this wonderful project. I will always be grateful to them for their support and kindness.
About Us:-
We (as a team of two members- DIGVIJAY SINGH and Sourabh Prajapati) built this project during our summer internship at Forsk Technologies.
QR Code to GitHub Repo:-
|
[
{
"code": null,
"e": 361,
"s": 171,
"text": "Humans have a social nature. Social nature means that we interact with each other in positive, friendly ways, and it also means that we know how to manipulate others in a very negative way."
},
{
"code": null,
"e": 476,
"s": 361,
"text": "Sarcasm, which is both positively funny and negatively nasty, plays an important part in human social interaction."
},
{
"code": null,
"e": 717,
"s": 476,
"text": "But sometimes it is difficult to detect whether someone is making fun of us with some irony. So to make it easy we built something which helps you in detecting sarcastic text, but before getting into much more detail, let’s define sarcasm:-"
},
{
"code": null,
"e": 825,
"s": 717,
"text": "Sarcasm is “a sharp, bitter, or cutting expression or remark”. The use of irony to mock or convey contempt."
},
{
"code": null,
"e": 899,
"s": 825,
"text": "So now it’s time to charge up and start the journey of sarcasm detection."
},
{
"code": null,
"e": 937,
"s": 899,
"text": "Let’s start by defining the problem:-"
},
{
"code": null,
"e": 959,
"s": 937,
"text": "Problem description:-"
},
{
"code": null,
"e": 1069,
"s": 959,
"text": "We have given the News Headlines Dataset and our goal is to predict whether a given text is sarcastic or not."
},
{
"code": null,
"e": 1273,
"s": 1069,
"text": "This News Headlines Dataset for Sarcasm Detection is collected from The Onion website which aims at producing sarcastic versions of current events and HuffPost website which collects real news headlines."
},
{
"code": null,
"e": 1363,
"s": 1273,
"text": "You can get this Dataset easily from the amazing website Kaggle, here is the link below:-"
},
{
"code": null,
"e": 1394,
"s": 1363,
"text": "Click here to download dataset"
},
{
"code": null,
"e": 1435,
"s": 1394,
"text": "Our dataset has three columns, where the"
},
{
"code": null,
"e": 1501,
"s": 1435,
"text": "article_link (type: Object): contains links to the news articles."
},
{
"code": null,
"e": 1567,
"s": 1501,
"text": "headline (type: Object): contains headlines of the news articles."
},
{
"code": null,
"e": 1656,
"s": 1567,
"text": "is_sarcastic (type: int64): contains 0(for nonsarcastic text) and 1(for sarcastic text)."
},
{
"code": null,
"e": 1678,
"s": 1656,
"text": "Source Code(Python):-"
},
{
"code": null,
"e": 1890,
"s": 1678,
"text": "This sarcasm detector was built-in Python language, so it’s time to import essential libraries and modules and don’t worry if you don’t know about these modules, we will learn about these as we will move ahead:-"
},
{
"code": null,
"e": 1975,
"s": 1890,
"text": "import pandas as pd, numpy as np, re, timefrom nltk.stem.porter import PorterStemmer"
},
{
"code": null,
"e": 2031,
"s": 1975,
"text": "Now it’s time to get our models and some dependencies:-"
},
{
"code": null,
"e": 2356,
"s": 2031,
"text": "from sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrixfrom sklearn.svm import LinearSVCfrom sklearn.model_selection import cross_val_scorefrom sklearn.naive_bayes import GaussianNBfrom sklearn.linear_model import LogisticRegressionfrom sklearn.ensemble import RandomForestClassifier"
},
{
"code": null,
"e": 2425,
"s": 2356,
"text": "and don’t worry, if you don’t have any of the modules, you can use:-"
},
{
"code": null,
"e": 2459,
"s": 2425,
"text": "pip install <module/library Name>"
},
{
"code": null,
"e": 2495,
"s": 2459,
"text": "to install any of the dependencies."
},
{
"code": null,
"e": 2583,
"s": 2495,
"text": "After getting all the dependencies it’s time to load our dataset into Pandas Dataframe."
},
{
"code": null,
"e": 2680,
"s": 2583,
"text": "# Loading data from json filedata = pd.read_json(‘Sarcasm_Headlines_Dataset.json’, lines = True)"
},
{
"code": null,
"e": 2775,
"s": 2680,
"text": "Now let’s see the first five rows of our dataset using data.head() method of Pandas Dataframe."
},
{
"code": null,
"e": 2842,
"s": 2775,
"text": "It is always better to check the null values in the dataset first."
},
{
"code": null,
"e": 3018,
"s": 2842,
"text": "print(data.isnull().any(axis = 0))# Output :-# ----------------------# article_link False# headline False# is_sarcastic False# dtype: bool# ----------------------"
},
{
"code": null,
"e": 3103,
"s": 3018,
"text": "Since our dataset doesn’t have any null value. So, we can proceed to clean the data."
},
{
"code": null,
"e": 3123,
"s": 3103,
"text": "Cleaning the data:-"
},
{
"code": null,
"e": 3242,
"s": 3123,
"text": "Although, it looks that our data is clean but the headline column has some special symbols that have to be eliminated."
},
{
"code": null,
"e": 3308,
"s": 3242,
"text": "So, we are using Regular Expression to eliminate special symbols."
},
{
"code": null,
"e": 3480,
"s": 3308,
"text": "# Relacing special symbols and digits in headline column# re stands for Regular Expressiondata['headline'] = data['headline'].apply(lambda s : re.sub('[^a-zA-Z]', ' ', s))"
},
{
"code": null,
"e": 3511,
"s": 3480,
"text": "Feature and label extraction:-"
},
{
"code": null,
"e": 3806,
"s": 3511,
"text": "It’s time to extract features and labels out of our data. It seems that we may consider article_link and headline as features. But, article_link doesn’t play an important role in predicting the label. So, the only feature that we have is the headline column. And is_sarcastic is the only label."
},
{
"code": null,
"e": 3892,
"s": 3806,
"text": "# getting features and labelsfeatures = data['headline']labels = data['is_sarcastic']"
},
{
"code": null,
"e": 3915,
"s": 3892,
"text": "Stemming of features:-"
},
{
"code": null,
"e": 4154,
"s": 3915,
"text": "Stemming is the process of reducing a word to its word stem that affixes to suffixes and prefixes or the roots of words known as a lemma. Stemming is important in natural language understanding (NLU) and natural language processing (NLP)."
},
{
"code": null,
"e": 4168,
"s": 4154,
"text": "for example:-"
},
{
"code": null,
"e": 4207,
"s": 4168,
"text": "original word: “reading” and “reader”."
},
{
"code": null,
"e": 4259,
"s": 4207,
"text": "after stemming: read (for all the above two words)."
},
{
"code": null,
"e": 4422,
"s": 4259,
"text": "# Stemming our dataps = PorterStemmer()features = features.apply(lambda x: x.split())features = features.apply(lambda x : ‘ ‘.join([ps.stem(word) for word in x]))"
},
{
"code": null,
"e": 4474,
"s": 4422,
"text": "Vectorization of features using TF-IDF Vectorizer:-"
},
{
"code": null,
"e": 4726,
"s": 4474,
"text": "TF-IDF is an abbreviation for Term Frequency-Inverse Document Frequency and is a very common algorithm to transform the text into a meaningful representation of numbers. The technique is widely used to extract features across various NLP applications."
},
{
"code": null,
"e": 4951,
"s": 4726,
"text": "# vectorizing the data with maximum of 5000 featuresfrom sklearn.feature_extraction.text import TfidfVectorizertv = TfidfVectorizer(max_features = 5000)features = list(features)features = tv.fit_transform(features).toarray()"
},
{
"code": null,
"e": 4979,
"s": 4951,
"text": "Training and Testing data:-"
},
{
"code": null,
"e": 5072,
"s": 4979,
"text": "After all the important stuff, it’s time to split our data into training and testing chunks."
},
{
"code": null,
"e": 5236,
"s": 5072,
"text": "# getting training and testing datafeatures_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size = .05, random_state = 0)"
},
{
"code": null,
"e": 5269,
"s": 5236,
"text": "Training and testing of models:-"
},
{
"code": null,
"e": 5365,
"s": 5269,
"text": "Now it’s showtime, we are going to train our model using different Machine Learning algorithms."
},
{
"code": null,
"e": 6301,
"s": 5365,
"text": "# model 1:-# Using linear support vector classifierlsvc = LinearSVC()# training the modellsvc.fit(features_train, labels_train)# getting the score of train and test dataprint(lsvc.score(features_train, labels_train)) # 90.93print(lsvc.score(features_test, labels_test)) # 83.75# model 2:-# Using Gaussuan Naive Bayesgnb = GaussianNB()gnb.fit(features_train, labels_train)print(gnb.score(features_train, labels_train)) # 78.86print(gnb.score(features_test, labels_test)) # 73.80# model 3:-# Logistic Regressionlr = LogisticRegression()lr.fit(features_train, labels_train)print(lr.score(features_train, labels_train)) # 88.16print(lr.score(features_test, labels_test)) # 83.08# model 4:-# Random Forest Classifierrfc = RandomForestClassifier(n_estimators = 10, random_state = 0)rfc.fit(features_train, labels_train)print(rfc.score(features_train, labels_train)) # 98.82print(rfc.score(features_test, labels_test)) # 79.71"
},
{
"code": null,
"e": 6364,
"s": 6301,
"text": "After applying all the above models, the score is as follows:-"
},
{
"code": null,
"e": 6589,
"s": 6364,
"text": "It can be seen that the best scorer is the Linear Support Vector Classifier with an accuracy of 83.75%. And remaining models have accuracies nearer to Linear Support Vector Classifier. Therefore, we have chosen the best one."
},
{
"code": null,
"e": 6606,
"s": 6589,
"text": "User-Interface:-"
},
{
"code": null,
"e": 6731,
"s": 6606,
"text": "For making it user-friendly, we also built a user-interface using HTML, CSS, and Bootstrap, which is supported by The Flask."
},
{
"code": null,
"e": 6775,
"s": 6731,
"text": "This is how our user interface looks like:-"
},
{
"code": null,
"e": 6846,
"s": 6775,
"text": "Based on the input text, our model predicts it to be sarcastic or not."
},
{
"code": null,
"e": 6856,
"s": 6846,
"text": "Summary:-"
},
{
"code": null,
"e": 6985,
"s": 6856,
"text": "It can be seen that how well we can use the power of Machine Learning algorithms to make this sentiment analysis an easier task."
},
{
"code": null,
"e": 7002,
"s": 6985,
"text": "Special Thanks:-"
},
{
"code": null,
"e": 7219,
"s": 7002,
"text": "The realization of this project was done at Forsk-Labs under the direction of amazing mentors, who helped us a lot in building this wonderful project. I will always be grateful to them for their support and kindness."
},
{
"code": null,
"e": 7230,
"s": 7219,
"text": "About Us:-"
},
{
"code": null,
"e": 7369,
"s": 7230,
"text": "We (as a team of two members- DIGVIJAY SINGH and Sourabh Prajapati) built this project during our summer internship at Forsk Technologies."
}
] |
Align HTML5 SVG to the center of the screen
|
SVG stands for Scalable Vector Graphics and it is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer.
Let us see an example of SVG −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-20%);
-ms-transform: translateX(-20%);
transform: translateX(-20%);
}
</style>
<title>SVG</title>
<meta charset="utf-8" />
</head>
<body>
<h2>HTML5 SVG Circle</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<circle id = "redcircle" cx = "50" cy = "50" r = "50" fill = "red" />
</svg>
</body>
</html>
To center it, add the CSS like the following −
# svgelem {
margin-left:auto;
margin-right:auto;
display:block;
}
|
[
{
"code": null,
"e": 1231,
"s": 1062,
"text": "SVG stands for Scalable Vector Graphics and it is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer."
},
{
"code": null,
"e": 1262,
"s": 1231,
"text": "Let us see an example of SVG −"
},
{
"code": null,
"e": 1844,
"s": 1262,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #svgelem {\n position: relative;\n left: 50%;\n -webkit-transform: translateX(-20%);\n -ms-transform: translateX(-20%);\n transform: translateX(-20%);\n }\n </style>\n <title>SVG</title>\n <meta charset=\"utf-8\" />\n </head>\n <body>\n <h2>HTML5 SVG Circle</h2>\n <svg id = \"svgelem\" height = \"200\" xmlns = \"http://www.w3.org/2000/svg\">\n <circle id = \"redcircle\" cx = \"50\" cy = \"50\" r = \"50\" fill = \"red\" />\n </svg>\n </body>\n</html>"
},
{
"code": null,
"e": 1891,
"s": 1844,
"text": "To center it, add the CSS like the following −"
},
{
"code": null,
"e": 1966,
"s": 1891,
"text": "# svgelem {\n margin-left:auto;\n margin-right:auto;\n display:block;\n}"
}
] |
How to create a vector with zero values in R?
|
In data analysis, sometimes we need to use zeros for certain calculations, either to nullify the effect of a variable or for some other purpose based on the objective of the analysis. To deal with such type of situations, we need a zero value or a vector of zeros. There are many ways to create a vector with zeros in R. The important thing is the length of the vector.
> x1<-integer(10)
> x1
[1] 0 0 0 0 0 0 0 0 0 0
> x2<-integer(20)
> x2
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> x3<-numeric(10)
> x3
[1] 0 0 0 0 0 0 0 0 0 0
> x4<-numeric(20)
> x4
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> x5<-replicate(10,0)
> x5
[1] 0 0 0 0 0 0 0 0 0 0
> x6<-replicate(100,0)
> x6
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> x7<-(1:10)*0
> x7
[1] 0 0 0 0 0 0 0 0 0 0
> x8<-(1:50)*0
> x8
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[39] 0 0 0 0 0 0 0 0 0 0 0 0
> x9<-rep(0,10)
> x9
[1] 0 0 0 0 0 0 0 0 0 0
> x10<-rep(0,40)
> x10
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[39] 0 0
> x11<-rep(0L,10)
> x11
[1] 0 0 0 0 0 0 0 0 0 0
> x12<-rep(0L,100)
> x12
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Checking whether each of these objects are vector or not −
> is.vector(x1)
[1] TRUE
> is.vector(x2)
[1] TRUE
> is.vector(x3)
[1] TRUE
> is.vector(x4)
[1] TRUE
> is.vector(x5)
[1] TRUE
> is.vector(x6)
[1] TRUE
> is.vector(x7)
[1] TRUE
> is.vector(x8)
[1] TRUE
> is.vector(x9)
[1] TRUE
> is.vector(x10)
[1] TRUE
> is.vector(x11)
[1] TRUE
> is.vector(x12)
[1] TRUE
|
[
{
"code": null,
"e": 1432,
"s": 1062,
"text": "In data analysis, sometimes we need to use zeros for certain calculations, either to nullify the effect of a variable or for some other purpose based on the objective of the analysis. To deal with such type of situations, we need a zero value or a vector of zeros. There are many ways to create a vector with zeros in R. The important thing is the length of the vector."
},
{
"code": null,
"e": 2570,
"s": 1432,
"text": "> x1<-integer(10)\n> x1\n[1] 0 0 0 0 0 0 0 0 0 0\n> x2<-integer(20)\n> x2\n[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n> x3<-numeric(10)\n> x3\n[1] 0 0 0 0 0 0 0 0 0 0\n> x4<-numeric(20)\n> x4\n[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n> x5<-replicate(10,0)\n> x5\n[1] 0 0 0 0 0 0 0 0 0 0\n> x6<-replicate(100,0)\n> x6\n[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n[38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n[75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n> x7<-(1:10)*0\n> x7\n[1] 0 0 0 0 0 0 0 0 0 0\n> x8<-(1:50)*0\n> x8\n[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n[39] 0 0 0 0 0 0 0 0 0 0 0 0\n> x9<-rep(0,10)\n> x9\n[1] 0 0 0 0 0 0 0 0 0 0\n> x10<-rep(0,40)\n> x10\n[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n[39] 0 0\n> x11<-rep(0L,10)\n> x11\n[1] 0 0 0 0 0 0 0 0 0 0\n> x12<-rep(0L,100)\n> x12\n[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n[38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n[75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"
},
{
"code": null,
"e": 2629,
"s": 2570,
"text": "Checking whether each of these objects are vector or not −"
},
{
"code": null,
"e": 2932,
"s": 2629,
"text": "> is.vector(x1)\n[1] TRUE\n> is.vector(x2)\n[1] TRUE\n> is.vector(x3)\n[1] TRUE\n> is.vector(x4)\n[1] TRUE\n> is.vector(x5)\n[1] TRUE\n> is.vector(x6)\n[1] TRUE\n> is.vector(x7)\n[1] TRUE\n> is.vector(x8)\n[1] TRUE\n> is.vector(x9)\n[1] TRUE\n> is.vector(x10)\n[1] TRUE\n> is.vector(x11)\n[1] TRUE\n> is.vector(x12)\n[1] TRUE"
}
] |
Change the Background of Any Image with 5 Lines of Code | by Ayoola Olafenwa (she/her) | Towards Data Science
|
Image segmentation has a lot of amazing applications that solve different computer vision problems. PixelLib is a library created to ensure easy integration of image segmentation in real life applications. PixelLib now supports a feature known as image tuning.
Image Tuning: It is the change in the background of an image through image segmentation. The key role of image segmentation is to remove the objects segmented from the image and place them in the new background created. This is done by producing a mask for the image and combining it with the modified background. We make use of deeplabv3+ model trained on pascalvoc dataset. The model supports 20 common object categories, which means you can change the background of these objects in images.
The model supports the following objects listed below;
person,bus,car,aeroplane, bicycle, ,motorbike,bird, boat, bottle, cat, chair, cow, dinningtable, dog, horse pottedplant, sheep, sofa, train, tv
Background effects supported are:
1 Changing the background of an image with a picture
2 Assigning a distinct color to the background of an image.
3 Blurring the background of an image
4 Grayscaling the background of an image
Install PixelLib and its dependencies:
Install Tensorflow with:(PixelLib supports tensorflow 2.0 and above)
pip3 install tensorflow
Install PixelLib with
pip3 install pixellib
If installed, upgrade to the latest version using:
pip3 install pixellib — upgrade
PixelLib makes it possible to change the background of any image with a picture with just 5 lines of code.
sample.jpg
We want to change the background of the image above with the image provided below.
background.jpg
Code to change the background of an image with a picture
import pixellibfrom pixellib.tune_bg import alter_bgchange_bg = alter_bg()
We imported pixellib, and from pixellib, we imported in the class alter_bg. We created an instance of the class.
change_bg.load_pascalvoc_model("deeplabv3_xception_tf_dim_ordering_tf_kernels.h5")
We loaded deeplabv3+ model. Download deeplabv3+ pascalvoc model from here.
change_bg.change_bg_img(f_image_path = "sample.jpg",b_image_path = "background.jpg", output_image_name="new_img.jpg")
We called the function change_bg_img that handled changing the background of the image with a picture.
The function takes the following parameters:
f_image_path: This is the foreground image, the image which background would be changed.
b_image_path: This is the image that will be used to change the background of the foreground image.
output_image_name: The new image with a changed background.
output Image
WOW! This is beautiful, we have successfully replaced the background of our image.
We are able to use PixelLib to perform excellent foreground and background subtraction through image segmentation.
Code to Obtain output array of the changed image array
For specialized uses, you can easily obtain the array of the changed image with the modified code below.
You can assign a distinct color to the background of your image, just the way you are able to change the background of an image with a picture. This is also possible with five lines of code.
Code to assign a distinct color to the background of an image
It is very similar to the code used above for changing the background of an image with a picture. The only difference is that we replaced the function change_bg_img to color_bg, the function that handled color change.
change_bg.color_bg("sample.jpg", colors = (0, 128, 0), output_image_name="colored_bg.jpg")
The function color_bg takes the parameter colors and we provide the RGB value of the color we want to use. We want the image to have a green background and the color’s RGB value is set to green which is (0, 128, 0).
green background
Note:You can assign any color to the background of your image by providing the RGB value of the color.
change_bg.color_bg("sample.jpg", colors = (255, 255, 255), output_image_name="colored_bg.jpg")
We want to change the background of the image to white and set color’s RGB value to white which is (255,255,255).
white background
The same image with a white background.
Code to Obtain output array of the colored image
For specialized uses, you can easily obtain the array of the changed image with the modified code below.
Grayscale the background of any image using the same lines of code with PixelLib.
Code to grayscale the background of an image
change_bg.gray_bg(“sample.jpg”,output_image_name=”gray_img.jpg”)
It is still the same code except we called the function gray_bg to grayscale the background of the image.
output image
Note:The background of the image would be altered and the objects present would maintain their original quality.
Code to Obtain output array of the grayed image
You can apply the effect of blurring the background of an image, and it is possible to control how blur the background will be.
sample2.jpg
change_bg.blur_bg("sample2.jpg", low = True, output_image_name="blur_img.jpg")
We called the function blur_bg to blur the background of the image, and set the blurred effect to be low. There are three parameters that determine the degree to which the background is blurred.
low: When it is set to true, the background is blurred slightly.
moderate: When it is set to true, the background is moderately blurred.
extreme: When it is set to true, the background is deeply blurred.
The image is blurred with a low effect.
change_bg.blur_bg("sample2.jpg", moderate = True, output_image_name="blur_img.jpg")
We want to moderately blur the background of the image, and we set moderate to true.
The image’s background is blurred with a moderate effect.
change_bg.blur_bg("sample2.jpg", extreme = True, output_image_name="blur_img.jpg")
We want to deeply blurred the background of the image, and we set extreme to true.
The image’s background is extremely blurred.
Full code to blur the background of an image
Code to Obtain output array of the blurred image
Note: Learn how to apply these background effects to videos and camera’s feeds on PixelLib’s github’s repository and PixelLib’s documentation. I will publish an explanatory article on how to apply these background effects to videos and camera’s feeds soon.
Reach to me via:
Email: olafenwaayoola@gmail.com
Linkedin: Ayoola Olafenwa
Twitter: @AyoolaOlafenwa
Facebook: Ayoola Olafenwa
Check out these articles written on how to make use of PixelLib for semantic and instance segmentation of objects in images and videos.
|
[
{
"code": null,
"e": 433,
"s": 172,
"text": "Image segmentation has a lot of amazing applications that solve different computer vision problems. PixelLib is a library created to ensure easy integration of image segmentation in real life applications. PixelLib now supports a feature known as image tuning."
},
{
"code": null,
"e": 927,
"s": 433,
"text": "Image Tuning: It is the change in the background of an image through image segmentation. The key role of image segmentation is to remove the objects segmented from the image and place them in the new background created. This is done by producing a mask for the image and combining it with the modified background. We make use of deeplabv3+ model trained on pascalvoc dataset. The model supports 20 common object categories, which means you can change the background of these objects in images."
},
{
"code": null,
"e": 982,
"s": 927,
"text": "The model supports the following objects listed below;"
},
{
"code": null,
"e": 1127,
"s": 982,
"text": "person,bus,car,aeroplane, bicycle, ,motorbike,bird, boat, bottle, cat, chair, cow, dinningtable, dog, horse pottedplant, sheep, sofa, train, tv"
},
{
"code": null,
"e": 1161,
"s": 1127,
"text": "Background effects supported are:"
},
{
"code": null,
"e": 1214,
"s": 1161,
"text": "1 Changing the background of an image with a picture"
},
{
"code": null,
"e": 1274,
"s": 1214,
"text": "2 Assigning a distinct color to the background of an image."
},
{
"code": null,
"e": 1312,
"s": 1274,
"text": "3 Blurring the background of an image"
},
{
"code": null,
"e": 1353,
"s": 1312,
"text": "4 Grayscaling the background of an image"
},
{
"code": null,
"e": 1392,
"s": 1353,
"text": "Install PixelLib and its dependencies:"
},
{
"code": null,
"e": 1461,
"s": 1392,
"text": "Install Tensorflow with:(PixelLib supports tensorflow 2.0 and above)"
},
{
"code": null,
"e": 1485,
"s": 1461,
"text": "pip3 install tensorflow"
},
{
"code": null,
"e": 1507,
"s": 1485,
"text": "Install PixelLib with"
},
{
"code": null,
"e": 1529,
"s": 1507,
"text": "pip3 install pixellib"
},
{
"code": null,
"e": 1580,
"s": 1529,
"text": "If installed, upgrade to the latest version using:"
},
{
"code": null,
"e": 1612,
"s": 1580,
"text": "pip3 install pixellib — upgrade"
},
{
"code": null,
"e": 1719,
"s": 1612,
"text": "PixelLib makes it possible to change the background of any image with a picture with just 5 lines of code."
},
{
"code": null,
"e": 1730,
"s": 1719,
"text": "sample.jpg"
},
{
"code": null,
"e": 1813,
"s": 1730,
"text": "We want to change the background of the image above with the image provided below."
},
{
"code": null,
"e": 1828,
"s": 1813,
"text": "background.jpg"
},
{
"code": null,
"e": 1885,
"s": 1828,
"text": "Code to change the background of an image with a picture"
},
{
"code": null,
"e": 1960,
"s": 1885,
"text": "import pixellibfrom pixellib.tune_bg import alter_bgchange_bg = alter_bg()"
},
{
"code": null,
"e": 2073,
"s": 1960,
"text": "We imported pixellib, and from pixellib, we imported in the class alter_bg. We created an instance of the class."
},
{
"code": null,
"e": 2156,
"s": 2073,
"text": "change_bg.load_pascalvoc_model(\"deeplabv3_xception_tf_dim_ordering_tf_kernels.h5\")"
},
{
"code": null,
"e": 2231,
"s": 2156,
"text": "We loaded deeplabv3+ model. Download deeplabv3+ pascalvoc model from here."
},
{
"code": null,
"e": 2349,
"s": 2231,
"text": "change_bg.change_bg_img(f_image_path = \"sample.jpg\",b_image_path = \"background.jpg\", output_image_name=\"new_img.jpg\")"
},
{
"code": null,
"e": 2452,
"s": 2349,
"text": "We called the function change_bg_img that handled changing the background of the image with a picture."
},
{
"code": null,
"e": 2497,
"s": 2452,
"text": "The function takes the following parameters:"
},
{
"code": null,
"e": 2586,
"s": 2497,
"text": "f_image_path: This is the foreground image, the image which background would be changed."
},
{
"code": null,
"e": 2686,
"s": 2586,
"text": "b_image_path: This is the image that will be used to change the background of the foreground image."
},
{
"code": null,
"e": 2746,
"s": 2686,
"text": "output_image_name: The new image with a changed background."
},
{
"code": null,
"e": 2759,
"s": 2746,
"text": "output Image"
},
{
"code": null,
"e": 2842,
"s": 2759,
"text": "WOW! This is beautiful, we have successfully replaced the background of our image."
},
{
"code": null,
"e": 2957,
"s": 2842,
"text": "We are able to use PixelLib to perform excellent foreground and background subtraction through image segmentation."
},
{
"code": null,
"e": 3012,
"s": 2957,
"text": "Code to Obtain output array of the changed image array"
},
{
"code": null,
"e": 3117,
"s": 3012,
"text": "For specialized uses, you can easily obtain the array of the changed image with the modified code below."
},
{
"code": null,
"e": 3308,
"s": 3117,
"text": "You can assign a distinct color to the background of your image, just the way you are able to change the background of an image with a picture. This is also possible with five lines of code."
},
{
"code": null,
"e": 3370,
"s": 3308,
"text": "Code to assign a distinct color to the background of an image"
},
{
"code": null,
"e": 3588,
"s": 3370,
"text": "It is very similar to the code used above for changing the background of an image with a picture. The only difference is that we replaced the function change_bg_img to color_bg, the function that handled color change."
},
{
"code": null,
"e": 3679,
"s": 3588,
"text": "change_bg.color_bg(\"sample.jpg\", colors = (0, 128, 0), output_image_name=\"colored_bg.jpg\")"
},
{
"code": null,
"e": 3895,
"s": 3679,
"text": "The function color_bg takes the parameter colors and we provide the RGB value of the color we want to use. We want the image to have a green background and the color’s RGB value is set to green which is (0, 128, 0)."
},
{
"code": null,
"e": 3912,
"s": 3895,
"text": "green background"
},
{
"code": null,
"e": 4015,
"s": 3912,
"text": "Note:You can assign any color to the background of your image by providing the RGB value of the color."
},
{
"code": null,
"e": 4110,
"s": 4015,
"text": "change_bg.color_bg(\"sample.jpg\", colors = (255, 255, 255), output_image_name=\"colored_bg.jpg\")"
},
{
"code": null,
"e": 4224,
"s": 4110,
"text": "We want to change the background of the image to white and set color’s RGB value to white which is (255,255,255)."
},
{
"code": null,
"e": 4241,
"s": 4224,
"text": "white background"
},
{
"code": null,
"e": 4281,
"s": 4241,
"text": "The same image with a white background."
},
{
"code": null,
"e": 4330,
"s": 4281,
"text": "Code to Obtain output array of the colored image"
},
{
"code": null,
"e": 4435,
"s": 4330,
"text": "For specialized uses, you can easily obtain the array of the changed image with the modified code below."
},
{
"code": null,
"e": 4517,
"s": 4435,
"text": "Grayscale the background of any image using the same lines of code with PixelLib."
},
{
"code": null,
"e": 4562,
"s": 4517,
"text": "Code to grayscale the background of an image"
},
{
"code": null,
"e": 4627,
"s": 4562,
"text": "change_bg.gray_bg(“sample.jpg”,output_image_name=”gray_img.jpg”)"
},
{
"code": null,
"e": 4733,
"s": 4627,
"text": "It is still the same code except we called the function gray_bg to grayscale the background of the image."
},
{
"code": null,
"e": 4746,
"s": 4733,
"text": "output image"
},
{
"code": null,
"e": 4859,
"s": 4746,
"text": "Note:The background of the image would be altered and the objects present would maintain their original quality."
},
{
"code": null,
"e": 4907,
"s": 4859,
"text": "Code to Obtain output array of the grayed image"
},
{
"code": null,
"e": 5035,
"s": 4907,
"text": "You can apply the effect of blurring the background of an image, and it is possible to control how blur the background will be."
},
{
"code": null,
"e": 5047,
"s": 5035,
"text": "sample2.jpg"
},
{
"code": null,
"e": 5126,
"s": 5047,
"text": "change_bg.blur_bg(\"sample2.jpg\", low = True, output_image_name=\"blur_img.jpg\")"
},
{
"code": null,
"e": 5321,
"s": 5126,
"text": "We called the function blur_bg to blur the background of the image, and set the blurred effect to be low. There are three parameters that determine the degree to which the background is blurred."
},
{
"code": null,
"e": 5386,
"s": 5321,
"text": "low: When it is set to true, the background is blurred slightly."
},
{
"code": null,
"e": 5458,
"s": 5386,
"text": "moderate: When it is set to true, the background is moderately blurred."
},
{
"code": null,
"e": 5525,
"s": 5458,
"text": "extreme: When it is set to true, the background is deeply blurred."
},
{
"code": null,
"e": 5565,
"s": 5525,
"text": "The image is blurred with a low effect."
},
{
"code": null,
"e": 5649,
"s": 5565,
"text": "change_bg.blur_bg(\"sample2.jpg\", moderate = True, output_image_name=\"blur_img.jpg\")"
},
{
"code": null,
"e": 5734,
"s": 5649,
"text": "We want to moderately blur the background of the image, and we set moderate to true."
},
{
"code": null,
"e": 5792,
"s": 5734,
"text": "The image’s background is blurred with a moderate effect."
},
{
"code": null,
"e": 5875,
"s": 5792,
"text": "change_bg.blur_bg(\"sample2.jpg\", extreme = True, output_image_name=\"blur_img.jpg\")"
},
{
"code": null,
"e": 5958,
"s": 5875,
"text": "We want to deeply blurred the background of the image, and we set extreme to true."
},
{
"code": null,
"e": 6003,
"s": 5958,
"text": "The image’s background is extremely blurred."
},
{
"code": null,
"e": 6048,
"s": 6003,
"text": "Full code to blur the background of an image"
},
{
"code": null,
"e": 6097,
"s": 6048,
"text": "Code to Obtain output array of the blurred image"
},
{
"code": null,
"e": 6354,
"s": 6097,
"text": "Note: Learn how to apply these background effects to videos and camera’s feeds on PixelLib’s github’s repository and PixelLib’s documentation. I will publish an explanatory article on how to apply these background effects to videos and camera’s feeds soon."
},
{
"code": null,
"e": 6371,
"s": 6354,
"text": "Reach to me via:"
},
{
"code": null,
"e": 6403,
"s": 6371,
"text": "Email: olafenwaayoola@gmail.com"
},
{
"code": null,
"e": 6429,
"s": 6403,
"text": "Linkedin: Ayoola Olafenwa"
},
{
"code": null,
"e": 6454,
"s": 6429,
"text": "Twitter: @AyoolaOlafenwa"
},
{
"code": null,
"e": 6480,
"s": 6454,
"text": "Facebook: Ayoola Olafenwa"
}
] |
JSF - f:convertDateTime
|
f:convertDateTime tag is used to convert a string value to a date of required format. It also acts as a validator, a required date format.
<f:convertDateTime pattern = "dd-mm-yyyy" />
type
date (default), time, or both
dateStyle
default, short, medium, long, or full
timeStyle
default, short, medium, long, or full
pattern
Formatting pattern, as defined in java.text.SimpleDateFormat
locale
Locale whose preferences are to be used for parsing and formatting
Time zone to use for parsing and formatting
Let us create a test JSF application to test the above tag.
package com.tutorialspoint.test;
import java.io.Serializable;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
public Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core">
<h:head>
<title>JSF tutorial</title>
</h:head>
<h:body>
<h2>ConvertDateTime Example</h2>
<h:form>
<h:inputText id = "dateInput" value = "#{userData.date}"
label = "Date" >
<f:convertDateTime pattern = "dd-mm-yyyy" />
</h:inputText>
<h:commandButton value = "submit" action = "result"/>
</h:form>
<br/>
<h:message for = "dateInput" style = "color:red" />
<h:outputText value = "12-01-2012" >
<f:convertDateTime pattern = "dd-mm-yyyy" />
</h:outputText>
</h:body>
</html>
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:ui = "http://java.sun.com/jsf/facelets">
<h:body>
<h2>Result</h2>
<hr />
#{userData.date}
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Enter any invalid value and press Submit button. See the following error message.
Enter any valid value and press Submit button. See the following result.
37 Lectures
3.5 hours
Chaand Sheikh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2091,
"s": 1952,
"text": "f:convertDateTime tag is used to convert a string value to a date of required format. It also acts as a validator, a required date format."
},
{
"code": null,
"e": 2136,
"s": 2091,
"text": "<f:convertDateTime pattern = \"dd-mm-yyyy\" />"
},
{
"code": null,
"e": 2141,
"s": 2136,
"text": "type"
},
{
"code": null,
"e": 2171,
"s": 2141,
"text": "date (default), time, or both"
},
{
"code": null,
"e": 2181,
"s": 2171,
"text": "dateStyle"
},
{
"code": null,
"e": 2219,
"s": 2181,
"text": "default, short, medium, long, or full"
},
{
"code": null,
"e": 2229,
"s": 2219,
"text": "timeStyle"
},
{
"code": null,
"e": 2267,
"s": 2229,
"text": "default, short, medium, long, or full"
},
{
"code": null,
"e": 2275,
"s": 2267,
"text": "pattern"
},
{
"code": null,
"e": 2336,
"s": 2275,
"text": "Formatting pattern, as defined in java.text.SimpleDateFormat"
},
{
"code": null,
"e": 2343,
"s": 2336,
"text": "locale"
},
{
"code": null,
"e": 2410,
"s": 2343,
"text": "Locale whose preferences are to be used for parsing and formatting"
},
{
"code": null,
"e": 2454,
"s": 2410,
"text": "Time zone to use for parsing and formatting"
},
{
"code": null,
"e": 2514,
"s": 2454,
"text": "Let us create a test JSF application to test the above tag."
},
{
"code": null,
"e": 2980,
"s": 2514,
"text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n public Date date;\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n}"
},
{
"code": null,
"e": 3896,
"s": 2980,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:f = \"http://java.sun.com/jsf/core\">\n \n <h:head>\n <title>JSF tutorial</title>\n </h:head>\n \n <h:body>\n <h2>ConvertDateTime Example</h2>\n \n <h:form>\n <h:inputText id = \"dateInput\" value = \"#{userData.date}\"\n label = \"Date\" >\n <f:convertDateTime pattern = \"dd-mm-yyyy\" />\n </h:inputText>\n <h:commandButton value = \"submit\" action = \"result\"/>\n </h:form>\n <br/>\n <h:message for = \"dateInput\" style = \"color:red\" />\n \n <h:outputText value = \"12-01-2012\" >\n <f:convertDateTime pattern = \"dd-mm-yyyy\" />\n </h:outputText>\n \n </h:body>\n</html>"
},
{
"code": null,
"e": 4340,
"s": 3896,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\"\n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <h:body>\n <h2>Result</h2>\n <hr />\n #{userData.date}\n </h:body>\n</html>"
},
{
"code": null,
"e": 4556,
"s": 4340,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 4638,
"s": 4556,
"text": "Enter any invalid value and press Submit button. See the following error message."
},
{
"code": null,
"e": 4711,
"s": 4638,
"text": "Enter any valid value and press Submit button. See the following result."
},
{
"code": null,
"e": 4746,
"s": 4711,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4761,
"s": 4746,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 4768,
"s": 4761,
"text": " Print"
},
{
"code": null,
"e": 4779,
"s": 4768,
"text": " Add Notes"
}
] |
Program to find absolute value of a given number - GeeksforGeeks
|
14 Jun, 2021
Given an integer N, the task is to find the absolute value of the given integer.Examples:
Input: N = -6 Output: 6Input: N = 12 Output: 12
Method 1 – Naive Approach: Since the absolute value of any number is always positive. For any positive number, the absolute value is the number itself and for any negative number, the absolute value is (-1) multiplied by the negative number.
C++
C
Java
Python3
C#
Javascript
// C++ program for Method 1#include <bits/stdc++.h>using namespace std; // Function to find the absolute valuevoid findAbsolute(int N){ // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value cout << " " << N;} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;} // This code is contributed by shivanisinghss2110
// C program for Method 1#include <stdio.h> // Function to find the absolute valuevoid findAbsolute(int N){ // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value printf("%d ", N);} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;}
// Java program for Method 1class GFG{ // Function to find the absolute valuestatic void findAbsolute(int N){ // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value System.out.printf("%d ", N);} // Driver Codepublic static void main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by 29AjayKumar
# Python3 program for Method 1 # Function to find the absolute valuedef findAbsolute(N): # If the number is less than # zero, then multiply by (-1) if (N < 0): N = (-1) * N; # Print the absolute value print(N); # Driver codeif __name__ == '__main__': # Given integer N = -12; # Function call findAbsolute(N); # This is code contributed by amal kumar choubey
// C# program for Method 1using System;using System.Collections.Generic; class GFG{ // Function to find the absolute valuestatic void findAbsolute(int N){ // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value Console.Write("{0} ", N);} // Driver Codepublic static void Main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by sapnasingh4991
<script> // Javascript program for Method 1 // Function to find the absolute value function findAbsolute(N) { // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value document.write(" " + N); } // Given integer let N = -12; // Function call findAbsolute(N); // This code is contributed by suresh07.</script>
12
Method 2 – Using Bitmasking: Since negative numbers are stored in 2s complement form, to get the absolute value, we have to toggle bits of the number and add 1 to the result. Below are the steps:
Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
mask = n >> 31
For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number.
For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number.
mask + n
XOR of mask +n and mask gives the absolute value.
XOR of mask +n and mask gives the absolute value.
(mask + n)^mask
C++
C
Java
Python3
C#
Javascript
// C++ program for Method 2#include <bits/stdc++.h>using namespace std;#define CHAR_BIT 8 // Function to find the absolute// valuevoid findAbsolute(int N){ // Find mask int mask = N >> (sizeof(int) * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask cout << ((mask + N) ^ mask);} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;} // This code is contributed by Code_Mech
// C program for Method 2#include <stdio.h>#define CHAR_BIT 8 // Function to find the absolute// valuevoid findAbsolute(int N){ // Find mask int mask = N >> (sizeof(int) * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask printf("%d ", (mask + N) ^ mask);} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;}
// Java program for Method 2class GFG{ static final int CHAR_BIT = 8; // Function to find the absolute valuestatic void findAbsolute(int N){ // Find mask int mask = N >> (Integer.SIZE / 8 * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask System.out.printf("%d ", (mask + N) ^ mask);} // Driver Codepublic static void main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by 29AjayKumar
# Python3 program for Method 2import sys CHAR_BIT = 8; # Function to find the absolute valuedef findAbsolute(N): # Find mask mask = N >> (sys.getsizeof(int()) // 8 * CHAR_BIT - 1); # Print the absolute value # by (mask + N)^mask print((mask + N) ^ mask); # Driver Codeif __name__ == '__main__': # Given integer N = -12; # Function call findAbsolute(N); # This code is contributed by 29AjayKumar
// C# program for Method 2using System; class GFG{ static readonly int CHAR_BIT = 8; // Function to find the absolute valuestatic void findAbsolute(int N){ // Find mask int mask = N >> (sizeof(int) / 8 * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask Console.Write((mask + N) ^ mask);} // Driver Codepublic static void Main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by 29AjayKumar
<script> // Javascript program for Method 2 let CHAR_BIT = 8; // Function to find the absolute value function findAbsolute(N) { // Find mask let mask = N >> (4 / 8 * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask document.write((mask + N) ^ mask); } // Given integer let N = -12; // Function call findAbsolute(N); // This code is contributed by mukesh07.</script>
12
Method 3 – Using inbuilt abs() function: The inbuilt function abs() in stdlib.h library finds the absolute value of any number.Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program for Method 3# include<bits/stdc++.h>using namespace std; // Function to find the absolute// valuevoid findAbsolute(int N){ // Find absolute int X = abs(N); // Print the absolute value cout << X;} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;} // This code is contributed by Nidhi_biet
// C program for Method 3 #include <stdio.h>#include <stdlib.h> // Function to find the absolute// valuevoid findAbsolute(int N){ // Find absolute int X = abs(N); // Print the absolute value printf("%d ", X);} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;}
// Java program for Method 3class GFG{ // Function to find the absolute// valuestatic void findAbsolute(int N){ // Find absolute int X = Math.abs(N); // Print the absolute value System.out.printf("%d", X);} // Driver Codepublic static void main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by sapnasingh4991
# Python3 program for Method 3import math # Function to find the absolute# valuedef findAbsolute(N): # Find absolute X = abs(N); # Print the absolute value print(X); # Driver Code # Given integerN = -12; # Function callfindAbsolute(N); # This code is contributed by Nidhi_biet
// C# program for Method 3using System; class GFG{ // Function to find the absolute// valuestatic void findAbsolute(int N){ // Find absolute int X = Math.Abs(N); // Print the absolute value Console.Write("{0}", X);} // Driver Codepublic static void Main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by 29AjayKumar
<script> // Javascript program for Method 3 // Function to find the absolute // value function findAbsolute(N) { // Find absolute let X = Math.abs(N); // Print the absolute value document.write(X); } // Given integer let N = -12; // Function call findAbsolute(N); </script>
12
sapnasingh4991
29AjayKumar
Amal Kumar Choubey
shivanisinghss2110
nidhi_biet
Code_Mech
divyeshrabadiya07
suresh07
mukesh07
Numbers
C Programs
C# Programs
C++ Programs
Java Programs
Mathematical
School Programming
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
Program to print ASCII Value of a character
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
|
[
{
"code": null,
"e": 25489,
"s": 25461,
"text": "\n14 Jun, 2021"
},
{
"code": null,
"e": 25581,
"s": 25489,
"text": "Given an integer N, the task is to find the absolute value of the given integer.Examples: "
},
{
"code": null,
"e": 25631,
"s": 25581,
"text": "Input: N = -6 Output: 6Input: N = 12 Output: 12 "
},
{
"code": null,
"e": 25877,
"s": 25633,
"text": "Method 1 – Naive Approach: Since the absolute value of any number is always positive. For any positive number, the absolute value is the number itself and for any negative number, the absolute value is (-1) multiplied by the negative number. "
},
{
"code": null,
"e": 25881,
"s": 25877,
"text": "C++"
},
{
"code": null,
"e": 25883,
"s": 25881,
"text": "C"
},
{
"code": null,
"e": 25888,
"s": 25883,
"text": "Java"
},
{
"code": null,
"e": 25896,
"s": 25888,
"text": "Python3"
},
{
"code": null,
"e": 25899,
"s": 25896,
"text": "C#"
},
{
"code": null,
"e": 25910,
"s": 25899,
"text": "Javascript"
},
{
"code": "// C++ program for Method 1#include <bits/stdc++.h>using namespace std; // Function to find the absolute valuevoid findAbsolute(int N){ // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value cout << \" \" << N;} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;} // This code is contributed by shivanisinghss2110",
"e": 26381,
"s": 25910,
"text": null
},
{
"code": "// C program for Method 1#include <stdio.h> // Function to find the absolute valuevoid findAbsolute(int N){ // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value printf(\"%d \", N);} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;}",
"e": 26771,
"s": 26381,
"text": null
},
{
"code": "// Java program for Method 1class GFG{ // Function to find the absolute valuestatic void findAbsolute(int N){ // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value System.out.printf(\"%d \", N);} // Driver Codepublic static void main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by 29AjayKumar",
"e": 27240,
"s": 26771,
"text": null
},
{
"code": "# Python3 program for Method 1 # Function to find the absolute valuedef findAbsolute(N): # If the number is less than # zero, then multiply by (-1) if (N < 0): N = (-1) * N; # Print the absolute value print(N); # Driver codeif __name__ == '__main__': # Given integer N = -12; # Function call findAbsolute(N); # This is code contributed by amal kumar choubey",
"e": 27640,
"s": 27240,
"text": null
},
{
"code": "// C# program for Method 1using System;using System.Collections.Generic; class GFG{ // Function to find the absolute valuestatic void findAbsolute(int N){ // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value Console.Write(\"{0} \", N);} // Driver Codepublic static void Main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by sapnasingh4991",
"e": 28154,
"s": 27640,
"text": null
},
{
"code": "<script> // Javascript program for Method 1 // Function to find the absolute value function findAbsolute(N) { // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value document.write(\" \" + N); } // Given integer let N = -12; // Function call findAbsolute(N); // This code is contributed by suresh07.</script>",
"e": 28635,
"s": 28154,
"text": null
},
{
"code": null,
"e": 28638,
"s": 28635,
"text": "12"
},
{
"code": null,
"e": 28838,
"s": 28640,
"text": "Method 2 – Using Bitmasking: Since negative numbers are stored in 2s complement form, to get the absolute value, we have to toggle bits of the number and add 1 to the result. Below are the steps: "
},
{
"code": null,
"e": 28931,
"s": 28838,
"text": "Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits). "
},
{
"code": null,
"e": 29024,
"s": 28931,
"text": "Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits). "
},
{
"code": null,
"e": 29039,
"s": 29024,
"text": "mask = n >> 31"
},
{
"code": null,
"e": 29180,
"s": 29039,
"text": " For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number. "
},
{
"code": null,
"e": 29322,
"s": 29182,
"text": "For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number. "
},
{
"code": null,
"e": 29331,
"s": 29322,
"text": "mask + n"
},
{
"code": null,
"e": 29384,
"s": 29331,
"text": " XOR of mask +n and mask gives the absolute value. "
},
{
"code": null,
"e": 29438,
"s": 29386,
"text": "XOR of mask +n and mask gives the absolute value. "
},
{
"code": null,
"e": 29455,
"s": 29438,
"text": "(mask + n)^mask "
},
{
"code": null,
"e": 29465,
"s": 29461,
"text": "C++"
},
{
"code": null,
"e": 29467,
"s": 29465,
"text": "C"
},
{
"code": null,
"e": 29472,
"s": 29467,
"text": "Java"
},
{
"code": null,
"e": 29480,
"s": 29472,
"text": "Python3"
},
{
"code": null,
"e": 29483,
"s": 29480,
"text": "C#"
},
{
"code": null,
"e": 29494,
"s": 29483,
"text": "Javascript"
},
{
"code": "// C++ program for Method 2#include <bits/stdc++.h>using namespace std;#define CHAR_BIT 8 // Function to find the absolute// valuevoid findAbsolute(int N){ // Find mask int mask = N >> (sizeof(int) * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask cout << ((mask + N) ^ mask);} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;} // This code is contributed by Code_Mech",
"e": 29965,
"s": 29494,
"text": null
},
{
"code": "// C program for Method 2#include <stdio.h>#define CHAR_BIT 8 // Function to find the absolute// valuevoid findAbsolute(int N){ // Find mask int mask = N >> (sizeof(int) * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask printf(\"%d \", (mask + N) ^ mask);} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;}",
"e": 30388,
"s": 29965,
"text": null
},
{
"code": "// Java program for Method 2class GFG{ static final int CHAR_BIT = 8; // Function to find the absolute valuestatic void findAbsolute(int N){ // Find mask int mask = N >> (Integer.SIZE / 8 * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask System.out.printf(\"%d \", (mask + N) ^ mask);} // Driver Codepublic static void main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by 29AjayKumar",
"e": 30911,
"s": 30388,
"text": null
},
{
"code": "# Python3 program for Method 2import sys CHAR_BIT = 8; # Function to find the absolute valuedef findAbsolute(N): # Find mask mask = N >> (sys.getsizeof(int()) // 8 * CHAR_BIT - 1); # Print the absolute value # by (mask + N)^mask print((mask + N) ^ mask); # Driver Codeif __name__ == '__main__': # Given integer N = -12; # Function call findAbsolute(N); # This code is contributed by 29AjayKumar",
"e": 31374,
"s": 30911,
"text": null
},
{
"code": "// C# program for Method 2using System; class GFG{ static readonly int CHAR_BIT = 8; // Function to find the absolute valuestatic void findAbsolute(int N){ // Find mask int mask = N >> (sizeof(int) / 8 * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask Console.Write((mask + N) ^ mask);} // Driver Codepublic static void Main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by 29AjayKumar",
"e": 31903,
"s": 31374,
"text": null
},
{
"code": "<script> // Javascript program for Method 2 let CHAR_BIT = 8; // Function to find the absolute value function findAbsolute(N) { // Find mask let mask = N >> (4 / 8 * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask document.write((mask + N) ^ mask); } // Given integer let N = -12; // Function call findAbsolute(N); // This code is contributed by mukesh07.</script>",
"e": 32366,
"s": 31903,
"text": null
},
{
"code": null,
"e": 32369,
"s": 32366,
"text": "12"
},
{
"code": null,
"e": 32551,
"s": 32371,
"text": "Method 3 – Using inbuilt abs() function: The inbuilt function abs() in stdlib.h library finds the absolute value of any number.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 32555,
"s": 32551,
"text": "C++"
},
{
"code": null,
"e": 32557,
"s": 32555,
"text": "C"
},
{
"code": null,
"e": 32562,
"s": 32557,
"text": "Java"
},
{
"code": null,
"e": 32570,
"s": 32562,
"text": "Python3"
},
{
"code": null,
"e": 32573,
"s": 32570,
"text": "C#"
},
{
"code": null,
"e": 32584,
"s": 32573,
"text": "Javascript"
},
{
"code": "// C++ program for Method 3# include<bits/stdc++.h>using namespace std; // Function to find the absolute// valuevoid findAbsolute(int N){ // Find absolute int X = abs(N); // Print the absolute value cout << X;} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;} // This code is contributed by Nidhi_biet",
"e": 32969,
"s": 32584,
"text": null
},
{
"code": "// C program for Method 3 #include <stdio.h>#include <stdlib.h> // Function to find the absolute// valuevoid findAbsolute(int N){ // Find absolute int X = abs(N); // Print the absolute value printf(\"%d \", X);} // Driver Codeint main(){ // Given integer int N = -12; // Function call findAbsolute(N); return 0;}",
"e": 33311,
"s": 32969,
"text": null
},
{
"code": "// Java program for Method 3class GFG{ // Function to find the absolute// valuestatic void findAbsolute(int N){ // Find absolute int X = Math.abs(N); // Print the absolute value System.out.printf(\"%d\", X);} // Driver Codepublic static void main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by sapnasingh4991",
"e": 33716,
"s": 33311,
"text": null
},
{
"code": "# Python3 program for Method 3import math # Function to find the absolute# valuedef findAbsolute(N): # Find absolute X = abs(N); # Print the absolute value print(X); # Driver Code # Given integerN = -12; # Function callfindAbsolute(N); # This code is contributed by Nidhi_biet",
"e": 34007,
"s": 33716,
"text": null
},
{
"code": "// C# program for Method 3using System; class GFG{ // Function to find the absolute// valuestatic void findAbsolute(int N){ // Find absolute int X = Math.Abs(N); // Print the absolute value Console.Write(\"{0}\", X);} // Driver Codepublic static void Main(String[] args){ // Given integer int N = -12; // Function call findAbsolute(N);}} // This code is contributed by 29AjayKumar",
"e": 34418,
"s": 34007,
"text": null
},
{
"code": "<script> // Javascript program for Method 3 // Function to find the absolute // value function findAbsolute(N) { // Find absolute let X = Math.abs(N); // Print the absolute value document.write(X); } // Given integer let N = -12; // Function call findAbsolute(N); </script>",
"e": 34764,
"s": 34418,
"text": null
},
{
"code": null,
"e": 34767,
"s": 34764,
"text": "12"
},
{
"code": null,
"e": 34784,
"s": 34769,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 34796,
"s": 34784,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34815,
"s": 34796,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 34834,
"s": 34815,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 34845,
"s": 34834,
"text": "nidhi_biet"
},
{
"code": null,
"e": 34855,
"s": 34845,
"text": "Code_Mech"
},
{
"code": null,
"e": 34873,
"s": 34855,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 34882,
"s": 34873,
"text": "suresh07"
},
{
"code": null,
"e": 34891,
"s": 34882,
"text": "mukesh07"
},
{
"code": null,
"e": 34899,
"s": 34891,
"text": "Numbers"
},
{
"code": null,
"e": 34910,
"s": 34899,
"text": "C Programs"
},
{
"code": null,
"e": 34922,
"s": 34910,
"text": "C# Programs"
},
{
"code": null,
"e": 34935,
"s": 34922,
"text": "C++ Programs"
},
{
"code": null,
"e": 34949,
"s": 34935,
"text": "Java Programs"
},
{
"code": null,
"e": 34962,
"s": 34949,
"text": "Mathematical"
},
{
"code": null,
"e": 34981,
"s": 34962,
"text": "School Programming"
},
{
"code": null,
"e": 34994,
"s": 34981,
"text": "Mathematical"
},
{
"code": null,
"e": 35002,
"s": 34994,
"text": "Numbers"
},
{
"code": null,
"e": 35100,
"s": 35002,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35141,
"s": 35100,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 35176,
"s": 35141,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 35235,
"s": 35176,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 35278,
"s": 35235,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 35322,
"s": 35278,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 35362,
"s": 35322,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 35387,
"s": 35362,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 35421,
"s": 35387,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 35467,
"s": 35421,
"text": "Getting a Month Name Using Month Number in C#"
}
] |
Data Types in C - GeeksforGeeks
|
28 Jun, 2021
Each variable in C has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Let us briefly describe them one by one:Following are the examples of some very common data types used in C:
char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.
int: As the name suggests, an int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with single precision.
double: It is used to store decimal numbers (numbers with floating point value) with double precision.
Different data types also have different ranges upto which they can store numbers. These ranges may vary from compiler to compiler. Below is list of ranges along with the memory requirement and format specifiers on 32 bit gcc compiler.
We can use the sizeof() operator to check the size of a variable. See the following C program for the usage of the various data types:
C
#include <stdio.h>int main(){ int a = 1; char b = 'G'; double c = 3.14; printf("Hello World!\n"); // printing the variables defined // above along with their sizes printf("Hello! I am a character. My value is %c and " "my size is %lu byte.\n", b, sizeof(char)); // can use sizeof(b) above as well printf("Hello! I am an integer. My value is %d and " "my size is %lu bytes.\n", a, sizeof(int)); // can use sizeof(a) above as well printf("Hello! I am a double floating point variable." " My value is %lf and my size is %lu bytes.\n", c, sizeof(double)); // can use sizeof(c) above as well printf("Bye! See you soon. :)\n"); return 0;}
Output:
Hello World!
Hello! I am a character. My value is G and my size is 1 byte.
Hello! I am an integer. My value is 1 and my size is 4 bytes.
Hello! I am a double floating point variable. My value is 3.140000 and my size i
s 8 bytes.
Bye! See you soon. :)
Srichandrahaas
pantpawan
C Basics
C-Data Types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Core Dump (Segmentation fault) in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Structures in C
|
[
{
"code": null,
"e": 24053,
"s": 24025,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24327,
"s": 24053,
"text": "Each variable in C has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Let us briefly describe them one by one:Following are the examples of some very common data types used in C:"
},
{
"code": null,
"e": 24455,
"s": 24327,
"text": "char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers."
},
{
"code": null,
"e": 24527,
"s": 24455,
"text": "int: As the name suggests, an int variable is used to store an integer."
},
{
"code": null,
"e": 24629,
"s": 24527,
"text": "float: It is used to store decimal numbers (numbers with floating point value) with single precision."
},
{
"code": null,
"e": 24733,
"s": 24629,
"text": "double: It is used to store decimal numbers (numbers with floating point value) with double precision. "
},
{
"code": null,
"e": 24970,
"s": 24733,
"text": "Different data types also have different ranges upto which they can store numbers. These ranges may vary from compiler to compiler. Below is list of ranges along with the memory requirement and format specifiers on 32 bit gcc compiler. "
},
{
"code": null,
"e": 25106,
"s": 24970,
"text": "We can use the sizeof() operator to check the size of a variable. See the following C program for the usage of the various data types: "
},
{
"code": null,
"e": 25108,
"s": 25106,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ int a = 1; char b = 'G'; double c = 3.14; printf(\"Hello World!\\n\"); // printing the variables defined // above along with their sizes printf(\"Hello! I am a character. My value is %c and \" \"my size is %lu byte.\\n\", b, sizeof(char)); // can use sizeof(b) above as well printf(\"Hello! I am an integer. My value is %d and \" \"my size is %lu bytes.\\n\", a, sizeof(int)); // can use sizeof(a) above as well printf(\"Hello! I am a double floating point variable.\" \" My value is %lf and my size is %lu bytes.\\n\", c, sizeof(double)); // can use sizeof(c) above as well printf(\"Bye! See you soon. :)\\n\"); return 0;}",
"e": 25849,
"s": 25108,
"text": null
},
{
"code": null,
"e": 25858,
"s": 25849,
"text": "Output: "
},
{
"code": null,
"e": 26111,
"s": 25858,
"text": "Hello World!\nHello! I am a character. My value is G and my size is 1 byte.\nHello! I am an integer. My value is 1 and my size is 4 bytes.\nHello! I am a double floating point variable. My value is 3.140000 and my size i\ns 8 bytes.\nBye! See you soon. :)\n"
},
{
"code": null,
"e": 26128,
"s": 26113,
"text": "Srichandrahaas"
},
{
"code": null,
"e": 26138,
"s": 26128,
"text": "pantpawan"
},
{
"code": null,
"e": 26147,
"s": 26138,
"text": "C Basics"
},
{
"code": null,
"e": 26160,
"s": 26147,
"text": "C-Data Types"
},
{
"code": null,
"e": 26171,
"s": 26160,
"text": "C Language"
},
{
"code": null,
"e": 26269,
"s": 26171,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26278,
"s": 26269,
"text": "Comments"
},
{
"code": null,
"e": 26291,
"s": 26278,
"text": "Old Comments"
},
{
"code": null,
"e": 26319,
"s": 26291,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26365,
"s": 26319,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26377,
"s": 26365,
"text": "fork() in C"
},
{
"code": null,
"e": 26409,
"s": 26377,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26449,
"s": 26409,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 26466,
"s": 26449,
"text": "Substring in C++"
},
{
"code": null,
"e": 26488,
"s": 26466,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 26535,
"s": 26488,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 26573,
"s": 26535,
"text": "TCP Server-Client implementation in C"
}
] |
Treating Most Common Data Uniformity Problems with Pandas | Towards Data Science
|
In my previous articles on data cleaning, I talked about how out-of-range values, incorrect data types, uniqueness constraints are common problems and that when left untouched can seriously compromise our analysis.
In this article, we are going to tackle a problem that is just as dangerous and that can similarly skew our analysis which is unit uniformity.
Problems related to uniformity can come in many shapes:
temperature data in both Fahrenheit and Celsius
weight given in both kilograms and pounds
multiple date formats
money represented in different currencies
Such problems arise because of many reasons. For example, data is collected across many locations and merged together into one. This can result in the above problems. It is imperative that you know how to handle uniformity problems for accurate analysis.
people.head()
The notebook and data using in this article can be found on this Kaggle Notebook or on this GitHub repo.
Consider this temperature dataset imported earlier. It gives information about daily average temperatures for 3 months in Celsius:
temperatures.sample(10)
If we look at index 48, unless a major climate event occurred, we can guess that values are given in Fahrenheit:
When you are in such situations, use a scatter plot to spot them visually:
A scatter plot clearly shows the values which are Fahrenheit. A quick Google search shows us the formula for converting Fahrenheit to Celsius:
Now, we will use this equation to convert any values over 40 to Celsius:
We can check that the conversion is successful in 2 ways. First, with assert statement:
Again using a scatter plot:
Even though this was a simple example, your case may be completely different. Sometimes, you might not even notice the inconsistencies in the sea of data. Before looking for them, it is essential that you completely understand your data and learn how it was collected.
One other very common problem is date uniformity. Different countries have different standard DateTime formats and when you have data from multiple sources, you are going to have to deal with multiple date formats. In Python, there are 3 main DateTime formats you can work with:
25–12–2019 -> (%d-%m-%Y) -> day, month, year
October 31, 2020 -> (%c) -> literal dates
12–25–2019 -> (%m-%d-%Y) -> month, day, year
When you load data into your environment with pandas, it always imports dates as object data type. In the Setup section, we imported sample data containing people's full name and birthday:
people.sample(5)
The birthday column represents the dates as YY-MM-DD format but as strings. Converting date columns to datetime has a number of advantages to perform analysis on. We will use pd.to_datetime() function to convert the column into datetime:
We got an error! If we look closer, the error says that month must be in 1, 2, ..., 12. That means, somewhere in the data, there is an inconsistent value(s) that is preventing the function to run. pd.to_datetime has a good workaround for such cases:
This time, we did not get any errors. If you set infer_datetime_format to True, pandas will automatically identify the date format based on the first non-NaN element and converts the rest to that format. If there are any values that do not fit the conversion, errors parameter decides what to do with them. If set to coerce, pandas will put NaTs which are missing values for dates.
Based on our assumptions, the above line of code should have spotted date inconsistencies and put NaTs to inconsistent dates:
There are a few methods to handle such inconsistencies:
convert to NA and treat accordingly
infer format by looking at the data source, how it was collected
infer format by looking at other dates
If you have many inconsistencies, converting them to NaN is not always an option. You should try to come up with custom solutions by looking at their patterns and inferring their formats.
After you are done with error-handling and conversions, it is best practice to convert date columns to global DateTime standard:
Read more articles related to the topic:
|
[
{
"code": null,
"e": 387,
"s": 172,
"text": "In my previous articles on data cleaning, I talked about how out-of-range values, incorrect data types, uniqueness constraints are common problems and that when left untouched can seriously compromise our analysis."
},
{
"code": null,
"e": 530,
"s": 387,
"text": "In this article, we are going to tackle a problem that is just as dangerous and that can similarly skew our analysis which is unit uniformity."
},
{
"code": null,
"e": 586,
"s": 530,
"text": "Problems related to uniformity can come in many shapes:"
},
{
"code": null,
"e": 634,
"s": 586,
"text": "temperature data in both Fahrenheit and Celsius"
},
{
"code": null,
"e": 676,
"s": 634,
"text": "weight given in both kilograms and pounds"
},
{
"code": null,
"e": 698,
"s": 676,
"text": "multiple date formats"
},
{
"code": null,
"e": 740,
"s": 698,
"text": "money represented in different currencies"
},
{
"code": null,
"e": 995,
"s": 740,
"text": "Such problems arise because of many reasons. For example, data is collected across many locations and merged together into one. This can result in the above problems. It is imperative that you know how to handle uniformity problems for accurate analysis."
},
{
"code": null,
"e": 1009,
"s": 995,
"text": "people.head()"
},
{
"code": null,
"e": 1114,
"s": 1009,
"text": "The notebook and data using in this article can be found on this Kaggle Notebook or on this GitHub repo."
},
{
"code": null,
"e": 1245,
"s": 1114,
"text": "Consider this temperature dataset imported earlier. It gives information about daily average temperatures for 3 months in Celsius:"
},
{
"code": null,
"e": 1269,
"s": 1245,
"text": "temperatures.sample(10)"
},
{
"code": null,
"e": 1382,
"s": 1269,
"text": "If we look at index 48, unless a major climate event occurred, we can guess that values are given in Fahrenheit:"
},
{
"code": null,
"e": 1457,
"s": 1382,
"text": "When you are in such situations, use a scatter plot to spot them visually:"
},
{
"code": null,
"e": 1600,
"s": 1457,
"text": "A scatter plot clearly shows the values which are Fahrenheit. A quick Google search shows us the formula for converting Fahrenheit to Celsius:"
},
{
"code": null,
"e": 1673,
"s": 1600,
"text": "Now, we will use this equation to convert any values over 40 to Celsius:"
},
{
"code": null,
"e": 1761,
"s": 1673,
"text": "We can check that the conversion is successful in 2 ways. First, with assert statement:"
},
{
"code": null,
"e": 1789,
"s": 1761,
"text": "Again using a scatter plot:"
},
{
"code": null,
"e": 2058,
"s": 1789,
"text": "Even though this was a simple example, your case may be completely different. Sometimes, you might not even notice the inconsistencies in the sea of data. Before looking for them, it is essential that you completely understand your data and learn how it was collected."
},
{
"code": null,
"e": 2337,
"s": 2058,
"text": "One other very common problem is date uniformity. Different countries have different standard DateTime formats and when you have data from multiple sources, you are going to have to deal with multiple date formats. In Python, there are 3 main DateTime formats you can work with:"
},
{
"code": null,
"e": 2382,
"s": 2337,
"text": "25–12–2019 -> (%d-%m-%Y) -> day, month, year"
},
{
"code": null,
"e": 2424,
"s": 2382,
"text": "October 31, 2020 -> (%c) -> literal dates"
},
{
"code": null,
"e": 2469,
"s": 2424,
"text": "12–25–2019 -> (%m-%d-%Y) -> month, day, year"
},
{
"code": null,
"e": 2658,
"s": 2469,
"text": "When you load data into your environment with pandas, it always imports dates as object data type. In the Setup section, we imported sample data containing people's full name and birthday:"
},
{
"code": null,
"e": 2675,
"s": 2658,
"text": "people.sample(5)"
},
{
"code": null,
"e": 2913,
"s": 2675,
"text": "The birthday column represents the dates as YY-MM-DD format but as strings. Converting date columns to datetime has a number of advantages to perform analysis on. We will use pd.to_datetime() function to convert the column into datetime:"
},
{
"code": null,
"e": 3163,
"s": 2913,
"text": "We got an error! If we look closer, the error says that month must be in 1, 2, ..., 12. That means, somewhere in the data, there is an inconsistent value(s) that is preventing the function to run. pd.to_datetime has a good workaround for such cases:"
},
{
"code": null,
"e": 3545,
"s": 3163,
"text": "This time, we did not get any errors. If you set infer_datetime_format to True, pandas will automatically identify the date format based on the first non-NaN element and converts the rest to that format. If there are any values that do not fit the conversion, errors parameter decides what to do with them. If set to coerce, pandas will put NaTs which are missing values for dates."
},
{
"code": null,
"e": 3671,
"s": 3545,
"text": "Based on our assumptions, the above line of code should have spotted date inconsistencies and put NaTs to inconsistent dates:"
},
{
"code": null,
"e": 3727,
"s": 3671,
"text": "There are a few methods to handle such inconsistencies:"
},
{
"code": null,
"e": 3763,
"s": 3727,
"text": "convert to NA and treat accordingly"
},
{
"code": null,
"e": 3828,
"s": 3763,
"text": "infer format by looking at the data source, how it was collected"
},
{
"code": null,
"e": 3867,
"s": 3828,
"text": "infer format by looking at other dates"
},
{
"code": null,
"e": 4055,
"s": 3867,
"text": "If you have many inconsistencies, converting them to NaN is not always an option. You should try to come up with custom solutions by looking at their patterns and inferring their formats."
},
{
"code": null,
"e": 4184,
"s": 4055,
"text": "After you are done with error-handling and conversions, it is best practice to convert date columns to global DateTime standard:"
}
] |
5 Interesting Jupyter Interactive Visualization Extensions | by Cornellius Yudha Wijaya | Towards Data Science
|
Visualization is an important part of data analysis. Without visualization, we would have a hard time summarizing the information from our data. However, there are times we want to have a dynamic visualization to ease our analysis activity.
Luckily, Jupyter Notebook has many visualization extensions we could use to create an interactive visualization from your Notebook. What are these extensions, and how can you use them? Let’s explore five interesting Jupyter Interactive Visualization Extensions.
The Jupyter extensions ipywidgets is an interactive HTML Jupyter widgets notebook. The package lets you create a widget to control your data via interactive GUI such as slider, checkboxes, text field, and many more. It is pretty helpful if we want to create a GUI-based visualization on Jupyter Notebook manually.
To start, we need to install the extensions package first.
pip install ipywidgets
Using ipywidgets, we could customize the Jupyter Notebook widget. Let’s explore the basic widgets available.
from ipywidgets import interact#Basic ipywidgets interact would generate UI from the functiondef f(x): return x
The ipywidgets extensions interact with the base to generate UI from the function. The generated UI would depend on the data type we are passed. Let’s try to pass integer data.
interact(f, x=10)
Passing integer values would return slider UI. Next, let’s use the Boolean data.
interact(f, x=True)
The Boolean value would return the checkbox. Finally, let’s use string value.
interact(f, x='hi')
All the UI was great, but how to apply it to the visualization? We need to create our function to return all the interactive visualization. Let’s use the Seaborn package to combine it with ipywidgets.
import seaborn as snsimport matplotlib.pyplot as pltmpg = sns.load_dataset('mpg')def f(x): img = sns.countplot(mpg[mpg['mpg']<x]['origin']) plt.title('Origin Countplot mpg = {}'.format(x)) return img
When we move the slide bar, we will execute the function to return the count plot of the ‘origin’ when we filter it with the slider ipywidget. If you want to read more about what ipywidgets could do, you can read it all here.
Pandas-Profiling is an exploratory package that produces interactive HTML reports on our Jupyter Notebook. The basic report from Pandas-Profiling is shown in the GIF below.
As we can see from the GIF, the report produced is an interactive HTML report within your Jupyter Notebook. How do you generate this? Let’s try it out with sample data.
First, we need to install the Pandas-Profiling package.
#Installing via pippip install -U pandas-profiling[notebook]#Enable the widget extension in Jupyterjupyter nbextension enable --py widgetsnbextension#or if you prefer via Condaconda env create -n pandas-profilingconda activate pandas-profilingconda install -c conda-forge pandas-profiling#or if you prefer installing directly from the sourcepip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip#in any case, if the code raise an error, it probably need permission from user. To do that, add --user in the end of the line.
After installing the package, we are ready to generate the report. Let’s use the mpg sample data we had previously.
#Importing the functionfrom pandas_profiling import ProfileReport#Generate the report. We would use the mpg dataset as sample, title parameter for naming our report, and explorative parameter set to True for Deeper exploration.profile = ProfileReport(mpg, title='MPG Pandas Profiling Report', explorative = True)profile
After some time, the report would show up, and you would explore the HTML.
The report selection is shown in the image above. You could try out all the options to explore the data. If you want to dig the package deeper, you can read my previous articles below.
towardsdatascience.com
towardsdatascience.com
Jupyter-Matplotlib or ipympl is a Jupyter Notebook extension to enable interactive Matplotlib visualization exploration within your Jupyter Notebook.
The exploration is simple yet powerful if we need a quick visualization with matplotlib. Let’s try to install the package first.
pip install ipympl
When you finish installing the package, you need to enable the ipympl extension in your Jupyter Notebook by using the following magic command: %matplotlib widget .
Let’s try the matplotlib extension with sample data.
%matplotlib widgetimport matplotlib.pyplot as pltimport numpy as npfig = plt.figure()plt.plot(np.sin(np.linspace(0, 20, 100)));
As you can see in the image above, our matplotlib visualization becomes an interactive visualization where you can pan and zoom within the plot.
We can pass another kind of matplotlib plot with our dataset. Let’s try it with our previous mpg dataset.
fig = plt.figure()plt.scatter(mpg['mpg'], mpg['horsepower'])
As long as the visualization is based on the matplotlib package, we could pass the interactive widget within the plot. That is why it would work with another kind of matplotlib visualization.
You could implement other widgets using ipympl that are similar to the ipywidgets; however, I feel the ipywidgets package has covered many of the functions. If you are interested in the ipympl widgets, you could explore the example.
If you want to have an interactive Pandas dataframe table, you might want to install itables package extensions. This package would allow you to have a simple exploration capability in the data frame.
How do you enable this extension? Let’s install the package first.
pip install itables
When you have finished installing the package, you only need to run the following code.
from itables import init_notebook_modeinit_notebook_mode(all_interactive=True)
Your data frame would automatically have interactive extensions similar to the GIF above. If you want to display only one series or data frame, you could use the following code.
from itables import showshow(mpg[['mpg', 'name']])
Do you want to have an interactive canvas you could play on your Jupyter Notebook? If so, then you should try the ipycanvas package extension. These extensions allow you to create a drawable canvas within your Jupyter Notebook with drawing style. Let’s install the package first.
pip install ipycanvas orjson
After installing the package, let’s try to initiate a hand-drawing canvas from the notebook example.
from ipywidgets import Image,ColorPicker, IntSlider, link, AppLayout, HBox, RoughCanvas, hold_canvaswidth = 800height = 800canvas = RoughCanvas(width=width, height=height)drawing = Falseposition = Noneshape = []def on_mouse_down(x, y): global drawing global position global shapedrawing = True position = (x, y) shape = [position]def on_mouse_move(x, y): global drawing global position global shapeif not drawing: returnwith hold_canvas(canvas): canvas.stroke_line(position[0], position[1], x, y)position = (x, y)shape.append(position)def on_mouse_up(x, y): global drawing global position global shapedrawing = False with hold_canvas(canvas): canvas.stroke_line(position[0], position[1], x, y) canvas.fill_polygon(shape)shape = []canvas.on_mouse_down(on_mouse_down)canvas.on_mouse_move(on_mouse_move)canvas.on_mouse_up(on_mouse_up)canvas.stroke_style = '#749cb8'picker = ColorPicker(description='Color:', value='#749cb8')link((picker, 'value'), (canvas, 'stroke_style'))link((picker, 'value'), (canvas, 'fill_style'))HBox((canvas, picker))
In the image above I am playing around with the Canvas I have created with the above code. You could try to click the canvas and draw something interesting.
If you still want to look at what ipycanvas could do, you can read the whole documentation here.
Jupyter Notebook is one of the most used IDE by data scientists for the versatility it offers. Activity such as data visualization is often done in the Notebook as well. To help with this activity, I am outlining five interesting Jupyter extensions interactive visualization. They are:
ipywidgetspandas-profilingipymplitablesipycanvas
ipywidgets
pandas-profiling
ipympl
itables
ipycanvas
I hope it helps!
Visit me on my LinkedIn or Twitter.
If you are not subscribed as a Medium Member, please consider subscribing through my referral.
|
[
{
"code": null,
"e": 413,
"s": 172,
"text": "Visualization is an important part of data analysis. Without visualization, we would have a hard time summarizing the information from our data. However, there are times we want to have a dynamic visualization to ease our analysis activity."
},
{
"code": null,
"e": 675,
"s": 413,
"text": "Luckily, Jupyter Notebook has many visualization extensions we could use to create an interactive visualization from your Notebook. What are these extensions, and how can you use them? Let’s explore five interesting Jupyter Interactive Visualization Extensions."
},
{
"code": null,
"e": 989,
"s": 675,
"text": "The Jupyter extensions ipywidgets is an interactive HTML Jupyter widgets notebook. The package lets you create a widget to control your data via interactive GUI such as slider, checkboxes, text field, and many more. It is pretty helpful if we want to create a GUI-based visualization on Jupyter Notebook manually."
},
{
"code": null,
"e": 1048,
"s": 989,
"text": "To start, we need to install the extensions package first."
},
{
"code": null,
"e": 1071,
"s": 1048,
"text": "pip install ipywidgets"
},
{
"code": null,
"e": 1180,
"s": 1071,
"text": "Using ipywidgets, we could customize the Jupyter Notebook widget. Let’s explore the basic widgets available."
},
{
"code": null,
"e": 1295,
"s": 1180,
"text": "from ipywidgets import interact#Basic ipywidgets interact would generate UI from the functiondef f(x): return x"
},
{
"code": null,
"e": 1472,
"s": 1295,
"text": "The ipywidgets extensions interact with the base to generate UI from the function. The generated UI would depend on the data type we are passed. Let’s try to pass integer data."
},
{
"code": null,
"e": 1490,
"s": 1472,
"text": "interact(f, x=10)"
},
{
"code": null,
"e": 1571,
"s": 1490,
"text": "Passing integer values would return slider UI. Next, let’s use the Boolean data."
},
{
"code": null,
"e": 1591,
"s": 1571,
"text": "interact(f, x=True)"
},
{
"code": null,
"e": 1669,
"s": 1591,
"text": "The Boolean value would return the checkbox. Finally, let’s use string value."
},
{
"code": null,
"e": 1689,
"s": 1669,
"text": "interact(f, x='hi')"
},
{
"code": null,
"e": 1890,
"s": 1689,
"text": "All the UI was great, but how to apply it to the visualization? We need to create our function to return all the interactive visualization. Let’s use the Seaborn package to combine it with ipywidgets."
},
{
"code": null,
"e": 2100,
"s": 1890,
"text": "import seaborn as snsimport matplotlib.pyplot as pltmpg = sns.load_dataset('mpg')def f(x): img = sns.countplot(mpg[mpg['mpg']<x]['origin']) plt.title('Origin Countplot mpg = {}'.format(x)) return img"
},
{
"code": null,
"e": 2326,
"s": 2100,
"text": "When we move the slide bar, we will execute the function to return the count plot of the ‘origin’ when we filter it with the slider ipywidget. If you want to read more about what ipywidgets could do, you can read it all here."
},
{
"code": null,
"e": 2499,
"s": 2326,
"text": "Pandas-Profiling is an exploratory package that produces interactive HTML reports on our Jupyter Notebook. The basic report from Pandas-Profiling is shown in the GIF below."
},
{
"code": null,
"e": 2668,
"s": 2499,
"text": "As we can see from the GIF, the report produced is an interactive HTML report within your Jupyter Notebook. How do you generate this? Let’s try it out with sample data."
},
{
"code": null,
"e": 2724,
"s": 2668,
"text": "First, we need to install the Pandas-Profiling package."
},
{
"code": null,
"e": 3276,
"s": 2724,
"text": "#Installing via pippip install -U pandas-profiling[notebook]#Enable the widget extension in Jupyterjupyter nbextension enable --py widgetsnbextension#or if you prefer via Condaconda env create -n pandas-profilingconda activate pandas-profilingconda install -c conda-forge pandas-profiling#or if you prefer installing directly from the sourcepip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip#in any case, if the code raise an error, it probably need permission from user. To do that, add --user in the end of the line."
},
{
"code": null,
"e": 3392,
"s": 3276,
"text": "After installing the package, we are ready to generate the report. Let’s use the mpg sample data we had previously."
},
{
"code": null,
"e": 3712,
"s": 3392,
"text": "#Importing the functionfrom pandas_profiling import ProfileReport#Generate the report. We would use the mpg dataset as sample, title parameter for naming our report, and explorative parameter set to True for Deeper exploration.profile = ProfileReport(mpg, title='MPG Pandas Profiling Report', explorative = True)profile"
},
{
"code": null,
"e": 3787,
"s": 3712,
"text": "After some time, the report would show up, and you would explore the HTML."
},
{
"code": null,
"e": 3972,
"s": 3787,
"text": "The report selection is shown in the image above. You could try out all the options to explore the data. If you want to dig the package deeper, you can read my previous articles below."
},
{
"code": null,
"e": 3995,
"s": 3972,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4018,
"s": 3995,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4168,
"s": 4018,
"text": "Jupyter-Matplotlib or ipympl is a Jupyter Notebook extension to enable interactive Matplotlib visualization exploration within your Jupyter Notebook."
},
{
"code": null,
"e": 4297,
"s": 4168,
"text": "The exploration is simple yet powerful if we need a quick visualization with matplotlib. Let’s try to install the package first."
},
{
"code": null,
"e": 4316,
"s": 4297,
"text": "pip install ipympl"
},
{
"code": null,
"e": 4480,
"s": 4316,
"text": "When you finish installing the package, you need to enable the ipympl extension in your Jupyter Notebook by using the following magic command: %matplotlib widget ."
},
{
"code": null,
"e": 4533,
"s": 4480,
"text": "Let’s try the matplotlib extension with sample data."
},
{
"code": null,
"e": 4661,
"s": 4533,
"text": "%matplotlib widgetimport matplotlib.pyplot as pltimport numpy as npfig = plt.figure()plt.plot(np.sin(np.linspace(0, 20, 100)));"
},
{
"code": null,
"e": 4806,
"s": 4661,
"text": "As you can see in the image above, our matplotlib visualization becomes an interactive visualization where you can pan and zoom within the plot."
},
{
"code": null,
"e": 4912,
"s": 4806,
"text": "We can pass another kind of matplotlib plot with our dataset. Let’s try it with our previous mpg dataset."
},
{
"code": null,
"e": 4973,
"s": 4912,
"text": "fig = plt.figure()plt.scatter(mpg['mpg'], mpg['horsepower'])"
},
{
"code": null,
"e": 5165,
"s": 4973,
"text": "As long as the visualization is based on the matplotlib package, we could pass the interactive widget within the plot. That is why it would work with another kind of matplotlib visualization."
},
{
"code": null,
"e": 5398,
"s": 5165,
"text": "You could implement other widgets using ipympl that are similar to the ipywidgets; however, I feel the ipywidgets package has covered many of the functions. If you are interested in the ipympl widgets, you could explore the example."
},
{
"code": null,
"e": 5599,
"s": 5398,
"text": "If you want to have an interactive Pandas dataframe table, you might want to install itables package extensions. This package would allow you to have a simple exploration capability in the data frame."
},
{
"code": null,
"e": 5666,
"s": 5599,
"text": "How do you enable this extension? Let’s install the package first."
},
{
"code": null,
"e": 5686,
"s": 5666,
"text": "pip install itables"
},
{
"code": null,
"e": 5774,
"s": 5686,
"text": "When you have finished installing the package, you only need to run the following code."
},
{
"code": null,
"e": 5853,
"s": 5774,
"text": "from itables import init_notebook_modeinit_notebook_mode(all_interactive=True)"
},
{
"code": null,
"e": 6031,
"s": 5853,
"text": "Your data frame would automatically have interactive extensions similar to the GIF above. If you want to display only one series or data frame, you could use the following code."
},
{
"code": null,
"e": 6082,
"s": 6031,
"text": "from itables import showshow(mpg[['mpg', 'name']])"
},
{
"code": null,
"e": 6362,
"s": 6082,
"text": "Do you want to have an interactive canvas you could play on your Jupyter Notebook? If so, then you should try the ipycanvas package extension. These extensions allow you to create a drawable canvas within your Jupyter Notebook with drawing style. Let’s install the package first."
},
{
"code": null,
"e": 6391,
"s": 6362,
"text": "pip install ipycanvas orjson"
},
{
"code": null,
"e": 6492,
"s": 6391,
"text": "After installing the package, let’s try to initiate a hand-drawing canvas from the notebook example."
},
{
"code": null,
"e": 7600,
"s": 6492,
"text": "from ipywidgets import Image,ColorPicker, IntSlider, link, AppLayout, HBox, RoughCanvas, hold_canvaswidth = 800height = 800canvas = RoughCanvas(width=width, height=height)drawing = Falseposition = Noneshape = []def on_mouse_down(x, y): global drawing global position global shapedrawing = True position = (x, y) shape = [position]def on_mouse_move(x, y): global drawing global position global shapeif not drawing: returnwith hold_canvas(canvas): canvas.stroke_line(position[0], position[1], x, y)position = (x, y)shape.append(position)def on_mouse_up(x, y): global drawing global position global shapedrawing = False with hold_canvas(canvas): canvas.stroke_line(position[0], position[1], x, y) canvas.fill_polygon(shape)shape = []canvas.on_mouse_down(on_mouse_down)canvas.on_mouse_move(on_mouse_move)canvas.on_mouse_up(on_mouse_up)canvas.stroke_style = '#749cb8'picker = ColorPicker(description='Color:', value='#749cb8')link((picker, 'value'), (canvas, 'stroke_style'))link((picker, 'value'), (canvas, 'fill_style'))HBox((canvas, picker))"
},
{
"code": null,
"e": 7757,
"s": 7600,
"text": "In the image above I am playing around with the Canvas I have created with the above code. You could try to click the canvas and draw something interesting."
},
{
"code": null,
"e": 7854,
"s": 7757,
"text": "If you still want to look at what ipycanvas could do, you can read the whole documentation here."
},
{
"code": null,
"e": 8140,
"s": 7854,
"text": "Jupyter Notebook is one of the most used IDE by data scientists for the versatility it offers. Activity such as data visualization is often done in the Notebook as well. To help with this activity, I am outlining five interesting Jupyter extensions interactive visualization. They are:"
},
{
"code": null,
"e": 8189,
"s": 8140,
"text": "ipywidgetspandas-profilingipymplitablesipycanvas"
},
{
"code": null,
"e": 8200,
"s": 8189,
"text": "ipywidgets"
},
{
"code": null,
"e": 8217,
"s": 8200,
"text": "pandas-profiling"
},
{
"code": null,
"e": 8224,
"s": 8217,
"text": "ipympl"
},
{
"code": null,
"e": 8232,
"s": 8224,
"text": "itables"
},
{
"code": null,
"e": 8242,
"s": 8232,
"text": "ipycanvas"
},
{
"code": null,
"e": 8259,
"s": 8242,
"text": "I hope it helps!"
},
{
"code": null,
"e": 8295,
"s": 8259,
"text": "Visit me on my LinkedIn or Twitter."
}
] |
Alternate vowel and consonant string - GeeksforGeeks
|
10 Mar, 2022
Given a string, rearrange characters of the given string such that the vowels and consonants occupy alternate position. If string can not be rearranged in desired way, print “no such string”. The order of vowels with respect to each other and the order of consonants with respect to each other should be maintained. If more than one required strings can be formed, print the lexicographically smaller.Examples:
Input : geeks
Output : gekes
Input : onse
Output : nose
There are two possible outcomes
"nose" and "ones". Since "nose"
is lexicographically smaller, we
print it.
Count number of vowels and consonants in given string.If difference between counts is more than one, return “Not Possible”.If there are more vowels than consonants, print first vowel first and recur for remaining string.If there are more consonants than vowels, print first consonant first and recur for remaining string.If counts are same, compare first vowel with first consonant and print the smaller one first.
Count number of vowels and consonants in given string.
If difference between counts is more than one, return “Not Possible”.
If there are more vowels than consonants, print first vowel first and recur for remaining string.
If there are more consonants than vowels, print first consonant first and recur for remaining string.
If counts are same, compare first vowel with first consonant and print the smaller one first.
C++
Java
Python 3
C#
Javascript
// C++ implementation of alternate vowel and// consonant string#include <bits/stdc++.h>using namespace std; // 'ch' is vowel or notbool isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') return true; return false;} // create alternate vowel and consonant string// str1[0...l1-1] and str2[start...l2-1]string createAltStr(string str1, string str2, int start, int l){ string finalStr = ""; // first adding character of vowel/consonant // then adding character of consonant/vowel for (int i=0, j=start; j<l; i++, j++) finalStr = (finalStr + str1.at(i)) + str2.at(j); return finalStr;} // function to find the required// alternate vowel and consonant stringstring findAltStr(string str){ int nv = 0, nc = 0; string vstr = "", cstr = ""; int l = str.size(); for (int i=0; i<l; i++) { char ch = str.at(i); // count vowels and update vowel string if (isVowel(ch)) { nv++; vstr = vstr + ch; } // count consonants and update consonant // string else { nc++; cstr = cstr + ch; } } // no such string can be formed if (abs(nv-nc) >= 2) return "no such string"; // remove first character of vowel string // then create alternate string with // cstr[0...nc-1] and vstr[1...nv-1] if (nv > nc) return (vstr.at(0) + createAltStr(cstr, vstr, 1, nv)); // remove first character of consonant string // then create alternate string with // vstr[0...nv-1] and cstr[1...nc-1] if (nc > nv) return (cstr.at(0) + createAltStr(vstr, cstr, 1, nc)); // if both vowel and consonant // strings are of equal length // start creating string with consonant if (cstr.at(0) < vstr.at(0)) return createAltStr(cstr, vstr, 0, nv); // start creating string with vowel return createAltStr(vstr, cstr, 0, nc);} // Driver program to test aboveint main(){ string str = "geeks"; cout << findAltStr(str); return 0;}
// Java implementation of alternate vowel and// consonant stringimport java.util.*; class GFG{ // 'ch' is vowel or notstatic boolean isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') return true; return false;} // create alternate vowel and consonant string// str1[0...l1-1] and str2[start...l2-1]static String createAltStr(String str1, String str2, int start, int l){ String finalStr = ""; // first adding character of vowel/consonant // then adding character of consonant/vowel for (int i = 0, j = start; j < l; i++, j++) finalStr = (finalStr + str1.charAt(i)) + str2.charAt(j); return finalStr;} // function to find the required// alternate vowel and consonant stringstatic String findAltStr(String str){ int nv = 0, nc = 0; String vstr = "", cstr = ""; int l = str.length(); for (int i = 0; i < l; i++) { char ch = str.charAt(i); // count vowels and update vowel string if (isVowel(ch)) { nv++; vstr = vstr + ch; } // count consonants and update consonant // string else { nc++; cstr = cstr + ch; } } // no such string can be formed if (Math.abs(nv - nc) >= 2) return "no such string"; // remove first character of vowel string // then create alternate string with // cstr[0...nc-1] and vstr[1...nv-1] if (nv > nc) return (vstr.charAt(0) + createAltStr(cstr, vstr, 1, nv)); // remove first character of consonant string // then create alternate string with // vstr[0...nv-1] and cstr[1...nc-1] if (nc > nv) return (cstr.charAt(0) + createAltStr(vstr, cstr, 1, nc)); // if both vowel and consonant // strings are of equal length // start creating string with consonant if (cstr.charAt(0) < vstr.charAt(0)) return createAltStr(cstr, vstr, 0, nv); // start creating string with vowel return createAltStr(vstr, cstr, 0, nc);} // Driver codepublic static void main(String args[]){ String str = "geeks"; System.out.println(findAltStr(str));}} // This code is contributed by// Shashank_Sharma
# Python implementation of alternate vowel# and consonant string # 'ch' is vowel or notdef isVowel(ch): if(ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'): return True return False # create alternate vowel and consonant string# str1[0...l1-1] and str2[start...l2-1]def createAltStr(str1, str2, start, l): finalStr = "" i = 0 # first adding character of vowel/consonant # then adding character of consonant/vowel for j in range(start, l): finalStr = (finalStr + str1[i]) + str2[j] i + 1 return finalStr # function to find the required# alternate vowel and consonant stringdef findAltStr(str1): nv = 0 nc = 0 vstr = "" cstr = "" l = len(str1) for i in range(0, l): # count vowels and update vowel string if(isVowel(str1[i])): nv += 1 vstr = vstr + str1[i] # count consonants and update # consonant string else: nc += 1 cstr = cstr + str1[i] # no such string can be formed if(abs(nv - nc) >= 2): return "no such string" # remove first character of vowel string # then create alternate string with # cstr[0...nc-1] and vstr[1...nv-1] if(nv > nc): return (vstr[0] + createAltStr(cstr, vstr, 1, nv)) # remove first character of consonant string # then create alternate string with # vstr[0...nv-1] and cstr[1...nc-1] if(nc > nv): return (cstr[0] + createAltStr(vstr, cstr, 1, nc)) # if both vowel and consonant # strings are of equal length # start creating string with consonant if(cstr[0] < vstr[0]): return createAltStr(cstr, vstr, 0, nv) return createAltStr(vstr, cstr, 0, nc) # Driver Codeif __name__ == "__main__": str1 = "geeks" print(findAltStr(str1)) # This code is contributed by Sairahul099
// C# implementation of alternate vowel and// consonant stringusing System; class GFG{ // 'ch' is vowel or notstatic Boolean isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') return true; return false;} // create alternate vowel and consonant string// str1[0...l1-1] and str2[start...l2-1]static String createAltStr(String str1, String str2, int start, int l){ String finalStr = ""; // first adding character of vowel/consonant // then adding character of consonant/vowel for (int i = 0, j = start; j < l; i++, j++) finalStr = (finalStr + str1[i]) + str2[j]; return finalStr;} // function to find the required// alternate vowel and consonant stringstatic String findAltStr(String str){ int nv = 0, nc = 0; String vstr = "", cstr = ""; int l = str.Length; for (int i = 0; i < l; i++) { char ch = str[i]; // count vowels and update vowel string if (isVowel(ch)) { nv++; vstr = vstr + ch; } // count consonants and update consonant // string else { nc++; cstr = cstr + ch; } } // no such string can be formed if (Math.Abs(nv - nc) >= 2) return "no such string"; // remove first character of vowel string // then create alternate string with // cstr[0...nc-1] and vstr[1...nv-1] if (nv > nc) return (vstr[0] + createAltStr(cstr, vstr, 1, nv)); // remove first character of consonant string // then create alternate string with // vstr[0...nv-1] and cstr[1...nc-1] if (nc > nv) return (cstr[0] + createAltStr(vstr, cstr, 1, nc)); // if both vowel and consonant // strings are of equal length // start creating string with consonant if (cstr[0] < vstr[0]) return createAltStr(cstr, vstr, 0, nv); // start creating string with vowel return createAltStr(vstr, cstr, 0, nc);} // Driver codepublic static void Main(String []args){ String str = "geeks"; Console.WriteLine(findAltStr(str));}} // This code is contributed by Princi Singh
<script> // JavaScript implementation of alternate vowel and// consonant string // 'ch' is vowel or notfunction isVowel(ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') return true; return false;} // create alternate vowel and consonant string// str1[0...l1-1] and str2[start...l2-1]function createAltStr(str1, str2,start,l){ let finalStr = ""; // first adding character of vowel/consonant // then adding character of consonant/vowel for (let i=0, j=start; j<l; i++, j++) finalStr = (finalStr + str1[i] + str2[j]); return finalStr;} // function to find the required// alternate vowel and consonant stringfunction findAltStr(str){ let nv = 0, nc = 0; let vstr = "", cstr = ""; let l = str.length; for (let i=0; i<l; i++) { let ch = str[i]; // count vowels and update vowel string if (isVowel(ch)) { nv++; vstr = vstr + ch; } // count consonants and update consonant // string else { nc++; cstr = cstr + ch; } } // no such string can be formed if (Math.abs(nv-nc) >= 2) return "no such string"; // remove first character of vowel string // then create alternate string with // cstr[0...nc-1] and vstr[1...nv-1] if (nv > nc) return (vstr[0] + createAltStr(cstr, vstr, 1, nv)); // remove first character of consonant string // then create alternate string with // vstr[0...nv-1] and cstr[1...nc-1] if (nc > nv) return (cstr[0] + createAltStr(vstr, cstr, 1, nc)); // if both vowel and consonant // strings are of equal length // start creating string with consonant if (cstr.at(0) < vstr.at(0)) return createAltStr(cstr, vstr, 0, nv); // start creating string with vowel return createAltStr(vstr, cstr, 0, nc);} // Driver program to test abovelet str = "geeks";document.write(findAltStr(str)); // This code is contributed by Shinjan_Patra</script>
Output:
gekes
Time Complexity: O(n), where ‘n’ the is length of the stringThis article is contributed by Ayush Jauhari. 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.
Sairahul Jella
Shashank_Sharma
princi singh
bunnyram19
shinjanpatra
vowel-consonant
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters
|
[
{
"code": null,
"e": 25276,
"s": 25248,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 25689,
"s": 25276,
"text": "Given a string, rearrange characters of the given string such that the vowels and consonants occupy alternate position. If string can not be rearranged in desired way, print “no such string”. The order of vowels with respect to each other and the order of consonants with respect to each other should be maintained. If more than one required strings can be formed, print the lexicographically smaller.Examples: "
},
{
"code": null,
"e": 25855,
"s": 25689,
"text": "Input : geeks\nOutput : gekes\n\nInput : onse\nOutput : nose\nThere are two possible outcomes\n\"nose\" and \"ones\". Since \"nose\"\nis lexicographically smaller, we \nprint it."
},
{
"code": null,
"e": 26274,
"s": 25859,
"text": "Count number of vowels and consonants in given string.If difference between counts is more than one, return “Not Possible”.If there are more vowels than consonants, print first vowel first and recur for remaining string.If there are more consonants than vowels, print first consonant first and recur for remaining string.If counts are same, compare first vowel with first consonant and print the smaller one first."
},
{
"code": null,
"e": 26329,
"s": 26274,
"text": "Count number of vowels and consonants in given string."
},
{
"code": null,
"e": 26399,
"s": 26329,
"text": "If difference between counts is more than one, return “Not Possible”."
},
{
"code": null,
"e": 26497,
"s": 26399,
"text": "If there are more vowels than consonants, print first vowel first and recur for remaining string."
},
{
"code": null,
"e": 26599,
"s": 26497,
"text": "If there are more consonants than vowels, print first consonant first and recur for remaining string."
},
{
"code": null,
"e": 26693,
"s": 26599,
"text": "If counts are same, compare first vowel with first consonant and print the smaller one first."
},
{
"code": null,
"e": 26699,
"s": 26695,
"text": "C++"
},
{
"code": null,
"e": 26704,
"s": 26699,
"text": "Java"
},
{
"code": null,
"e": 26713,
"s": 26704,
"text": "Python 3"
},
{
"code": null,
"e": 26716,
"s": 26713,
"text": "C#"
},
{
"code": null,
"e": 26727,
"s": 26716,
"text": "Javascript"
},
{
"code": "// C++ implementation of alternate vowel and// consonant string#include <bits/stdc++.h>using namespace std; // 'ch' is vowel or notbool isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') return true; return false;} // create alternate vowel and consonant string// str1[0...l1-1] and str2[start...l2-1]string createAltStr(string str1, string str2, int start, int l){ string finalStr = \"\"; // first adding character of vowel/consonant // then adding character of consonant/vowel for (int i=0, j=start; j<l; i++, j++) finalStr = (finalStr + str1.at(i)) + str2.at(j); return finalStr;} // function to find the required// alternate vowel and consonant stringstring findAltStr(string str){ int nv = 0, nc = 0; string vstr = \"\", cstr = \"\"; int l = str.size(); for (int i=0; i<l; i++) { char ch = str.at(i); // count vowels and update vowel string if (isVowel(ch)) { nv++; vstr = vstr + ch; } // count consonants and update consonant // string else { nc++; cstr = cstr + ch; } } // no such string can be formed if (abs(nv-nc) >= 2) return \"no such string\"; // remove first character of vowel string // then create alternate string with // cstr[0...nc-1] and vstr[1...nv-1] if (nv > nc) return (vstr.at(0) + createAltStr(cstr, vstr, 1, nv)); // remove first character of consonant string // then create alternate string with // vstr[0...nv-1] and cstr[1...nc-1] if (nc > nv) return (cstr.at(0) + createAltStr(vstr, cstr, 1, nc)); // if both vowel and consonant // strings are of equal length // start creating string with consonant if (cstr.at(0) < vstr.at(0)) return createAltStr(cstr, vstr, 0, nv); // start creating string with vowel return createAltStr(vstr, cstr, 0, nc);} // Driver program to test aboveint main(){ string str = \"geeks\"; cout << findAltStr(str); return 0;}",
"e": 28820,
"s": 26727,
"text": null
},
{
"code": "// Java implementation of alternate vowel and// consonant stringimport java.util.*; class GFG{ // 'ch' is vowel or notstatic boolean isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') return true; return false;} // create alternate vowel and consonant string// str1[0...l1-1] and str2[start...l2-1]static String createAltStr(String str1, String str2, int start, int l){ String finalStr = \"\"; // first adding character of vowel/consonant // then adding character of consonant/vowel for (int i = 0, j = start; j < l; i++, j++) finalStr = (finalStr + str1.charAt(i)) + str2.charAt(j); return finalStr;} // function to find the required// alternate vowel and consonant stringstatic String findAltStr(String str){ int nv = 0, nc = 0; String vstr = \"\", cstr = \"\"; int l = str.length(); for (int i = 0; i < l; i++) { char ch = str.charAt(i); // count vowels and update vowel string if (isVowel(ch)) { nv++; vstr = vstr + ch; } // count consonants and update consonant // string else { nc++; cstr = cstr + ch; } } // no such string can be formed if (Math.abs(nv - nc) >= 2) return \"no such string\"; // remove first character of vowel string // then create alternate string with // cstr[0...nc-1] and vstr[1...nv-1] if (nv > nc) return (vstr.charAt(0) + createAltStr(cstr, vstr, 1, nv)); // remove first character of consonant string // then create alternate string with // vstr[0...nv-1] and cstr[1...nc-1] if (nc > nv) return (cstr.charAt(0) + createAltStr(vstr, cstr, 1, nc)); // if both vowel and consonant // strings are of equal length // start creating string with consonant if (cstr.charAt(0) < vstr.charAt(0)) return createAltStr(cstr, vstr, 0, nv); // start creating string with vowel return createAltStr(vstr, cstr, 0, nc);} // Driver codepublic static void main(String args[]){ String str = \"geeks\"; System.out.println(findAltStr(str));}} // This code is contributed by// Shashank_Sharma",
"e": 31066,
"s": 28820,
"text": null
},
{
"code": "# Python implementation of alternate vowel# and consonant string # 'ch' is vowel or notdef isVowel(ch): if(ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'): return True return False # create alternate vowel and consonant string# str1[0...l1-1] and str2[start...l2-1]def createAltStr(str1, str2, start, l): finalStr = \"\" i = 0 # first adding character of vowel/consonant # then adding character of consonant/vowel for j in range(start, l): finalStr = (finalStr + str1[i]) + str2[j] i + 1 return finalStr # function to find the required# alternate vowel and consonant stringdef findAltStr(str1): nv = 0 nc = 0 vstr = \"\" cstr = \"\" l = len(str1) for i in range(0, l): # count vowels and update vowel string if(isVowel(str1[i])): nv += 1 vstr = vstr + str1[i] # count consonants and update # consonant string else: nc += 1 cstr = cstr + str1[i] # no such string can be formed if(abs(nv - nc) >= 2): return \"no such string\" # remove first character of vowel string # then create alternate string with # cstr[0...nc-1] and vstr[1...nv-1] if(nv > nc): return (vstr[0] + createAltStr(cstr, vstr, 1, nv)) # remove first character of consonant string # then create alternate string with # vstr[0...nv-1] and cstr[1...nc-1] if(nc > nv): return (cstr[0] + createAltStr(vstr, cstr, 1, nc)) # if both vowel and consonant # strings are of equal length # start creating string with consonant if(cstr[0] < vstr[0]): return createAltStr(cstr, vstr, 0, nv) return createAltStr(vstr, cstr, 0, nc) # Driver Codeif __name__ == \"__main__\": str1 = \"geeks\" print(findAltStr(str1)) # This code is contributed by Sairahul099",
"e": 32975,
"s": 31066,
"text": null
},
{
"code": "// C# implementation of alternate vowel and// consonant stringusing System; class GFG{ // 'ch' is vowel or notstatic Boolean isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') return true; return false;} // create alternate vowel and consonant string// str1[0...l1-1] and str2[start...l2-1]static String createAltStr(String str1, String str2, int start, int l){ String finalStr = \"\"; // first adding character of vowel/consonant // then adding character of consonant/vowel for (int i = 0, j = start; j < l; i++, j++) finalStr = (finalStr + str1[i]) + str2[j]; return finalStr;} // function to find the required// alternate vowel and consonant stringstatic String findAltStr(String str){ int nv = 0, nc = 0; String vstr = \"\", cstr = \"\"; int l = str.Length; for (int i = 0; i < l; i++) { char ch = str[i]; // count vowels and update vowel string if (isVowel(ch)) { nv++; vstr = vstr + ch; } // count consonants and update consonant // string else { nc++; cstr = cstr + ch; } } // no such string can be formed if (Math.Abs(nv - nc) >= 2) return \"no such string\"; // remove first character of vowel string // then create alternate string with // cstr[0...nc-1] and vstr[1...nv-1] if (nv > nc) return (vstr[0] + createAltStr(cstr, vstr, 1, nv)); // remove first character of consonant string // then create alternate string with // vstr[0...nv-1] and cstr[1...nc-1] if (nc > nv) return (cstr[0] + createAltStr(vstr, cstr, 1, nc)); // if both vowel and consonant // strings are of equal length // start creating string with consonant if (cstr[0] < vstr[0]) return createAltStr(cstr, vstr, 0, nv); // start creating string with vowel return createAltStr(vstr, cstr, 0, nc);} // Driver codepublic static void Main(String []args){ String str = \"geeks\"; Console.WriteLine(findAltStr(str));}} // This code is contributed by Princi Singh",
"e": 35156,
"s": 32975,
"text": null
},
{
"code": "<script> // JavaScript implementation of alternate vowel and// consonant string // 'ch' is vowel or notfunction isVowel(ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') return true; return false;} // create alternate vowel and consonant string// str1[0...l1-1] and str2[start...l2-1]function createAltStr(str1, str2,start,l){ let finalStr = \"\"; // first adding character of vowel/consonant // then adding character of consonant/vowel for (let i=0, j=start; j<l; i++, j++) finalStr = (finalStr + str1[i] + str2[j]); return finalStr;} // function to find the required// alternate vowel and consonant stringfunction findAltStr(str){ let nv = 0, nc = 0; let vstr = \"\", cstr = \"\"; let l = str.length; for (let i=0; i<l; i++) { let ch = str[i]; // count vowels and update vowel string if (isVowel(ch)) { nv++; vstr = vstr + ch; } // count consonants and update consonant // string else { nc++; cstr = cstr + ch; } } // no such string can be formed if (Math.abs(nv-nc) >= 2) return \"no such string\"; // remove first character of vowel string // then create alternate string with // cstr[0...nc-1] and vstr[1...nv-1] if (nv > nc) return (vstr[0] + createAltStr(cstr, vstr, 1, nv)); // remove first character of consonant string // then create alternate string with // vstr[0...nv-1] and cstr[1...nc-1] if (nc > nv) return (cstr[0] + createAltStr(vstr, cstr, 1, nc)); // if both vowel and consonant // strings are of equal length // start creating string with consonant if (cstr.at(0) < vstr.at(0)) return createAltStr(cstr, vstr, 0, nv); // start creating string with vowel return createAltStr(vstr, cstr, 0, nc);} // Driver program to test abovelet str = \"geeks\";document.write(findAltStr(str)); // This code is contributed by Shinjan_Patra</script>",
"e": 37183,
"s": 35156,
"text": null
},
{
"code": null,
"e": 37193,
"s": 37183,
"text": "Output: "
},
{
"code": null,
"e": 37199,
"s": 37193,
"text": "gekes"
},
{
"code": null,
"e": 37681,
"s": 37199,
"text": "Time Complexity: O(n), where ‘n’ the is length of the stringThis article is contributed by Ayush Jauhari. 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": 37696,
"s": 37681,
"text": "Sairahul Jella"
},
{
"code": null,
"e": 37712,
"s": 37696,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 37725,
"s": 37712,
"text": "princi singh"
},
{
"code": null,
"e": 37736,
"s": 37725,
"text": "bunnyram19"
},
{
"code": null,
"e": 37749,
"s": 37736,
"text": "shinjanpatra"
},
{
"code": null,
"e": 37765,
"s": 37749,
"text": "vowel-consonant"
},
{
"code": null,
"e": 37773,
"s": 37765,
"text": "Strings"
},
{
"code": null,
"e": 37781,
"s": 37773,
"text": "Strings"
},
{
"code": null,
"e": 37879,
"s": 37781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37954,
"s": 37879,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 38011,
"s": 37954,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 38047,
"s": 38011,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 38094,
"s": 38047,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 38130,
"s": 38094,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 38183,
"s": 38130,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 38221,
"s": 38183,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 38251,
"s": 38221,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 38303,
"s": 38251,
"text": "Check whether two strings are anagram of each other"
}
] |
Difference between jquery.size() and jquery.length - GeeksforGeeks
|
22 Jul, 2021
JQuery.size() method gives us the number of elements present. For Example, if we are calling the size() method for “p” tag, then it will return the number of “p” tags present on our page.
Syntax:
$(selector).size()
Return value: It returns the number of “selector” present.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Using jquery v1.6 library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </script></head> <body> <p>para-1</p> <p>para-2</p> <p>para-3</p> <p>para-4</p> <p>para-5</p> <script> console.log($("p").size()) </script></body> </html>
Output:
5
Note: This method has been removed in jQuery 3.0. So, the above code will not work in the latest version of jQuery. Now, you have to use length property.
JQuery.size() implementation:
size()->function()
{
return this.length;
}
Here, We can clearly see that size() method is internally calling the length property. So, it is quite obvious that when we have to find the size of an element, we can directly call the length property instead of the calling method.
jQuery.length Property: The JQuery.length property is faster than JQuery.size() because here we are not calling any function.
Syntax:
$(selector).length
Return value: It returns the length of the selector.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- using jquery library --> <script src="https://code.jquery.com/jquery-git.js"> </script></head> <body> <p>para-1</p> <p>para-2</p> <p>para-3</p> <p>para-4</p> <p>para-5</p> <script> console.log($("p").length) </script></body> </html>
Output:
5
Difference between jQuery.size() and jQuery.length:
jQuery-Methods
jQuery-Questions
Picked
Difference Between
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Mealy machine and Moore machine
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to change the background color after clicking the button in JavaScript ?
How to Dynamically Add/Remove Table Rows using jQuery ?
|
[
{
"code": null,
"e": 24921,
"s": 24893,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 25109,
"s": 24921,
"text": "JQuery.size() method gives us the number of elements present. For Example, if we are calling the size() method for “p” tag, then it will return the number of “p” tags present on our page."
},
{
"code": null,
"e": 25117,
"s": 25109,
"text": "Syntax:"
},
{
"code": null,
"e": 25136,
"s": 25117,
"text": "$(selector).size()"
},
{
"code": null,
"e": 25195,
"s": 25136,
"text": "Return value: It returns the number of “selector” present."
},
{
"code": null,
"e": 25204,
"s": 25195,
"text": "Example:"
},
{
"code": null,
"e": 25209,
"s": 25204,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Using jquery v1.6 library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js\"> </script></head> <body> <p>para-1</p> <p>para-2</p> <p>para-3</p> <p>para-4</p> <p>para-5</p> <script> console.log($(\"p\").size()) </script></body> </html>",
"e": 25560,
"s": 25209,
"text": null
},
{
"code": null,
"e": 25568,
"s": 25560,
"text": "Output:"
},
{
"code": null,
"e": 25570,
"s": 25568,
"text": "5"
},
{
"code": null,
"e": 25724,
"s": 25570,
"text": "Note: This method has been removed in jQuery 3.0. So, the above code will not work in the latest version of jQuery. Now, you have to use length property."
},
{
"code": null,
"e": 25754,
"s": 25724,
"text": "JQuery.size() implementation:"
},
{
"code": null,
"e": 25800,
"s": 25754,
"text": "size()->function()\n{\n return this.length; \n}"
},
{
"code": null,
"e": 26033,
"s": 25800,
"text": "Here, We can clearly see that size() method is internally calling the length property. So, it is quite obvious that when we have to find the size of an element, we can directly call the length property instead of the calling method."
},
{
"code": null,
"e": 26160,
"s": 26033,
"text": "jQuery.length Property: The JQuery.length property is faster than JQuery.size() because here we are not calling any function. "
},
{
"code": null,
"e": 26168,
"s": 26160,
"text": "Syntax:"
},
{
"code": null,
"e": 26187,
"s": 26168,
"text": "$(selector).length"
},
{
"code": null,
"e": 26240,
"s": 26187,
"text": "Return value: It returns the length of the selector."
},
{
"code": null,
"e": 26249,
"s": 26240,
"text": "Example:"
},
{
"code": null,
"e": 26254,
"s": 26249,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- using jquery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script></head> <body> <p>para-1</p> <p>para-2</p> <p>para-3</p> <p>para-4</p> <p>para-5</p> <script> console.log($(\"p\").length) </script></body> </html>",
"e": 26577,
"s": 26254,
"text": null
},
{
"code": null,
"e": 26585,
"s": 26577,
"text": "Output:"
},
{
"code": null,
"e": 26587,
"s": 26585,
"text": "5"
},
{
"code": null,
"e": 26639,
"s": 26587,
"text": "Difference between jQuery.size() and jQuery.length:"
},
{
"code": null,
"e": 26654,
"s": 26639,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 26671,
"s": 26654,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 26678,
"s": 26671,
"text": "Picked"
},
{
"code": null,
"e": 26697,
"s": 26678,
"text": "Difference Between"
},
{
"code": null,
"e": 26704,
"s": 26697,
"text": "JQuery"
},
{
"code": null,
"e": 26721,
"s": 26704,
"text": "Web Technologies"
},
{
"code": null,
"e": 26819,
"s": 26721,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26880,
"s": 26819,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26948,
"s": 26880,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 27006,
"s": 26948,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 27061,
"s": 27006,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 27112,
"s": 27061,
"text": "Difference between Mealy machine and Moore machine"
},
{
"code": null,
"e": 27158,
"s": 27112,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 27221,
"s": 27158,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 27250,
"s": 27221,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27327,
"s": 27250,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
DS Project: How to Predict Google Apps Rating? | by Anass El Houd | Towards Data Science
|
In this article, I share with you my experience in analyzing and predicting the Google Apps ratings. This is one of the tests I had to solve in Data Science interviews. I have to point out that this is a personal way of solving the problem, it can help you draw your own reasoning.
As with any other DS project, we start with downloading the data file from here.
You can check the code I used in this project by visualizing the Jupyter Notebook of this project on my Github from here.
Without further ado, Let’s go!
The first step is data preprocessing. We clean, play and transform all the elements and columns of the data based on their formats and types. As we can see, our data has the following format:
apps = pd.read_csv('GooglePlayApp-ELHOUD.csv')apps.info()
The data frame contains 13 different columns and 8281 rows. The column “Rating” represents the Y-vector of our model: what we try to predict. We visualize the different values of “Rating”:
apps['Rating'].value_counts()
While visualizing the values of “Rating”, we notice that there is an unreasonable rating in our data (19.0). In general, the Apps rating is between 0 and 5 stars. We delete this value to avoid biasing our model. We can replace it with 1.9 if we think it was a typing mistake, but since we can’t be sure and we have no direct contact with the data owner, it is better to remove it.
After that, we check all the duplicate apps and remove them:
print('Number of apps at the beginning:', len(apps))apps.drop_duplicates(subset='App', inplace=True) print('Number of apps after removing duplicates:', len(apps))
I think that dropping the three columns (Current Ver, Android Ver, and Last Updated ) is recommended since these three columns are unnecessary for our analysis and have no direct effect on the rating (visualizing correlations after).
In order to visualize the data, we have to convert it into numerical. The conversion is done by replacing all the string and transforming them in different ways to numerical format. In the figure below, we recapitulate all the cleaning, scaling, and conversions steps.
I recapitulate all the steps in the figure below:
All the parts of the code of the transformations I used are set on my Github repository.
Once we did all the transformations, we visualize at the beginning the distribution of the “apps ratings” and the distribution of the “apps size” using Seaborn. So let’s take a look at it and check for normality, and try to correct it otherwise:
sns.distplot(apps['Rating'],fit=norm)print('- Total number of ratings:', len(apps['Rating']))print('- Mean of distribution of rating :', np.mean(apps['Rating']))print('- Standard deviation:', np.std(apps['Rating']))
We notice that “the fit” of the dataset rating doesn’t follow -technically- a normal distribution with a mean of 4.16 and a standard deviation of 0.559. This information will give a helping hand in defining and developing the model after. Let’s check the probability plot:
from scipy import stats fig = plt.figure() prob = stats.probplot(apps[‘Rating’], plot=plt)
So, certainly not normal: we have skewness.
I thought of doing some transformations in order to fit a gaussian distribution. Let’s apply a Box-Cox transformation on the data and see what happens... The Box-Cox transformation is expressed as follows:
After that, we re-visualize the distribution of the “apps ratings” after transformation:
Much more like a gaussian (normal) distribution! We will be using this transformation for the rest of this project.
Next, we visualize different correlations. This is a crucial step that helps us choose the important features of our model. The correlation matrix is shown below:
apps.corr()
Some remarks related to the correlations:
It is obvious that the number of installs is highly correlated with the number of reviews (k=0,59).
The higher the price, the lower the rating with a correlation coefficient of 0,02.
We build two models:
Random Forest Regressor
from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import auc, accuracy_score, mean_absolute_error, mean_squared_errorchosen_features = ['Reviews', 'Size', 'Installs', 'Type','Category', 'Price', 'Content Rating', 'Genres']X = apps[chosen_features]y= bcx_target #transformed ratingX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state=10)rf_reg = RandomForestRegressor()rf_reg.fit(X_train,y_train)y_rfpred = rf_reg.predict(X_test)
For a simple RF Regressor (with the transformed rating), we get:
Mean Squared Error: 0.269
Mean Absolute Error: 0.352
In the figure below, we have a better visualization of the actual and predicted rating by Random Forest Regressor.:
Now, let’s visualize the effect of the number of estimators of the random forest on MSE:
estimators = np.arange(10, 500, 10)mse_list = []for i in estimators: rf_reg.set_params(n_estimators=i) rf_reg.fit(X_train, y_train) y_rfpred = rf_reg.predict(X_test) mse_list.append(mean_squared_error(inv_boxcox(y_test,lam), inv_boxcox(y_rfpred,lam)))plt.figure(figsize=(10, 5))plt.xlabel("No. of Estimators")plt.ylabel("MSE")plt.title("Effect of Number of Estimators")plt.plot(estimators, mse_list)
We get the lowest MSE for a number of estimators around 370. The lowest MSE is approximatively equal to 0,2697.
XGBoost Regressor
y_xgpred = xgb_model.predict(X_test)mse=mean_squared_error(inv_boxcox(y_test,lam), inv_boxcox(y_xgpred,lam))print('Mean Squared Error:',mse)
MSE of XGboost is approximatively equal to 0,2695.
In the following figure, we compare the prediction performances of the two models (Random Forest and XGboost).
I stopped here in order to not make the development too long. Although, if I want to go further in this, I would have tried these two ideas:
Trying some neural networks model (using Keras). I believe that if we have chosen the best architecture for this problem, we would get good results.
I would also get a hand on the second part of the dataset, and apply NLP (Natural Language Processing) to predict the rating of an application based on the review comments of its users (by using all the NLP techniques like Tokenization, Text segmentation...)
I recommend you to check the code I used in this project by visualizing the Jupyter Notebook of this project on my Github from here and follow for more related articles and projects.
|
[
{
"code": null,
"e": 454,
"s": 172,
"text": "In this article, I share with you my experience in analyzing and predicting the Google Apps ratings. This is one of the tests I had to solve in Data Science interviews. I have to point out that this is a personal way of solving the problem, it can help you draw your own reasoning."
},
{
"code": null,
"e": 535,
"s": 454,
"text": "As with any other DS project, we start with downloading the data file from here."
},
{
"code": null,
"e": 657,
"s": 535,
"text": "You can check the code I used in this project by visualizing the Jupyter Notebook of this project on my Github from here."
},
{
"code": null,
"e": 688,
"s": 657,
"text": "Without further ado, Let’s go!"
},
{
"code": null,
"e": 880,
"s": 688,
"text": "The first step is data preprocessing. We clean, play and transform all the elements and columns of the data based on their formats and types. As we can see, our data has the following format:"
},
{
"code": null,
"e": 938,
"s": 880,
"text": "apps = pd.read_csv('GooglePlayApp-ELHOUD.csv')apps.info()"
},
{
"code": null,
"e": 1127,
"s": 938,
"text": "The data frame contains 13 different columns and 8281 rows. The column “Rating” represents the Y-vector of our model: what we try to predict. We visualize the different values of “Rating”:"
},
{
"code": null,
"e": 1157,
"s": 1127,
"text": "apps['Rating'].value_counts()"
},
{
"code": null,
"e": 1538,
"s": 1157,
"text": "While visualizing the values of “Rating”, we notice that there is an unreasonable rating in our data (19.0). In general, the Apps rating is between 0 and 5 stars. We delete this value to avoid biasing our model. We can replace it with 1.9 if we think it was a typing mistake, but since we can’t be sure and we have no direct contact with the data owner, it is better to remove it."
},
{
"code": null,
"e": 1599,
"s": 1538,
"text": "After that, we check all the duplicate apps and remove them:"
},
{
"code": null,
"e": 1762,
"s": 1599,
"text": "print('Number of apps at the beginning:', len(apps))apps.drop_duplicates(subset='App', inplace=True) print('Number of apps after removing duplicates:', len(apps))"
},
{
"code": null,
"e": 1996,
"s": 1762,
"text": "I think that dropping the three columns (Current Ver, Android Ver, and Last Updated ) is recommended since these three columns are unnecessary for our analysis and have no direct effect on the rating (visualizing correlations after)."
},
{
"code": null,
"e": 2265,
"s": 1996,
"text": "In order to visualize the data, we have to convert it into numerical. The conversion is done by replacing all the string and transforming them in different ways to numerical format. In the figure below, we recapitulate all the cleaning, scaling, and conversions steps."
},
{
"code": null,
"e": 2315,
"s": 2265,
"text": "I recapitulate all the steps in the figure below:"
},
{
"code": null,
"e": 2404,
"s": 2315,
"text": "All the parts of the code of the transformations I used are set on my Github repository."
},
{
"code": null,
"e": 2650,
"s": 2404,
"text": "Once we did all the transformations, we visualize at the beginning the distribution of the “apps ratings” and the distribution of the “apps size” using Seaborn. So let’s take a look at it and check for normality, and try to correct it otherwise:"
},
{
"code": null,
"e": 2866,
"s": 2650,
"text": "sns.distplot(apps['Rating'],fit=norm)print('- Total number of ratings:', len(apps['Rating']))print('- Mean of distribution of rating :', np.mean(apps['Rating']))print('- Standard deviation:', np.std(apps['Rating']))"
},
{
"code": null,
"e": 3139,
"s": 2866,
"text": "We notice that “the fit” of the dataset rating doesn’t follow -technically- a normal distribution with a mean of 4.16 and a standard deviation of 0.559. This information will give a helping hand in defining and developing the model after. Let’s check the probability plot:"
},
{
"code": null,
"e": 3230,
"s": 3139,
"text": "from scipy import stats fig = plt.figure() prob = stats.probplot(apps[‘Rating’], plot=plt)"
},
{
"code": null,
"e": 3274,
"s": 3230,
"text": "So, certainly not normal: we have skewness."
},
{
"code": null,
"e": 3480,
"s": 3274,
"text": "I thought of doing some transformations in order to fit a gaussian distribution. Let’s apply a Box-Cox transformation on the data and see what happens... The Box-Cox transformation is expressed as follows:"
},
{
"code": null,
"e": 3569,
"s": 3480,
"text": "After that, we re-visualize the distribution of the “apps ratings” after transformation:"
},
{
"code": null,
"e": 3685,
"s": 3569,
"text": "Much more like a gaussian (normal) distribution! We will be using this transformation for the rest of this project."
},
{
"code": null,
"e": 3848,
"s": 3685,
"text": "Next, we visualize different correlations. This is a crucial step that helps us choose the important features of our model. The correlation matrix is shown below:"
},
{
"code": null,
"e": 3860,
"s": 3848,
"text": "apps.corr()"
},
{
"code": null,
"e": 3902,
"s": 3860,
"text": "Some remarks related to the correlations:"
},
{
"code": null,
"e": 4002,
"s": 3902,
"text": "It is obvious that the number of installs is highly correlated with the number of reviews (k=0,59)."
},
{
"code": null,
"e": 4085,
"s": 4002,
"text": "The higher the price, the lower the rating with a correlation coefficient of 0,02."
},
{
"code": null,
"e": 4106,
"s": 4085,
"text": "We build two models:"
},
{
"code": null,
"e": 4130,
"s": 4106,
"text": "Random Forest Regressor"
},
{
"code": null,
"e": 4616,
"s": 4130,
"text": "from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import auc, accuracy_score, mean_absolute_error, mean_squared_errorchosen_features = ['Reviews', 'Size', 'Installs', 'Type','Category', 'Price', 'Content Rating', 'Genres']X = apps[chosen_features]y= bcx_target #transformed ratingX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state=10)rf_reg = RandomForestRegressor()rf_reg.fit(X_train,y_train)y_rfpred = rf_reg.predict(X_test)"
},
{
"code": null,
"e": 4681,
"s": 4616,
"text": "For a simple RF Regressor (with the transformed rating), we get:"
},
{
"code": null,
"e": 4707,
"s": 4681,
"text": "Mean Squared Error: 0.269"
},
{
"code": null,
"e": 4734,
"s": 4707,
"text": "Mean Absolute Error: 0.352"
},
{
"code": null,
"e": 4850,
"s": 4734,
"text": "In the figure below, we have a better visualization of the actual and predicted rating by Random Forest Regressor.:"
},
{
"code": null,
"e": 4939,
"s": 4850,
"text": "Now, let’s visualize the effect of the number of estimators of the random forest on MSE:"
},
{
"code": null,
"e": 5351,
"s": 4939,
"text": "estimators = np.arange(10, 500, 10)mse_list = []for i in estimators: rf_reg.set_params(n_estimators=i) rf_reg.fit(X_train, y_train) y_rfpred = rf_reg.predict(X_test) mse_list.append(mean_squared_error(inv_boxcox(y_test,lam), inv_boxcox(y_rfpred,lam)))plt.figure(figsize=(10, 5))plt.xlabel(\"No. of Estimators\")plt.ylabel(\"MSE\")plt.title(\"Effect of Number of Estimators\")plt.plot(estimators, mse_list)"
},
{
"code": null,
"e": 5463,
"s": 5351,
"text": "We get the lowest MSE for a number of estimators around 370. The lowest MSE is approximatively equal to 0,2697."
},
{
"code": null,
"e": 5481,
"s": 5463,
"text": "XGBoost Regressor"
},
{
"code": null,
"e": 5622,
"s": 5481,
"text": "y_xgpred = xgb_model.predict(X_test)mse=mean_squared_error(inv_boxcox(y_test,lam), inv_boxcox(y_xgpred,lam))print('Mean Squared Error:',mse)"
},
{
"code": null,
"e": 5673,
"s": 5622,
"text": "MSE of XGboost is approximatively equal to 0,2695."
},
{
"code": null,
"e": 5784,
"s": 5673,
"text": "In the following figure, we compare the prediction performances of the two models (Random Forest and XGboost)."
},
{
"code": null,
"e": 5925,
"s": 5784,
"text": "I stopped here in order to not make the development too long. Although, if I want to go further in this, I would have tried these two ideas:"
},
{
"code": null,
"e": 6074,
"s": 5925,
"text": "Trying some neural networks model (using Keras). I believe that if we have chosen the best architecture for this problem, we would get good results."
},
{
"code": null,
"e": 6333,
"s": 6074,
"text": "I would also get a hand on the second part of the dataset, and apply NLP (Natural Language Processing) to predict the rating of an application based on the review comments of its users (by using all the NLP techniques like Tokenization, Text segmentation...)"
}
] |
Key Programming Concepts for Pandas Beginners | by Skyler Dale | Towards Data Science
|
If you’re just getting started with Python or Pandas, welcome.
Let me begin with a quick note of encouragement.
Learning to code can feel a bit daunting in the beginning because there is a lot of unknown.
On top of that, sometimes the people around you are discouraging: you don’t have the right background... if you don’t know x you can’t do y... the only proper way to get started with technology is to get a degree.
They’re wrong.
As is the case with any discipline, programming is a skillset that exists on a spectrum. Don’t buy in to any circular reasoning that suggests you can’t write code if you don’t know how to write code. The only thing you need is persistence.
You belong.
What is true is that there is a lot to learn. It’s not always going to be easy, and it takes continuous effort to move along that skillset spectrum.
In this post, I’ll provide an overview of some of the fundamental programming concepts so that when you start writing Pandas code, you have a better sense of what is going on.
I’ll try to bring each concept back to the Pandas library in order to make this as tangible as possible.
Put simply, a programming language is a set of rules and conventions that govern how we can instruct a computer to do what we want it to do.
Different programming languages use a different vocabulary or “syntax”.
In python, we can get the computer to return the words “hello world” by writing:
print(“hello world”)
In Java (another programming language) we write:
System.out.println("hello world");
Behind the scenes, programming languages are converted from high-level words, like “print”, all the way down to 1s and 0s.
Our computers can “understand” 1s and 0s because we can represent those values in a physical state.
For example, we could use a light switch. When it's on we could say it represents the number 1 and when it’s off it represents 0.
Computers have billions of tiny switches, called transistors, that work in the same way. Combined together, they encode all of the data you need.
A “high level” language is further away from those 1s and 0s, which means there is more translation required to get from the language to the state of the hardware.
A “low level” language is closer to the 1s and 0s and requires less translation.
There is a natural tradeoff here — high level languages tend to be slower but easier to use. Low level languages tend to be faster but harder to use.
A library (aka package), on the other hand, is code that someone else has written in a programming language and then tied up neatly so that other programmers can borrow it.
Python is a programming language. Pandas is an open source (ie. free, publicly available) data analysis library written in python.
One of the reasons why Python is such a popular choice for data analysis is because it’s community of developers has created a wide array of useful libraries including Pandas, Numpy, Matplotlib, Scikit-learn and many more.
When we want to leverage one of these libraries, we need to install the code (once) and import it into our files (each time we want to use it).
At its core, programming is all about transforming data; converting an input to an output.
But not all data is the same. We have different data types that we can use in different ways.
To further illustrate this point lets compare two of the most commonly used data types — a string (aka text) and an integer.
Integers can be divided. Strings cannot.
4/2=2. But “hello” / “goodbye” doesn’t mean anything.
Conversely, you can capitalize a string, but not an integer.
Thus, the major thing that distinguishes data types from one another is the functionalities that are associated with them.
In object oriented languages like Python, we can create our own data types, which are commonly referred to as classes.
A class is a blueprint that tells us what we can do with our data types (methods) and what information we can store about them (attributes).
A single instance of a class is called an object.
Drawing from our example above, we can run the capitalize method on a string:
But not an int:
Python has some built in data types (classes) like int, string, boolean, list, etc.
Pandas also has its own classes that make it possible to do data analysis work.
The most prevalent class in Pandas is the DataFrame, which stores tabular data (like an excel spreadsheet).
The developers that designed the DataFrame class wrote the code to give it the functionality that it has.
For example, we can use the “to_csv” method to create a csv file with the data in our DataFrame:
dataframe.to_csv(‘my_df.csv’)
Again, this functionality is tied to the DataFrame class, which is a part of the Pandas library.
In layman’s term: someone else wrote a lot of code so that you don’t have to.
This is what is meant by the term abstraction — and it's one of the most fundamentally awe-inspiring things about programming.
An army of other people has written millions of lines of code to go from the 1s and 0s, to the python language, to the Pandas library, to the DataFrame class, to the to_csv method.
But all you have to do is write one line of code.
A variable is a container that stores a value.
In some languages, you are required to assign a particular data type to a variable (these are called statically typed languages).
In other languages, you can store data in variables without assigning a particular type (dynamically typed languages).
Python is dynamically typed. As such, we can directly store a value inside a variable:
my_variable = 5
Java is statically typed, so if we want to put the integer, 5, directly in the variable we have to declare that the variable is a container for an integer and not any other data type:
Int myVariable = 10
Our variables can “store” any class in python.
A function is a process for converting inputs to outputs.
If that sounds familiar, it should.
We’ve already discussed “methods” which are a type of function. All methods are functions, not all functions are methods.
The key difference is that methods are tied to specific data types/classes, while general functions are not.
If that’s confusing, an example should clear things up.
When we want to capitalize a string, we can call the capitalize method. This method is explicitly tied to strings.
On the other hand, we can create our own functions that are not tied to a specific class.
Let’s say we want to write a function that adds the number 5 to the end of a string:
Now we have some functionality that is not called by an object, but rather called with a user-defined input (input_string).
In theory, strings could have this method. But it would be ridiculous to expect python to account for this arbitrary task in their definition of the string class.
In a real sense, then, functions help us create reusable code that is not already accounted for by the language or libraries we are using.
One of the most common mistakes that Pandas users make is not taking advantage of functions when they perform analytical tasks with their data.
What this leads to is messy and repetitive code.
Messy and repetitive code is more error prone and difficult to maintain.
It is best practice to use functions any time you might want to reuse the code you’re writing — both in practice and in theory.
Its also best practice to keep functions limited in scope so that they each perform a unique and isolated task.
Functions typically have inputs, which are called “parameters”. These are ingredients for the code of your function. They will typically be used in some way to produce an output.
Nothing happens until a user (usually yourself) runs the function by passing in values to take the place of those parameters.
The values you pass in are technically called “arguments”.
There’s a lot of words to keep track of here, so let’s close with some example code, which covers most of the concepts discussed above:
In this post, we went through some of the most important programming concepts and how they apply to the Pandas library.
If you want to learn more about how to get started with Pandas, check out some of my intuitive guides and make sure to subscribe below. Happy coding!
|
[
{
"code": null,
"e": 234,
"s": 171,
"text": "If you’re just getting started with Python or Pandas, welcome."
},
{
"code": null,
"e": 283,
"s": 234,
"text": "Let me begin with a quick note of encouragement."
},
{
"code": null,
"e": 376,
"s": 283,
"text": "Learning to code can feel a bit daunting in the beginning because there is a lot of unknown."
},
{
"code": null,
"e": 590,
"s": 376,
"text": "On top of that, sometimes the people around you are discouraging: you don’t have the right background... if you don’t know x you can’t do y... the only proper way to get started with technology is to get a degree."
},
{
"code": null,
"e": 605,
"s": 590,
"text": "They’re wrong."
},
{
"code": null,
"e": 845,
"s": 605,
"text": "As is the case with any discipline, programming is a skillset that exists on a spectrum. Don’t buy in to any circular reasoning that suggests you can’t write code if you don’t know how to write code. The only thing you need is persistence."
},
{
"code": null,
"e": 857,
"s": 845,
"text": "You belong."
},
{
"code": null,
"e": 1006,
"s": 857,
"text": "What is true is that there is a lot to learn. It’s not always going to be easy, and it takes continuous effort to move along that skillset spectrum."
},
{
"code": null,
"e": 1182,
"s": 1006,
"text": "In this post, I’ll provide an overview of some of the fundamental programming concepts so that when you start writing Pandas code, you have a better sense of what is going on."
},
{
"code": null,
"e": 1287,
"s": 1182,
"text": "I’ll try to bring each concept back to the Pandas library in order to make this as tangible as possible."
},
{
"code": null,
"e": 1428,
"s": 1287,
"text": "Put simply, a programming language is a set of rules and conventions that govern how we can instruct a computer to do what we want it to do."
},
{
"code": null,
"e": 1500,
"s": 1428,
"text": "Different programming languages use a different vocabulary or “syntax”."
},
{
"code": null,
"e": 1581,
"s": 1500,
"text": "In python, we can get the computer to return the words “hello world” by writing:"
},
{
"code": null,
"e": 1602,
"s": 1581,
"text": "print(“hello world”)"
},
{
"code": null,
"e": 1651,
"s": 1602,
"text": "In Java (another programming language) we write:"
},
{
"code": null,
"e": 1686,
"s": 1651,
"text": "System.out.println(\"hello world\");"
},
{
"code": null,
"e": 1809,
"s": 1686,
"text": "Behind the scenes, programming languages are converted from high-level words, like “print”, all the way down to 1s and 0s."
},
{
"code": null,
"e": 1909,
"s": 1809,
"text": "Our computers can “understand” 1s and 0s because we can represent those values in a physical state."
},
{
"code": null,
"e": 2039,
"s": 1909,
"text": "For example, we could use a light switch. When it's on we could say it represents the number 1 and when it’s off it represents 0."
},
{
"code": null,
"e": 2185,
"s": 2039,
"text": "Computers have billions of tiny switches, called transistors, that work in the same way. Combined together, they encode all of the data you need."
},
{
"code": null,
"e": 2349,
"s": 2185,
"text": "A “high level” language is further away from those 1s and 0s, which means there is more translation required to get from the language to the state of the hardware."
},
{
"code": null,
"e": 2430,
"s": 2349,
"text": "A “low level” language is closer to the 1s and 0s and requires less translation."
},
{
"code": null,
"e": 2580,
"s": 2430,
"text": "There is a natural tradeoff here — high level languages tend to be slower but easier to use. Low level languages tend to be faster but harder to use."
},
{
"code": null,
"e": 2753,
"s": 2580,
"text": "A library (aka package), on the other hand, is code that someone else has written in a programming language and then tied up neatly so that other programmers can borrow it."
},
{
"code": null,
"e": 2884,
"s": 2753,
"text": "Python is a programming language. Pandas is an open source (ie. free, publicly available) data analysis library written in python."
},
{
"code": null,
"e": 3107,
"s": 2884,
"text": "One of the reasons why Python is such a popular choice for data analysis is because it’s community of developers has created a wide array of useful libraries including Pandas, Numpy, Matplotlib, Scikit-learn and many more."
},
{
"code": null,
"e": 3251,
"s": 3107,
"text": "When we want to leverage one of these libraries, we need to install the code (once) and import it into our files (each time we want to use it)."
},
{
"code": null,
"e": 3342,
"s": 3251,
"text": "At its core, programming is all about transforming data; converting an input to an output."
},
{
"code": null,
"e": 3436,
"s": 3342,
"text": "But not all data is the same. We have different data types that we can use in different ways."
},
{
"code": null,
"e": 3561,
"s": 3436,
"text": "To further illustrate this point lets compare two of the most commonly used data types — a string (aka text) and an integer."
},
{
"code": null,
"e": 3602,
"s": 3561,
"text": "Integers can be divided. Strings cannot."
},
{
"code": null,
"e": 3656,
"s": 3602,
"text": "4/2=2. But “hello” / “goodbye” doesn’t mean anything."
},
{
"code": null,
"e": 3717,
"s": 3656,
"text": "Conversely, you can capitalize a string, but not an integer."
},
{
"code": null,
"e": 3840,
"s": 3717,
"text": "Thus, the major thing that distinguishes data types from one another is the functionalities that are associated with them."
},
{
"code": null,
"e": 3959,
"s": 3840,
"text": "In object oriented languages like Python, we can create our own data types, which are commonly referred to as classes."
},
{
"code": null,
"e": 4100,
"s": 3959,
"text": "A class is a blueprint that tells us what we can do with our data types (methods) and what information we can store about them (attributes)."
},
{
"code": null,
"e": 4150,
"s": 4100,
"text": "A single instance of a class is called an object."
},
{
"code": null,
"e": 4228,
"s": 4150,
"text": "Drawing from our example above, we can run the capitalize method on a string:"
},
{
"code": null,
"e": 4244,
"s": 4228,
"text": "But not an int:"
},
{
"code": null,
"e": 4328,
"s": 4244,
"text": "Python has some built in data types (classes) like int, string, boolean, list, etc."
},
{
"code": null,
"e": 4408,
"s": 4328,
"text": "Pandas also has its own classes that make it possible to do data analysis work."
},
{
"code": null,
"e": 4516,
"s": 4408,
"text": "The most prevalent class in Pandas is the DataFrame, which stores tabular data (like an excel spreadsheet)."
},
{
"code": null,
"e": 4622,
"s": 4516,
"text": "The developers that designed the DataFrame class wrote the code to give it the functionality that it has."
},
{
"code": null,
"e": 4719,
"s": 4622,
"text": "For example, we can use the “to_csv” method to create a csv file with the data in our DataFrame:"
},
{
"code": null,
"e": 4749,
"s": 4719,
"text": "dataframe.to_csv(‘my_df.csv’)"
},
{
"code": null,
"e": 4846,
"s": 4749,
"text": "Again, this functionality is tied to the DataFrame class, which is a part of the Pandas library."
},
{
"code": null,
"e": 4924,
"s": 4846,
"text": "In layman’s term: someone else wrote a lot of code so that you don’t have to."
},
{
"code": null,
"e": 5051,
"s": 4924,
"text": "This is what is meant by the term abstraction — and it's one of the most fundamentally awe-inspiring things about programming."
},
{
"code": null,
"e": 5232,
"s": 5051,
"text": "An army of other people has written millions of lines of code to go from the 1s and 0s, to the python language, to the Pandas library, to the DataFrame class, to the to_csv method."
},
{
"code": null,
"e": 5282,
"s": 5232,
"text": "But all you have to do is write one line of code."
},
{
"code": null,
"e": 5329,
"s": 5282,
"text": "A variable is a container that stores a value."
},
{
"code": null,
"e": 5459,
"s": 5329,
"text": "In some languages, you are required to assign a particular data type to a variable (these are called statically typed languages)."
},
{
"code": null,
"e": 5578,
"s": 5459,
"text": "In other languages, you can store data in variables without assigning a particular type (dynamically typed languages)."
},
{
"code": null,
"e": 5665,
"s": 5578,
"text": "Python is dynamically typed. As such, we can directly store a value inside a variable:"
},
{
"code": null,
"e": 5681,
"s": 5665,
"text": "my_variable = 5"
},
{
"code": null,
"e": 5865,
"s": 5681,
"text": "Java is statically typed, so if we want to put the integer, 5, directly in the variable we have to declare that the variable is a container for an integer and not any other data type:"
},
{
"code": null,
"e": 5885,
"s": 5865,
"text": "Int myVariable = 10"
},
{
"code": null,
"e": 5932,
"s": 5885,
"text": "Our variables can “store” any class in python."
},
{
"code": null,
"e": 5990,
"s": 5932,
"text": "A function is a process for converting inputs to outputs."
},
{
"code": null,
"e": 6026,
"s": 5990,
"text": "If that sounds familiar, it should."
},
{
"code": null,
"e": 6148,
"s": 6026,
"text": "We’ve already discussed “methods” which are a type of function. All methods are functions, not all functions are methods."
},
{
"code": null,
"e": 6257,
"s": 6148,
"text": "The key difference is that methods are tied to specific data types/classes, while general functions are not."
},
{
"code": null,
"e": 6313,
"s": 6257,
"text": "If that’s confusing, an example should clear things up."
},
{
"code": null,
"e": 6428,
"s": 6313,
"text": "When we want to capitalize a string, we can call the capitalize method. This method is explicitly tied to strings."
},
{
"code": null,
"e": 6518,
"s": 6428,
"text": "On the other hand, we can create our own functions that are not tied to a specific class."
},
{
"code": null,
"e": 6603,
"s": 6518,
"text": "Let’s say we want to write a function that adds the number 5 to the end of a string:"
},
{
"code": null,
"e": 6727,
"s": 6603,
"text": "Now we have some functionality that is not called by an object, but rather called with a user-defined input (input_string)."
},
{
"code": null,
"e": 6890,
"s": 6727,
"text": "In theory, strings could have this method. But it would be ridiculous to expect python to account for this arbitrary task in their definition of the string class."
},
{
"code": null,
"e": 7029,
"s": 6890,
"text": "In a real sense, then, functions help us create reusable code that is not already accounted for by the language or libraries we are using."
},
{
"code": null,
"e": 7173,
"s": 7029,
"text": "One of the most common mistakes that Pandas users make is not taking advantage of functions when they perform analytical tasks with their data."
},
{
"code": null,
"e": 7222,
"s": 7173,
"text": "What this leads to is messy and repetitive code."
},
{
"code": null,
"e": 7295,
"s": 7222,
"text": "Messy and repetitive code is more error prone and difficult to maintain."
},
{
"code": null,
"e": 7423,
"s": 7295,
"text": "It is best practice to use functions any time you might want to reuse the code you’re writing — both in practice and in theory."
},
{
"code": null,
"e": 7535,
"s": 7423,
"text": "Its also best practice to keep functions limited in scope so that they each perform a unique and isolated task."
},
{
"code": null,
"e": 7714,
"s": 7535,
"text": "Functions typically have inputs, which are called “parameters”. These are ingredients for the code of your function. They will typically be used in some way to produce an output."
},
{
"code": null,
"e": 7840,
"s": 7714,
"text": "Nothing happens until a user (usually yourself) runs the function by passing in values to take the place of those parameters."
},
{
"code": null,
"e": 7899,
"s": 7840,
"text": "The values you pass in are technically called “arguments”."
},
{
"code": null,
"e": 8035,
"s": 7899,
"text": "There’s a lot of words to keep track of here, so let’s close with some example code, which covers most of the concepts discussed above:"
},
{
"code": null,
"e": 8155,
"s": 8035,
"text": "In this post, we went through some of the most important programming concepts and how they apply to the Pandas library."
}
] |
Gensim - Transformations
|
This chapter will help you in learning about the various transformations in Gensim. Let us begin by understanding the transforming documents.
Transforming documents means to represent the document in such a way that the document can be manipulated mathematically. Apart from deducing the latent structure of the corpus, transforming documents will also serve the following goals −
It discovers the relationship between words.
It discovers the relationship between words.
It brings out the hidden structure in the corpus.
It brings out the hidden structure in the corpus.
It describes the documents in a new and more semantic way.
It describes the documents in a new and more semantic way.
It makes the representation of the documents more compact.
It makes the representation of the documents more compact.
It improves efficiency because new representation consumes less resources.
It improves efficiency because new representation consumes less resources.
It improves efficacy because in new representation marginal data trends are ignored.
It improves efficacy because in new representation marginal data trends are ignored.
The noise is also reduced in new document representation.
The noise is also reduced in new document representation.
Let’s see the implementation steps for transforming the documents from one vector space representation to another.
In order to transform documents, we must follow the following steps −
The very first and basic step is to create the corpus from the documents. We have already created the corpus in previous examples. Let’s create another one with some enhancements (removing common words and the words that appear only once) −
import gensim
import pprint
from collections import defaultdict
from gensim import corpora
Now provide the documents for creating the corpus −
t_corpus = ["CNTK formerly known as Computational Network Toolkit", "is a free easy-to-use open-source commercial-grade toolkit", "that enable us to train deep learning algorithms to learn like the human brain.", "You can find its free tutorial on tutorialspoint.com", "Tutorialspoint.com also provide best technical tutorials on technologies like AI deep learning machine learning for free"]
Next, we need to do tokenise and along with it we will remove the common words also −
stoplist = set('for a of the and to in'.split(' '))
processed_corpus = [
[
word for word in document.lower().split() if word not in stoplist
]
for document in t_corpus
]
Following script will remove those words that appear only −
frequency = defaultdict(int)
for text in processed_corpus:
for token in text:
frequency[token] += 1
processed_corpus = [
[token for token in text if frequency[token] > 1]
for text in processed_corpus
]
pprint.pprint(processed_corpus)
[
['toolkit'],
['free', 'toolkit'],
['deep', 'learning', 'like'],
['free', 'on', 'tutorialspoint.com'],
['tutorialspoint.com', 'on', 'like', 'deep', 'learning', 'learning', 'free']
]
Now pass it to the corpora.dictionary() object to get the unique objects in our corpus −
dictionary = corpora.Dictionary(processed_corpus)
print(dictionary)
Dictionary(7 unique tokens: ['toolkit', 'free', 'deep', 'learning', 'like']...)
Next, the following line of codes will create the Bag of Word model for our corpus −
BoW_corpus = [dictionary.doc2bow(text) for text in processed_corpus]
pprint.pprint(BoW_corpus)
[
[(0, 1)],
[(0, 1), (1, 1)],
[(2, 1), (3, 1), (4, 1)],
[(1, 1), (5, 1), (6, 1)],
[(1, 1), (2, 1), (3, 2), (4, 1), (5, 1), (6, 1)]
]
The transformations are some standard Python objects. We can initialize these transformations i.e. Python objects by using a trained corpus. Here we are going to use tf-idf model to create a transformation of our trained corpus i.e. BoW_corpus.
First, we need to import the models package from gensim.
from gensim import models
Now, we need to initialise the model as follows −
tfidf = models.TfidfModel(BoW_corpus)
Now, in this last step, the vectors will be converted from old representation to new representation. As we have initialised the tfidf model in above step, the tfidf will now be treated as a read only object. Here, by using this tfidf object we will convert our vector from bag of word representation (old representation) to Tfidf real-valued weights (new representation).
doc_BoW = [(1,1),(3,1)]
print(tfidf[doc_BoW]
[(1, 0.4869354917707381), (3, 0.8734379353188121)]
We applied the transformation on two values of corpus, but we can also apply it to the whole corpus as follows −
corpus_tfidf = tfidf[BoW_corpus]
for doc in corpus_tfidf:
print(doc)
[(0, 1.0)]
[(0, 0.8734379353188121), (1, 0.4869354917707381)]
[(2, 0.5773502691896257), (3, 0.5773502691896257), (4, 0.5773502691896257)]
[(1, 0.3667400603126873), (5, 0.657838022678017), (6, 0.657838022678017)]
[
(1, 0.19338287240886842), (2, 0.34687949360312714), (3, 0.6937589872062543),
(4, 0.34687949360312714), (5, 0.34687949360312714), (6, 0.34687949360312714)
]
import gensim
import pprint
from collections import defaultdict
from gensim import corpora
t_corpus = [
"CNTK formerly known as Computational Network Toolkit",
"is a free easy-to-use open-source commercial-grade toolkit",
"that enable us to train deep learning algorithms to learn like the human brain.",
"You can find its free tutorial on tutorialspoint.com",
"Tutorialspoint.com also provide best technical tutorials on
technologies like AI deep learning machine learning for free"
]
stoplist = set('for a of the and to in'.split(' '))
processed_corpus = [
[word for word in document.lower().split() if word not in stoplist]
for document in t_corpus
]
frequency = defaultdict(int)
for text in processed_corpus:
for token in text:
frequency[token] += 1
processed_corpus = [
[token for token in text if frequency[token] > 1]
for text in processed_corpus
]
pprint.pprint(processed_corpus)
dictionary = corpora.Dictionary(processed_corpus)
print(dictionary)
BoW_corpus = [dictionary.doc2bow(text) for text in processed_corpus]
pprint.pprint(BoW_corpus)
from gensim import models
tfidf = models.TfidfModel(BoW_corpus)
doc_BoW = [(1,1),(3,1)]
print(tfidf[doc_BoW])
corpus_tfidf = tfidf[BoW_corpus]
for doc in corpus_tfidf:
print(doc)
Using Gensim, we can implement various popular transformations, i.e. Vector Space Model algorithms. Some of them are as follows −
During initialisation, this tf-idf model algorithm expects a training corpus having integer values (such as Bag-of-Words model). Then after that, at the time of transformation, it takes a vector representation and returns another vector representation.
The output vector will have the same dimensionality but the value of the rare features (at the time of training) will be increased. It basically converts integer-valued vectors into real-valued vectors. Following is the syntax of Tf-idf transformation −
Model=models.TfidfModel(corpus, normalize=True)
LSI model algorithm can transform document from either integer valued vector model (such as Bag-of-Words model) or Tf-Idf weighted space into latent space. The output vector will be of lower dimensionality. Following is the syntax of LSI transformation −
Model=models.LsiModel(tfidf_corpus, id2word=dictionary, num_topics=300)
LDA model algorithm is another algorithm that transforms document from Bag-of-Words model space into a topic space. The output vector will be of lower dimensionality. Following is the syntax of LSI transformation −
Model=models.LdaModel(corpus, id2word=dictionary, num_topics=100)
RP, a very efficient approach, aims to reduce the dimensionality of vector space. This approach is basically approximate the Tf-Idf distances between the documents. It does this by throwing in a little randomness.
Model=models.RpModel(tfidf_corpus, num_topics=500)
HDP is a non-parametric Bayesian method which is a new addition to Gensim. We should have to take care while using it.
Model=models.HdpModel(corpus, id2word=dictionary
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2194,
"s": 2052,
"text": "This chapter will help you in learning about the various transformations in Gensim. Let us begin by understanding the transforming documents."
},
{
"code": null,
"e": 2433,
"s": 2194,
"text": "Transforming documents means to represent the document in such a way that the document can be manipulated mathematically. Apart from deducing the latent structure of the corpus, transforming documents will also serve the following goals −"
},
{
"code": null,
"e": 2478,
"s": 2433,
"text": "It discovers the relationship between words."
},
{
"code": null,
"e": 2523,
"s": 2478,
"text": "It discovers the relationship between words."
},
{
"code": null,
"e": 2573,
"s": 2523,
"text": "It brings out the hidden structure in the corpus."
},
{
"code": null,
"e": 2623,
"s": 2573,
"text": "It brings out the hidden structure in the corpus."
},
{
"code": null,
"e": 2682,
"s": 2623,
"text": "It describes the documents in a new and more semantic way."
},
{
"code": null,
"e": 2741,
"s": 2682,
"text": "It describes the documents in a new and more semantic way."
},
{
"code": null,
"e": 2800,
"s": 2741,
"text": "It makes the representation of the documents more compact."
},
{
"code": null,
"e": 2859,
"s": 2800,
"text": "It makes the representation of the documents more compact."
},
{
"code": null,
"e": 2934,
"s": 2859,
"text": "It improves efficiency because new representation consumes less resources."
},
{
"code": null,
"e": 3009,
"s": 2934,
"text": "It improves efficiency because new representation consumes less resources."
},
{
"code": null,
"e": 3094,
"s": 3009,
"text": "It improves efficacy because in new representation marginal data trends are ignored."
},
{
"code": null,
"e": 3179,
"s": 3094,
"text": "It improves efficacy because in new representation marginal data trends are ignored."
},
{
"code": null,
"e": 3237,
"s": 3179,
"text": "The noise is also reduced in new document representation."
},
{
"code": null,
"e": 3295,
"s": 3237,
"text": "The noise is also reduced in new document representation."
},
{
"code": null,
"e": 3410,
"s": 3295,
"text": "Let’s see the implementation steps for transforming the documents from one vector space representation to another."
},
{
"code": null,
"e": 3480,
"s": 3410,
"text": "In order to transform documents, we must follow the following steps −"
},
{
"code": null,
"e": 3721,
"s": 3480,
"text": "The very first and basic step is to create the corpus from the documents. We have already created the corpus in previous examples. Let’s create another one with some enhancements (removing common words and the words that appear only once) −"
},
{
"code": null,
"e": 3812,
"s": 3721,
"text": "import gensim\nimport pprint\nfrom collections import defaultdict\nfrom gensim import corpora"
},
{
"code": null,
"e": 3864,
"s": 3812,
"text": "Now provide the documents for creating the corpus −"
},
{
"code": null,
"e": 4257,
"s": 3864,
"text": "t_corpus = [\"CNTK formerly known as Computational Network Toolkit\", \"is a free easy-to-use open-source commercial-grade toolkit\", \"that enable us to train deep learning algorithms to learn like the human brain.\", \"You can find its free tutorial on tutorialspoint.com\", \"Tutorialspoint.com also provide best technical tutorials on technologies like AI deep learning machine learning for free\"]"
},
{
"code": null,
"e": 4343,
"s": 4257,
"text": "Next, we need to do tokenise and along with it we will remove the common words also −"
},
{
"code": null,
"e": 4526,
"s": 4343,
"text": "stoplist = set('for a of the and to in'.split(' '))\nprocessed_corpus = [\n [\n word for word in document.lower().split() if word not in stoplist\n ]\n\tfor document in t_corpus\n]"
},
{
"code": null,
"e": 4586,
"s": 4526,
"text": "Following script will remove those words that appear only −"
},
{
"code": null,
"e": 4848,
"s": 4586,
"text": "frequency = defaultdict(int)\nfor text in processed_corpus:\n for token in text:\n frequency[token] += 1\n processed_corpus = [\n [token for token in text if frequency[token] > 1] \n for text in processed_corpus\n ]\npprint.pprint(processed_corpus)"
},
{
"code": null,
"e": 5047,
"s": 4848,
"text": "[\n ['toolkit'],\n ['free', 'toolkit'],\n ['deep', 'learning', 'like'],\n ['free', 'on', 'tutorialspoint.com'],\n ['tutorialspoint.com', 'on', 'like', 'deep', 'learning', 'learning', 'free']\n]\n"
},
{
"code": null,
"e": 5136,
"s": 5047,
"text": "Now pass it to the corpora.dictionary() object to get the unique objects in our corpus −"
},
{
"code": null,
"e": 5204,
"s": 5136,
"text": "dictionary = corpora.Dictionary(processed_corpus)\nprint(dictionary)"
},
{
"code": null,
"e": 5285,
"s": 5204,
"text": "Dictionary(7 unique tokens: ['toolkit', 'free', 'deep', 'learning', 'like']...)\n"
},
{
"code": null,
"e": 5370,
"s": 5285,
"text": "Next, the following line of codes will create the Bag of Word model for our corpus −"
},
{
"code": null,
"e": 5466,
"s": 5370,
"text": "BoW_corpus = [dictionary.doc2bow(text) for text in processed_corpus]\npprint.pprint(BoW_corpus)\n"
},
{
"code": null,
"e": 5615,
"s": 5466,
"text": "[\n [(0, 1)],\n [(0, 1), (1, 1)],\n [(2, 1), (3, 1), (4, 1)],\n [(1, 1), (5, 1), (6, 1)],\n [(1, 1), (2, 1), (3, 2), (4, 1), (5, 1), (6, 1)]\n]\n"
},
{
"code": null,
"e": 5860,
"s": 5615,
"text": "The transformations are some standard Python objects. We can initialize these transformations i.e. Python objects by using a trained corpus. Here we are going to use tf-idf model to create a transformation of our trained corpus i.e. BoW_corpus."
},
{
"code": null,
"e": 5917,
"s": 5860,
"text": "First, we need to import the models package from gensim."
},
{
"code": null,
"e": 5944,
"s": 5917,
"text": "from gensim import models\n"
},
{
"code": null,
"e": 5994,
"s": 5944,
"text": "Now, we need to initialise the model as follows −"
},
{
"code": null,
"e": 6033,
"s": 5994,
"text": "tfidf = models.TfidfModel(BoW_corpus)\n"
},
{
"code": null,
"e": 6405,
"s": 6033,
"text": "Now, in this last step, the vectors will be converted from old representation to new representation. As we have initialised the tfidf model in above step, the tfidf will now be treated as a read only object. Here, by using this tfidf object we will convert our vector from bag of word representation (old representation) to Tfidf real-valued weights (new representation)."
},
{
"code": null,
"e": 6450,
"s": 6405,
"text": "doc_BoW = [(1,1),(3,1)]\nprint(tfidf[doc_BoW]"
},
{
"code": null,
"e": 6502,
"s": 6450,
"text": "[(1, 0.4869354917707381), (3, 0.8734379353188121)]\n"
},
{
"code": null,
"e": 6615,
"s": 6502,
"text": "We applied the transformation on two values of corpus, but we can also apply it to the whole corpus as follows −"
},
{
"code": null,
"e": 6687,
"s": 6615,
"text": "corpus_tfidf = tfidf[BoW_corpus]\nfor doc in corpus_tfidf:\n print(doc)"
},
{
"code": null,
"e": 7065,
"s": 6687,
"text": "[(0, 1.0)]\n[(0, 0.8734379353188121), (1, 0.4869354917707381)]\n[(2, 0.5773502691896257), (3, 0.5773502691896257), (4, 0.5773502691896257)]\n[(1, 0.3667400603126873), (5, 0.657838022678017), (6, 0.657838022678017)]\n[\n (1, 0.19338287240886842), (2, 0.34687949360312714), (3, 0.6937589872062543), \n (4, 0.34687949360312714), (5, 0.34687949360312714), (6, 0.34687949360312714)\n]\n"
},
{
"code": null,
"e": 8370,
"s": 7065,
"text": "import gensim\nimport pprint\nfrom collections import defaultdict\nfrom gensim import corpora\nt_corpus = [\n \"CNTK formerly known as Computational Network Toolkit\", \n \"is a free easy-to-use open-source commercial-grade toolkit\", \n \"that enable us to train deep learning algorithms to learn like the human brain.\", \n \"You can find its free tutorial on tutorialspoint.com\", \n \"Tutorialspoint.com also provide best technical tutorials on \n technologies like AI deep learning machine learning for free\"\n]\nstoplist = set('for a of the and to in'.split(' '))\nprocessed_corpus = [\n [word for word in document.lower().split() if word not in stoplist]\n for document in t_corpus\n]\nfrequency = defaultdict(int)\nfor text in processed_corpus:\n for token in text:\n frequency[token] += 1\n processed_corpus = [\n [token for token in text if frequency[token] > 1] \n for text in processed_corpus\n ]\npprint.pprint(processed_corpus)\ndictionary = corpora.Dictionary(processed_corpus)\nprint(dictionary)\nBoW_corpus = [dictionary.doc2bow(text) for text in processed_corpus]\npprint.pprint(BoW_corpus)\n from gensim import models\n tfidf = models.TfidfModel(BoW_corpus)\n doc_BoW = [(1,1),(3,1)]\n print(tfidf[doc_BoW])\n corpus_tfidf = tfidf[BoW_corpus]\n for doc in corpus_tfidf:\nprint(doc)"
},
{
"code": null,
"e": 8500,
"s": 8370,
"text": "Using Gensim, we can implement various popular transformations, i.e. Vector Space Model algorithms. Some of them are as follows −"
},
{
"code": null,
"e": 8753,
"s": 8500,
"text": "During initialisation, this tf-idf model algorithm expects a training corpus having integer values (such as Bag-of-Words model). Then after that, at the time of transformation, it takes a vector representation and returns another vector representation."
},
{
"code": null,
"e": 9007,
"s": 8753,
"text": "The output vector will have the same dimensionality but the value of the rare features (at the time of training) will be increased. It basically converts integer-valued vectors into real-valued vectors. Following is the syntax of Tf-idf transformation −"
},
{
"code": null,
"e": 9056,
"s": 9007,
"text": "Model=models.TfidfModel(corpus, normalize=True)\n"
},
{
"code": null,
"e": 9311,
"s": 9056,
"text": "LSI model algorithm can transform document from either integer valued vector model (such as Bag-of-Words model) or Tf-Idf weighted space into latent space. The output vector will be of lower dimensionality. Following is the syntax of LSI transformation −"
},
{
"code": null,
"e": 9384,
"s": 9311,
"text": "Model=models.LsiModel(tfidf_corpus, id2word=dictionary, num_topics=300)\n"
},
{
"code": null,
"e": 9599,
"s": 9384,
"text": "LDA model algorithm is another algorithm that transforms document from Bag-of-Words model space into a topic space. The output vector will be of lower dimensionality. Following is the syntax of LSI transformation −"
},
{
"code": null,
"e": 9666,
"s": 9599,
"text": "Model=models.LdaModel(corpus, id2word=dictionary, num_topics=100)\n"
},
{
"code": null,
"e": 9880,
"s": 9666,
"text": "RP, a very efficient approach, aims to reduce the dimensionality of vector space. This approach is basically approximate the Tf-Idf distances between the documents. It does this by throwing in a little randomness."
},
{
"code": null,
"e": 9932,
"s": 9880,
"text": "Model=models.RpModel(tfidf_corpus, num_topics=500)\n"
},
{
"code": null,
"e": 10051,
"s": 9932,
"text": "HDP is a non-parametric Bayesian method which is a new addition to Gensim. We should have to take care while using it."
},
{
"code": null,
"e": 10101,
"s": 10051,
"text": "Model=models.HdpModel(corpus, id2word=dictionary\n"
},
{
"code": null,
"e": 10108,
"s": 10101,
"text": " Print"
},
{
"code": null,
"e": 10119,
"s": 10108,
"text": " Add Notes"
}
] |
Automate your Model Documentation using H2O AutoDoc | by Parul Pandey | Towards Data Science
|
Proper documentation is essential not only for your own credibility but the credibility of the organization you represent.
The Federal Reserve’s 2011 guidelines state that model risk assessment and management would be ineffective without adequate documentation. A similar requirement is put forward today by many regulatory and corporate governance bodies. This clearly means that model documentation today is more of a necessity than a choice. However, there is still no denying that it is one of the most time-consuming jobs for a data scientist. As opposed to building and validating machine learning models, describing how a model works in detail is tedious and takes a considerable amount of time and effort, let alone dealing with the issues of consistency, clarity, and collaboration.
What if there was a way to automate the entire documentation process? Well, this is precisely the issue that the H2O AutoDoc tries to address by creating comprehensive and high-quality model documentation in minutes. The AutoDoc feature frees up the user from the time-consuming task of documenting and summarizing their workflow while building machine learning models. Additionally, it increases the consistency of documentation by applying a standard template across all models which in a way is essential for model governance, reproducibility, and regulatory compliance.
Typical model documentation consists of the following attributes — how a model was created, the training and the test data characteristics, what alternatives were considered, model evaluation strategies, information on model performance, etc. Documenting the models is necessary both from a best practice point of view as well as a vital requirement from the business point of view. The figure below highlights the major challenges associated with documentation in the machine learning domain.
But creating good documentation isn’t a piece of cake, and at times, many teams struggle with it. The process is often tedious and time-consuming for the business because the data scientist could be using that time to build additional models and create more value. Additionally, inconsistent or inaccurate model documentation can be an issue for model validation, governance, and regulatory compliance.
A better idea: Automate the documentation process
Automated Model Documentation (H2O AutoDoc) is a new time-saving ML documentation product from H2O.ai. H2O AutoDoc can automatically generate model Documentation for supervised learning models created in H2O-3 and Scikit-Learn. Interestingly, automated documentation is already being used in production as part of H2O Driverless AI — the AutoML platform. The good news is that this industry-leading capability is now available as a new standalone module.
Inherently, H2O AutoDoc is a Python package for creating automatic reports for supervised learning models. It comes equipped with the following features:
Distributed automatic document generation in Microsoft Word (.docx) and Markdown (.md) formats.
Out-of-the-box documentation template included
Customizable templates to fit unique business needs, internal best practices, and compliance requirements
Support for a variety of supervised models generated in H2O-3 and Scikit-Learn
H2O AutoDoc provides various advantages over the traditional method of manual documentation.
H2O AutoDoc ensures compliance and provides a consistent, accurate, and thorough approach to model documentation.
It can be shared with production teams and other data scientists, thereby improving collaboration amongst teams.
Saves time and money by automatically creating model documents instead of having valuable resources writing and editing documents.
We know that H2O AutoDoc can automatically generate model documentation for supervised learning models created in H2O-3 and Scikit-Learn. Let’s see some of the ways by which we can generate the automatic report:
H2O-3 is a fully open-source, distributed in-memory machine learning platform with linear scalability. The speed, quality, ease-of-use, and model-deployment for the various cutting-edge algorithms make H2O a highly sought-after API for big data science. H2O also has an industry-leading AutoML functionality that can be used for automating the machine learning workflow.
The documentation can be generated in an editable word or a markdown format as follows:
from h2o_autodoc import Configfrom h2o_autodoc import render_autodoc# get the H2O-3 model object required to create an H2O AutoDocmodel = h2o.get_model(“my_gbm_model”)# configure and render an AutoDocConfig = Config(output_path=”full/path/AutoDoc_H2O3.docx”)render_autodoc(h2o, config, model)
Scikit-learn is an open-source software machine learning library for the Python programming language. It features various classification, regression, and clustering algorithms. The process to create automatic documentation for models created in scikit learn is also pretty similar to the ones created in H2O-3 and is as follows:
from h2o_autodoc import Configfrom h2o_autodoc.scikit.autodoc import render_autodoc# build a logistic regression modelmodel = LogisticRegression()model.fit(X_train, y_train)# configure and render an AutoDocConfig = Config(output_path=”full/path/AutoDoc_ScikitLearn.docx”)render_autodoc(config, model, X_train, y_train)
The H2O AutoDoc is also available in Steam, another H2O.ai product that allows you to launch or connect to an H2O Cluster securely. This version of the H2O AutoDoc leverages the Steam Python API. The code follows the same structure as the H2O AutoDoc Python API, and the generated report is almost identical. One difference is that the Steam version only supports H2O-3 models.
import h2osteamfrom h2osteam.clients import H2oClient# login to steamh2osteam.login(url=”https://steam.h2o.ai:9555", username=”user01", password=”token-here”, verify_ssl=True)cluster = H2oClient.get_cluster(“test-cluster”)from h2osteam import AutoDocConfig# get H2O-3 objects using their keysmodel = h2o.get_model(“gbm_model”)train = h2o.get_frame(“CreditCard_TRAIN”)# use default configuration settingsconfig = AutoDocConfig()# specify the path to the output fileoutput_file_path = “autodoc_report.docx”# download an H2O AutoDoccluster.download_autodoc(model, config, train, output_file_path)
H2O AutoDoc generates an editable Word document based on an automated template that includes several features. Some of the important ones have been tabulated below:
* For supported algorithms
Here is a short demo of how to generate the documentation for scikit-learn models.
Do you also want to get your hands dirty and experience the power that H2O AutoDoc brings to your machine learning project? If yes then we have made it easy for you. All you have to do is to register for the trial license here, and then try H2O AutoDoc in your environment. Experiment and use it with your H2O-3 and scikit-learn models and share your feedback.
H2O AutoDoc automatically generates comprehensive model documentation in minutes using out-of-the-box or custom templates. H2O AutoDoc saves data science teams weeks of tedious work and increases data science productivity by allowing them to focus on model building. H2O AutoDoc increases model documentation consistency by applying a standard template across all models and teams, which is essential for model governance, reproducibility, and compliance with regulations.
|
[
{
"code": null,
"e": 295,
"s": 172,
"text": "Proper documentation is essential not only for your own credibility but the credibility of the organization you represent."
},
{
"code": null,
"e": 964,
"s": 295,
"text": "The Federal Reserve’s 2011 guidelines state that model risk assessment and management would be ineffective without adequate documentation. A similar requirement is put forward today by many regulatory and corporate governance bodies. This clearly means that model documentation today is more of a necessity than a choice. However, there is still no denying that it is one of the most time-consuming jobs for a data scientist. As opposed to building and validating machine learning models, describing how a model works in detail is tedious and takes a considerable amount of time and effort, let alone dealing with the issues of consistency, clarity, and collaboration."
},
{
"code": null,
"e": 1538,
"s": 964,
"text": "What if there was a way to automate the entire documentation process? Well, this is precisely the issue that the H2O AutoDoc tries to address by creating comprehensive and high-quality model documentation in minutes. The AutoDoc feature frees up the user from the time-consuming task of documenting and summarizing their workflow while building machine learning models. Additionally, it increases the consistency of documentation by applying a standard template across all models which in a way is essential for model governance, reproducibility, and regulatory compliance."
},
{
"code": null,
"e": 2032,
"s": 1538,
"text": "Typical model documentation consists of the following attributes — how a model was created, the training and the test data characteristics, what alternatives were considered, model evaluation strategies, information on model performance, etc. Documenting the models is necessary both from a best practice point of view as well as a vital requirement from the business point of view. The figure below highlights the major challenges associated with documentation in the machine learning domain."
},
{
"code": null,
"e": 2435,
"s": 2032,
"text": "But creating good documentation isn’t a piece of cake, and at times, many teams struggle with it. The process is often tedious and time-consuming for the business because the data scientist could be using that time to build additional models and create more value. Additionally, inconsistent or inaccurate model documentation can be an issue for model validation, governance, and regulatory compliance."
},
{
"code": null,
"e": 2485,
"s": 2435,
"text": "A better idea: Automate the documentation process"
},
{
"code": null,
"e": 2940,
"s": 2485,
"text": "Automated Model Documentation (H2O AutoDoc) is a new time-saving ML documentation product from H2O.ai. H2O AutoDoc can automatically generate model Documentation for supervised learning models created in H2O-3 and Scikit-Learn. Interestingly, automated documentation is already being used in production as part of H2O Driverless AI — the AutoML platform. The good news is that this industry-leading capability is now available as a new standalone module."
},
{
"code": null,
"e": 3094,
"s": 2940,
"text": "Inherently, H2O AutoDoc is a Python package for creating automatic reports for supervised learning models. It comes equipped with the following features:"
},
{
"code": null,
"e": 3190,
"s": 3094,
"text": "Distributed automatic document generation in Microsoft Word (.docx) and Markdown (.md) formats."
},
{
"code": null,
"e": 3237,
"s": 3190,
"text": "Out-of-the-box documentation template included"
},
{
"code": null,
"e": 3343,
"s": 3237,
"text": "Customizable templates to fit unique business needs, internal best practices, and compliance requirements"
},
{
"code": null,
"e": 3422,
"s": 3343,
"text": "Support for a variety of supervised models generated in H2O-3 and Scikit-Learn"
},
{
"code": null,
"e": 3515,
"s": 3422,
"text": "H2O AutoDoc provides various advantages over the traditional method of manual documentation."
},
{
"code": null,
"e": 3629,
"s": 3515,
"text": "H2O AutoDoc ensures compliance and provides a consistent, accurate, and thorough approach to model documentation."
},
{
"code": null,
"e": 3742,
"s": 3629,
"text": "It can be shared with production teams and other data scientists, thereby improving collaboration amongst teams."
},
{
"code": null,
"e": 3873,
"s": 3742,
"text": "Saves time and money by automatically creating model documents instead of having valuable resources writing and editing documents."
},
{
"code": null,
"e": 4085,
"s": 3873,
"text": "We know that H2O AutoDoc can automatically generate model documentation for supervised learning models created in H2O-3 and Scikit-Learn. Let’s see some of the ways by which we can generate the automatic report:"
},
{
"code": null,
"e": 4456,
"s": 4085,
"text": "H2O-3 is a fully open-source, distributed in-memory machine learning platform with linear scalability. The speed, quality, ease-of-use, and model-deployment for the various cutting-edge algorithms make H2O a highly sought-after API for big data science. H2O also has an industry-leading AutoML functionality that can be used for automating the machine learning workflow."
},
{
"code": null,
"e": 4544,
"s": 4456,
"text": "The documentation can be generated in an editable word or a markdown format as follows:"
},
{
"code": null,
"e": 4837,
"s": 4544,
"text": "from h2o_autodoc import Configfrom h2o_autodoc import render_autodoc# get the H2O-3 model object required to create an H2O AutoDocmodel = h2o.get_model(“my_gbm_model”)# configure and render an AutoDocConfig = Config(output_path=”full/path/AutoDoc_H2O3.docx”)render_autodoc(h2o, config, model)"
},
{
"code": null,
"e": 5166,
"s": 4837,
"text": "Scikit-learn is an open-source software machine learning library for the Python programming language. It features various classification, regression, and clustering algorithms. The process to create automatic documentation for models created in scikit learn is also pretty similar to the ones created in H2O-3 and is as follows:"
},
{
"code": null,
"e": 5485,
"s": 5166,
"text": "from h2o_autodoc import Configfrom h2o_autodoc.scikit.autodoc import render_autodoc# build a logistic regression modelmodel = LogisticRegression()model.fit(X_train, y_train)# configure and render an AutoDocConfig = Config(output_path=”full/path/AutoDoc_ScikitLearn.docx”)render_autodoc(config, model, X_train, y_train)"
},
{
"code": null,
"e": 5863,
"s": 5485,
"text": "The H2O AutoDoc is also available in Steam, another H2O.ai product that allows you to launch or connect to an H2O Cluster securely. This version of the H2O AutoDoc leverages the Steam Python API. The code follows the same structure as the H2O AutoDoc Python API, and the generated report is almost identical. One difference is that the Steam version only supports H2O-3 models."
},
{
"code": null,
"e": 6457,
"s": 5863,
"text": "import h2osteamfrom h2osteam.clients import H2oClient# login to steamh2osteam.login(url=”https://steam.h2o.ai:9555\", username=”user01\", password=”token-here”, verify_ssl=True)cluster = H2oClient.get_cluster(“test-cluster”)from h2osteam import AutoDocConfig# get H2O-3 objects using their keysmodel = h2o.get_model(“gbm_model”)train = h2o.get_frame(“CreditCard_TRAIN”)# use default configuration settingsconfig = AutoDocConfig()# specify the path to the output fileoutput_file_path = “autodoc_report.docx”# download an H2O AutoDoccluster.download_autodoc(model, config, train, output_file_path)"
},
{
"code": null,
"e": 6622,
"s": 6457,
"text": "H2O AutoDoc generates an editable Word document based on an automated template that includes several features. Some of the important ones have been tabulated below:"
},
{
"code": null,
"e": 6649,
"s": 6622,
"text": "* For supported algorithms"
},
{
"code": null,
"e": 6732,
"s": 6649,
"text": "Here is a short demo of how to generate the documentation for scikit-learn models."
},
{
"code": null,
"e": 7093,
"s": 6732,
"text": "Do you also want to get your hands dirty and experience the power that H2O AutoDoc brings to your machine learning project? If yes then we have made it easy for you. All you have to do is to register for the trial license here, and then try H2O AutoDoc in your environment. Experiment and use it with your H2O-3 and scikit-learn models and share your feedback."
}
] |
MySQL query to display columns name first name, last name as full name in a single column?
|
For this, use CONCAT() method in MySQL. Let us first create a table −
mysql> create table DemoTable
(
FirstName varchar(50),
LastName varchar(50)
);
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris','Brown');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('David','Miller');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('John','Doe');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Adam','Smith');
Query OK, 1 row affected (0.25 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Chris | Brown |
| David | Miller |
| John | Doe |
| Adam | Smith |
+-----------+----------+
4 rows in set (0.00 sec)
Following is the query to concatenate first name and last name to full name −
mysql> select concat(FirstName,' ',LastName) AS FullName from DemoTable;
This will produce the following output −
+--------------+
| FullName |
+--------------+
| Chris Brown |
| David Miller |
| John Doe |
| Adam Smith |
+--------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "For this, use CONCAT() method in MySQL. Let us first create a table −"
},
{
"code": null,
"e": 1254,
"s": 1132,
"text": "mysql> create table DemoTable\n(\n FirstName varchar(50),\n LastName varchar(50)\n);\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1310,
"s": 1254,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1667,
"s": 1310,
"text": "mysql> insert into DemoTable values('Chris','Brown');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable values('David','Miller');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values('John','Doe');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable values('Adam','Smith');\nQuery OK, 1 row affected (0.25 sec)"
},
{
"code": null,
"e": 1727,
"s": 1667,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1758,
"s": 1727,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1799,
"s": 1758,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2024,
"s": 1799,
"text": "+-----------+----------+\n| FirstName | LastName |\n+-----------+----------+\n| Chris | Brown |\n| David | Miller |\n| John | Doe |\n| Adam | Smith |\n+-----------+----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2102,
"s": 2024,
"text": "Following is the query to concatenate first name and last name to full name −"
},
{
"code": null,
"e": 2175,
"s": 2102,
"text": "mysql> select concat(FirstName,' ',LastName) AS FullName from DemoTable;"
},
{
"code": null,
"e": 2216,
"s": 2175,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2377,
"s": 2216,
"text": "+--------------+\n| FullName |\n+--------------+\n| Chris Brown |\n| David Miller |\n| John Doe |\n| Adam Smith |\n+--------------+\n4 rows in set (0.00 sec)"
}
] |
What is the use of sprintf() and sscanf() functions in C language?
|
It reads data from a character string.
sscanf(string,formatspecifier,&var1,&var2,........)
String refers to the char string to read from.
Format string refers to char string containing certain required formatting information.
Var1,var2 etc., represent the individual input data items.
For example, sscanf(string,"%d%d",&hours,&minutes);
This function is used to write data to a character string.
sprintf(string,format specifier,&var1,&var2.......);
String refers to char string to write.
Format specifier refers to char string containing certain required formatting information.
Var1,var2 etc., represent the individual input data items.
Example − sprint(value,"cube of two is %d and square of two is %d\n", 2*2*2 ,2*2);
//value=cube of two is 8 and square of two is 4.
Live Demo
#include<stdio.h>
int main(){
char instring[]="Tutorials Point";
char outstring[50],string1[10],string2[10];
sscanf(instring,"%s %s",string1,string2);
printf("%s\n",string1);
printf("%s",instring);
return 0;
}
Tutorials
Tutorials Point
Live Demo
#include <stdio.h>
int main(){
char value[50];
int p = 20, q = 30, r;
r= p + q;
sprintf(value, "adding two numbers %d and %d the result is %d", p, q,r);
printf("%s", value);
return 0;
}
adding two numbers 20 and 30 the result is 50
|
[
{
"code": null,
"e": 1101,
"s": 1062,
"text": "It reads data from a character string."
},
{
"code": null,
"e": 1153,
"s": 1101,
"text": "sscanf(string,formatspecifier,&var1,&var2,........)"
},
{
"code": null,
"e": 1200,
"s": 1153,
"text": "String refers to the char string to read from."
},
{
"code": null,
"e": 1288,
"s": 1200,
"text": "Format string refers to char string containing certain required formatting information."
},
{
"code": null,
"e": 1347,
"s": 1288,
"text": "Var1,var2 etc., represent the individual input data items."
},
{
"code": null,
"e": 1399,
"s": 1347,
"text": "For example, sscanf(string,\"%d%d\",&hours,&minutes);"
},
{
"code": null,
"e": 1458,
"s": 1399,
"text": "This function is used to write data to a character string."
},
{
"code": null,
"e": 1511,
"s": 1458,
"text": "sprintf(string,format specifier,&var1,&var2.......);"
},
{
"code": null,
"e": 1550,
"s": 1511,
"text": "String refers to char string to write."
},
{
"code": null,
"e": 1641,
"s": 1550,
"text": "Format specifier refers to char string containing certain required formatting information."
},
{
"code": null,
"e": 1700,
"s": 1641,
"text": "Var1,var2 etc., represent the individual input data items."
},
{
"code": null,
"e": 1783,
"s": 1700,
"text": "Example − sprint(value,\"cube of two is %d and square of two is %d\\n\", 2*2*2 ,2*2);"
},
{
"code": null,
"e": 1832,
"s": 1783,
"text": "//value=cube of two is 8 and square of two is 4."
},
{
"code": null,
"e": 1843,
"s": 1832,
"text": " Live Demo"
},
{
"code": null,
"e": 2071,
"s": 1843,
"text": "#include<stdio.h>\nint main(){\n char instring[]=\"Tutorials Point\";\n char outstring[50],string1[10],string2[10];\n sscanf(instring,\"%s %s\",string1,string2);\n printf(\"%s\\n\",string1);\n printf(\"%s\",instring);\n return 0;\n}"
},
{
"code": null,
"e": 2097,
"s": 2071,
"text": "Tutorials\nTutorials Point"
},
{
"code": null,
"e": 2108,
"s": 2097,
"text": " Live Demo"
},
{
"code": null,
"e": 2312,
"s": 2108,
"text": "#include <stdio.h>\nint main(){\n char value[50];\n int p = 20, q = 30, r;\n r= p + q;\n sprintf(value, \"adding two numbers %d and %d the result is %d\", p, q,r);\n printf(\"%s\", value);\n return 0;\n}"
},
{
"code": null,
"e": 2358,
"s": 2312,
"text": "adding two numbers 20 and 30 the result is 50"
}
] |
Number of relations that are neither Reflexive nor Irreflexive on a Set - GeeksforGeeks
|
27 May, 2021
Given a positive intege N, the task is to find the number of relations that are neither reflexive nor irreflexive on a set of first N natural numbers. Since the count of relations can be very large, print it to modulo 109 + 7.
A relation R on a set A is called reflexive, if no (a, a) € R holds for every element a € A.For Example: If set A = {a, b} then R = {(a, b), (b, a)} is irreflexive relation.
Examples:
Input: N = 2Output: 8Explanation: Considering the set {1, 2}, the total possible relations that are neither reflexive nor irreflexive are:
{(1, 1)}{(1, 1), (1, 2)}{(1, 1), (2, 1)}{(1, 1), (1, 2), (2, 1)}{(2, 2)}{(2, 2), (2, 1)}{(2, 2), (1, 2)}{(2, 2), (2, 1), (1, 2)}
{(1, 1)}
{(1, 1), (1, 2)}
{(1, 1), (2, 1)}
{(1, 1), (1, 2), (2, 1)}
{(2, 2)}
{(2, 2), (2, 1)}
{(2, 2), (1, 2)}
{(2, 2), (2, 1), (1, 2)}
Therefore, the total count is 8.
Input: N = 3Output: 384
Approach: The given problem can be solved based on the following observations:
A relation R on a set A is a subset of the cartesian product of a set, i.e., A * A with N2 elements.
A relation will be non-reflexive if it doesn’t contain at least one pair of (x, x) and relation will be non-irreflexive if it contains at least one pair of (x, x) where x € R.
It can be concluded that the relation will be non-reflexive and non-irreflexive if it contains at least one pair of (x, x) and at most (N – 1) pairs of (x, x).
Among N pairs of (x, x), the total number of possibilities of choosing any number of pairs except 0 and N – 1 is (2N – 2). For the remaining (N2 – N) elements, each element has two choices i.e., either to include or exclude it in the subset.
From the above observations, the total number of relations that are neither reflexive nor irreflexive on a set of first N natural numbers is given by .
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; const int mod = 1000000007; // Function to calculate x^y// modulo 10^9 + 7 in O(log y)int power(long long x, unsigned int y){ // Stores the result of (x^y) int res = 1; // Update x, if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with res if (y & 1) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the value of x^y return res;} // Function to count the number// of relations that are neither// reflexive nor irreflexivevoid countRelations(int N){ // Return the resultant count cout << (power(2, N) - 2) * power(2, N * N - N);} // Driver Codeint main(){ int N = 2; countRelations(N); return 0;}
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ static int mod = 1000000007; // Function to calculate x^y// modulo 10^9 + 7 in O(log y)static int power(int x, int y){ // Stores the result of (x^y) int res = 1; // Update x, if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with res if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the value of x^y return res;} // Function to count the number// of relations that are neither// reflexive nor irreflexivestatic void countRelations(int N){ // Return the resultant count System.out.print((power(2, N) - 2) * power(2, N * N - N));} // Driver Codepublic static void main(String[] args){ int N = 2; countRelations(N);}} // This code is contributed by susmitakundugoaldanga
# Python program for the above approachmod = 1000000007 # Function to calculate x^y# modulo 10^9 + 7 in O(log y)def power(x, y): # Stores the result of (x^y) res = 1 # Update x, if it exceeds mod x = x % mod # If x is divisible by mod if(x == 0): return 0 while(y > 0): # If y is odd, then # multiply x with res if (y % 2 == 1): res = (res * x) % mod # Divide y by 2 y = y >> 1 # Update the value of x x = (x * x) % mod # Return the value of x^y return res # Function to count the number# of relations that are neither# reflexive nor irreflexivedef countRelations(N): # Return the resultant count print((power(2, N) - 2) * power(2, N * N - N)) # Driver CodeN = 2countRelations(N) # This code is contributed by abhinavjain194
// C# program for the above approachusing System; class GFG{ static int mod = 1000000007; // Function to calculate x^y// modulo 10^9 + 7 in O(log y)static int power(int x, int y){ // Stores the result of (x^y) int res = 1; // Update x, if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with res if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the value of x^y return res;} // Function to count the number// of relations that are neither// reflexive nor irreflexivestatic void countRelations(int N){ // Return the resultant count Console.Write((power(2, N) - 2) * power(2, N * N - N));} // Driver Codepublic static void Main(String[] args){ int N = 2; countRelations(N);}} // This code is contributed by 29AjayKumar
<script> // Javascript program for the above approach var mod = 1000000007; // Function to calculate x^y// modulo 10^9 + 7 in O(log y)function power(x, y){ // Stores the result of (x^y) var res = 1; // Update x, if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with res if (y %2 != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the value of x^y return res;} // Function to count the number// of relations that are neither// reflexive nor irreflexivefunction countRelations(N){ // Return the resultant count document.write((power(2, N) - 2) * power(2, (N * N) - N));} // Driver Codevar N = 2;countRelations(N); </script>
8
Time Complexity: O(log N)Auxiliary Space: O(1)
abhinavjain194
noob2000
susmitakundugoaldanga
29AjayKumar
maths-power
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Program to add two binary strings
Find Union and Intersection of two unsorted arrays
Count ways to reach the n'th stair
Add two numbers without using arithmetic operators
Program to convert a given number to words
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 24528,
"s": 24301,
"text": "Given a positive intege N, the task is to find the number of relations that are neither reflexive nor irreflexive on a set of first N natural numbers. Since the count of relations can be very large, print it to modulo 109 + 7."
},
{
"code": null,
"e": 24702,
"s": 24528,
"text": "A relation R on a set A is called reflexive, if no (a, a) € R holds for every element a € A.For Example: If set A = {a, b} then R = {(a, b), (b, a)} is irreflexive relation."
},
{
"code": null,
"e": 24712,
"s": 24702,
"text": "Examples:"
},
{
"code": null,
"e": 24851,
"s": 24712,
"text": "Input: N = 2Output: 8Explanation: Considering the set {1, 2}, the total possible relations that are neither reflexive nor irreflexive are:"
},
{
"code": null,
"e": 24980,
"s": 24851,
"text": "{(1, 1)}{(1, 1), (1, 2)}{(1, 1), (2, 1)}{(1, 1), (1, 2), (2, 1)}{(2, 2)}{(2, 2), (2, 1)}{(2, 2), (1, 2)}{(2, 2), (2, 1), (1, 2)}"
},
{
"code": null,
"e": 24989,
"s": 24980,
"text": "{(1, 1)}"
},
{
"code": null,
"e": 25006,
"s": 24989,
"text": "{(1, 1), (1, 2)}"
},
{
"code": null,
"e": 25023,
"s": 25006,
"text": "{(1, 1), (2, 1)}"
},
{
"code": null,
"e": 25048,
"s": 25023,
"text": "{(1, 1), (1, 2), (2, 1)}"
},
{
"code": null,
"e": 25057,
"s": 25048,
"text": "{(2, 2)}"
},
{
"code": null,
"e": 25074,
"s": 25057,
"text": "{(2, 2), (2, 1)}"
},
{
"code": null,
"e": 25091,
"s": 25074,
"text": "{(2, 2), (1, 2)}"
},
{
"code": null,
"e": 25116,
"s": 25091,
"text": "{(2, 2), (2, 1), (1, 2)}"
},
{
"code": null,
"e": 25149,
"s": 25116,
"text": "Therefore, the total count is 8."
},
{
"code": null,
"e": 25173,
"s": 25149,
"text": "Input: N = 3Output: 384"
},
{
"code": null,
"e": 25252,
"s": 25173,
"text": "Approach: The given problem can be solved based on the following observations:"
},
{
"code": null,
"e": 25353,
"s": 25252,
"text": "A relation R on a set A is a subset of the cartesian product of a set, i.e., A * A with N2 elements."
},
{
"code": null,
"e": 25529,
"s": 25353,
"text": "A relation will be non-reflexive if it doesn’t contain at least one pair of (x, x) and relation will be non-irreflexive if it contains at least one pair of (x, x) where x € R."
},
{
"code": null,
"e": 25689,
"s": 25529,
"text": "It can be concluded that the relation will be non-reflexive and non-irreflexive if it contains at least one pair of (x, x) and at most (N – 1) pairs of (x, x)."
},
{
"code": null,
"e": 25931,
"s": 25689,
"text": "Among N pairs of (x, x), the total number of possibilities of choosing any number of pairs except 0 and N – 1 is (2N – 2). For the remaining (N2 – N) elements, each element has two choices i.e., either to include or exclude it in the subset."
},
{
"code": null,
"e": 26083,
"s": 25931,
"text": "From the above observations, the total number of relations that are neither reflexive nor irreflexive on a set of first N natural numbers is given by ."
},
{
"code": null,
"e": 26134,
"s": 26083,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26138,
"s": 26134,
"text": "C++"
},
{
"code": null,
"e": 26143,
"s": 26138,
"text": "Java"
},
{
"code": null,
"e": 26151,
"s": 26143,
"text": "Python3"
},
{
"code": null,
"e": 26154,
"s": 26151,
"text": "C#"
},
{
"code": null,
"e": 26165,
"s": 26154,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; const int mod = 1000000007; // Function to calculate x^y// modulo 10^9 + 7 in O(log y)int power(long long x, unsigned int y){ // Stores the result of (x^y) int res = 1; // Update x, if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with res if (y & 1) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the value of x^y return res;} // Function to count the number// of relations that are neither// reflexive nor irreflexivevoid countRelations(int N){ // Return the resultant count cout << (power(2, N) - 2) * power(2, N * N - N);} // Driver Codeint main(){ int N = 2; countRelations(N); return 0;}",
"e": 27121,
"s": 26165,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ static int mod = 1000000007; // Function to calculate x^y// modulo 10^9 + 7 in O(log y)static int power(int x, int y){ // Stores the result of (x^y) int res = 1; // Update x, if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with res if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the value of x^y return res;} // Function to count the number// of relations that are neither// reflexive nor irreflexivestatic void countRelations(int N){ // Return the resultant count System.out.print((power(2, N) - 2) * power(2, N * N - N));} // Driver Codepublic static void main(String[] args){ int N = 2; countRelations(N);}} // This code is contributed by susmitakundugoaldanga",
"e": 28216,
"s": 27121,
"text": null
},
{
"code": "# Python program for the above approachmod = 1000000007 # Function to calculate x^y# modulo 10^9 + 7 in O(log y)def power(x, y): # Stores the result of (x^y) res = 1 # Update x, if it exceeds mod x = x % mod # If x is divisible by mod if(x == 0): return 0 while(y > 0): # If y is odd, then # multiply x with res if (y % 2 == 1): res = (res * x) % mod # Divide y by 2 y = y >> 1 # Update the value of x x = (x * x) % mod # Return the value of x^y return res # Function to count the number# of relations that are neither# reflexive nor irreflexivedef countRelations(N): # Return the resultant count print((power(2, N) - 2) * power(2, N * N - N)) # Driver CodeN = 2countRelations(N) # This code is contributed by abhinavjain194",
"e": 29050,
"s": 28216,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ static int mod = 1000000007; // Function to calculate x^y// modulo 10^9 + 7 in O(log y)static int power(int x, int y){ // Stores the result of (x^y) int res = 1; // Update x, if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with res if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the value of x^y return res;} // Function to count the number// of relations that are neither// reflexive nor irreflexivestatic void countRelations(int N){ // Return the resultant count Console.Write((power(2, N) - 2) * power(2, N * N - N));} // Driver Codepublic static void Main(String[] args){ int N = 2; countRelations(N);}} // This code is contributed by 29AjayKumar",
"e": 30080,
"s": 29050,
"text": null
},
{
"code": "<script> // Javascript program for the above approach var mod = 1000000007; // Function to calculate x^y// modulo 10^9 + 7 in O(log y)function power(x, y){ // Stores the result of (x^y) var res = 1; // Update x, if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with res if (y %2 != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the value of x^y return res;} // Function to count the number// of relations that are neither// reflexive nor irreflexivefunction countRelations(N){ // Return the resultant count document.write((power(2, N) - 2) * power(2, (N * N) - N));} // Driver Codevar N = 2;countRelations(N); </script>",
"e": 30973,
"s": 30080,
"text": null
},
{
"code": null,
"e": 30975,
"s": 30973,
"text": "8"
},
{
"code": null,
"e": 31024,
"s": 30977,
"text": "Time Complexity: O(log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31039,
"s": 31024,
"text": "abhinavjain194"
},
{
"code": null,
"e": 31048,
"s": 31039,
"text": "noob2000"
},
{
"code": null,
"e": 31070,
"s": 31048,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 31082,
"s": 31070,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31094,
"s": 31082,
"text": "maths-power"
},
{
"code": null,
"e": 31113,
"s": 31094,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 31126,
"s": 31113,
"text": "Mathematical"
},
{
"code": null,
"e": 31139,
"s": 31126,
"text": "Mathematical"
},
{
"code": null,
"e": 31158,
"s": 31139,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 31256,
"s": 31158,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31265,
"s": 31256,
"text": "Comments"
},
{
"code": null,
"e": 31278,
"s": 31265,
"text": "Old Comments"
},
{
"code": null,
"e": 31323,
"s": 31278,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 31355,
"s": 31323,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 31399,
"s": 31355,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 31424,
"s": 31399,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 31457,
"s": 31424,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 31491,
"s": 31457,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 31542,
"s": 31491,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 31577,
"s": 31542,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 31628,
"s": 31577,
"text": "Add two numbers without using arithmetic operators"
}
] |
Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix using Python?
|
In this section we are going to see a python program that counts negative numbers in Row-wise and Column-wise sorted matrix with optimal solution.
Row-wise and column-wise sorted array means, each value at any index is small or equal to the value at the index in next column and next row.
M = [[-40, -12, 1, 5],
[-20, -2, 5, 15],
[-22, -1, 13, 18],
[-12, 0, 15, 38]]
In above matrix M, the first column of first row is -40, which is smaller than the value at next column value in same row i.e. -12 and is also smaller than the value in next row in the same column i.e. -20 and so on.
# The matrix must be sorted in ascending order. If not, the algorithm will not work properly
matrix = [
[-40, -12, 1, 5],
[-20, -2, 5, 15],
[-22, -1, 13, 18],
[-12, 0, 15, 38]]
# To obtain the number of row
rowCount = len(matrix)
columnCount = 0
# To obtain the number of column
for i in matrix[0]:
columnCount += 1
a = 0
b = 0
count_Of_Negative_Integer = 0
while a < rowCount and b < columnCount:
if matrix[a][b] >= 0:
a += 1
b = 0
else:
count_Of_Negative_Integer += 1
b += 1
print("Count of Negative Integers in sorted Matrix is: ",count_Of_Negative_Integer)
Count of Negative Integers in sorted Matrix is: 7
In above program,
>=0: first we try to find the count of negative integer, less than 0.
>=0: first we try to find the count of negative integer, less than 0.
Because in above program, we are trying to get negative integers, however, same program can be used to find the count of integer that is less than any particular integers(n). For example to find the count of integer that is less than or equal to 5 using >5.
Because in above program, we are trying to get negative integers, however, same program can be used to find the count of integer that is less than any particular integers(n). For example to find the count of integer that is less than or equal to 5 using >5.
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "In this section we are going to see a python program that counts negative numbers in Row-wise and Column-wise sorted matrix with optimal solution."
},
{
"code": null,
"e": 1352,
"s": 1209,
"text": "Row-wise and column-wise sorted array means, each value at any index is small or equal to the value at the index in next column and next row. "
},
{
"code": null,
"e": 1430,
"s": 1352,
"text": "M = [[-40, -12, 1, 5],\n[-20, -2, 5, 15],\n[-22, -1, 13, 18],\n[-12, 0, 15, 38]]"
},
{
"code": null,
"e": 1647,
"s": 1430,
"text": "In above matrix M, the first column of first row is -40, which is smaller than the value at next column value in same row i.e. -12 and is also smaller than the value in next row in the same column i.e. -20 and so on."
},
{
"code": null,
"e": 2260,
"s": 1647,
"text": "# The matrix must be sorted in ascending order. If not, the algorithm will not work properly\nmatrix = [\n [-40, -12, 1, 5],\n [-20, -2, 5, 15],\n [-22, -1, 13, 18],\n [-12, 0, 15, 38]]\n# To obtain the number of row\nrowCount = len(matrix)\ncolumnCount = 0\n\n# To obtain the number of column\nfor i in matrix[0]:\n columnCount += 1\n a = 0\n b = 0\n count_Of_Negative_Integer = 0\nwhile a < rowCount and b < columnCount:\n if matrix[a][b] >= 0:\n a += 1\n b = 0\n else:\n count_Of_Negative_Integer += 1\n b += 1\nprint(\"Count of Negative Integers in sorted Matrix is: \",count_Of_Negative_Integer)"
},
{
"code": null,
"e": 2310,
"s": 2260,
"text": "Count of Negative Integers in sorted Matrix is: 7"
},
{
"code": null,
"e": 2328,
"s": 2310,
"text": "In above program,"
},
{
"code": null,
"e": 2398,
"s": 2328,
"text": ">=0: first we try to find the count of negative integer, less than 0."
},
{
"code": null,
"e": 2468,
"s": 2398,
"text": ">=0: first we try to find the count of negative integer, less than 0."
},
{
"code": null,
"e": 2726,
"s": 2468,
"text": "Because in above program, we are trying to get negative integers, however, same program can be used to find the count of integer that is less than any particular integers(n). For example to find the count of integer that is less than or equal to 5 using >5."
},
{
"code": null,
"e": 2984,
"s": 2726,
"text": "Because in above program, we are trying to get negative integers, however, same program can be used to find the count of integer that is less than any particular integers(n). For example to find the count of integer that is less than or equal to 5 using >5."
}
] |
C++ Quick Guide
|
C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic programming.
C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
Note − A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time.
C++ fully supports object-oriented programming, including the four pillars of object-oriented development −
Encapsulation
Data hiding
Inheritance
Polymorphism
Standard C++ consists of three important parts −
The core language giving all the building blocks including variables, data types and literals, etc.
The core language giving all the building blocks including variables, data types and literals, etc.
The C++ Standard Library giving a rich set of functions manipulating files, strings, etc.
The C++ Standard Library giving a rich set of functions manipulating files, strings, etc.
The Standard Template Library (STL) giving a rich set of methods manipulating data structures, etc.
The Standard Template Library (STL) giving a rich set of methods manipulating data structures, etc.
The ANSI standard is an attempt to ensure that C++ is portable; that code you write for Microsoft's compiler will compile without errors, using a compiler on a Mac, UNIX, a Windows box, or an Alpha.
The ANSI standard has been stable for a while, and all the major C++ compiler manufacturers support the ANSI standard.
The most important thing while learning C++ is to focus on concepts.
The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones.
C++ supports a variety of programming styles. You can write in the style of Fortran, C, Smalltalk, etc., in any language. Each style can achieve its aims effectively while maintaining runtime and space efficiency.
C++ is used by hundreds of thousands of programmers in essentially every application domain.
C++ is being highly used to write device drivers and other software that rely on direct manipulation of hardware under realtime constraints.
C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts.
Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interfaces of these systems are written in C++.
If you are still willing to set up your environment for C++, you need to have the following two softwares on your computer.
This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows as well as Linux, or UNIX.
The files you create with your editor are called source files and for C++ they typically are named with the extension .cpp, .cp, or .c.
A text editor should be in place to start your C++ programming.
This is an actual C++ compiler, which will be used to compile your source code into final executable program.
Most C++ compilers don't care what extension you give to your source code, but if you don't specify otherwise, many will use .cpp by default.
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective Operating Systems.
If you are using Linux or UNIX then check whether GCC is installed on your system by entering the following command from the command line −
$ g++ -v
If you have installed GCC, then it should print a message such as the following −
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's website and follow the simple installation instructions.
Xcode is currently available at developer.apple.com/technologies/tools/.
To install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program which should be named MinGW-<version>.exe.
While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can specify these tools on the command line by their simple names.
When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line.
When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what a class, object, methods, and instant variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support.
Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
Let us look at a simple code that would print the words Hello World.
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
Let us look at the various parts of the above program −
The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.
The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.
The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.
The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
The line int main() is the main function where program execution begins.
The line int main() is the main function where program execution begins.
The next line cout << "Hello World"; causes the message "Hello World" to be displayed on the screen.
The next line cout << "Hello World"; causes the message "Hello World" to be displayed on the screen.
The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.
The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.
Let's look at how to save the file, compile and run the program. Please follow the steps given below −
Open a text editor and add the code as above.
Open a text editor and add the code as above.
Save the file as: hello.cpp
Save the file as: hello.cpp
Open a command prompt and go to the directory where you saved the file.
Open a command prompt and go to the directory where you saved the file.
Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file.
Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file.
Now, type 'a.out' to run your program.
Now, type 'a.out' to run your program.
You will be able to see ' Hello World ' printed on the window.
You will be able to see ' Hello World ' printed on the window.
$ g++ hello.cpp
$ ./a.out
Hello World
Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp.
You can compile C/C++ programs using makefile. For more details, you can check our 'Makefile Tutorial'.
In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.
For example, following are three different statements −
x = y;
y = y + 1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and closing braces. For example −
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a statement in a line. For example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C++.
Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names.
A few characters have an alternative representation, called a trigraph sequence. A trigraph is a three-character sequence that represents a single character and the sequence always starts with two question marks.
Trigraphs are expanded anywhere they appear, including within string literals and character literals, in comments, and in preprocessor directives.
Following are most frequently used trigraph sequences −
All the compilers do not support trigraphs and they are not advised to be used because of their confusing nature.
A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler totally ignores it.
Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins.
int age;
In the above statement there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them.
fruit = apples + oranges; // Get the total fruit
In the above statement 2, no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.
Program comments are explanatory statements that you can include in the C++ code. These comments help anyone reading the source code. All programming languages allow for some form of comments.
C++ supports single-line and multi-line comments. All characters available inside any comment are ignored by C++ compiler.
C++ comments start with /* and end with */. For example −
/* This is a comment */
/* C++ comments can also
* span multiple lines
*/
A comment can also start with //, extending to the end of the line. For example −
#include <iostream>
using namespace std;
main() {
cout << "Hello World"; // prints Hello World
return 0;
}
When the above code is compiled, it will ignore // prints Hello World and final executable will produce the following result −
Hello World
Within a /* and */ comment, // characters have no special meaning. Within a // comment, /* and */ have no special meaning. Thus, you can "nest" one kind of comment within the other kind. For example −
/* Comment out printing of Hello World:
cout << "Hello World"; // prints Hello World
*/
While writing program in any language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character, integer, floating point, double floating point, boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.
C++ offers the programmer a rich assortment of built-in as well as user defined data types. Following table lists down seven basic C++ data types −
Several of the basic types can be modified using one or more of these type modifiers −
signed
unsigned
short
long
The following table shows the variable type, how much memory it takes to store the value in memory, and what is maximum and minimum value which can be stored in such type of variables.
The size of variables might be different from those shown in the above table, depending on the compiler and the computer you are using.
Following is the example, which will produce correct size of various data types on your computer.
#include <iostream>
using namespace std;
int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
This example uses endl, which inserts a new-line character after every line and << operator is being used to pass multiple values out to the screen. We are also using sizeof() operator to get size of various data types.
When the above code is compiled and executed, it produces the following result which can vary from machine to machine −
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
You can create a new name for an existing type using typedef. Following is the simple syntax to define a new type using typedef −
typedef type newname;
For example, the following tells the compiler that feet is another name for int −
typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable called distance −
feet distance;
An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each enumerator is a constant whose type is the enumeration.
Creating an enumeration requires the use of the keyword enum. The general form of an enumeration type is −
enum enum-name { list of names } var-list;
Here, the enum-name is the enumeration's type name. The list of names is comma separated.
For example, the following code defines an enumeration of colors called colors and the variable c of type color. Finally, c is assigned the value "blue".
enum color { red, green, blue } c;
c = blue;
By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and so on. But you can give a name, a specific value by adding an initializer. For example, in the following enumeration, green will have the value 5.
enum color { red, green = 5, blue };
Here, blue will have a value of 6 because each name will be one greater than the one that precedes it.
A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive −
There are following basic types of variable in C++ as explained in last chapter −
bool
Stores either value true or false.
char
Typically a single octet (one byte). This is an integer type.
int
The most natural size of integer for the machine.
float
A single-precision floating point value.
double
A double-precision floating point value.
void
Represents the absence of type.
wchar_t
A wide character type.
C++ also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes.
Following section will cover how to define, declare and use various types of variables.
A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.
A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable definition at the time of linking of the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your C++ program, but it can be defined only once in a file, a function or a block of code.
Try the following example where a variable has been declared at the top, but it has been defined inside the main function −
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
30
23.3333
Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
There are two kinds of expressions in C++ −
lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −
int g = 20;
But the following is not a valid statement and would generate compile-time error −
10 = 20;
A scope is a region of the program and broadly speaking there are three places, where variables can be declared −
Inside a function or a block which is called local variables,
Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters.
In the definition of function parameters which is called formal parameters.
Outside of all functions which is called global variables.
Outside of all functions which is called global variables.
We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local and global variables.
Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables −
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables −
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value of local variable inside a function will take preference. For example −
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following result −
10
When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −
It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result.
Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.
Again, constants are treated just like regular variables except that their values cannot be modified after their definition.
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
Following are other examples of various types of Integer literals −
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction
There are two Boolean literals and they are part of standard C++ keywords −
A value of true representing true.
A value of true representing true.
A value of false representing false.
A value of false representing false.
You should not consider the value of true equal to 1 and value of false equal to 0.
Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable . Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
There are certain characters in C++ when they are preceded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes −
Following is the example to show a few escape sequence characters −
#include <iostream>
using namespace std;
int main() {
cout << "Hello\tWorld\n\n";
return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
String literals are enclosed in double quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separate them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
There are two simple ways in C++ to define constants −
Using #define preprocessor.
Using #define preprocessor.
Using const keyword.
Using const keyword.
Following is the form to use #define preprocessor to define a constant −
#define identifier value
Following example explains it in detail −
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
When the above code is compiled and executed, it produces the following result −
50
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
Following example explains it in detail −
#include <iostream>
using namespace std;
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
When the above code is compiled and executed, it produces the following result −
50
Note that it is a good programming practice to define constants in CAPITALS.
C++ allows the char, int, and double data types to have modifiers preceding them. A modifier is used to alter the meaning of the base type so that it more precisely fits the needs of various situations.
The data type modifiers are listed here −
signed
unsigned
long
short
The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition, signed and unsigned can be applied to char, and long can be applied to double.
The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example, unsigned long int.
C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without int. It automatically implies int. For example, the following two statements both declare unsigned integer variables.
unsigned x;
unsigned int y;
To understand the difference between the way signed and unsigned integer modifiers are interpreted by C++, you should run the following short program −
#include <iostream>
using namespace std;
/* This program shows the difference between
* signed and unsigned integers.
*/
int main() {
short int i; // a signed short integer
short unsigned int j; // an unsigned short integer
j = 50000;
i = j;
cout << i << " " << j;
return 0;
}
When this program is run, following is the output −
-15536 50000
The above result is because the bit pattern that represents 50,000 as a short unsigned integer is interpreted as -15,536 by a short.
The type qualifiers provide additional information about the variables they precede.
const
Objects of type const cannot be changed by your program during execution.
volatile
The modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program.
restrict
A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Only C99 adds a new type qualifier called restrict.
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program
auto
register
static
extern
mutable
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables.
The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared.
In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.
#include <iostream>
// Function declaration
void func(void);
static int count = 10; /* Global variable */
main() {
while(count--) {
func();
}
return 0;
}
// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.
#include <iostream>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
#include <iostream>
extern int count;
void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}
Here, extern keyword is being used to declare count in another file. Now compile these two files as follows −
$g++ main.cpp support.cpp -o write
This will produce write executable program, try to execute write and check the result as follows −
$./write
5
The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member of an object to override const member function. That is, a mutable member can be modified by a const member function.
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provide the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one.
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Show Examples
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Show Examples
There are following assignment operators supported by C++ language −
Show Examples
The following table lists some other operators that C++ supports.
sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and will return 4.
Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of Y.
,
Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list.
. (dot) and -> (arrow)
Member operators are used to reference individual members of classes, structures, and unions.
Cast
Casting operators convert one data type to another. For example, int(2.2000) would return 2.
&
Pointer operator & returns the address of a variable. For example &a; will give actual address of the variable.
*
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages −
C++ programming language provides the following type of loops to handle looping requirements.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C++ supports the following control statements.
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless loop by leaving the conditional expression empty.
#include <iostream>
using namespace std;
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the ‘for (;;)’ construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages −
C++ programming language provides following types of decision making statements.
An ‘if’ statement consists of a boolean expression followed by one or more statements.
An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the boolean expression is false.
A ‘switch’ statement allows a variable to be tested for equality against a list of values.
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).
You can use one ‘switch’ statement inside another ‘switch’ statement(s).
We have covered conditional operator “? :” in previous chapter which can be used to replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the parts of a function −
Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that define what the function does.
Function Body − The function body contains a collection of statements that define what the function does.
Following is the source code for a function called max(). This function takes two parameters num1 and num2 and return the biggest of both −
// function returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so following is also valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function performs defined task and when it’s return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example −
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result −
Max value is : 200
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function −
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.
When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead. Consider the following example −
#include <iostream>
using namespace std;
int sum(int a, int b = 20) {
int result;
result = a + b;
return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;
// calling a function to add the values.
result = sum(a, b);
cout << "Total value is :" << result << endl;
// calling a function again as follows.
result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120
Normally, when we work with Numbers, we use primitive data types such as int, short, long, float and double, etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types.
You have already defined numbers in various examples given in previous chapters. Here is another consolidated example to define various types of numbers in C++ −
#include <iostream>
using namespace std;
int main () {
// number definition:
short s;
int i;
long l;
float f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
In addition to the various functions you can create, C++ also includes some useful functions you can use. These functions are available in standard C and C++ libraries and called built-in functions. These are functions that can be included in your program and then use.
C++ has a rich set of mathematical operations, which can be performed on various numbers. Following table lists down some useful built-in mathematical functions available in C++.
To utilize these functions you need to include the math header file <cmath>.
double cos(double);
This function takes an angle (as a double) and returns the cosine.
double sin(double);
This function takes an angle (as a double) and returns the sine.
double tan(double);
This function takes an angle (as a double) and returns the tangent.
double log(double);
This function takes a number and returns the natural log of that number.
double pow(double, double);
The first is a number you wish to raise and the second is the power you wish to raise it t
double hypot(double, double);
If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse.
double sqrt(double);
You pass this function a number and it gives you the square root.
int abs(int);
This function returns the absolute value of an integer that is passed to it.
double fabs(double);
This function returns the absolute value of any decimal number passed to it.
double floor(double);
Finds the integer which is less than or equal to the argument passed to it.
Following is a simple example to show few of the mathematical operations −
#include <iostream>
#include <cmath>
using namespace std;
int main () {
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
sign(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
There are many cases where you will wish to generate a random number. There are actually two functions you will need to know about random number generation. The first is rand(), this function will only return a pseudo random number. The way to fix this is to first call the srand() function.
Following is a simple example to generate few random numbers. This example makes use of time() function to get the number of seconds on your system time, to randomly seed the rand() function −
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main () {
int i,j;
// set the seed
srand( (unsigned)time( NULL ) );
/* generate 10 random numbers. */
for( i = 0; i < 10; i++ ) {
// generate actual random number
j = rand();
cout <<" Random Number : " << j << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Random Number : 1748144778
Random Number : 630873888
Random Number : 2134540646
Random Number : 219404170
Random Number : 902129458
Random Number : 920445370
Random Number : 1319072661
Random Number : 257938873
Random Number : 1256201101
Random Number : 580322989
C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double,
use this statement −
double balance[10];
You can initialize C++ array elements either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representaion of the same array we discussed above −
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays −
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main () {
int n[ 10 ]; // n is an array of 10 integers
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ ) {
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;
// output each array element's value
for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}
return 0;
}
This program makes use of setw() function to format the output. When the above code is compiled and executed, it produces the following result −
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Arrays are important to C++ and should need lots of more detail. There are following few important concepts, which should be clear to a C++ programmer −
C++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.
You can generate a pointer to the first element of an array by simply specifying the array name, without any index.
You can pass to the function a pointer to an array by specifying the array's name without an index.
C++ allows a function to return an array.
C++ provides following two types of string representations −
The C-style character string.
The string class type introduced with Standard C++.
The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization, then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above-mentioned string −
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C++ supports a wide range of functions that manipulate null-terminated strings −
strcpy(s1, s2);
Copies string s2 into string s1.
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
strlen(s1);
Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
Following example makes use of few of the above-mentioned functions −
#include <iostream>
#include <cstring>
using namespace std;
int main () {
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
// copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
// concatenates str1 and str2
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
// total lenghth of str1 after concatenation
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. Let us check the following example −
#include <iostream>
#include <string>
using namespace std;
int main () {
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
// copy str1 into str3
str3 = str1;
cout << "str3 : " << str3 << endl;
// concatenates str1 and str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
// total length of str3 after concatenation
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them.
As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined −
#include <iostream>
using namespace std;
int main () {
int var1;
char var2[10];
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
There are few important operations, which we will do with the pointers very frequently. (a) We define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations −
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer −
C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.
There are four arithmetic operators that can be used on pointers: ++, --, +, -
There is a close relationship between pointers and arrays.
You can define arrays to hold a number of pointers.
C++ allows you to have pointer on a pointer and so on.
Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.
A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.
References are often confused with pointers but three major differences between references and pointers are −
You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.
Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.
A reference must be initialized when it is created. Pointers can be initialized at any time.
A reference must be initialized when it is created. Pointers can be initialized at any time.
Think of a variable name as a label attached to the variable's location in memory. You can then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the reference. For example, suppose we have the following example −
int i = 17;
We can declare reference variables for i as follows.
int& r = i;
Read the & in these declarations as reference. Thus, read the first declaration as "r is an integer reference initialized to i" and read the second declaration as "s is a double reference initialized to d.". Following example makes use of references on int and double −
#include <iostream>
using namespace std;
int main () {
// declare simple variables
int i;
double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
When the above code is compiled together and executed, it produces the following result −
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
References are usually used for function argument lists and function return values. So following are two important subjects related to C++ references which should be clear to a C++ programmer −
C++ supports passing references as function parameter more safely than parameters.
You can return reference from a C++ function like any other data type.
The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program.
There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer.
The structure type tm holds the date and time in the form of a C structure having the following elements −
struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
}
Following are the important functions, which we use while working with date and time in C or C++. All these functions are part of standard C and C++ library and you can check their detail using reference to C++ standard library given below.
time_t time(time_t *time);
This returns the current calendar time of the system in number of seconds elapsed since January 1, 1970. If the system has no time, .1 is returned.
char *ctime(const time_t *time);
This returns a pointer to a string of the form day month year hours:minutes:seconds year\n\0.
struct tm *localtime(const time_t *time);
This returns a pointer to the tm structure representing local time.
clock_t clock(void);
This returns a value that approximates the amount of time the calling program has been running. A value of .1 is returned if the time is not available.
char * asctime ( const struct tm * time );
This returns a pointer to a string that contains the information stored in the structure pointed to by time converted into the form: day month date hours:minutes:seconds year\n\0
struct tm *gmtime(const time_t *time);
This returns a pointer to the time in the form of a tm structure. The time is represented in Coordinated Universal Time (UTC), which is essentially Greenwich Mean Time (GMT).
time_t mktime(struct tm *time);
This returns the calendar-time equivalent of the time found in the structure pointed to by time.
double difftime ( time_t time2, time_t time1 );
This function calculates the difference in seconds between time1 and time2.
size_t strftime();
This function can be used to format date and time in a specific format.
Suppose you want to retrieve the current system date and time, either as a local time or as a Coordinated Universal Time (UTC). Following is the example to achieve the same −
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
// convert now to string form
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
// convert now to tm struct for UTC
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
}
When the above code is compiled and executed, it produces the following result −
The local date and time is: Sat Jan 8 20:07:41 2011
The UTC date and time is:Sun Jan 9 03:07:41 2011
The tm structure is very important while working with date and time in either C or C++. This structure holds the date and time in the form of a C structure as mentioned above. Most of the time related functions makes use of tm structure. Following is an example which makes use of various date and time related functions and tm structure −
While using structure in this chapter, I'm making an assumption that you have basic understanding on C structure and how to access structure members using arrow -> operator.
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
cout << "Number of sec since January 1,1970 is:: " << now << endl;
tm *ltm = localtime(&now);
// print various components of tm structure.
cout << "Year:" << 1900 + ltm->tm_year<<endl;
cout << "Month: "<< 1 + ltm->tm_mon<< endl;
cout << "Day: "<< ltm->tm_mday << endl;
cout << "Time: "<< 5+ltm->tm_hour << ":";
cout << 30+ltm->tm_min << ":";
cout << ltm->tm_sec << endl;
}
When the above code is compiled and executed, it produces the following result −
Number of sec since January 1,1970 is:: 1588485717
Year:2020
Month: 5
Day: 3
Time: 11:31:57
The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called output operation.
There are following header files important to C++ programs −
<iostream>
This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively.
<iomanip>
This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision.
<fstream>
This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter.
The predefined object cout is an instance of ostream class. The cout object is said to be "connected to" the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example.
#include <iostream>
using namespace std;
int main() {
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
}
When the above code is compiled and executed, it produces the following result −
Value of str is : Hello C++
The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line.
The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example.
#include <iostream>
using namespace std;
int main() {
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}
When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the following result −
Please enter your name: cplusplus
Your name is: cplusplus
The C++ compiler also determines the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables.
The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following −
cin >> name >> age;
This will be equivalent to the following two statements −
cin >> name;
cin >> age;
The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately.
The cerr is also used in conjunction with the stream insertion operator as shown in the following example.
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the following result −
Error message : Unable to read....
The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed.
The clog is also used in conjunction with the stream insertion operator as shown in the following example.
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read....";
clog << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the following result −
Error message : Unable to read....
You would not be able to see any difference in cout, cerr and clog with these small examples, but while writing and executing big programs the difference becomes obvious. So it is good practice to display error messages using cerr stream and while displaying other log messages then clog should be used.
C/C++ arrays allow you to define variables that combine several data items of the same kind, but structure is another user defined data type which allows you to combine data items of different kinds.
Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure −
#include <iostream>
#include <cstring>
using namespace std;
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
// Print Book1 info
cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;
// Print Book2 info
cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700
You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example −
#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books book );
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
// Print Book1 info
printBook( Book1 );
// Print Book2 info
printBook( Book2 );
return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
When the above code is compiled and executed, it produces the following result −
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
You can define pointers to structures in very similar way as you define pointer to any other variable as follows −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the -> operator as follows −
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept −
#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books *book );
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
// Print Book1 info, passing address of structure
printBook( &Book1 );
// Print Book1 info, passing address of structure
printBook( &Book2 );
return 0;
}
// This function accept pointer to structure as parameter.
void printBook( struct Books *book ) {
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}
When the above code is compiled and executed, it produces the following result −
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
There is an easier way to define structs or you could "alias" types you create. For example −
typedef struct {
char title[50];
char author[50];
char subject[100];
int book_id;
} Books;
Now, you can use Books directly to define variables of Books type without using struct keyword. Following is the example −
Books Book1, Book2;
You can use typedef keyword for non-structs as well as follows −
typedef long int *pint32;
pint32 x, y, z;
x, y and z are all pointers to long ints.
The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types.
A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that follows it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section.
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box −
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.
The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try the following example to make the things clear −
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
It is important to note that private and protected members can not be accessed directly using direct member access operator (.). We will learn how private and protected members can be accessed.
So far, you have got very basic idea about C++ Classes and Objects. There are further interesting concepts related to C++ Classes and Objects which we will discuss in various sub-sections listed below −
A member function of a class is a function that has its definition or its prototype within the class definition like any other variable.
A class member can be defined as public, private or protected. By default members would be assumed as private.
A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted.
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
A friend function is permitted full access to private and protected members of a class.
With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function.
Every object has a special pointer this which points to the object itself.
A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it.
Both data members and function members of a class can be declared as static.
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.
A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form −
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows −
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.
We can summarize the different access types according to - who can access them in the following way −
A derived class inherits all base class methods with the following exceptions −
Constructors, destructors and copy constructors of the base class.
Overloaded operators of the base class.
The friend functions of the base class.
When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. The type of inheritance is specified by the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance is commonly used. While using different type of inheritance, following rules are applied −
Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.
Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.
Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class.
Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class.
A C++ class can inherit members from more than one class and here is the extended syntax −
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every base class and they will be separated by comma as shown above. Let us try the following example −
#include <iostream>
using namespace std;
// Base class Shape
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Base class PaintCost
class PaintCost {
public:
int getCost(int area) {
return area * 70;
}
};
// Derived class
class Rectangle: public Shape, public PaintCost {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
// Print the total cost of painting
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Total paint cost: $2450
C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that is declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different data types −
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void) {
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows −
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below −
#include <iostream>
using namespace std;
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Following is the list of operators which can be overloaded −
Following is the list of operators, which can not be overloaded −
Here are various operator overloading examples to help you in understanding the concept.
The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two classes −
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
}
When the above code is compiled and executed, it produces the following result −
Parent class area :
Parent class area :
The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage - the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program.
But now, let's make a slight modification in our program and precede the declaration of area() in the Shape class with the keyword virtual so that it looks like this −
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
After this slight modification, when the previous example code is compiled and executed, it produces the following result −
Rectangle class area
Triangle class area
This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called.
As you can see, each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations.
A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding.
It is possible that you want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class.
We can change the virtual function area() in the base class to the following −
class Shape {
protected:
int width, height;
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
// pure virtual function
virtual int area() = 0;
};
The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function.
Data abstraction refers to providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know its internal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen.
Thus, we can say a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having any knowledge of its internals.
In C++, classes provides great level of data abstraction. They provide sufficient public methods to the outside world to play with the functionality of the object and to manipulate object data, i.e., state without actually knowing how class has been implemented internally.
For example, your program can make a call to the sort() function without knowing what algorithm the function actually uses to sort the given values. In fact, the underlying implementation of the sorting functionality could change between releases of the library, and as long as the interface stays the same, your function call will still work.
In C++, we use classes to define our own abstract data types (ADT). You can use the cout object of class ostream to stream data to standard output like this −
#include <iostream>
using namespace std;
int main() {
cout << "Hello C++" <<endl;
return 0;
}
Here, you don't need to understand how cout displays the text on the user's screen. You need to only know the public interface and the underlying implementation of ‘cout’ is free to change.
In C++, we use access labels to define the abstract interface to the class. A class may contain zero or more access labels −
Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members.
Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members.
Members defined with a private label are not accessible to code that uses the class. The private sections hide the implementation from code that uses the type.
Members defined with a private label are not accessible to code that uses the class. The private sections hide the implementation from code that uses the type.
There are no restrictions on how often an access label may appear. Each access label specifies the access level of the succeeding member definitions. The specified access level remains in effect until the next access label is encountered or the closing right brace of the class body is seen.
Data abstraction provides two important advantages −
Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object.
Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object.
The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code.
The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code.
By defining data members only in the private section of the class, the class author is free to make changes in the data. If the implementation changes, only the class code needs to be examined to see what affect the change may have. If data is public, then any function that directly access the data members of the old representation might be broken.
Any C++ program where you implement a class with public and private members is an example of data abstraction. Consider the following example −
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
// interface to outside world
void addNum(int number) {
total += number;
}
// interface to outside world
int getTotal() {
return total;
};
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total 60
Above class adds numbers together, and returns the sum. The public members - addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that the user doesn't need to know about, but is needed for the class to operate properly.
Abstraction separates code into interface and implementation. So while designing your component, you must keep interface independent of the implementation so that if you change underlying implementation then interface would remain intact.
In this case whatever programs are using these interfaces, they would not be impacted and would just need a recompilation with the latest implementation.
All C++ programs are composed of the following two fundamental elements −
Program statements (code) − This is the part of a program that performs actions and they are called functions.
Program statements (code) − This is the part of a program that performs actions and they are called functions.
Program data − The data is the information of the program which gets affected by the program functions.
Program data − The data is the information of the program which gets affected by the program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. For example −
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as many of the details of each class hidden from all other classes as possible.
Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example −
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
// interface to outside world
void addNum(int number) {
total += number;
}
// interface to outside world
int getTotal() {
return total;
};
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total 60
Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly.
Most of us have learnt to make class members private by default unless we really need to expose them. That's just good encapsulation.
This is applied most frequently to data members, but it applies equally to all members, including virtual functions.
An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class.
The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data.
A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration as follows −
class Box {
public:
// pure virtual function
virtual double getVolume() = 0;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error.
Classes that can be used to instantiate objects are called concrete classes.
Consider the following example where parent class provides an interface to the base class to implement a function called getArea() −
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
class Triangle: public Shape {
public:
int getArea() {
return (width * height)/2;
}
};
int main(void) {
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total Rectangle area: 35
Total Triangle area: 17
You can see how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape.
An object-oriented system might use an abstract base class to provide a common and standardized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that operate similarly.
The capabilities (i.e., the public functions) offered by the external applications are provided as pure virtual functions in the abstract base class. The implementations of these pure virtual functions are provided in the derived classes that correspond to the specific types of the application.
This architecture also allows new applications to be added to a system easily, even after the system has been defined.
So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively.
This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types −
ofstream
This data type represents the output file stream and is used to create files and to write information to files.
ifstream
This data type represents the input file stream and is used to read information from files.
fstream
This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.
ios::app
Append mode. All output to that file to be appended to the end.
ios::ate
Open a file for output and move the read/write control to the end of the file.
ios::in
Open a file for reading.
ios::out
Open a file for writing.
ios::trunc
If the file already exists, its contents will be truncated before opening the file.
You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
void close();
While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.
You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.
Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen −
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
When the above code is compiled and executed, it produces the following sample input and output −
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.
Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file's starting location. Some examples of positioning the "get" file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );
// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );
// position n bytes back from end of fileObject
fileObject.seekg( n, ios::end );
// position at end of fileObject
fileObject.seekg( 0, ios::end );
An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.
throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.
Exceptions can be thrown anywhere within a code block using throw statement. The operand of the throw statement determines a type for the exception and can be any expression and the type of the result of the expression determines the type of exception thrown.
Following is an example of throwing an exception when dividing by zero condition occurs −
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
The catch block following the try block catches any exception. You can specify what type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify that a catch block should handle any type of exception that is thrown in a try block, you must put an ellipsis, ..., between the parentheses enclosing the exception declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch it in catch block.
#include <iostream>
using namespace std;
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Because we are raising an exception of type const char*, so while catching this exception, we have to use const char* in catch block. If we compile and run above code, this would produce the following result −
Division by zero condition!
C++ provides a list of standard exceptions defined in <exception> which we can use in our programs. These are arranged in a parent-child class hierarchy shown below −
Here is the small description of each exception mentioned in the above hierarchy −
std::exception
An exception and parent class of all the standard C++ exceptions.
std::bad_alloc
This can be thrown by new.
std::bad_cast
This can be thrown by dynamic_cast.
std::bad_exception
This is useful device to handle unexpected exceptions in a C++ program.
std::bad_typeid
This can be thrown by typeid.
std::logic_error
An exception that theoretically can be detected by reading the code.
std::domain_error
This is an exception thrown when a mathematically invalid domain is used.
std::invalid_argument
This is thrown due to invalid arguments.
std::length_error
This is thrown when a too big std::string is created.
std::out_of_range
This can be thrown by the 'at' method, for example a std::vector and std::bitset<>::operator[]().
std::runtime_error
An exception that theoretically cannot be detected by reading the code.
std::overflow_error
This is thrown if a mathematical overflow occurs.
std::range_error
This is occurred when you try to store a value which is out of range.
std::underflow_error
This is thrown if a mathematical underflow occurs.
You can define your own exceptions by inheriting and overriding exception class functionality. Following is the example, which shows how you can use std::exception class to implement your own exception in standard way −
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception {
const char * what () const throw () {
return "C++ Exception";
}
};
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}
This would produce the following result −
MyException caught
C++ Exception
Here, what() is a public method provided by exception class and it has been overridden by all the child exception classes. This returns the cause of an exception.
A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++ programmer. Memory in your C++ program is divided into two parts −
The stack − All variables declared inside the function will take up memory from the stack.
The stack − All variables declared inside the function will take up memory from the stack.
The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs.
The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs.
Many times, you are not aware in advance how much memory you will need to store particular information in a defined variable and the size of required memory can be determined at run time.
You can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator.
If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-allocates memory that was previously allocated by new operator.
There is following generic syntax to use new operator to allocate memory dynamically for any data-type.
new data-type;
Here, data-type could be any built-in data type including an array or any user defined data types include class or structure. Let us start with built-in data types. For example we can define a pointer to type double and then request that the memory be allocated at execution time. We can do this using the new operator with the following statements −
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below −
double* pvalue = NULL;
if( !(pvalue = new double )) {
cout << "Error: out of memory." <<endl;
exit(1);
}
The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn't just allocate memory, it constructs objects which is prime purpose of C++.
At any point, when you feel a variable that has been dynamically allocated is not anymore required, you can free up the memory that it occupies in the free store with the ‘delete’ operator as follows −
delete pvalue; // Release memory pointed to by pvalue
Let us put above concepts and form the following example to show how ‘new’ and ‘delete’ work −
#include <iostream>
using namespace std;
int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
*pvalue = 29494.99; // Store value at allocated address
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue; // free up the memory.
return 0;
}
If we compile and run above code, this would produce the following result −
Value of pvalue : 29495
Consider you want to allocate memory for an array of characters, i.e., string of 20 characters. Using the same syntax what we have used above we can allocate memory dynamically as shown below.
char* pvalue = NULL; // Pointer initialized with null
pvalue = new char[20]; // Request memory for the variable
To remove the array that we have just created the statement would look like this −
delete [] pvalue; // Delete array pointed to by pvalue
Following the similar generic syntax of new operator, you can allocate for a multi-dimensional array as follows −
double** pvalue = NULL; // Pointer initialized with null
pvalue = new double [3][4]; // Allocate memory for a 3x4 array
However, the syntax to release the memory for multi-dimensional array will still remain same as above −
delete [] pvalue; // Delete array pointed to by pvalue
Objects are no different from simple data types. For example, consider the following code where we are going to use an array of objects to clarify the concept −
#include <iostream>
using namespace std;
class Box {
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};
int main() {
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete array
return 0;
}
If you were to allocate an array of four Box objects, the Simple constructor would be called four times and similarly while deleting these objects, destructor will also be called same number of times.
If we compile and run above code, this would produce the following result −
Constructor called!
Constructor called!
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!
Consider a situation, when we have two persons with the same name, Zara, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother’s or father’s name, etc.
Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
A namespace definition begins with the keyword namespace followed by the namespace name as follows −
namespace namespace_name {
// code declarations
}
To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows −
name::code; // code could be variable or function.
Let us see how namespace scope the entities including variable and functions −
#include <iostream>
using namespace std;
// first name space
namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
}
// second name space
namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}
int main () {
// Calls function from first name space.
first_space::func();
// Calls function from second name space.
second_space::func();
return 0;
}
If we compile and run above code, this would produce the following result −
Inside first_space
Inside second_space
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code −
#include <iostream>
using namespace std;
// first name space
namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
}
// second name space
namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}
using namespace first_space;
int main () {
// This calls function from first name space.
func();
return 0;
}
If we compile and run above code, this would produce the following result −
Inside first_space
The ‘using’ directive can also be used to refer to a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows −
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but other items in the std namespace will still need to be explicit as follows −
#include <iostream>
using std::cout;
int main () {
cout << "std::endl is used with std!" << std::endl;
return 0;
}
If we compile and run above code, this would produce the following result −
std::endl is used with std!
Names introduced in a using directive obey normal scope rules. The name is visible from the point of the using directive to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden.
A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files.
So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one −
namespace namespace_name {
// code declarations
}
Namespaces can be nested where you can define one namespace inside another name space as follows −
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
You can access members of nested namespace by using resolution operators as follows −
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace:name1
using namespace namespace_name1;
In the above statements if you are using namespace_name1, then it will make elements of namespace_name2 available in the scope as follows −
#include <iostream>
using namespace std;
// first name space
namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
// second name space
namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}
}
using namespace first_space::second_space;
int main () {
// This calls function from second name space.
func();
return 0;
}
If we compile and run above code, this would produce the following result −
Inside second_space
Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.
There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector <int> or vector <string>.
You can use templates to define functions as well as classes, let us see how they work −
The general form of a template function definition is shown here −
template <class type> ret-type func-name(parameter list) {
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.
The following is the example of a function template that returns the maximum of two values −
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b) {
return a < b ? b:a;
}
int main () {
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
If we compile and run above code, this would produce the following result −
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here −
template <class type> class class-name {
.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by using a comma-separated list.
Following is the example to define class Stack<> and implement generic methods to push and pop the elements from the stack −
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T>
class Stack {
private:
vector<T> elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const { // return true if empty.
return elems.empty();
}
};
template <class T>
void Stack<T>::push (T const& elem) {
// append copy of passed element
elems.push_back(elem);
}
template <class T>
void Stack<T>::pop () {
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}
// remove last element
elems.pop_back();
}
template <class T>
T Stack<T>::top () const {
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}
int main() {
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings
// manipulate int stack
intStack.push(7);
cout << intStack.top() <<endl;
// manipulate string stack
stringStack.push("hello");
cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
} catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}
If we compile and run above code, this would produce the following result −
7
hello
Exception: Stack<>::pop(): empty stack
The preprocessors are the directives, which give instructions to the compiler to preprocess the information before actual compilation starts.
All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not C++ statements, so they do not end in a semicolon (;).
You already have seen a #include directive in all the examples. This macro is used to include a header file into the source file.
There are number of preprocessor directives supported by C++ like #include, #define, #if, #else, #line, etc. Let us see important directives −
The #define preprocessor directive creates symbolic constants. The symbolic constant is called a macro and the general form of the directive is −
#define macro-name replacement-text
When this line appears in a file, all subsequent occurrences of macro in that file will be replaced by replacement-text before the program is compiled. For example −
#include <iostream>
using namespace std;
#define PI 3.14159
int main () {
cout << "Value of PI :" << PI << endl;
return 0;
}
Now, let us do the preprocessing of this code to see the result assuming we have the source code file. So let us compile it with -E option and redirect the result to test.p. Now, if you check test.p, it will have lots of information and at the bottom, you will find the value replaced as follows −
$gcc -E test.cpp > test.p
...
int main () {
cout << "Value of PI :" << 3.14159 << endl;
return 0;
}
You can use #define to define a macro which will take argument as follows −
#include <iostream>
using namespace std;
#define MIN(a,b) (((a)<(b)) ? a : b)
int main () {
int i, j;
i = 100;
j = 30;
cout <<"The minimum is " << MIN(i, j) << endl;
return 0;
}
If we compile and run above code, this would produce the following result −
The minimum is 30
There are several directives, which can be used to compile selective portions of your program's source code. This process is called conditional compilation.
The conditional preprocessor construct is much like the ‘if’ selection structure. Consider the following preprocessor code −
#ifndef NULL
#define NULL 0
#endif
You can compile a program for debugging purpose. You can also turn on or off the debugging using a single macro as follows −
#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif
This causes the cerr statement to be compiled in the program if the symbolic constant DEBUG has been defined before directive #ifdef DEBUG. You can use #if 0 statment to comment out a portion of the program as follows −
#if 0
code prevented from compiling
#endif
Let us try the following example −
#include <iostream>
using namespace std;
#define DEBUG
#define MIN(a,b) (((a)<(b)) ? a : b)
int main () {
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
cerr <<"Trace: Inside main function" << endl;
#endif
#if 0
/* This is commented part */
cout << MKSTR(HELLO C++) << endl;
#endif
cout <<"The minimum is " << MIN(i, j) << endl;
#ifdef DEBUG
cerr <<"Trace: Coming out of main function" << endl;
#endif
return 0;
}
If we compile and run above code, this would produce the following result −
The minimum is 30
Trace: Inside main function
Trace: Coming out of main function
The # and ## preprocessor operators are available in C++ and ANSI/ISO C. The # operator causes a replacement-text token to be converted to a string surrounded by quotes.
Consider the following macro definition −
#include <iostream>
using namespace std;
#define MKSTR( x ) #x
int main () {
cout << MKSTR(HELLO C++) << endl;
return 0;
}
If we compile and run above code, this would produce the following result −
HELLO C++
Let us see how it worked. It is simple to understand that the C++ preprocessor turns the line −
cout << MKSTR(HELLO C++) << endl;
Above line will be turned into the following line −
cout << "HELLO C++" << endl;
The ## operator is used to concatenate two tokens. Here is an example −
#define CONCAT( x, y ) x ## y
When CONCAT appears in the program, its arguments are concatenated and used to replace the macro. For example, CONCAT(HELLO, C++) is replaced by "HELLO C++" in the program as follows.
#include <iostream>
using namespace std;
#define concat(a, b) a ## b
int main() {
int xy = 100;
cout << concat(x, y);
return 0;
}
If we compile and run above code, this would produce the following result −
100
Let us see how it worked. It is simple to understand that the C++ preprocessor transforms −
cout << concat(x, y);
Above line will be transformed into the following line −
cout << xy;
C++ provides a number of predefined macros mentioned below −
__LINE__
This contains the current line number of the program when it is being compiled.
__FILE__
This contains the current file name of the program when it is being compiled.
__DATE__
This contains a string of the form month/day/year that is the date of the translation of the source file into object code.
__TIME__
This contains a string of the form hour:minute:second that is the time at which the program was compiled.
Let us see an example for all the above macros −
#include <iostream>
using namespace std;
int main () {
cout << "Value of __LINE__ : " << __LINE__ << endl;
cout << "Value of __FILE__ : " << __FILE__ << endl;
cout << "Value of __DATE__ : " << __DATE__ << endl;
cout << "Value of __TIME__ : " << __TIME__ << endl;
return 0;
}
If we compile and run above code, this would produce the following result −
Value of __LINE__ : 6
Value of __FILE__ : test.cpp
Value of __DATE__ : Feb 28 2011
Value of __TIME__ : 18:52:48
Signals are the interrupts delivered to a process by the operating system which can terminate a program prematurely. You can generate interrupts by pressing Ctrl+C on a UNIX, LINUX, Mac OS X or Windows system.
There are signals which can not be caught by the program but there is a following list of signals which you can catch in your program and can take appropriate actions based on the signal. These signals are defined in C++ header file <csignal>.
SIGABRT
Abnormal termination of the program, such as a call to abort.
SIGFPE
An erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow.
SIGILL
Detection of an illegal instruction.
SIGINT
Receipt of an interactive attention signal.
SIGSEGV
An invalid access to storage.
SIGTERM
A termination request sent to the program.
C++ signal-handling library provides function signal to trap unexpected events. Following is the syntax of the signal() function −
void (*signal (int sig, void (*func)(int)))(int);
Keeping it simple, this function receives two arguments: first argument as an integer which represents signal number and second argument as a pointer to the signal-handling function.
Let us write a simple C++ program where we will catch SIGINT signal using signal() function. Whatever signal you want to catch in your program, you must register that signal using signal function and associate it with a signal handler. Examine the following example −
#include <iostream>
#include <csignal>
using namespace std;
void signalHandler( int signum ) {
cout << "Interrupt signal (" << signum << ") received.\n";
// cleanup and close up stuff here
// terminate program
exit(signum);
}
int main () {
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(1) {
cout << "Going to sleep...." << endl;
sleep(1);
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Going to sleep....
Going to sleep....
Going to sleep....
Now, press Ctrl+c to interrupt the program and you will see that your program will catch the signal and would come out by printing something as follows −
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.
You can generate signals by function raise(), which takes an integer signal number as an argument and has the following syntax.
int raise (signal sig);
Here, sig is the signal number to send any of the signals: SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Following is the example where we raise a signal internally using raise() function as follows −
#include <iostream>
#include <csignal>
using namespace std;
void signalHandler( int signum ) {
cout << "Interrupt signal (" << signum << ") received.\n";
// cleanup and close up stuff here
// terminate program
exit(signum);
}
int main () {
int i = 0;
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(++i) {
cout << "Going to sleep...." << endl;
if( i == 3 ) {
raise( SIGINT);
}
sleep(1);
}
return 0;
}
When the above code is compiled and executed, it produces the following result and would come out automatically −
Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.
Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based.
Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program.
A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
Before C++ 11, there is no built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature.
This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris.
The following routine is used to create a POSIX thread −
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters −
thread
An opaque, unique identifier for the new thread returned by the subroutine.
attr
An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values.
start_routine
The C++ routine that the thread will execute once it is created.
arg
A single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed.
The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads.
There is following routine which we use to terminate a POSIX thread −
#include <pthread.h>
pthread_exit (status)
Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist.
If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.
Example
This simple example code creates 5 threads with the pthread_create() routine. Each thread prints a "Hello World!" message, and then terminates with a call to pthread_exit().
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid) {
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
Compile the following program using -lpthread library as follows −
$gcc test.cpp -lpthread
Now, execute your program which gives the following output −
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 1
Hello World! Thread ID, 2
Hello World! Thread ID, 3
Hello World! Thread ID, 4
This example shows how to pass multiple arguments via a structure. You can pass any data type in a thread callback because it points to void as explained in the following example −
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
struct thread_data {
int thread_id;
char *message;
};
void *PrintHello(void *threadarg) {
struct thread_data *my_data;
my_data = (struct thread_data *) threadarg;
cout << "Thread ID : " << my_data->thread_id ;
cout << " Message : " << my_data->message << endl;
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout <<"main() : creating thread, " << i << endl;
td[i].thread_id = i;
td[i].message = "This is message";
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]);
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
When the above code is compiled and executed, it produces the following result −
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Thread ID : 3 Message : This is message
Thread ID : 2 Message : This is message
Thread ID : 0 Message : This is message
Thread ID : 1 Message : This is message
Thread ID : 4 Message : This is message
There are following two routines which we can use to join or detach threads −
pthread_join (threadid, status)
pthread_detach (threadid)
The pthread_join() subroutine blocks the calling thread until the specified 'threadid' thread terminates. When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined.
This example demonstrates how to wait for thread completions by using the Pthread join routine.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 5
void *wait(void *t) {
int i;
long tid;
tid = (long)t;
sleep(1);
cout << "Sleeping in thread " << endl;
cout << "Thread with id : " << tid << " ...exiting " << endl;
pthread_exit(NULL);
}
int main () {
int rc;
int i;
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
void *status;
// Initialize and set thread joinable
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for( i = 0; i < NUM_THREADS; i++ ) {
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], &attr, wait, (void *)i );
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
// free attribute and wait for the other threads
pthread_attr_destroy(&attr);
for( i = 0; i < NUM_THREADS; i++ ) {
rc = pthread_join(threads[i], &status);
if (rc) {
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
cout << "Main: completed thread id :" << i ;
cout << " exiting with status :" << status << endl;
}
cout << "Main: program exiting." << endl;
pthread_exit(NULL);
}
When the above code is compiled and executed, it produces the following result −
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Sleeping in thread
Thread with id : 0 .... exiting
Sleeping in thread
Thread with id : 1 .... exiting
Sleeping in thread
Thread with id : 2 .... exiting
Sleeping in thread
Thread with id : 3 .... exiting
Sleeping in thread
Thread with id : 4 .... exiting
Main: completed thread id :0 exiting with status :0
Main: completed thread id :1 exiting with status :0
Main: completed thread id :2 exiting with status :0
Main: completed thread id :3 exiting with status :0
Main: completed thread id :4 exiting with status :0
Main: program exiting.
The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.
The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.
The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows −
The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows −
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
The current version is CGI/1.1 and CGI/1.2 is under progress.
The current version is CGI/1.1 and CGI/1.2 is under progress.
To understand the concept of CGI, let's see what happens when we click a hyperlink to browse a particular web page or URL.
Your browser contacts the HTTP web server and demand for the URL ie. filename.
Your browser contacts the HTTP web server and demand for the URL ie. filename.
Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file.
Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file.
Web browser takes response from web server and displays either the received file or error message based on the received response.
Web browser takes response from web server and displays either the received file or error message based on the received response.
However, it is possible to set up the HTTP server in such a way that whenever a file in a certain directory is requested, that file is not sent back; instead it is executed as a program, and produced output from the program is sent back to your browser to display.
The Common Gateway Interface (CGI) is a standard protocol for enabling applications (called CGI programs or CGI scripts) to interact with Web servers and with clients. These CGI programs can be a written in Python, PERL, Shell, C or C++ etc.
The following simple program shows a simple architecture of CGI −
Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /var/www/cgi-bin. By convention CGI files will have extension as .cgi, though they are C++ executable.
By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify any other directory to run your CGI scripts, you can modify the following section in the httpd.conf file −
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
Here, I assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell etc.
Consider the following C++ Program content −
#include <iostream>
using namespace std;
int main () {
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Hello World - First CGI Program</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<h2>Hello World! This is my first CGI program</h2>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Compile above code and name the executable as cplusplus.cgi. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program make sure you have change mode of file using chmod 755 cplusplus.cgi UNIX command to make file executable.
The above C++ program is a simple program which is writing its output on STDOUT file i.e. screen. There is one important and extra feature available which is first line printing Content-type:text/html\r\n\r\n. This line is sent back to the browser and specify the content type to be displayed on the browser screen. Now you must have understood the basic concept of CGI and you can write many complicated CGI programs using Python. A C++ CGI program can interact with any other external system, such as RDBMS, to exchange information.
The line Content-type:text/html\r\n\r\n is a part of HTTP header, which is sent to the browser to understand the content. All the HTTP header will be in the following form −
HTTP Field Name: Field Content
For Example
Content-type: text/html\r\n\r\n
There are few other important HTTP headers, which you will use frequently in your CGI Programming.
Content-type:
A MIME string defining the format of the file being returned. Example is Content-type:text/html.
Expires: Date
The date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT.
Location: URL
The URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any file.
Last-modified: Date
The date of last modification of the resource.
Content-length: N
The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.
Set-Cookie: String
Set the cookie passed through the string.
All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program.
CONTENT_TYPE
The data type of the content, used when the client is sending attached content to the server. For example file upload etc.
CONTENT_LENGTH
The length of the query information that is available only for POST requests.
HTTP_COOKIE
Returns the set cookies in the form of key & value pair.
HTTP_USER_AGENT
The User-Agent request-header field contains information about the user agent originating the request. It is a name of the web browser.
PATH_INFO
The path for the CGI script.
QUERY_STRING
The URL-encoded information that is sent with GET method request.
REMOTE_ADDR
The IP address of the remote host making the request. This can be useful for logging or for authentication purpose.
REMOTE_HOST
The fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address.
REQUEST_METHOD
The method used to make the request. The most common methods are GET and POST.
SCRIPT_FILENAME
The full path to the CGI script.
SCRIPT_NAME
The name of the CGI script.
SERVER_NAME
The server's hostname or IP Address.
SERVER_SOFTWARE
The name and version of the software the server is running.
Here is small CGI program to list out all the CGI variables.
#include <iostream>
#include <stdlib.h>
using namespace std;
const string ENV[ 24 ] = {
"COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE",
"HTTP_ACCEPT", "HTTP_ACCEPT_ENCODING",
"HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",
"HTTP_HOST", "HTTP_USER_AGENT", "PATH",
"QUERY_STRING", "REMOTE_ADDR", "REMOTE_PORT",
"REQUEST_METHOD", "REQUEST_URI", "SCRIPT_FILENAME",
"SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN",
"SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL",
"SERVER_SIGNATURE","SERVER_SOFTWARE" };
int main () {
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>CGI Environment Variables</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<table border = \"0\" cellspacing = \"2\">";
for ( int i = 0; i < 24; i++ ) {
cout << "<tr><td>" << ENV[ i ] << "</td><td>";
// attempt to retrieve value of environment variable
char *value = getenv( ENV[ i ].c_str() );
if ( value != 0 ) {
cout << value;
} else {
cout << "Environment variable does not exist.";
}
cout << "</td></tr>\n";
}
cout << "</table><\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
For real examples, you would need to do many operations by your CGI program. There is a CGI library written for C++ program which you can download from ftp://ftp.gnu.org/gnu/cgicc/ and follow the steps to install the library −
$tar xzf cgicc-X.X.X.tar.gz
$cd cgicc-X.X.X/
$./configure --prefix=/usr
$make
$make install
You can check related documentation available at ‘C++ CGI Lib Documentation.
You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently browser uses two methods to pass this information to web server. These methods are GET Method and POST Method.
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows −
http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation and you can pass upto 1024 characters in a request string.
When using GET method, information is passed using QUERY_STRING http header and will be accessible in your CGI Program through QUERY_STRING environment variable.
You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM> tags to pass information using GET method.
Here is a simple URL which will pass two values to hello_get.py program using GET method.
Below is a program to generate cpp_get.cgi CGI program to handle input given by web browser. We are going to use C++ CGI library which makes it very easy to access passed information −
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
using namespace std;
using namespace cgicc;
int main () {
Cgicc formData;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Using GET and POST Methods</title>\n";
cout << "</head>\n";
cout << "<body>\n";
form_iterator fi = formData.getElement("first_name");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "First name: " << **fi << endl;
} else {
cout << "No text entered for first name" << endl;
}
cout << "<br/>\n";
fi = formData.getElement("last_name");
if( !fi->isEmpty() &&fi != (*formData).end()) {
cout << "Last name: " << **fi << endl;
} else {
cout << "No text entered for last name" << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Now, compile the above program as follows −
$g++ -o cpp_get.cgi cpp_get.cpp -lcgicc
Generate cpp_get.cgi and put it in your CGI directory and try to access using following link −
This would generate following result −
First name: ZARA
Last name: ALI
Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same CGI script cpp_get.cgi to handle this input.
<form action = "/cgi-bin/cpp_get.cgi" method = "get">
First Name: <input type = "text" name = "first_name"> <br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
Here is the actual output of the above form. You enter First and Last Name and
then click submit button to see the result.
A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.
The same cpp_get.cgi program will handle POST method as well. Let us take same example as above, which passes two values using HTML FORM and submit button but this time with POST method as follows −
<form action = "/cgi-bin/cpp_get.cgi" method = "post">
First Name: <input type = "text" name = "first_name"><br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
Here is the actual output of the above form. You enter First and Last Name and
then click submit button to see the result.
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code for a form with two checkboxes −
<form action = "/cgi-bin/cpp_checkbox.cgi" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" value = "on" /> Maths
<input type = "checkbox" name = "physics" value = "on" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
The result of this code is the following form −
Below is C++ program, which will generate cpp_checkbox.cgi script to handle input given by web browser through checkbox button.
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
using namespace std;
using namespace cgicc;
int main () {
Cgicc formData;
bool maths_flag, physics_flag;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Checkbox Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
maths_flag = formData.queryCheckbox("maths");
if( maths_flag ) {
cout << "Maths Flag: ON " << endl;
} else {
cout << "Maths Flag: OFF " << endl;
}
cout << "<br/>\n";
physics_flag = formData.queryCheckbox("physics");
if( physics_flag ) {
cout << "Physics Flag: ON " << endl;
} else {
cout << "Physics Flag: OFF " << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Radio Buttons are used when only one option is required to be selected.
Here is example HTML code for a form with two radio button −
<form action = "/cgi-bin/cpp_radiobutton.cgi" method = "post" target = "_blank">
<input type = "radio" name = "subject" value = "maths" checked = "checked"/> Maths
<input type = "radio" name = "subject" value = "physics" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
The result of this code is the following form −
Below is C++ program, which will generate cpp_radiobutton.cgi script to handle input given by web browser through radio buttons.
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
using namespace std;
using namespace cgicc;
int main () {
Cgicc formData;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Radio Button Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
form_iterator fi = formData.getElement("subject");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Radio box selected: " << **fi << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
TEXTAREA element is used when multiline text has to be passed to the CGI Program.
Here is example HTML code for a form with a TEXTAREA box −
<form action = "/cgi-bin/cpp_textarea.cgi" method = "post" target = "_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>
The result of this code is the following form −
Below is C++ program, which will generate cpp_textarea.cgi script to handle input given by web browser through text area.
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
using namespace std;
using namespace cgicc;
int main () {
Cgicc formData;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Text Area Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
form_iterator fi = formData.getElement("textcontent");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Text Content: " << **fi << endl;
} else {
cout << "No text entered" << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Drop down Box is used when we have many options available but only one or two will be selected.
Here is example HTML code for a form with one drop down box −
<form action = "/cgi-bin/cpp_dropdown.cgi" method = "post" target = "_blank">
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
<input type = "submit" value = "Submit"/>
</form>
The result of this code is the following form −
Below is C++ program, which will generate cpp_dropdown.cgi script to handle input given by web browser through drop down box.
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
using namespace std;
using namespace cgicc;
int main () {
Cgicc formData;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Drop Down Box Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
form_iterator fi = formData.getElement("dropdown");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Value Selected: " << **fi << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after completing many pages. But how to maintain user's session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.
Cookies are a plain text data record of 5 variable-length fields −
Expires − This shows date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Expires − This shows date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Domain − This shows domain name of your site.
Domain − This shows domain name of your site.
Path − This shows path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Path − This shows path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Secure − If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Name = Value − Cookies are set and retrieved in the form of key and value pairs.
Name = Value − Cookies are set and retrieved in the form of key and value pairs.
It is very easy to send cookies to browser. These cookies will be sent along with HTTP Header before the Content-type filed. Assuming you want to set UserID and Password as cookies. So cookies setting will be done as follows
#include <iostream>
using namespace std;
int main () {
cout << "Set-Cookie:UserID = XYZ;\r\n";
cout << "Set-Cookie:Password = XYZ123;\r\n";
cout << "Set-Cookie:Domain = www.tutorialspoint.com;\r\n";
cout << "Set-Cookie:Path = /perl;\n";
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Cookies in CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "Setting cookies" << endl;
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.
Here, it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
Compile above program to produce setcookies.cgi, and try to set cookies using following link. It will set four cookies at your computer −
/cgi-bin/setcookies.cgi
It is easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form.
key1 = value1; key2 = value2; key3 = value3....
Here is an example of how to retrieve cookies.
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
using namespace std;
using namespace cgicc;
int main () {
Cgicc cgi;
const_cookie_iterator cci;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Cookies in CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<table border = \"0\" cellspacing = \"2\">";
// get environment variables
const CgiEnvironment& env = cgi.getEnvironment();
for( cci = env.getCookieList().begin();
cci != env.getCookieList().end();
++cci ) {
cout << "<tr><td>" << cci->getName() << "</td><td>";
cout << cci->getValue();
cout << "</td></tr>\n";
}
cout << "</table><\n";
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Now, compile above program to produce getcookies.cgi, and try to get a list of all the cookies available at your computer −
/cgi-bin/getcookies.cgi
This will produce a list of all the four cookies set in previous section and all other cookies set in your computer −
UserID XYZ
Password XYZ123
Domain www.tutorialspoint.com
Path /perl
To upload a file the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type will create a "Browse" button.
<html>
<body>
<form enctype = "multipart/form-data" action = "/cgi-bin/cpp_uploadfile.cgi"
method = "post">
<p>File: <input type = "file" name = "userfile" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
The result of this code is the following form −
File:
Note − Above example has been disabled intentionally to stop people uploading files on our server. But you can try above code with your server.
Here is the script cpp_uploadfile.cpp to handle file upload −
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
using namespace std;
using namespace cgicc;
int main () {
Cgicc cgi;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>File Upload in CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
// get list of files to be uploaded
const_file_iterator file = cgi.getFile("userfile");
if(file != cgi.getFiles().end()) {
// send data type at cout.
cout << HTTPContentHeader(file->getDataType());
// write content at cout.
file->writeToStream(cout);
}
cout << "<File uploaded successfully>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
The above example is for writing content at cout stream but you can open your file stream and save the content of uploaded file in a file at desired location.
Hope you have enjoyed this tutorial. If yes, please send us your feedback.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2487,
"s": 2318,
"text": "C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic programming."
},
{
"code": null,
"e": 2613,
"s": 2487,
"text": "C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features."
},
{
"code": null,
"e": 2820,
"s": 2613,
"text": "C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983."
},
{
"code": null,
"e": 2907,
"s": 2820,
"text": "C++ is a superset of C, and that virtually any legal C program is a legal C++ program."
},
{
"code": null,
"e": 3042,
"s": 2907,
"text": "Note − A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time."
},
{
"code": null,
"e": 3150,
"s": 3042,
"text": "C++ fully supports object-oriented programming, including the four pillars of object-oriented development −"
},
{
"code": null,
"e": 3164,
"s": 3150,
"text": "Encapsulation"
},
{
"code": null,
"e": 3176,
"s": 3164,
"text": "Data hiding"
},
{
"code": null,
"e": 3188,
"s": 3176,
"text": "Inheritance"
},
{
"code": null,
"e": 3201,
"s": 3188,
"text": "Polymorphism"
},
{
"code": null,
"e": 3250,
"s": 3201,
"text": "Standard C++ consists of three important parts −"
},
{
"code": null,
"e": 3350,
"s": 3250,
"text": "The core language giving all the building blocks including variables, data types and literals, etc."
},
{
"code": null,
"e": 3450,
"s": 3350,
"text": "The core language giving all the building blocks including variables, data types and literals, etc."
},
{
"code": null,
"e": 3540,
"s": 3450,
"text": "The C++ Standard Library giving a rich set of functions manipulating files, strings, etc."
},
{
"code": null,
"e": 3630,
"s": 3540,
"text": "The C++ Standard Library giving a rich set of functions manipulating files, strings, etc."
},
{
"code": null,
"e": 3730,
"s": 3630,
"text": "The Standard Template Library (STL) giving a rich set of methods manipulating data structures, etc."
},
{
"code": null,
"e": 3830,
"s": 3730,
"text": "The Standard Template Library (STL) giving a rich set of methods manipulating data structures, etc."
},
{
"code": null,
"e": 4029,
"s": 3830,
"text": "The ANSI standard is an attempt to ensure that C++ is portable; that code you write for Microsoft's compiler will compile without errors, using a compiler on a Mac, UNIX, a Windows box, or an Alpha."
},
{
"code": null,
"e": 4148,
"s": 4029,
"text": "The ANSI standard has been stable for a while, and all the major C++ compiler manufacturers support the ANSI standard."
},
{
"code": null,
"e": 4217,
"s": 4148,
"text": "The most important thing while learning C++ is to focus on concepts."
},
{
"code": null,
"e": 4403,
"s": 4217,
"text": "The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones."
},
{
"code": null,
"e": 4617,
"s": 4403,
"text": "C++ supports a variety of programming styles. You can write in the style of Fortran, C, Smalltalk, etc., in any language. Each style can achieve its aims effectively while maintaining runtime and space efficiency."
},
{
"code": null,
"e": 4710,
"s": 4617,
"text": "C++ is used by hundreds of thousands of programmers in essentially every application domain."
},
{
"code": null,
"e": 4851,
"s": 4710,
"text": "C++ is being highly used to write device drivers and other software that rely on direct manipulation of hardware under realtime constraints."
},
{
"code": null,
"e": 4966,
"s": 4851,
"text": "C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts."
},
{
"code": null,
"e": 5133,
"s": 4966,
"text": "Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interfaces of these systems are written in C++."
},
{
"code": null,
"e": 5257,
"s": 5133,
"text": "If you are still willing to set up your environment for C++, you need to have the following two softwares on your computer."
},
{
"code": null,
"e": 5401,
"s": 5257,
"text": "This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi."
},
{
"code": null,
"e": 5584,
"s": 5401,
"text": "Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows as well as Linux, or UNIX."
},
{
"code": null,
"e": 5720,
"s": 5584,
"text": "The files you create with your editor are called source files and for C++ they typically are named with the extension .cpp, .cp, or .c."
},
{
"code": null,
"e": 5784,
"s": 5720,
"text": "A text editor should be in place to start your C++ programming."
},
{
"code": null,
"e": 5894,
"s": 5784,
"text": "This is an actual C++ compiler, which will be used to compile your source code into final executable program."
},
{
"code": null,
"e": 6036,
"s": 5894,
"text": "Most C++ compilers don't care what extension you give to your source code, but if you don't specify otherwise, many will use .cpp by default."
},
{
"code": null,
"e": 6213,
"s": 6036,
"text": "Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective Operating Systems."
},
{
"code": null,
"e": 6353,
"s": 6213,
"text": "If you are using Linux or UNIX then check whether GCC is installed on your system by entering the following command from the command line −"
},
{
"code": null,
"e": 6363,
"s": 6353,
"text": "$ g++ -v\n"
},
{
"code": null,
"e": 6445,
"s": 6363,
"text": "If you have installed GCC, then it should print a message such as the following −"
},
{
"code": null,
"e": 6612,
"s": 6445,
"text": "Using built-in specs.\nTarget: i386-redhat-linux\nConfigured with: ../configure --prefix=/usr .......\nThread model: posix\ngcc version 4.1.2 20080704 (Red Hat 4.1.2-46)\n"
},
{
"code": null,
"e": 6753,
"s": 6612,
"text": "If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/"
},
{
"code": null,
"e": 6923,
"s": 6753,
"text": "If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's website and follow the simple installation instructions."
},
{
"code": null,
"e": 6996,
"s": 6923,
"text": "Xcode is currently available at developer.apple.com/technologies/tools/."
},
{
"code": null,
"e": 7261,
"s": 6996,
"text": "To install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program which should be named MinGW-<version>.exe."
},
{
"code": null,
"e": 7402,
"s": 7261,
"text": "While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more."
},
{
"code": null,
"e": 7567,
"s": 7402,
"text": "Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can specify these tools on the command line by their simple names."
},
{
"code": null,
"e": 7716,
"s": 7567,
"text": "When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line."
},
{
"code": null,
"e": 7933,
"s": 7716,
"text": "When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what a class, object, methods, and instant variables mean."
},
{
"code": null,
"e": 8111,
"s": 7933,
"text": "Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class. "
},
{
"code": null,
"e": 8289,
"s": 8111,
"text": "Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class. "
},
{
"code": null,
"e": 8413,
"s": 8289,
"text": "Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support."
},
{
"code": null,
"e": 8537,
"s": 8413,
"text": "Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support."
},
{
"code": null,
"e": 8716,
"s": 8537,
"text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 8895,
"s": 8716,
"text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 9051,
"s": 8895,
"text": "Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables."
},
{
"code": null,
"e": 9207,
"s": 9051,
"text": "Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables."
},
{
"code": null,
"e": 9276,
"s": 9207,
"text": "Let us look at a simple code that would print the words Hello World."
},
{
"code": null,
"e": 9439,
"s": 9276,
"text": "#include <iostream>\nusing namespace std;\n\n// main() is where program execution begins.\nint main() {\n cout << \"Hello World\"; // prints Hello World\n return 0;\n}"
},
{
"code": null,
"e": 9495,
"s": 9439,
"text": "Let us look at the various parts of the above program −"
},
{
"code": null,
"e": 9666,
"s": 9495,
"text": "The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed."
},
{
"code": null,
"e": 9837,
"s": 9666,
"text": "The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed."
},
{
"code": null,
"e": 9964,
"s": 9837,
"text": "The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++."
},
{
"code": null,
"e": 10091,
"s": 9964,
"text": "The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++."
},
{
"code": null,
"e": 10263,
"s": 10091,
"text": "The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line."
},
{
"code": null,
"e": 10435,
"s": 10263,
"text": "The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line."
},
{
"code": null,
"e": 10508,
"s": 10435,
"text": "The line int main() is the main function where program execution begins."
},
{
"code": null,
"e": 10581,
"s": 10508,
"text": "The line int main() is the main function where program execution begins."
},
{
"code": null,
"e": 10682,
"s": 10581,
"text": "The next line cout << \"Hello World\"; causes the message \"Hello World\" to be displayed on the screen."
},
{
"code": null,
"e": 10783,
"s": 10682,
"text": "The next line cout << \"Hello World\"; causes the message \"Hello World\" to be displayed on the screen."
},
{
"code": null,
"e": 10894,
"s": 10783,
"text": "The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process."
},
{
"code": null,
"e": 11005,
"s": 10894,
"text": "The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process."
},
{
"code": null,
"e": 11108,
"s": 11005,
"text": "Let's look at how to save the file, compile and run the program. Please follow the steps given below −"
},
{
"code": null,
"e": 11154,
"s": 11108,
"text": "Open a text editor and add the code as above."
},
{
"code": null,
"e": 11200,
"s": 11154,
"text": "Open a text editor and add the code as above."
},
{
"code": null,
"e": 11228,
"s": 11200,
"text": "Save the file as: hello.cpp"
},
{
"code": null,
"e": 11256,
"s": 11228,
"text": "Save the file as: hello.cpp"
},
{
"code": null,
"e": 11328,
"s": 11256,
"text": "Open a command prompt and go to the directory where you saved the file."
},
{
"code": null,
"e": 11400,
"s": 11328,
"text": "Open a command prompt and go to the directory where you saved the file."
},
{
"code": null,
"e": 11587,
"s": 11400,
"text": "Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file."
},
{
"code": null,
"e": 11774,
"s": 11587,
"text": "Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file."
},
{
"code": null,
"e": 11813,
"s": 11774,
"text": "Now, type 'a.out' to run your program."
},
{
"code": null,
"e": 11852,
"s": 11813,
"text": "Now, type 'a.out' to run your program."
},
{
"code": null,
"e": 11915,
"s": 11852,
"text": "You will be able to see ' Hello World ' printed on the window."
},
{
"code": null,
"e": 11978,
"s": 11915,
"text": "You will be able to see ' Hello World ' printed on the window."
},
{
"code": null,
"e": 12017,
"s": 11978,
"text": "$ g++ hello.cpp\n$ ./a.out\nHello World\n"
},
{
"code": null,
"e": 12124,
"s": 12017,
"text": "Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp."
},
{
"code": null,
"e": 12228,
"s": 12124,
"text": "You can compile C/C++ programs using makefile. For more details, you can check our 'Makefile Tutorial'."
},
{
"code": null,
"e": 12388,
"s": 12228,
"text": "In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity."
},
{
"code": null,
"e": 12444,
"s": 12388,
"text": "For example, following are three different statements −"
},
{
"code": null,
"e": 12474,
"s": 12444,
"text": "x = y;\ny = y + 1;\nadd(x, y);\n"
},
{
"code": null,
"e": 12590,
"s": 12474,
"text": "A block is a set of logically connected statements that are surrounded by opening and closing braces. For example −"
},
{
"code": null,
"e": 12656,
"s": 12590,
"text": "{\n cout << \"Hello World\"; // prints Hello World\n return 0;\n}\n"
},
{
"code": null,
"e": 12803,
"s": 12656,
"text": "C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a statement in a line. For example −"
},
{
"code": null,
"e": 12833,
"s": 12803,
"text": "x = y;\ny = y + 1;\nadd(x, y);\n"
},
{
"code": null,
"e": 12848,
"s": 12833,
"text": "is the same as"
},
{
"code": null,
"e": 12878,
"s": 12848,
"text": "x = y; y = y + 1; add(x, y);\n"
},
{
"code": null,
"e": 13132,
"s": 12878,
"text": "A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9)."
},
{
"code": null,
"e": 13327,
"s": 13132,
"text": "C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C++."
},
{
"code": null,
"e": 13378,
"s": 13327,
"text": "Here are some examples of acceptable identifiers −"
},
{
"code": null,
"e": 13464,
"s": 13378,
"text": "mohd zara abc move_name a_123\nmyname50 _temp j a23b9 retVal\n"
},
{
"code": null,
"e": 13608,
"s": 13464,
"text": "The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names."
},
{
"code": null,
"e": 13821,
"s": 13608,
"text": "A few characters have an alternative representation, called a trigraph sequence. A trigraph is a three-character sequence that represents a single character and the sequence always starts with two question marks."
},
{
"code": null,
"e": 13968,
"s": 13821,
"text": "Trigraphs are expanded anywhere they appear, including within string literals and character literals, in comments, and in preprocessor directives."
},
{
"code": null,
"e": 14024,
"s": 13968,
"text": "Following are most frequently used trigraph sequences −"
},
{
"code": null,
"e": 14138,
"s": 14024,
"text": "All the compilers do not support trigraphs and they are not advised to be used because of their confusing nature."
},
{
"code": null,
"e": 14261,
"s": 14138,
"text": "A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler totally ignores it."
},
{
"code": null,
"e": 14531,
"s": 14261,
"text": "Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins."
},
{
"code": null,
"e": 14541,
"s": 14531,
"text": "int age;\n"
},
{
"code": null,
"e": 14699,
"s": 14541,
"text": "In the above statement there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them."
},
{
"code": null,
"e": 14751,
"s": 14699,
"text": "fruit = apples + oranges; // Get the total fruit\n"
},
{
"code": null,
"e": 14937,
"s": 14751,
"text": "In the above statement 2, no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose."
},
{
"code": null,
"e": 15130,
"s": 14937,
"text": "Program comments are explanatory statements that you can include in the C++ code. These comments help anyone reading the source code. All programming languages allow for some form of comments."
},
{
"code": null,
"e": 15253,
"s": 15130,
"text": "C++ supports single-line and multi-line comments. All characters available inside any comment are ignored by C++ compiler."
},
{
"code": null,
"e": 15311,
"s": 15253,
"text": "C++ comments start with /* and end with */. For example −"
},
{
"code": null,
"e": 15390,
"s": 15311,
"text": "/* This is a comment */\n\n/* C++ comments can also\n * span multiple lines\n*/\n"
},
{
"code": null,
"e": 15472,
"s": 15390,
"text": "A comment can also start with //, extending to the end of the line. For example −"
},
{
"code": null,
"e": 15590,
"s": 15472,
"text": "#include <iostream>\nusing namespace std;\n\nmain() {\n cout << \"Hello World\"; // prints Hello World\n \n return 0;\n}"
},
{
"code": null,
"e": 15717,
"s": 15590,
"text": "When the above code is compiled, it will ignore // prints Hello World and final executable will produce the following result −"
},
{
"code": null,
"e": 15730,
"s": 15717,
"text": "Hello World\n"
},
{
"code": null,
"e": 15931,
"s": 15730,
"text": "Within a /* and */ comment, // characters have no special meaning. Within a // comment, /* and */ have no special meaning. Thus, you can \"nest\" one kind of comment within the other kind. For example −"
},
{
"code": null,
"e": 16022,
"s": 15931,
"text": "/* Comment out printing of Hello World:\n\ncout << \"Hello World\"; // prints Hello World\n\n*/\n"
},
{
"code": null,
"e": 16271,
"s": 16022,
"text": "While writing program in any language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory."
},
{
"code": null,
"e": 16551,
"s": 16271,
"text": "You may like to store information of various data types like character, wide character, integer, floating point, double floating point, boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory."
},
{
"code": null,
"e": 16699,
"s": 16551,
"text": "C++ offers the programmer a rich assortment of built-in as well as user defined data types. Following table lists down seven basic C++ data types −"
},
{
"code": null,
"e": 16786,
"s": 16699,
"text": "Several of the basic types can be modified using one or more of these type modifiers −"
},
{
"code": null,
"e": 16793,
"s": 16786,
"text": "signed"
},
{
"code": null,
"e": 16802,
"s": 16793,
"text": "unsigned"
},
{
"code": null,
"e": 16808,
"s": 16802,
"text": "short"
},
{
"code": null,
"e": 16813,
"s": 16808,
"text": "long"
},
{
"code": null,
"e": 16998,
"s": 16813,
"text": "The following table shows the variable type, how much memory it takes to store the value in memory, and what is maximum and minimum value which can be stored in such type of variables."
},
{
"code": null,
"e": 17134,
"s": 16998,
"text": "The size of variables might be different from those shown in the above table, depending on the compiler and the computer you are using."
},
{
"code": null,
"e": 17232,
"s": 17134,
"text": "Following is the example, which will produce correct size of various data types on your computer."
},
{
"code": null,
"e": 17712,
"s": 17232,
"text": "#include <iostream>\nusing namespace std;\n\nint main() {\n cout << \"Size of char : \" << sizeof(char) << endl;\n cout << \"Size of int : \" << sizeof(int) << endl;\n cout << \"Size of short int : \" << sizeof(short int) << endl;\n cout << \"Size of long int : \" << sizeof(long int) << endl;\n cout << \"Size of float : \" << sizeof(float) << endl;\n cout << \"Size of double : \" << sizeof(double) << endl;\n cout << \"Size of wchar_t : \" << sizeof(wchar_t) << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 17933,
"s": 17712,
"text": "This example uses endl, which inserts a new-line character after every line and << operator is being used to pass multiple values out to the screen. We are also using sizeof() operator to get size of various data types."
},
{
"code": null,
"e": 18053,
"s": 17933,
"text": "When the above code is compiled and executed, it produces the following result which can vary from machine to machine −"
},
{
"code": null,
"e": 18187,
"s": 18053,
"text": "Size of char : 1\nSize of int : 4\nSize of short int : 2\nSize of long int : 4\nSize of float : 4\nSize of double : 8\nSize of wchar_t : 4\n"
},
{
"code": null,
"e": 18317,
"s": 18187,
"text": "You can create a new name for an existing type using typedef. Following is the simple syntax to define a new type using typedef −"
},
{
"code": null,
"e": 18341,
"s": 18317,
"text": "typedef type newname; \n"
},
{
"code": null,
"e": 18423,
"s": 18341,
"text": "For example, the following tells the compiler that feet is another name for int −"
},
{
"code": null,
"e": 18442,
"s": 18423,
"text": "typedef int feet;\n"
},
{
"code": null,
"e": 18542,
"s": 18442,
"text": "Now, the following declaration is perfectly legal and creates an integer variable called distance −"
},
{
"code": null,
"e": 18558,
"s": 18542,
"text": "feet distance;\n"
},
{
"code": null,
"e": 18748,
"s": 18558,
"text": "An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each enumerator is a constant whose type is the enumeration."
},
{
"code": null,
"e": 18855,
"s": 18748,
"text": "Creating an enumeration requires the use of the keyword enum. The general form of an enumeration type is −"
},
{
"code": null,
"e": 18900,
"s": 18855,
"text": "enum enum-name { list of names } var-list; \n"
},
{
"code": null,
"e": 18990,
"s": 18900,
"text": "Here, the enum-name is the enumeration's type name. The list of names is comma separated."
},
{
"code": null,
"e": 19144,
"s": 18990,
"text": "For example, the following code defines an enumeration of colors called colors and the variable c of type color. Finally, c is assigned the value \"blue\"."
},
{
"code": null,
"e": 19190,
"s": 19144,
"text": "enum color { red, green, blue } c;\nc = blue;\n"
},
{
"code": null,
"e": 19451,
"s": 19190,
"text": "By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and so on. But you can give a name, a specific value by adding an initializer. For example, in the following enumeration, green will have the value 5."
},
{
"code": null,
"e": 19489,
"s": 19451,
"text": "enum color { red, green = 5, blue };\n"
},
{
"code": null,
"e": 19592,
"s": 19489,
"text": "Here, blue will have a value of 6 because each name will be one greater than the one that precedes it."
},
{
"code": null,
"e": 19895,
"s": 19592,
"text": "A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 20110,
"s": 19895,
"text": "The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive −"
},
{
"code": null,
"e": 20192,
"s": 20110,
"text": "There are following basic types of variable in C++ as explained in last chapter −"
},
{
"code": null,
"e": 20197,
"s": 20192,
"text": "bool"
},
{
"code": null,
"e": 20232,
"s": 20197,
"text": "Stores either value true or false."
},
{
"code": null,
"e": 20237,
"s": 20232,
"text": "char"
},
{
"code": null,
"e": 20299,
"s": 20237,
"text": "Typically a single octet (one byte). This is an integer type."
},
{
"code": null,
"e": 20303,
"s": 20299,
"text": "int"
},
{
"code": null,
"e": 20353,
"s": 20303,
"text": "The most natural size of integer for the machine."
},
{
"code": null,
"e": 20359,
"s": 20353,
"text": "float"
},
{
"code": null,
"e": 20400,
"s": 20359,
"text": "A single-precision floating point value."
},
{
"code": null,
"e": 20407,
"s": 20400,
"text": "double"
},
{
"code": null,
"e": 20448,
"s": 20407,
"text": "A double-precision floating point value."
},
{
"code": null,
"e": 20453,
"s": 20448,
"text": "void"
},
{
"code": null,
"e": 20485,
"s": 20453,
"text": "Represents the absence of type."
},
{
"code": null,
"e": 20493,
"s": 20485,
"text": "wchar_t"
},
{
"code": null,
"e": 20516,
"s": 20493,
"text": "A wide character type."
},
{
"code": null,
"e": 20694,
"s": 20516,
"text": "C++ also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes."
},
{
"code": null,
"e": 20782,
"s": 20694,
"text": "Following section will cover how to define, declare and use various types of variables."
},
{
"code": null,
"e": 20994,
"s": 20782,
"text": "A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows −"
},
{
"code": null,
"e": 21015,
"s": 20994,
"text": "type variable_list;\n"
},
{
"code": null,
"e": 21263,
"s": 21015,
"text": "Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −"
},
{
"code": null,
"e": 21322,
"s": 21263,
"text": "int i, j, k;\nchar c, ch;\nfloat f, salary;\ndouble d;\n"
},
{
"code": null,
"e": 21475,
"s": 21322,
"text": "The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int."
},
{
"code": null,
"e": 21643,
"s": 21475,
"text": "Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −"
},
{
"code": null,
"e": 21672,
"s": 21643,
"text": "type variable_name = value;\n"
},
{
"code": null,
"e": 21692,
"s": 21672,
"text": "Some examples are −"
},
{
"code": null,
"e": 21945,
"s": 21692,
"text": "extern int d = 3, f = 5; // declaration of d and f. \nint d = 3, f = 5; // definition and initializing d and f. \nbyte z = 22; // definition and initializes z. \nchar x = 'x'; // the variable x has the value 'x'.\n"
},
{
"code": null,
"e": 22145,
"s": 21945,
"text": "For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined."
},
{
"code": null,
"e": 22522,
"s": 22145,
"text": "A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable definition at the time of linking of the program."
},
{
"code": null,
"e": 22909,
"s": 22522,
"text": "A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your C++ program, but it can be defined only once in a file, a function or a block of code."
},
{
"code": null,
"e": 23033,
"s": 22909,
"text": "Try the following example where a variable has been declared at the top, but it has been defined inside the main function −"
},
{
"code": null,
"e": 23375,
"s": 23033,
"text": "#include <iostream>\nusing namespace std;\n\n// Variable declaration:\nextern int a, b;\nextern int c;\nextern float f;\n \nint main () {\n // Variable definition:\n int a, b;\n int c;\n float f;\n \n // actual initialization\n a = 10;\n b = 20;\n c = a + b;\n \n cout << c << endl ;\n\n f = 70.0/3.0;\n cout << f << endl ;\n \n return 0;\n}"
},
{
"code": null,
"e": 23456,
"s": 23375,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 23468,
"s": 23456,
"text": "30\n23.3333\n"
},
{
"code": null,
"e": 23646,
"s": 23468,
"text": "Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −"
},
{
"code": null,
"e": 23789,
"s": 23646,
"text": "// function declaration\nint func();\nint main() {\n // function call\n int i = func();\n}\n\n// function definition\nint func() {\n return 0;\n}\n"
},
{
"code": null,
"e": 23833,
"s": 23789,
"text": "There are two kinds of expressions in C++ −"
},
{
"code": null,
"e": 24000,
"s": 23833,
"text": "lvalue − Expressions that refer to a memory location is called \"lvalue\" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 24167,
"s": 24000,
"text": "lvalue − Expressions that refer to a memory location is called \"lvalue\" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 24412,
"s": 24167,
"text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 24657,
"s": 24412,
"text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 24868,
"s": 24657,
"text": "Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −"
},
{
"code": null,
"e": 24881,
"s": 24868,
"text": "int g = 20;\n"
},
{
"code": null,
"e": 24964,
"s": 24881,
"text": "But the following is not a valid statement and would generate compile-time error −"
},
{
"code": null,
"e": 24974,
"s": 24964,
"text": "10 = 20;\n"
},
{
"code": null,
"e": 25088,
"s": 24974,
"text": "A scope is a region of the program and broadly speaking there are three places, where variables can be declared −"
},
{
"code": null,
"e": 25150,
"s": 25088,
"text": "Inside a function or a block which is called local variables,"
},
{
"code": null,
"e": 25212,
"s": 25150,
"text": "Inside a function or a block which is called local variables,"
},
{
"code": null,
"e": 25288,
"s": 25212,
"text": "In the definition of function parameters which is called formal parameters."
},
{
"code": null,
"e": 25364,
"s": 25288,
"text": "In the definition of function parameters which is called formal parameters."
},
{
"code": null,
"e": 25423,
"s": 25364,
"text": "Outside of all functions which is called global variables."
},
{
"code": null,
"e": 25482,
"s": 25423,
"text": "Outside of all functions which is called global variables."
},
{
"code": null,
"e": 25615,
"s": 25482,
"text": "We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local and global variables."
},
{
"code": null,
"e": 25886,
"s": 25615,
"text": "Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables −"
},
{
"code": null,
"e": 26099,
"s": 25886,
"text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // Local variable declaration:\n int a, b;\n int c;\n \n // actual initialization\n a = 10;\n b = 20;\n c = a + b;\n \n cout << c;\n \n return 0;\n}"
},
{
"code": null,
"e": 26274,
"s": 26099,
"text": "Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program."
},
{
"code": null,
"e": 26487,
"s": 26274,
"text": "A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables −"
},
{
"code": null,
"e": 26732,
"s": 26487,
"text": "#include <iostream>\nusing namespace std;\n \n// Global variable declaration:\nint g;\n \nint main () {\n // Local variable declaration:\n int a, b;\n \n // actual initialization\n a = 10;\n b = 20;\n g = a + b;\n \n cout << g;\n \n return 0;\n}"
},
{
"code": null,
"e": 26874,
"s": 26732,
"text": "A program can have same name for local and global variables but value of local variable inside a function will take preference. For example −"
},
{
"code": null,
"e": 27059,
"s": 26874,
"text": "#include <iostream>\nusing namespace std;\n \n// Global variable declaration:\nint g = 20;\n \nint main () {\n // Local variable declaration:\n int g = 10;\n \n cout << g;\n \n return 0;\n}"
},
{
"code": null,
"e": 27140,
"s": 27059,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 27144,
"s": 27140,
"text": "10\n"
},
{
"code": null,
"e": 27343,
"s": 27144,
"text": "When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −"
},
{
"code": null,
"e": 27472,
"s": 27343,
"text": "It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result."
},
{
"code": null,
"e": 27565,
"s": 27472,
"text": "Constants refer to fixed values that the program may not alter and they are called literals."
},
{
"code": null,
"e": 27720,
"s": 27565,
"text": "Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values."
},
{
"code": null,
"e": 27845,
"s": 27720,
"text": "Again, constants are treated just like regular variables except that their values cannot be modified after their definition."
},
{
"code": null,
"e": 28016,
"s": 27845,
"text": "An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal."
},
{
"code": null,
"e": 28195,
"s": 28016,
"text": "An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order."
},
{
"code": null,
"e": 28240,
"s": 28195,
"text": "Here are some examples of integer literals −"
},
{
"code": null,
"e": 28399,
"s": 28240,
"text": "212 // Legal\n215u // Legal\n0xFeeL // Legal\n078 // Illegal: 8 is not an octal digit\n032UU // Illegal: cannot repeat a suffix\n"
},
{
"code": null,
"e": 28467,
"s": 28399,
"text": "Following are other examples of various types of Integer literals −"
},
{
"code": null,
"e": 28628,
"s": 28467,
"text": "85 // decimal\n0213 // octal\n0x4b // hexadecimal\n30 // int\n30u // unsigned int\n30l // long\n30ul // unsigned long\n"
},
{
"code": null,
"e": 28818,
"s": 28628,
"text": "A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form."
},
{
"code": null,
"e": 29072,
"s": 28818,
"text": "While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E."
},
{
"code": null,
"e": 29124,
"s": 29072,
"text": "Here are some examples of floating-point literals −"
},
{
"code": null,
"e": 29320,
"s": 29124,
"text": "3.14159 // Legal\n314159E-5L // Legal\n510E // Illegal: incomplete exponent\n210f // Illegal: no decimal or exponent\n.e55 // Illegal: missing integer or fraction\n"
},
{
"code": null,
"e": 29396,
"s": 29320,
"text": "There are two Boolean literals and they are part of standard C++ keywords −"
},
{
"code": null,
"e": 29431,
"s": 29396,
"text": "A value of true representing true."
},
{
"code": null,
"e": 29466,
"s": 29431,
"text": "A value of true representing true."
},
{
"code": null,
"e": 29503,
"s": 29466,
"text": "A value of false representing false."
},
{
"code": null,
"e": 29540,
"s": 29503,
"text": "A value of false representing false."
},
{
"code": null,
"e": 29624,
"s": 29540,
"text": "You should not consider the value of true equal to 1 and value of false equal to 0."
},
{
"code": null,
"e": 29925,
"s": 29624,
"text": "Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable . Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type."
},
{
"code": null,
"e": 30060,
"s": 29925,
"text": "A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\\t'), or a universal character (e.g., '\\u02C0'). "
},
{
"code": null,
"e": 30289,
"s": 30060,
"text": "There are certain characters in C++ when they are preceded by a backslash they will have special meaning and they are used to represent like newline (\\n) or tab (\\t). Here, you have a list of some of such escape sequence codes −"
},
{
"code": null,
"e": 30357,
"s": 30289,
"text": "Following is the example to show a few escape sequence characters −"
},
{
"code": null,
"e": 30458,
"s": 30357,
"text": "#include <iostream>\nusing namespace std;\n\nint main() {\n cout << \"Hello\\tWorld\\n\\n\";\n return 0;\n}"
},
{
"code": null,
"e": 30539,
"s": 30458,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 30554,
"s": 30539,
"text": "Hello World\n"
},
{
"code": null,
"e": 30732,
"s": 30554,
"text": "String literals are enclosed in double quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters."
},
{
"code": null,
"e": 30837,
"s": 30732,
"text": "You can break a long line into multiple lines using string literals and separate them using whitespaces."
},
{
"code": null,
"e": 30923,
"s": 30837,
"text": "Here are some examples of string literals. All the three forms are identical strings."
},
{
"code": null,
"e": 30977,
"s": 30923,
"text": "\"hello, dear\"\n\n\"hello, \\\n\ndear\"\n\n\"hello, \" \"d\" \"ear\"\n"
},
{
"code": null,
"e": 31032,
"s": 30977,
"text": "There are two simple ways in C++ to define constants −"
},
{
"code": null,
"e": 31060,
"s": 31032,
"text": "Using #define preprocessor."
},
{
"code": null,
"e": 31088,
"s": 31060,
"text": "Using #define preprocessor."
},
{
"code": null,
"e": 31109,
"s": 31088,
"text": "Using const keyword."
},
{
"code": null,
"e": 31130,
"s": 31109,
"text": "Using const keyword."
},
{
"code": null,
"e": 31203,
"s": 31130,
"text": "Following is the form to use #define preprocessor to define a constant −"
},
{
"code": null,
"e": 31229,
"s": 31203,
"text": "#define identifier value\n"
},
{
"code": null,
"e": 31271,
"s": 31229,
"text": "Following example explains it in detail −"
},
{
"code": null,
"e": 31483,
"s": 31271,
"text": "#include <iostream>\nusing namespace std;\n\n#define LENGTH 10 \n#define WIDTH 5\n#define NEWLINE '\\n'\n\nint main() {\n int area; \n \n area = LENGTH * WIDTH;\n cout << area;\n cout << NEWLINE;\n return 0;\n}"
},
{
"code": null,
"e": 31564,
"s": 31483,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 31568,
"s": 31564,
"text": "50\n"
},
{
"code": null,
"e": 31648,
"s": 31568,
"text": "You can use const prefix to declare constants with a specific type as follows −"
},
{
"code": null,
"e": 31678,
"s": 31648,
"text": "const type variable = value;\n"
},
{
"code": null,
"e": 31720,
"s": 31678,
"text": "Following example explains it in detail −"
},
{
"code": null,
"e": 31955,
"s": 31720,
"text": "#include <iostream>\nusing namespace std;\n\nint main() {\n const int LENGTH = 10;\n const int WIDTH = 5;\n const char NEWLINE = '\\n';\n int area; \n \n area = LENGTH * WIDTH;\n cout << area;\n cout << NEWLINE;\n return 0;\n}"
},
{
"code": null,
"e": 32036,
"s": 31955,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 32040,
"s": 32036,
"text": "50\n"
},
{
"code": null,
"e": 32117,
"s": 32040,
"text": "Note that it is a good programming practice to define constants in CAPITALS."
},
{
"code": null,
"e": 32321,
"s": 32117,
"text": "C++ allows the char, int, and double data types to have modifiers preceding them. A modifier is used to alter the meaning of the base type so that it more precisely fits the needs of various situations."
},
{
"code": null,
"e": 32363,
"s": 32321,
"text": "The data type modifiers are listed here −"
},
{
"code": null,
"e": 32370,
"s": 32363,
"text": "signed"
},
{
"code": null,
"e": 32379,
"s": 32370,
"text": "unsigned"
},
{
"code": null,
"e": 32384,
"s": 32379,
"text": "long"
},
{
"code": null,
"e": 32390,
"s": 32384,
"text": "short"
},
{
"code": null,
"e": 32568,
"s": 32390,
"text": "The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition, signed and unsigned can be applied to char, and long can be applied to double."
},
{
"code": null,
"e": 32689,
"s": 32568,
"text": "The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example, unsigned long int."
},
{
"code": null,
"e": 32950,
"s": 32689,
"text": "C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without int. It automatically implies int. For example, the following two statements both declare unsigned integer variables."
},
{
"code": null,
"e": 32979,
"s": 32950,
"text": "unsigned x;\nunsigned int y;\n"
},
{
"code": null,
"e": 33131,
"s": 32979,
"text": "To understand the difference between the way signed and unsigned integer modifiers are interpreted by C++, you should run the following short program −"
},
{
"code": null,
"e": 33445,
"s": 33131,
"text": "#include <iostream>\nusing namespace std;\n \n/* This program shows the difference between\n * signed and unsigned integers.\n*/\nint main() {\n short int i; // a signed short integer\n short unsigned int j; // an unsigned short integer\n\n j = 50000;\n\n i = j;\n cout << i << \" \" << j;\n\n return 0;\n}"
},
{
"code": null,
"e": 33497,
"s": 33445,
"text": "When this program is run, following is the output −"
},
{
"code": null,
"e": 33511,
"s": 33497,
"text": "-15536 50000\n"
},
{
"code": null,
"e": 33644,
"s": 33511,
"text": "The above result is because the bit pattern that represents 50,000 as a short unsigned integer is interpreted as -15,536 by a short."
},
{
"code": null,
"e": 33729,
"s": 33644,
"text": "The type qualifiers provide additional information about the variables they precede."
},
{
"code": null,
"e": 33735,
"s": 33729,
"text": "const"
},
{
"code": null,
"e": 33809,
"s": 33735,
"text": "Objects of type const cannot be changed by your program during execution."
},
{
"code": null,
"e": 33818,
"s": 33809,
"text": "volatile"
},
{
"code": null,
"e": 33947,
"s": 33818,
"text": "The modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program."
},
{
"code": null,
"e": 33956,
"s": 33947,
"text": "restrict"
},
{
"code": null,
"e": 34118,
"s": 33956,
"text": "A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Only C99 adds a new type qualifier called restrict."
},
{
"code": null,
"e": 34355,
"s": 34118,
"text": "A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program"
},
{
"code": null,
"e": 34360,
"s": 34355,
"text": "auto"
},
{
"code": null,
"e": 34369,
"s": 34360,
"text": "register"
},
{
"code": null,
"e": 34376,
"s": 34369,
"text": "static"
},
{
"code": null,
"e": 34383,
"s": 34376,
"text": "extern"
},
{
"code": null,
"e": 34391,
"s": 34383,
"text": "mutable"
},
{
"code": null,
"e": 34468,
"s": 34391,
"text": "The auto storage class is the default storage class for all local variables."
},
{
"code": null,
"e": 34506,
"s": 34468,
"text": "{\n int mount;\n auto int month;\n}\n"
},
{
"code": null,
"e": 34638,
"s": 34506,
"text": "The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables."
},
{
"code": null,
"e": 34938,
"s": 34638,
"text": "The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location)."
},
{
"code": null,
"e": 34967,
"s": 34938,
"text": "{\n register int miles;\n}\n"
},
{
"code": null,
"e": 35271,
"s": 34967,
"text": "The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions."
},
{
"code": null,
"e": 35581,
"s": 35271,
"text": "The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls."
},
{
"code": null,
"e": 35747,
"s": 35581,
"text": "The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared."
},
{
"code": null,
"e": 35880,
"s": 35747,
"text": "In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class."
},
{
"code": null,
"e": 36246,
"s": 35880,
"text": "#include <iostream>\n \n// Function declaration\nvoid func(void);\n \nstatic int count = 10; /* Global variable */\n \nmain() {\n while(count--) {\n func();\n }\n \n return 0;\n}\n\n// Function definition\nvoid func( void ) {\n static int i = 5; // local static variable\n i++;\n std::cout << \"i is \" << i ;\n std::cout << \" and count is \" << count << std::endl;\n}"
},
{
"code": null,
"e": 36327,
"s": 36246,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 36554,
"s": 36327,
"text": "i is 6 and count is 9\ni is 7 and count is 8\ni is 8 and count is 7\ni is 9 and count is 6\ni is 10 and count is 5\ni is 11 and count is 4\ni is 12 and count is 3\ni is 13 and count is 2\ni is 14 and count is 1\ni is 15 and count is 0\n"
},
{
"code": null,
"e": 36827,
"s": 36554,
"text": "The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined."
},
{
"code": null,
"e": 37132,
"s": 36827,
"text": "When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file."
},
{
"code": null,
"e": 37274,
"s": 37132,
"text": "The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below."
},
{
"code": null,
"e": 37380,
"s": 37274,
"text": "#include <iostream>\nint count ;\nextern void write_extern();\n \nmain() {\n count = 5;\n write_extern();\n}"
},
{
"code": null,
"e": 37500,
"s": 37380,
"text": "#include <iostream>\n\nextern int count;\n\nvoid write_extern(void) {\n std::cout << \"Count is \" << count << std::endl;\n}\n"
},
{
"code": null,
"e": 37610,
"s": 37500,
"text": "Here, extern keyword is being used to declare count in another file. Now compile these two files as follows −"
},
{
"code": null,
"e": 37646,
"s": 37610,
"text": "$g++ main.cpp support.cpp -o write\n"
},
{
"code": null,
"e": 37745,
"s": 37646,
"text": "This will produce write executable program, try to execute write and check the result as follows −"
},
{
"code": null,
"e": 37757,
"s": 37745,
"text": "$./write\n5\n"
},
{
"code": null,
"e": 37991,
"s": 37757,
"text": "The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member of an object to override const member function. That is, a mutable member can be modified by a const member function."
},
{
"code": null,
"e": 38179,
"s": 37991,
"text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provide the following types of operators −"
},
{
"code": null,
"e": 38200,
"s": 38179,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 38221,
"s": 38200,
"text": "Relational Operators"
},
{
"code": null,
"e": 38239,
"s": 38221,
"text": "Logical Operators"
},
{
"code": null,
"e": 38257,
"s": 38239,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 38278,
"s": 38257,
"text": "Assignment Operators"
},
{
"code": null,
"e": 38293,
"s": 38278,
"text": "Misc Operators"
},
{
"code": null,
"e": 38408,
"s": 38293,
"text": "This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one."
},
{
"code": null,
"e": 38477,
"s": 38408,
"text": "There are following arithmetic operators supported by C++ language −"
},
{
"code": null,
"e": 38536,
"s": 38477,
"text": "Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 38550,
"s": 38536,
"text": "Show Examples"
},
{
"code": null,
"e": 38617,
"s": 38550,
"text": "There are following relational operators supported by C++ language"
},
{
"code": null,
"e": 38676,
"s": 38617,
"text": "Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 38690,
"s": 38676,
"text": "Show Examples"
},
{
"code": null,
"e": 38755,
"s": 38690,
"text": "There are following logical operators supported by C++ language."
},
{
"code": null,
"e": 38812,
"s": 38755,
"text": "Assume variable A holds 1 and variable B holds 0, then −"
},
{
"code": null,
"e": 38826,
"s": 38812,
"text": "Show Examples"
},
{
"code": null,
"e": 38941,
"s": 38826,
"text": "Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −"
},
{
"code": null,
"e": 39018,
"s": 38941,
"text": "Assume if A = 60; and B = 13; now in binary format they will be as follows −"
},
{
"code": null,
"e": 39032,
"s": 39018,
"text": "A = 0011 1100"
},
{
"code": null,
"e": 39046,
"s": 39032,
"text": "B = 0000 1101"
},
{
"code": null,
"e": 39064,
"s": 39046,
"text": "-----------------"
},
{
"code": null,
"e": 39080,
"s": 39064,
"text": "A&B = 0000 1100"
},
{
"code": null,
"e": 39096,
"s": 39080,
"text": "A|B = 0011 1101"
},
{
"code": null,
"e": 39112,
"s": 39096,
"text": "A^B = 0011 0001"
},
{
"code": null,
"e": 39128,
"s": 39112,
"text": "~A = 1100 0011"
},
{
"code": null,
"e": 39270,
"s": 39128,
"text": "The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −"
},
{
"code": null,
"e": 39284,
"s": 39270,
"text": "Show Examples"
},
{
"code": null,
"e": 39353,
"s": 39284,
"text": "There are following assignment operators supported by C++ language −"
},
{
"code": null,
"e": 39367,
"s": 39353,
"text": "Show Examples"
},
{
"code": null,
"e": 39433,
"s": 39367,
"text": "The following table lists some other operators that C++ supports."
},
{
"code": null,
"e": 39440,
"s": 39433,
"text": "sizeof"
},
{
"code": null,
"e": 39553,
"s": 39440,
"text": "sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and will return 4."
},
{
"code": null,
"e": 39571,
"s": 39553,
"text": "Condition ? X : Y"
},
{
"code": null,
"e": 39675,
"s": 39571,
"text": "Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of Y."
},
{
"code": null,
"e": 39677,
"s": 39675,
"text": ","
},
{
"code": null,
"e": 39847,
"s": 39677,
"text": "Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list."
},
{
"code": null,
"e": 39871,
"s": 39847,
"text": ". (dot) and -> (arrow)"
},
{
"code": null,
"e": 39965,
"s": 39871,
"text": "Member operators are used to reference individual members of classes, structures, and unions."
},
{
"code": null,
"e": 39970,
"s": 39965,
"text": "Cast"
},
{
"code": null,
"e": 40063,
"s": 39970,
"text": "Casting operators convert one data type to another. For example, int(2.2000) would return 2."
},
{
"code": null,
"e": 40065,
"s": 40063,
"text": "&"
},
{
"code": null,
"e": 40177,
"s": 40065,
"text": "Pointer operator & returns the address of a variable. For example &a; will give actual address of the variable."
},
{
"code": null,
"e": 40179,
"s": 40177,
"text": "*"
},
{
"code": null,
"e": 40274,
"s": 40179,
"text": "Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var."
},
{
"code": null,
"e": 40536,
"s": 40274,
"text": "Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −"
},
{
"code": null,
"e": 40702,
"s": 40536,
"text": "For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7."
},
{
"code": null,
"e": 40897,
"s": 40702,
"text": "Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first."
},
{
"code": null,
"e": 40911,
"s": 40897,
"text": "Show Examples"
},
{
"code": null,
"e": 41141,
"s": 40911,
"text": "There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": null,
"e": 41247,
"s": 41141,
"text": "Programming languages provide various control structures that allow for more complicated execution paths."
},
{
"code": null,
"e": 41428,
"s": 41247,
"text": "A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages −"
},
{
"code": null,
"e": 41522,
"s": 41428,
"text": "C++ programming language provides the following type of loops to handle looping requirements."
},
{
"code": null,
"e": 41653,
"s": 41522,
"text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 41758,
"s": 41653,
"text": "Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable."
},
{
"code": null,
"e": 41848,
"s": 41758,
"text": "Like a ‘while’ statement, except that it tests the condition at the end of the loop body."
},
{
"code": null,
"e": 41932,
"s": 41848,
"text": "You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop."
},
{
"code": null,
"e": 42099,
"s": 41932,
"text": "Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed."
},
{
"code": null,
"e": 42146,
"s": 42099,
"text": "C++ supports the following control statements."
},
{
"code": null,
"e": 42269,
"s": 42146,
"text": "Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch."
},
{
"code": null,
"e": 42378,
"s": 42269,
"text": "Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating."
},
{
"code": null,
"e": 42486,
"s": 42378,
"text": "Transfers control to the labeled statement. Though it is not advised to use goto statement in your program."
},
{
"code": null,
"e": 42753,
"s": 42486,
"text": "A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless loop by leaving the conditional expression empty."
},
{
"code": null,
"e": 42894,
"s": 42753,
"text": "#include <iostream>\nusing namespace std;\n \nint main () {\n for( ; ; ) {\n printf(\"This loop will run forever.\\n\");\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 43112,
"s": 42894,
"text": "When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the ‘for (;;)’ construct to signify an infinite loop."
},
{
"code": null,
"e": 43181,
"s": 43112,
"text": "NOTE − You can terminate an infinite loop by pressing Ctrl + C keys."
},
{
"code": null,
"e": 43496,
"s": 43181,
"text": "Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false."
},
{
"code": null,
"e": 43610,
"s": 43496,
"text": "Following is the general form of a typical decision making structure found in most of the programming languages −"
},
{
"code": null,
"e": 43691,
"s": 43610,
"text": "C++ programming language provides following types of decision making statements."
},
{
"code": null,
"e": 43778,
"s": 43691,
"text": "An ‘if’ statement consists of a boolean expression followed by one or more statements."
},
{
"code": null,
"e": 43898,
"s": 43778,
"text": "An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the boolean expression is false."
},
{
"code": null,
"e": 43989,
"s": 43898,
"text": "A ‘switch’ statement allows a variable to be tested for equality against a list of values."
},
{
"code": null,
"e": 44080,
"s": 43989,
"text": "You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s)."
},
{
"code": null,
"e": 44153,
"s": 44080,
"text": "You can use one ‘switch’ statement inside another ‘switch’ statement(s)."
},
{
"code": null,
"e": 44303,
"s": 44153,
"text": "We have covered conditional operator “? :” in previous chapter which can be used to replace if...else statements. It has the following general form −"
},
{
"code": null,
"e": 44324,
"s": 44303,
"text": "Exp1 ? Exp2 : Exp3;\n"
},
{
"code": null,
"e": 44405,
"s": 44324,
"text": "Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon."
},
{
"code": null,
"e": 44661,
"s": 44405,
"text": "The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression."
},
{
"code": null,
"e": 44856,
"s": 44661,
"text": "A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions."
},
{
"code": null,
"e": 45065,
"s": 44856,
"text": "You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is such that each function performs a specific task."
},
{
"code": null,
"e": 45225,
"s": 45065,
"text": "A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function."
},
{
"code": null,
"e": 45465,
"s": 45225,
"text": "The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions."
},
{
"code": null,
"e": 45555,
"s": 45465,
"text": "A function is known with various names like a method or a sub-routine or a procedure etc."
},
{
"code": null,
"e": 45617,
"s": 45555,
"text": "The general form of a C++ function definition is as follows −"
},
{
"code": null,
"e": 45690,
"s": 45617,
"text": "return_type function_name( parameter list ) {\n body of the function\n}\n"
},
{
"code": null,
"e": 45806,
"s": 45690,
"text": "A C++ function definition consists of a function header and a function body. Here are all the parts of a function −"
},
{
"code": null,
"e": 46043,
"s": 45806,
"text": "Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void."
},
{
"code": null,
"e": 46280,
"s": 46043,
"text": "Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void."
},
{
"code": null,
"e": 46422,
"s": 46280,
"text": "Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature."
},
{
"code": null,
"e": 46564,
"s": 46422,
"text": "Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature."
},
{
"code": null,
"e": 46896,
"s": 46564,
"text": "Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters."
},
{
"code": null,
"e": 47228,
"s": 46896,
"text": "Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters."
},
{
"code": null,
"e": 47334,
"s": 47228,
"text": "Function Body − The function body contains a collection of statements that define what the function does."
},
{
"code": null,
"e": 47440,
"s": 47334,
"text": "Function Body − The function body contains a collection of statements that define what the function does."
},
{
"code": null,
"e": 47580,
"s": 47440,
"text": "Following is the source code for a function called max(). This function takes two parameters num1 and num2 and return the biggest of both −"
},
{
"code": null,
"e": 47806,
"s": 47580,
"text": "// function returning the max between two numbers\n \nint max(int num1, int num2) {\n // local variable declaration\n int result;\n \n if (num1 > num2)\n result = num1;\n else\n result = num2;\n \n return result; \n}\n"
},
{
"code": null,
"e": 47959,
"s": 47806,
"text": "A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately."
},
{
"code": null,
"e": 48008,
"s": 47959,
"text": "A function declaration has the following parts −"
},
{
"code": null,
"e": 48054,
"s": 48008,
"text": "return_type function_name( parameter list );\n"
},
{
"code": null,
"e": 48132,
"s": 48054,
"text": "For the above defined function max(), following is the function declaration −"
},
{
"code": null,
"e": 48162,
"s": 48132,
"text": "int max(int num1, int num2);\n"
},
{
"code": null,
"e": 48290,
"s": 48162,
"text": "Parameter names are not important in function declaration only their type is required, so following is also valid declaration −"
},
{
"code": null,
"e": 48310,
"s": 48290,
"text": "int max(int, int);\n"
},
{
"code": null,
"e": 48524,
"s": 48310,
"text": "Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function."
},
{
"code": null,
"e": 48675,
"s": 48524,
"text": "While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function."
},
{
"code": null,
"e": 48953,
"s": 48675,
"text": "When a program calls a function, program control is transferred to the called function. A called function performs defined task and when it’s return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program."
},
{
"code": null,
"e": 49129,
"s": 48953,
"text": "To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example −"
},
{
"code": null,
"e": 49671,
"s": 49129,
"text": "#include <iostream>\nusing namespace std;\n \n// function declaration\nint max(int num1, int num2);\n \nint main () {\n // local variable declaration:\n int a = 100;\n int b = 200;\n int ret;\n \n // calling a function to get max value.\n ret = max(a, b);\n cout << \"Max value is : \" << ret << endl;\n \n return 0;\n}\n \n// function returning the max between two numbers\nint max(int num1, int num2) {\n // local variable declaration\n int result;\n \n if (num1 > num2)\n result = num1;\n else\n result = num2;\n \n return result; \n}"
},
{
"code": null,
"e": 49822,
"s": 49671,
"text": "I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result −"
},
{
"code": null,
"e": 49842,
"s": 49822,
"text": "Max value is : 200\n"
},
{
"code": null,
"e": 50010,
"s": 49842,
"text": "If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function."
},
{
"code": null,
"e": 50156,
"s": 50010,
"text": "The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit."
},
{
"code": null,
"e": 50246,
"s": 50156,
"text": "While calling a function, there are two ways that arguments can be passed to a function −"
},
{
"code": null,
"e": 50436,
"s": 50246,
"text": "This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument."
},
{
"code": null,
"e": 50665,
"s": 50436,
"text": "This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument."
},
{
"code": null,
"e": 50898,
"s": 50665,
"text": "This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument."
},
{
"code": null,
"e": 51135,
"s": 50898,
"text": "By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method."
},
{
"code": null,
"e": 51326,
"s": 51135,
"text": "When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function."
},
{
"code": null,
"e": 51675,
"s": 51326,
"text": "This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead. Consider the following example −"
},
{
"code": null,
"e": 52149,
"s": 51675,
"text": "#include <iostream>\nusing namespace std;\n \nint sum(int a, int b = 20) {\n int result;\n result = a + b;\n \n return (result);\n}\nint main () {\n // local variable declaration:\n int a = 100;\n int b = 200;\n int result;\n \n // calling a function to add the values.\n result = sum(a, b);\n cout << \"Total value is :\" << result << endl;\n\n // calling a function again as follows.\n result = sum(a);\n cout << \"Total value is :\" << result << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 52230,
"s": 52149,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 52271,
"s": 52230,
"text": "Total value is :300\nTotal value is :120\n"
},
{
"code": null,
"e": 52501,
"s": 52271,
"text": "Normally, when we work with Numbers, we use primitive data types such as int, short, long, float and double, etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types."
},
{
"code": null,
"e": 52663,
"s": 52501,
"text": "You have already defined numbers in various examples given in previous chapters. Here is another consolidated example to define various types of numbers in C++ −"
},
{
"code": null,
"e": 53160,
"s": 52663,
"text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // number definition:\n short s;\n int i;\n long l;\n float f;\n double d;\n \n // number assignments;\n s = 10; \n i = 1000; \n l = 1000000; \n f = 230.47; \n d = 30949.374;\n \n // number printing;\n cout << \"short s :\" << s << endl;\n cout << \"int i :\" << i << endl;\n cout << \"long l :\" << l << endl;\n cout << \"float f :\" << f << endl;\n cout << \"double d :\" << d << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 53241,
"s": 53160,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 53323,
"s": 53241,
"text": "short s :10\nint i :1000\nlong l :1000000\nfloat f :230.47\ndouble d :30949.4\n"
},
{
"code": null,
"e": 53593,
"s": 53323,
"text": "In addition to the various functions you can create, C++ also includes some useful functions you can use. These functions are available in standard C and C++ libraries and called built-in functions. These are functions that can be included in your program and then use."
},
{
"code": null,
"e": 53772,
"s": 53593,
"text": "C++ has a rich set of mathematical operations, which can be performed on various numbers. Following table lists down some useful built-in mathematical functions available in C++."
},
{
"code": null,
"e": 53849,
"s": 53772,
"text": "To utilize these functions you need to include the math header file <cmath>."
},
{
"code": null,
"e": 53869,
"s": 53849,
"text": "double cos(double);"
},
{
"code": null,
"e": 53936,
"s": 53869,
"text": "This function takes an angle (as a double) and returns the cosine."
},
{
"code": null,
"e": 53956,
"s": 53936,
"text": "double sin(double);"
},
{
"code": null,
"e": 54021,
"s": 53956,
"text": "This function takes an angle (as a double) and returns the sine."
},
{
"code": null,
"e": 54041,
"s": 54021,
"text": "double tan(double);"
},
{
"code": null,
"e": 54109,
"s": 54041,
"text": "This function takes an angle (as a double) and returns the tangent."
},
{
"code": null,
"e": 54129,
"s": 54109,
"text": "double log(double);"
},
{
"code": null,
"e": 54202,
"s": 54129,
"text": "This function takes a number and returns the natural log of that number."
},
{
"code": null,
"e": 54230,
"s": 54202,
"text": "double pow(double, double);"
},
{
"code": null,
"e": 54321,
"s": 54230,
"text": "The first is a number you wish to raise and the second is the power you wish to raise it t"
},
{
"code": null,
"e": 54351,
"s": 54321,
"text": "double hypot(double, double);"
},
{
"code": null,
"e": 54471,
"s": 54351,
"text": "If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse."
},
{
"code": null,
"e": 54492,
"s": 54471,
"text": "double sqrt(double);"
},
{
"code": null,
"e": 54558,
"s": 54492,
"text": "You pass this function a number and it gives you the square root."
},
{
"code": null,
"e": 54572,
"s": 54558,
"text": "int abs(int);"
},
{
"code": null,
"e": 54649,
"s": 54572,
"text": "This function returns the absolute value of an integer that is passed to it."
},
{
"code": null,
"e": 54670,
"s": 54649,
"text": "double fabs(double);"
},
{
"code": null,
"e": 54747,
"s": 54670,
"text": "This function returns the absolute value of any decimal number passed to it."
},
{
"code": null,
"e": 54769,
"s": 54747,
"text": "double floor(double);"
},
{
"code": null,
"e": 54845,
"s": 54769,
"text": "Finds the integer which is less than or equal to the argument passed to it."
},
{
"code": null,
"e": 54920,
"s": 54845,
"text": "Following is a simple example to show few of the mathematical operations −"
},
{
"code": null,
"e": 55393,
"s": 54920,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\n \nint main () {\n // number definition:\n short s = 10;\n int i = -1000;\n long l = 100000;\n float f = 230.47;\n double d = 200.374;\n\n // mathematical operations;\n cout << \"sin(d) :\" << sin(d) << endl;\n cout << \"abs(i) :\" << abs(i) << endl;\n cout << \"floor(d) :\" << floor(d) << endl;\n cout << \"sqrt(f) :\" << sqrt(f) << endl;\n cout << \"pow( d, 2) :\" << pow(d, 2) << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 55474,
"s": 55393,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 55575,
"s": 55474,
"text": "sign(d) :-0.634939\nabs(i) :1000\nfloor(d) :200\nsqrt(f) :15.1812\npow( d, 2 ) :40149.7\n"
},
{
"code": null,
"e": 55867,
"s": 55575,
"text": "There are many cases where you will wish to generate a random number. There are actually two functions you will need to know about random number generation. The first is rand(), this function will only return a pseudo random number. The way to fix this is to first call the srand() function."
},
{
"code": null,
"e": 56060,
"s": 55867,
"text": "Following is a simple example to generate few random numbers. This example makes use of time() function to get the number of seconds on your system time, to randomly seed the rand() function −"
},
{
"code": null,
"e": 56418,
"s": 56060,
"text": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nusing namespace std;\n \nint main () {\n int i,j;\n \n // set the seed\n srand( (unsigned)time( NULL ) );\n\n /* generate 10 random numbers. */\n for( i = 0; i < 10; i++ ) {\n // generate actual random number\n j = rand();\n cout <<\" Random Number : \" << j << endl;\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 56499,
"s": 56418,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 56764,
"s": 56499,
"text": "Random Number : 1748144778\nRandom Number : 630873888\nRandom Number : 2134540646\nRandom Number : 219404170\nRandom Number : 902129458\nRandom Number : 920445370\nRandom Number : 1319072661\nRandom Number : 257938873\nRandom Number : 1256201101\nRandom Number : 580322989\n"
},
{
"code": null,
"e": 57028,
"s": 56764,
"text": "C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 57308,
"s": 57028,
"text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. "
},
{
"code": null,
"e": 57456,
"s": 57308,
"text": "All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element."
},
{
"code": null,
"e": 57595,
"s": 57456,
"text": "To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows −"
},
{
"code": null,
"e": 57626,
"s": 57595,
"text": "type arrayName [ arraySize ];\n"
},
{
"code": null,
"e": 57863,
"s": 57626,
"text": "This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double,\nuse this statement −"
},
{
"code": null,
"e": 57884,
"s": 57863,
"text": "double balance[10];\n"
},
{
"code": null,
"e": 57981,
"s": 57884,
"text": "You can initialize C++ array elements either one by one or using a single statement as follows −"
},
{
"code": null,
"e": 58034,
"s": 57981,
"text": "double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};\n"
},
{
"code": null,
"e": 58245,
"s": 58034,
"text": "The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array −"
},
{
"code": null,
"e": 58371,
"s": 58245,
"text": "If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −"
},
{
"code": null,
"e": 58423,
"s": 58371,
"text": "double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};\n"
},
{
"code": null,
"e": 58498,
"s": 58423,
"text": "You will create exactly the same array as you did in the previous example."
},
{
"code": null,
"e": 58518,
"s": 58498,
"text": "balance[4] = 50.0;\n"
},
{
"code": null,
"e": 58823,
"s": 58518,
"text": "The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representaion of the same array we discussed above −"
},
{
"code": null,
"e": 58989,
"s": 58823,
"text": "An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −"
},
{
"code": null,
"e": 59018,
"s": 58989,
"text": "double salary = balance[9];\n"
},
{
"code": null,
"e": 59248,
"s": 59018,
"text": "The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays −"
},
{
"code": null,
"e": 59789,
"s": 59248,
"text": "#include <iostream>\nusing namespace std;\n \n#include <iomanip>\nusing std::setw;\n \nint main () {\n\n int n[ 10 ]; // n is an array of 10 integers\n \n // initialize elements of array n to 0 \n for ( int i = 0; i < 10; i++ ) {\n n[ i ] = i + 100; // set element at location i to i + 100\n }\n cout << \"Element\" << setw( 13 ) << \"Value\" << endl;\n \n // output each array element's value \n for ( int j = 0; j < 10; j++ ) {\n cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 59934,
"s": 59789,
"text": "This program makes use of setw() function to format the output. When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 60166,
"s": 59934,
"text": "Element Value\n 0 100\n 1 101\n 2 102\n 3 103\n 4 104\n 5 105\n 6 106\n 7 107\n 8 108\n 9 109\n"
},
{
"code": null,
"e": 60319,
"s": 60166,
"text": "Arrays are important to C++ and should need lots of more detail. There are following few important concepts, which should be clear to a C++ programmer −"
},
{
"code": null,
"e": 60435,
"s": 60319,
"text": "C++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array."
},
{
"code": null,
"e": 60551,
"s": 60435,
"text": "You can generate a pointer to the first element of an array by simply specifying the array name, without any index."
},
{
"code": null,
"e": 60651,
"s": 60551,
"text": "You can pass to the function a pointer to an array by specifying the array's name without an index."
},
{
"code": null,
"e": 60693,
"s": 60651,
"text": "C++ allows a function to return an array."
},
{
"code": null,
"e": 60754,
"s": 60693,
"text": "C++ provides following two types of string representations −"
},
{
"code": null,
"e": 60784,
"s": 60754,
"text": "The C-style character string."
},
{
"code": null,
"e": 60836,
"s": 60784,
"text": "The string class type introduced with Standard C++."
},
{
"code": null,
"e": 61148,
"s": 60836,
"text": "The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null."
},
{
"code": null,
"e": 61410,
"s": 61148,
"text": "The following declaration and initialization create a string consisting of the word \"Hello\". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word \"Hello.\""
},
{
"code": null,
"e": 61463,
"s": 61410,
"text": "char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\\0'};\n"
},
{
"code": null,
"e": 61564,
"s": 61463,
"text": "If you follow the rule of array initialization, then you can write the above statement as follows −"
},
{
"code": null,
"e": 61592,
"s": 61564,
"text": "char greeting[] = \"Hello\";\n"
},
{
"code": null,
"e": 61664,
"s": 61592,
"text": "Following is the memory presentation of above defined string in C/C++ −"
},
{
"code": null,
"e": 61891,
"s": 61664,
"text": "Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\\0' at the end of the string when it initializes the array. Let us try to print above-mentioned string −"
},
{
"code": null,
"e": 62083,
"s": 61891,
"text": "#include <iostream>\n\nusing namespace std;\n\nint main () {\n\n char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\\0'};\n\n cout << \"Greeting message: \";\n cout << greeting << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 62164,
"s": 62083,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 62189,
"s": 62164,
"text": "Greeting message: Hello\n"
},
{
"code": null,
"e": 62270,
"s": 62189,
"text": "C++ supports a wide range of functions that manipulate null-terminated strings −"
},
{
"code": null,
"e": 62286,
"s": 62270,
"text": "strcpy(s1, s2);"
},
{
"code": null,
"e": 62319,
"s": 62286,
"text": "Copies string s2 into string s1."
},
{
"code": null,
"e": 62335,
"s": 62319,
"text": "strcat(s1, s2);"
},
{
"code": null,
"e": 62385,
"s": 62335,
"text": "Concatenates string s2 onto the end of string s1."
},
{
"code": null,
"e": 62397,
"s": 62385,
"text": "strlen(s1);"
},
{
"code": null,
"e": 62430,
"s": 62397,
"text": "Returns the length of string s1."
},
{
"code": null,
"e": 62446,
"s": 62430,
"text": "strcmp(s1, s2);"
},
{
"code": null,
"e": 62530,
"s": 62446,
"text": "Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2."
},
{
"code": null,
"e": 62546,
"s": 62530,
"text": "strchr(s1, ch);"
},
{
"code": null,
"e": 62618,
"s": 62546,
"text": "Returns a pointer to the first occurrence of character ch in string s1."
},
{
"code": null,
"e": 62634,
"s": 62618,
"text": "strstr(s1, s2);"
},
{
"code": null,
"e": 62703,
"s": 62634,
"text": "Returns a pointer to the first occurrence of string s2 in string s1."
},
{
"code": null,
"e": 62773,
"s": 62703,
"text": "Following example makes use of few of the above-mentioned functions −"
},
{
"code": null,
"e": 63285,
"s": 62773,
"text": "#include <iostream>\n#include <cstring>\n\nusing namespace std;\n\nint main () {\n\n char str1[10] = \"Hello\";\n char str2[10] = \"World\";\n char str3[10];\n int len ;\n\n // copy str1 into str3\n strcpy( str3, str1);\n cout << \"strcpy( str3, str1) : \" << str3 << endl;\n\n // concatenates str1 and str2\n strcat( str1, str2);\n cout << \"strcat( str1, str2): \" << str1 << endl;\n\n // total lenghth of str1 after concatenation\n len = strlen(str1);\n cout << \"strlen(str1) : \" << len << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 63373,
"s": 63285,
"text": "When the above code is compiled and executed, it produces result something as follows −"
},
{
"code": null,
"e": 63452,
"s": 63373,
"text": "strcpy( str3, str1) : Hello\nstrcat( str1, str2): HelloWorld\nstrlen(str1) : 10\n"
},
{
"code": null,
"e": 63631,
"s": 63452,
"text": "The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. Let us check the following example −"
},
{
"code": null,
"e": 64103,
"s": 63631,
"text": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main () {\n\n string str1 = \"Hello\";\n string str2 = \"World\";\n string str3;\n int len ;\n\n // copy str1 into str3\n str3 = str1;\n cout << \"str3 : \" << str3 << endl;\n\n // concatenates str1 and str2\n str3 = str1 + str2;\n cout << \"str1 + str2 : \" << str3 << endl;\n\n // total length of str3 after concatenation\n len = str3.size();\n cout << \"str3.size() : \" << len << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 64191,
"s": 64103,
"text": "When the above code is compiled and executed, it produces result something as follows −"
},
{
"code": null,
"e": 64248,
"s": 64191,
"text": "str3 : Hello\nstr1 + str2 : HelloWorld\nstr3.size() : 10\n"
},
{
"code": null,
"e": 64434,
"s": 64248,
"text": "C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them."
},
{
"code": null,
"e": 64698,
"s": 64434,
"text": "As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined −"
},
{
"code": null,
"e": 64938,
"s": 64698,
"text": "#include <iostream>\n\nusing namespace std;\nint main () {\n int var1;\n char var2[10];\n\n cout << \"Address of var1 variable: \";\n cout << &var1 << endl;\n\n cout << \"Address of var2 variable: \";\n cout << &var2 << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 65019,
"s": 64938,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 65094,
"s": 65019,
"text": "Address of var1 variable: 0xbfebd5c0\nAddress of var2 variable: 0xbfebd5b6\n"
},
{
"code": null,
"e": 65309,
"s": 65094,
"text": "A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is −"
},
{
"code": null,
"e": 65326,
"s": 65309,
"text": "type *var-name;\n"
},
{
"code": null,
"e": 65678,
"s": 65326,
"text": "Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −"
},
{
"code": null,
"e": 65833,
"s": 65678,
"text": "int *ip; // pointer to an integer\ndouble *dp; // pointer to a double\nfloat *fp; // pointer to a float\nchar *ch // pointer to character\n"
},
{
"code": null,
"e": 66140,
"s": 65833,
"text": "The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to."
},
{
"code": null,
"e": 66569,
"s": 66140,
"text": "There are few important operations, which we will do with the pointers very frequently. (a) We define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations −"
},
{
"code": null,
"e": 67109,
"s": 66569,
"text": "#include <iostream>\n\nusing namespace std;\n\nint main () {\n int var = 20; // actual variable declaration.\n int *ip; // pointer variable \n\n ip = &var; // store address of var in pointer variable\n\n cout << \"Value of var variable: \";\n cout << var << endl;\n\n // print the address stored in ip pointer variable\n cout << \"Address stored in ip variable: \";\n cout << ip << endl;\n\n // access the value at the address available in pointer\n cout << \"Value of *ip variable: \";\n cout << *ip << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 67197,
"s": 67109,
"text": "When the above code is compiled and executed, it produces result something as follows −"
},
{
"code": null,
"e": 67292,
"s": 67197,
"text": "Value of var variable: 20\nAddress stored in ip variable: 0xbfc601ac\nValue of *ip variable: 20\n"
},
{
"code": null,
"e": 67472,
"s": 67292,
"text": "Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer −"
},
{
"code": null,
"e": 67579,
"s": 67472,
"text": "C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries."
},
{
"code": null,
"e": 67658,
"s": 67579,
"text": "There are four arithmetic operators that can be used on pointers: ++, --, +, -"
},
{
"code": null,
"e": 67717,
"s": 67658,
"text": "There is a close relationship between pointers and arrays."
},
{
"code": null,
"e": 67769,
"s": 67717,
"text": "You can define arrays to hold a number of pointers."
},
{
"code": null,
"e": 67824,
"s": 67769,
"text": "C++ allows you to have pointer on a pointer and so on."
},
{
"code": null,
"e": 67965,
"s": 67824,
"text": "Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function."
},
{
"code": null,
"e": 68084,
"s": 67965,
"text": "C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well."
},
{
"code": null,
"e": 68308,
"s": 68084,
"text": "A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable."
},
{
"code": null,
"e": 68418,
"s": 68308,
"text": "References are often confused with pointers but three major differences between references and pointers are −"
},
{
"code": null,
"e": 68549,
"s": 68418,
"text": "You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage."
},
{
"code": null,
"e": 68680,
"s": 68549,
"text": "You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage."
},
{
"code": null,
"e": 68830,
"s": 68680,
"text": "Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time."
},
{
"code": null,
"e": 68980,
"s": 68830,
"text": "Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time."
},
{
"code": null,
"e": 69073,
"s": 68980,
"text": "A reference must be initialized when it is created. Pointers can be initialized at any time."
},
{
"code": null,
"e": 69166,
"s": 69073,
"text": "A reference must be initialized when it is created. Pointers can be initialized at any time."
},
{
"code": null,
"e": 69503,
"s": 69166,
"text": "Think of a variable name as a label attached to the variable's location in memory. You can then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the reference. For example, suppose we have the following example −"
},
{
"code": null,
"e": 69516,
"s": 69503,
"text": "int i = 17;\n"
},
{
"code": null,
"e": 69569,
"s": 69516,
"text": "We can declare reference variables for i as follows."
},
{
"code": null,
"e": 69582,
"s": 69569,
"text": "int& r = i;\n"
},
{
"code": null,
"e": 69852,
"s": 69582,
"text": "Read the & in these declarations as reference. Thus, read the first declaration as \"r is an integer reference initialized to i\" and read the second declaration as \"s is a double reference initialized to d.\". Following example makes use of references on int and double −"
},
{
"code": null,
"e": 70274,
"s": 69852,
"text": "#include <iostream>\n \nusing namespace std;\n \nint main () {\n // declare simple variables\n int i;\n double d;\n \n // declare reference variables\n int& r = i;\n double& s = d;\n \n i = 5;\n cout << \"Value of i : \" << i << endl;\n cout << \"Value of i reference : \" << r << endl;\n \n d = 11.7;\n cout << \"Value of d : \" << d << endl;\n cout << \"Value of d reference : \" << s << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 70364,
"s": 70274,
"text": "When the above code is compiled together and executed, it produces the following result −"
},
{
"code": null,
"e": 70451,
"s": 70364,
"text": "Value of i : 5\nValue of i reference : 5\nValue of d : 11.7\nValue of d reference : 11.7\n"
},
{
"code": null,
"e": 70645,
"s": 70451,
"text": "References are usually used for function argument lists and function return values. So following are two important subjects related to C++ references which should be clear to a C++ programmer −"
},
{
"code": null,
"e": 70728,
"s": 70645,
"text": "C++ supports passing references as function parameter more safely than parameters."
},
{
"code": null,
"e": 70799,
"s": 70728,
"text": "You can return reference from a C++ function like any other data type."
},
{
"code": null,
"e": 71064,
"s": 70799,
"text": "The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program."
},
{
"code": null,
"e": 71249,
"s": 71064,
"text": "There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer."
},
{
"code": null,
"e": 71356,
"s": 71249,
"text": "The structure type tm holds the date and time in the form of a C structure having the following elements −"
},
{
"code": null,
"e": 71779,
"s": 71356,
"text": "struct tm {\n int tm_sec; // seconds of minutes from 0 to 61\n int tm_min; // minutes of hour from 0 to 59\n int tm_hour; // hours of day from 0 to 24\n int tm_mday; // day of month from 1 to 31\n int tm_mon; // month of year from 0 to 11\n int tm_year; // year since 1900\n int tm_wday; // days since sunday\n int tm_yday; // days since January 1st\n int tm_isdst; // hours of daylight savings time\n}\n"
},
{
"code": null,
"e": 72020,
"s": 71779,
"text": "Following are the important functions, which we use while working with date and time in C or C++. All these functions are part of standard C and C++ library and you can check their detail using reference to C++ standard library given below."
},
{
"code": null,
"e": 72047,
"s": 72020,
"text": "time_t time(time_t *time);"
},
{
"code": null,
"e": 72195,
"s": 72047,
"text": "This returns the current calendar time of the system in number of seconds elapsed since January 1, 1970. If the system has no time, .1 is returned."
},
{
"code": null,
"e": 72228,
"s": 72195,
"text": "char *ctime(const time_t *time);"
},
{
"code": null,
"e": 72322,
"s": 72228,
"text": "This returns a pointer to a string of the form day month year hours:minutes:seconds year\\n\\0."
},
{
"code": null,
"e": 72364,
"s": 72322,
"text": "struct tm *localtime(const time_t *time);"
},
{
"code": null,
"e": 72432,
"s": 72364,
"text": "This returns a pointer to the tm structure representing local time."
},
{
"code": null,
"e": 72453,
"s": 72432,
"text": "clock_t clock(void);"
},
{
"code": null,
"e": 72605,
"s": 72453,
"text": "This returns a value that approximates the amount of time the calling program has been running. A value of .1 is returned if the time is not available."
},
{
"code": null,
"e": 72648,
"s": 72605,
"text": "char * asctime ( const struct tm * time );"
},
{
"code": null,
"e": 72827,
"s": 72648,
"text": "This returns a pointer to a string that contains the information stored in the structure pointed to by time converted into the form: day month date hours:minutes:seconds year\\n\\0"
},
{
"code": null,
"e": 72866,
"s": 72827,
"text": "struct tm *gmtime(const time_t *time);"
},
{
"code": null,
"e": 73041,
"s": 72866,
"text": "This returns a pointer to the time in the form of a tm structure. The time is represented in Coordinated Universal Time (UTC), which is essentially Greenwich Mean Time (GMT)."
},
{
"code": null,
"e": 73073,
"s": 73041,
"text": "time_t mktime(struct tm *time);"
},
{
"code": null,
"e": 73170,
"s": 73073,
"text": "This returns the calendar-time equivalent of the time found in the structure pointed to by time."
},
{
"code": null,
"e": 73218,
"s": 73170,
"text": "double difftime ( time_t time2, time_t time1 );"
},
{
"code": null,
"e": 73294,
"s": 73218,
"text": "This function calculates the difference in seconds between time1 and time2."
},
{
"code": null,
"e": 73313,
"s": 73294,
"text": "size_t strftime();"
},
{
"code": null,
"e": 73385,
"s": 73313,
"text": "This function can be used to format date and time in a specific format."
},
{
"code": null,
"e": 73560,
"s": 73385,
"text": "Suppose you want to retrieve the current system date and time, either as a local time or as a Coordinated Universal Time (UTC). Following is the example to achieve the same −"
},
{
"code": null,
"e": 73974,
"s": 73560,
"text": "#include <iostream>\n#include <ctime>\n\nusing namespace std;\n\nint main() {\n // current date/time based on current system\n time_t now = time(0);\n \n // convert now to string form\n char* dt = ctime(&now);\n\n cout << \"The local date and time is: \" << dt << endl;\n\n // convert now to tm struct for UTC\n tm *gmtm = gmtime(&now);\n dt = asctime(gmtm);\n cout << \"The UTC date and time is:\"<< dt << endl;\n}"
},
{
"code": null,
"e": 74055,
"s": 73974,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 74160,
"s": 74055,
"text": "The local date and time is: Sat Jan 8 20:07:41 2011\n\nThe UTC date and time is:Sun Jan 9 03:07:41 2011\n"
},
{
"code": null,
"e": 74500,
"s": 74160,
"text": "The tm structure is very important while working with date and time in either C or C++. This structure holds the date and time in the form of a C structure as mentioned above. Most of the time related functions makes use of tm structure. Following is an example which makes use of various date and time related functions and tm structure −"
},
{
"code": null,
"e": 74674,
"s": 74500,
"text": "While using structure in this chapter, I'm making an assumption that you have basic understanding on C structure and how to access structure members using arrow -> operator."
},
{
"code": null,
"e": 75223,
"s": 74674,
"text": "#include <iostream>\n#include <ctime>\n\nusing namespace std;\n\nint main() {\n // current date/time based on current system\n time_t now = time(0);\n\n cout << \"Number of sec since January 1,1970 is:: \" << now << endl;\n\n tm *ltm = localtime(&now);\n\n // print various components of tm structure.\n cout << \"Year:\" << 1900 + ltm->tm_year<<endl;\n cout << \"Month: \"<< 1 + ltm->tm_mon<< endl;\n cout << \"Day: \"<< ltm->tm_mday << endl;\n cout << \"Time: \"<< 5+ltm->tm_hour << \":\";\n cout << 30+ltm->tm_min << \":\";\n cout << ltm->tm_sec << endl;\n}"
},
{
"code": null,
"e": 75304,
"s": 75223,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 75397,
"s": 75304,
"text": "Number of sec since January 1,1970 is:: 1588485717\nYear:2020\nMonth: 5\nDay: 3\nTime: 11:31:57\n"
},
{
"code": null,
"e": 75618,
"s": 75397,
"text": "The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming."
},
{
"code": null,
"e": 75970,
"s": 75618,
"text": "C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called output operation."
},
{
"code": null,
"e": 76031,
"s": 75970,
"text": "There are following header files important to C++ programs −"
},
{
"code": null,
"e": 76042,
"s": 76031,
"text": "<iostream>"
},
{
"code": null,
"e": 76265,
"s": 76042,
"text": "This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively."
},
{
"code": null,
"e": 76275,
"s": 76265,
"text": "<iomanip>"
},
{
"code": null,
"e": 76420,
"s": 76275,
"text": "This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision."
},
{
"code": null,
"e": 76430,
"s": 76420,
"text": "<fstream>"
},
{
"code": null,
"e": 76566,
"s": 76430,
"text": "This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter."
},
{
"code": null,
"e": 76892,
"s": 76566,
"text": "The predefined object cout is an instance of ostream class. The cout object is said to be \"connected to\" the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example."
},
{
"code": null,
"e": 77031,
"s": 76892,
"text": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n char str[] = \"Hello C++\";\n \n cout << \"Value of str is : \" << str << endl;\n}"
},
{
"code": null,
"e": 77112,
"s": 77031,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 77141,
"s": 77112,
"text": "Value of str is : Hello C++\n"
},
{
"code": null,
"e": 77411,
"s": 77141,
"text": "The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings and pointer values."
},
{
"code": null,
"e": 77560,
"s": 77411,
"text": "The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line."
},
{
"code": null,
"e": 77878,
"s": 77560,
"text": "The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example."
},
{
"code": null,
"e": 78060,
"s": 77878,
"text": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n char name[50];\n \n cout << \"Please enter your name: \";\n cin >> name;\n cout << \"Your name is: \" << name << endl;\n \n}"
},
{
"code": null,
"e": 78209,
"s": 78060,
"text": "When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the following result −"
},
{
"code": null,
"e": 78268,
"s": 78209,
"text": "Please enter your name: cplusplus\nYour name is: cplusplus\n"
},
{
"code": null,
"e": 78449,
"s": 78268,
"text": "The C++ compiler also determines the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables."
},
{
"code": null,
"e": 78592,
"s": 78449,
"text": "The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following −"
},
{
"code": null,
"e": 78613,
"s": 78592,
"text": "cin >> name >> age;\n"
},
{
"code": null,
"e": 78671,
"s": 78613,
"text": "This will be equivalent to the following two statements −"
},
{
"code": null,
"e": 78697,
"s": 78671,
"text": "cin >> name;\ncin >> age;\n"
},
{
"code": null,
"e": 78967,
"s": 78697,
"text": "The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately."
},
{
"code": null,
"e": 79074,
"s": 78967,
"text": "The cerr is also used in conjunction with the stream insertion operator as shown in the following example."
},
{
"code": null,
"e": 79220,
"s": 79074,
"text": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n char str[] = \"Unable to read....\";\n \n cerr << \"Error message : \" << str << endl;\n}"
},
{
"code": null,
"e": 79301,
"s": 79220,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 79337,
"s": 79301,
"text": "Error message : Unable to read....\n"
},
{
"code": null,
"e": 79674,
"s": 79337,
"text": "The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed."
},
{
"code": null,
"e": 79781,
"s": 79674,
"text": "The clog is also used in conjunction with the stream insertion operator as shown in the following example."
},
{
"code": null,
"e": 79927,
"s": 79781,
"text": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n char str[] = \"Unable to read....\";\n \n clog << \"Error message : \" << str << endl;\n}"
},
{
"code": null,
"e": 80008,
"s": 79927,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 80044,
"s": 80008,
"text": "Error message : Unable to read....\n"
},
{
"code": null,
"e": 80348,
"s": 80044,
"text": "You would not be able to see any difference in cout, cerr and clog with these small examples, but while writing and executing big programs the difference becomes obvious. So it is good practice to display error messages using cerr stream and while displaying other log messages then clog should be used."
},
{
"code": null,
"e": 80548,
"s": 80348,
"text": "C/C++ arrays allow you to define variables that combine several data items of the same kind, but structure is another user defined data type which allows you to combine data items of different kinds."
},
{
"code": null,
"e": 80717,
"s": 80548,
"text": "Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −"
},
{
"code": null,
"e": 80723,
"s": 80717,
"text": "Title"
},
{
"code": null,
"e": 80730,
"s": 80723,
"text": "Author"
},
{
"code": null,
"e": 80738,
"s": 80730,
"text": "Subject"
},
{
"code": null,
"e": 80746,
"s": 80738,
"text": "Book ID"
},
{
"code": null,
"e": 80940,
"s": 80746,
"text": "To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this −"
},
{
"code": null,
"e": 81078,
"s": 80940,
"text": "struct [structure tag] {\n member definition;\n member definition;\n ...\n member definition;\n} [one or more structure variables]; \n"
},
{
"code": null,
"e": 81428,
"s": 81078,
"text": "The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −"
},
{
"code": null,
"e": 81536,
"s": 81428,
"text": "struct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n} book; \n"
},
{
"code": null,
"e": 81870,
"s": 81536,
"text": "To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure −"
},
{
"code": null,
"e": 83035,
"s": 81870,
"text": "#include <iostream>\n#include <cstring>\n \nusing namespace std;\n \nstruct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n};\n \nint main() {\n struct Books Book1; // Declare Book1 of type Book\n struct Books Book2; // Declare Book2 of type Book\n \n // book 1 specification\n strcpy( Book1.title, \"Learn C++ Programming\");\n strcpy( Book1.author, \"Chand Miyan\"); \n strcpy( Book1.subject, \"C++ Programming\");\n Book1.book_id = 6495407;\n\n // book 2 specification\n strcpy( Book2.title, \"Telecom Billing\");\n strcpy( Book2.author, \"Yakit Singha\");\n strcpy( Book2.subject, \"Telecom\");\n Book2.book_id = 6495700;\n \n // Print Book1 info\n cout << \"Book 1 title : \" << Book1.title <<endl;\n cout << \"Book 1 author : \" << Book1.author <<endl;\n cout << \"Book 1 subject : \" << Book1.subject <<endl;\n cout << \"Book 1 id : \" << Book1.book_id <<endl;\n\n // Print Book2 info\n cout << \"Book 2 title : \" << Book2.title <<endl;\n cout << \"Book 2 author : \" << Book2.author <<endl;\n cout << \"Book 2 subject : \" << Book2.subject <<endl;\n cout << \"Book 2 id : \" << Book2.book_id <<endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 83116,
"s": 83035,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 83340,
"s": 83116,
"text": "Book 1 title : Learn C++ Programming\nBook 1 author : Chand Miyan\nBook 1 subject : C++ Programming\nBook 1 id : 6495407\nBook 2 title : Telecom Billing\nBook 2 author : Yakit Singha\nBook 2 subject : Telecom\nBook 2 id : 6495700\n"
},
{
"code": null,
"e": 83551,
"s": 83340,
"text": "You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example −"
},
{
"code": null,
"e": 84613,
"s": 83551,
"text": "#include <iostream>\n#include <cstring>\n \nusing namespace std;\nvoid printBook( struct Books book );\n\nstruct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n};\n \nint main() {\n struct Books Book1; // Declare Book1 of type Book\n struct Books Book2; // Declare Book2 of type Book\n \n // book 1 specification\n strcpy( Book1.title, \"Learn C++ Programming\");\n strcpy( Book1.author, \"Chand Miyan\"); \n strcpy( Book1.subject, \"C++ Programming\");\n Book1.book_id = 6495407;\n\n // book 2 specification\n strcpy( Book2.title, \"Telecom Billing\");\n strcpy( Book2.author, \"Yakit Singha\");\n strcpy( Book2.subject, \"Telecom\");\n Book2.book_id = 6495700;\n \n // Print Book1 info\n printBook( Book1 );\n\n // Print Book2 info\n printBook( Book2 );\n\n return 0;\n}\nvoid printBook( struct Books book ) {\n cout << \"Book title : \" << book.title <<endl;\n cout << \"Book author : \" << book.author <<endl;\n cout << \"Book subject : \" << book.subject <<endl;\n cout << \"Book id : \" << book.book_id <<endl;\n}"
},
{
"code": null,
"e": 84694,
"s": 84613,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 84902,
"s": 84694,
"text": "Book title : Learn C++ Programming\nBook author : Chand Miyan\nBook subject : C++ Programming\nBook id : 6495407\nBook title : Telecom Billing\nBook author : Yakit Singha\nBook subject : Telecom\nBook id : 6495700\n"
},
{
"code": null,
"e": 85017,
"s": 84902,
"text": "You can define pointers to structures in very similar way as you define pointer to any other variable as follows −"
},
{
"code": null,
"e": 85048,
"s": 85017,
"text": "struct Books *struct_pointer;\n"
},
{
"code": null,
"e": 85249,
"s": 85048,
"text": "Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows −"
},
{
"code": null,
"e": 85275,
"s": 85249,
"text": "struct_pointer = &Book1;\n"
},
{
"code": null,
"e": 85389,
"s": 85275,
"text": "To access the members of a structure using a pointer to that structure, you must use the -> operator as follows −"
},
{
"code": null,
"e": 85413,
"s": 85389,
"text": "struct_pointer->title;\n"
},
{
"code": null,
"e": 85527,
"s": 85413,
"text": "Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept −"
},
{
"code": null,
"e": 86715,
"s": 85527,
"text": "#include <iostream>\n#include <cstring>\n \nusing namespace std;\nvoid printBook( struct Books *book );\n\nstruct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n};\nint main() {\n struct Books Book1; // Declare Book1 of type Book\n struct Books Book2; // Declare Book2 of type Book\n \n // Book 1 specification\n strcpy( Book1.title, \"Learn C++ Programming\");\n strcpy( Book1.author, \"Chand Miyan\"); \n strcpy( Book1.subject, \"C++ Programming\");\n Book1.book_id = 6495407;\n\n // Book 2 specification\n strcpy( Book2.title, \"Telecom Billing\");\n strcpy( Book2.author, \"Yakit Singha\");\n strcpy( Book2.subject, \"Telecom\");\n Book2.book_id = 6495700;\n \n // Print Book1 info, passing address of structure\n printBook( &Book1 );\n\n // Print Book1 info, passing address of structure\n printBook( &Book2 );\n\n return 0;\n}\n\n// This function accept pointer to structure as parameter.\nvoid printBook( struct Books *book ) {\n cout << \"Book title : \" << book->title <<endl;\n cout << \"Book author : \" << book->author <<endl;\n cout << \"Book subject : \" << book->subject <<endl;\n cout << \"Book id : \" << book->book_id <<endl;\n}"
},
{
"code": null,
"e": 86796,
"s": 86715,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 87004,
"s": 86796,
"text": "Book title : Learn C++ Programming\nBook author : Chand Miyan\nBook subject : C++ Programming\nBook id : 6495407\nBook title : Telecom Billing\nBook author : Yakit Singha\nBook subject : Telecom\nBook id : 6495700\n"
},
{
"code": null,
"e": 87098,
"s": 87004,
"text": "There is an easier way to define structs or you could \"alias\" types you create. For example −"
},
{
"code": null,
"e": 87207,
"s": 87098,
"text": "typedef struct {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n} Books;\n"
},
{
"code": null,
"e": 87331,
"s": 87207,
"text": "Now, you can use Books directly to define variables of Books type without using struct keyword. Following is the example −"
},
{
"code": null,
"e": 87352,
"s": 87331,
"text": "Books Book1, Book2;\n"
},
{
"code": null,
"e": 87417,
"s": 87352,
"text": "You can use typedef keyword for non-structs as well as follows −"
},
{
"code": null,
"e": 87462,
"s": 87417,
"text": "typedef long int *pint32;\n \npint32 x, y, z;\n"
},
{
"code": null,
"e": 87504,
"s": 87462,
"text": "x, y and z are all pointers to long ints."
},
{
"code": null,
"e": 87725,
"s": 87504,
"text": "The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types."
},
{
"code": null,
"e": 87943,
"s": 87725,
"text": "A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class."
},
{
"code": null,
"e": 88202,
"s": 87943,
"text": "When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object."
},
{
"code": null,
"e": 88499,
"s": 88202,
"text": "A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows −"
},
{
"code": null,
"e": 88653,
"s": 88499,
"text": "class Box {\n public:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\n"
},
{
"code": null,
"e": 88960,
"s": 88653,
"text": "The keyword public determines the access attributes of the members of the class that follows it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section."
},
{
"code": null,
"e": 89223,
"s": 88960,
"text": "A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box −"
},
{
"code": null,
"e": 89318,
"s": 89223,
"text": "Box Box1; // Declare Box1 of type Box\nBox Box2; // Declare Box2 of type Box\n"
},
{
"code": null,
"e": 89394,
"s": 89318,
"text": "Both of the objects Box1 and Box2 will have their own copy of data members."
},
{
"code": null,
"e": 89561,
"s": 89394,
"text": "The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try the following example to make the things clear −"
},
{
"code": null,
"e": 90393,
"s": 89561,
"text": "#include <iostream>\n\nusing namespace std;\n\nclass Box {\n public:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\n\nint main() {\n Box Box1; // Declare Box1 of type Box\n Box Box2; // Declare Box2 of type Box\n double volume = 0.0; // Store the volume of a box here\n \n // box 1 specification\n Box1.height = 5.0; \n Box1.length = 6.0; \n Box1.breadth = 7.0;\n\n // box 2 specification\n Box2.height = 10.0;\n Box2.length = 12.0;\n Box2.breadth = 13.0;\n \n // volume of box 1\n volume = Box1.height * Box1.length * Box1.breadth;\n cout << \"Volume of Box1 : \" << volume <<endl;\n\n // volume of box 2\n volume = Box2.height * Box2.length * Box2.breadth;\n cout << \"Volume of Box2 : \" << volume <<endl;\n return 0;\n}"
},
{
"code": null,
"e": 90474,
"s": 90393,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 90518,
"s": 90474,
"text": "Volume of Box1 : 210\nVolume of Box2 : 1560\n"
},
{
"code": null,
"e": 90712,
"s": 90518,
"text": "It is important to note that private and protected members can not be accessed directly using direct member access operator (.). We will learn how private and protected members can be accessed."
},
{
"code": null,
"e": 90915,
"s": 90712,
"text": "So far, you have got very basic idea about C++ Classes and Objects. There are further interesting concepts related to C++ Classes and Objects which we will discuss in various sub-sections listed below −"
},
{
"code": null,
"e": 91052,
"s": 90915,
"text": "A member function of a class is a function that has its definition or its prototype within the class definition like any other variable."
},
{
"code": null,
"e": 91163,
"s": 91052,
"text": "A class member can be defined as public, private or protected. By default members would be assumed as private."
},
{
"code": null,
"e": 91362,
"s": 91163,
"text": "A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted."
},
{
"code": null,
"e": 91512,
"s": 91362,
"text": "The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously."
},
{
"code": null,
"e": 91600,
"s": 91512,
"text": "A friend function is permitted full access to private and protected members of a class."
},
{
"code": null,
"e": 91727,
"s": 91600,
"text": "With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function."
},
{
"code": null,
"e": 91802,
"s": 91727,
"text": "Every object has a special pointer this which points to the object itself."
},
{
"code": null,
"e": 91946,
"s": 91802,
"text": "A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it."
},
{
"code": null,
"e": 92023,
"s": 91946,
"text": "Both data members and function members of a class can be declared as static."
},
{
"code": null,
"e": 92337,
"s": 92023,
"text": "One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time."
},
{
"code": null,
"e": 92627,
"s": 92337,
"text": "When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class."
},
{
"code": null,
"e": 92775,
"s": 92627,
"text": "The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on."
},
{
"code": null,
"e": 93063,
"s": 92775,
"text": "A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form −"
},
{
"code": null,
"e": 93113,
"s": 93063,
"text": "class derived-class: access-specifier base-class\n"
},
{
"code": null,
"e": 93303,
"s": 93113,
"text": "Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default."
},
{
"code": null,
"e": 93376,
"s": 93303,
"text": "Consider a base class Shape and its derived class Rectangle as follows −"
},
{
"code": null,
"e": 93952,
"s": 93376,
"text": "#include <iostream>\n \nusing namespace std;\n\n// Base class\nclass Shape {\n public:\n void setWidth(int w) {\n width = w;\n }\n void setHeight(int h) {\n height = h;\n }\n \n protected:\n int width;\n int height;\n};\n\n// Derived class\nclass Rectangle: public Shape {\n public:\n int getArea() { \n return (width * height); \n }\n};\n\nint main(void) {\n Rectangle Rect;\n \n Rect.setWidth(5);\n Rect.setHeight(7);\n\n // Print the area of the object.\n cout << \"Total area: \" << Rect.getArea() << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 94033,
"s": 93952,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 94049,
"s": 94033,
"text": "Total area: 35\n"
},
{
"code": null,
"e": 94266,
"s": 94049,
"text": "A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class."
},
{
"code": null,
"e": 94368,
"s": 94266,
"text": "We can summarize the different access types according to - who can access them in the following way −"
},
{
"code": null,
"e": 94448,
"s": 94368,
"text": "A derived class inherits all base class methods with the following exceptions −"
},
{
"code": null,
"e": 94515,
"s": 94448,
"text": "Constructors, destructors and copy constructors of the base class."
},
{
"code": null,
"e": 94555,
"s": 94515,
"text": "Overloaded operators of the base class."
},
{
"code": null,
"e": 94595,
"s": 94555,
"text": "The friend functions of the base class."
},
{
"code": null,
"e": 94800,
"s": 94595,
"text": "When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. The type of inheritance is specified by the access-specifier as explained above."
},
{
"code": null,
"e": 94963,
"s": 94800,
"text": "We hardly use protected or private inheritance, but public inheritance is commonly used. While using different type of inheritance, following rules are applied −"
},
{
"code": null,
"e": 95367,
"s": 94963,
"text": "Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class."
},
{
"code": null,
"e": 95771,
"s": 95367,
"text": "Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class."
},
{
"code": null,
"e": 95933,
"s": 95771,
"text": "Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class."
},
{
"code": null,
"e": 96095,
"s": 95933,
"text": "Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class."
},
{
"code": null,
"e": 96250,
"s": 96095,
"text": "Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class."
},
{
"code": null,
"e": 96405,
"s": 96250,
"text": "Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class."
},
{
"code": null,
"e": 96496,
"s": 96405,
"text": "A C++ class can inherit members from more than one class and here is the extended syntax −"
},
{
"code": null,
"e": 96549,
"s": 96496,
"text": "class derived-class: access baseA, access baseB....\n"
},
{
"code": null,
"e": 96729,
"s": 96549,
"text": "Where access is one of public, protected, or private and would be given for every base class and they will be separated by comma as shown above. Let us try the following example −"
},
{
"code": null,
"e": 97597,
"s": 96729,
"text": "#include <iostream>\n \nusing namespace std;\n\n// Base class Shape\nclass Shape {\n public:\n void setWidth(int w) {\n width = w;\n }\n void setHeight(int h) {\n height = h;\n }\n \n protected:\n int width;\n int height;\n};\n\n// Base class PaintCost\nclass PaintCost {\n public:\n int getCost(int area) {\n return area * 70;\n }\n};\n\n// Derived class\nclass Rectangle: public Shape, public PaintCost {\n public:\n int getArea() {\n return (width * height); \n }\n};\n\nint main(void) {\n Rectangle Rect;\n int area;\n \n Rect.setWidth(5);\n Rect.setHeight(7);\n\n area = Rect.getArea();\n \n // Print the area of the object.\n cout << \"Total area: \" << Rect.getArea() << endl;\n\n // Print the total cost of painting\n cout << \"Total paint cost: $\" << Rect.getCost(area) << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 97678,
"s": 97597,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 97718,
"s": 97678,
"text": "Total area: 35\nTotal paint cost: $2450\n"
},
{
"code": null,
"e": 97899,
"s": 97718,
"text": "C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively."
},
{
"code": null,
"e": 98142,
"s": 97899,
"text": "An overloaded declaration is a declaration that is declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation)."
},
{
"code": null,
"e": 98499,
"s": 98142,
"text": "When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution."
},
{
"code": null,
"e": 98779,
"s": 98499,
"text": "You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type."
},
{
"code": null,
"e": 98878,
"s": 98779,
"text": "Following is the example where same function print() is being used to print different data types −"
},
{
"code": null,
"e": 99438,
"s": 98878,
"text": "#include <iostream>\nusing namespace std;\n \nclass printData {\n public:\n void print(int i) {\n cout << \"Printing int: \" << i << endl;\n }\n void print(double f) {\n cout << \"Printing float: \" << f << endl;\n }\n void print(char* c) {\n cout << \"Printing character: \" << c << endl;\n }\n};\n\nint main(void) {\n printData pd;\n \n // Call print to print integer\n pd.print(5);\n \n // Call print to print float\n pd.print(500.263);\n \n // Call print to print character\n pd.print(\"Hello C++\");\n \n return 0;\n}"
},
{
"code": null,
"e": 99519,
"s": 99438,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 99590,
"s": 99519,
"text": "Printing int: 5\nPrinting float: 500.263\nPrinting character: Hello C++\n"
},
{
"code": null,
"e": 99738,
"s": 99590,
"text": "You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well."
},
{
"code": null,
"e": 99959,
"s": 99738,
"text": "Overloaded operators are functions with special names: the keyword \"operator\" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list."
},
{
"code": null,
"e": 99987,
"s": 99959,
"text": "Box operator+(const Box&);\n"
},
{
"code": null,
"e": 100330,
"s": 99987,
"text": "declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows −"
},
{
"code": null,
"e": 100370,
"s": 100330,
"text": "Box operator+(const Box&, const Box&);\n"
},
{
"code": null,
"e": 100656,
"s": 100370,
"text": "Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below −"
},
{
"code": null,
"e": 102321,
"s": 100656,
"text": "#include <iostream>\nusing namespace std;\n\nclass Box {\n public:\n double getVolume(void) {\n return length * breadth * height;\n }\n void setLength( double len ) {\n length = len;\n }\n void setBreadth( double bre ) {\n breadth = bre;\n }\n void setHeight( double hei ) {\n height = hei;\n }\n \n // Overload + operator to add two Box objects.\n Box operator+(const Box& b) {\n Box box;\n box.length = this->length + b.length;\n box.breadth = this->breadth + b.breadth;\n box.height = this->height + b.height;\n return box;\n }\n \n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\n\n// Main function for the program\nint main() {\n Box Box1; // Declare Box1 of type Box\n Box Box2; // Declare Box2 of type Box\n Box Box3; // Declare Box3 of type Box\n double volume = 0.0; // Store the volume of a box here\n \n // box 1 specification\n Box1.setLength(6.0); \n Box1.setBreadth(7.0); \n Box1.setHeight(5.0);\n \n // box 2 specification\n Box2.setLength(12.0); \n Box2.setBreadth(13.0); \n Box2.setHeight(10.0);\n \n // volume of box 1\n volume = Box1.getVolume();\n cout << \"Volume of Box1 : \" << volume <<endl;\n \n // volume of box 2\n volume = Box2.getVolume();\n cout << \"Volume of Box2 : \" << volume <<endl;\n\n // Add two object as follows:\n Box3 = Box1 + Box2;\n\n // volume of box 3\n volume = Box3.getVolume();\n cout << \"Volume of Box3 : \" << volume <<endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 102402,
"s": 102321,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 102468,
"s": 102402,
"text": "Volume of Box1 : 210\nVolume of Box2 : 1560\nVolume of Box3 : 5400\n"
},
{
"code": null,
"e": 102529,
"s": 102468,
"text": "Following is the list of operators which can be overloaded −"
},
{
"code": null,
"e": 102595,
"s": 102529,
"text": "Following is the list of operators, which can not be overloaded −"
},
{
"code": null,
"e": 102684,
"s": 102595,
"text": "Here are various operator overloading examples to help you in understanding the concept."
},
{
"code": null,
"e": 102836,
"s": 102684,
"text": "The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance."
},
{
"code": null,
"e": 102998,
"s": 102836,
"text": "C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function."
},
{
"code": null,
"e": 103088,
"s": 102998,
"text": "Consider the following example where a base class has been derived by other two classes −"
},
{
"code": null,
"e": 104167,
"s": 103088,
"text": "#include <iostream> \nusing namespace std;\n \nclass Shape {\n protected:\n int width, height;\n \n public:\n Shape( int a = 0, int b = 0){\n width = a;\n height = b;\n }\n int area() {\n cout << \"Parent class area :\" <<endl;\n return 0;\n }\n};\nclass Rectangle: public Shape {\n public:\n Rectangle( int a = 0, int b = 0):Shape(a, b) { }\n \n int area () { \n cout << \"Rectangle class area :\" <<endl;\n return (width * height); \n }\n};\n\nclass Triangle: public Shape {\n public:\n Triangle( int a = 0, int b = 0):Shape(a, b) { }\n \n int area () { \n cout << \"Triangle class area :\" <<endl;\n return (width * height / 2); \n }\n};\n\n// Main function for the program\nint main() {\n Shape *shape;\n Rectangle rec(10,7);\n Triangle tri(10,5);\n\n // store the address of Rectangle\n shape = &rec;\n \n // call rectangle area.\n shape->area();\n\n // store the address of Triangle\n shape = &tri;\n \n // call triangle area.\n shape->area();\n \n return 0;\n}"
},
{
"code": null,
"e": 104248,
"s": 104167,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 104289,
"s": 104248,
"text": "Parent class area :\nParent class area :\n"
},
{
"code": null,
"e": 104693,
"s": 104289,
"text": "The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage - the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program."
},
{
"code": null,
"e": 104862,
"s": 104693,
"text": "But now, let's make a slight modification in our program and precede the declaration of area() in the Shape class with the keyword virtual so that it looks like this −"
},
{
"code": null,
"e": 105124,
"s": 104862,
"text": "class Shape {\n protected:\n int width, height;\n \n public:\n Shape( int a = 0, int b = 0) {\n width = a;\n height = b;\n }\n virtual int area() {\n cout << \"Parent class area :\" <<endl;\n return 0;\n }\n};\n"
},
{
"code": null,
"e": 105248,
"s": 105124,
"text": "After this slight modification, when the previous example code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 105290,
"s": 105248,
"text": "Rectangle class area\nTriangle class area\n"
},
{
"code": null,
"e": 105493,
"s": 105290,
"text": "This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called."
},
{
"code": null,
"e": 105761,
"s": 105493,
"text": "As you can see, each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations."
},
{
"code": null,
"e": 106017,
"s": 105761,
"text": "A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function."
},
{
"code": null,
"e": 106247,
"s": 106017,
"text": "What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding."
},
{
"code": null,
"e": 106498,
"s": 106247,
"text": "It is possible that you want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class."
},
{
"code": null,
"e": 106577,
"s": 106498,
"text": "We can change the virtual function area() in the base class to the following −"
},
{
"code": null,
"e": 106799,
"s": 106577,
"text": "class Shape {\n protected:\n int width, height;\n\n public:\n Shape(int a = 0, int b = 0) {\n width = a;\n height = b;\n }\n \n // pure virtual function\n virtual int area() = 0;\n};\n"
},
{
"code": null,
"e": 106922,
"s": 106799,
"text": "The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function."
},
{
"code": null,
"e": 107129,
"s": 106922,
"text": "Data abstraction refers to providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details."
},
{
"code": null,
"e": 107249,
"s": 107129,
"text": "Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation."
},
{
"code": null,
"e": 107620,
"s": 107249,
"text": "Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know its internal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen."
},
{
"code": null,
"e": 107867,
"s": 107620,
"text": "Thus, we can say a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having any knowledge of its internals."
},
{
"code": null,
"e": 108141,
"s": 107867,
"text": "In C++, classes provides great level of data abstraction. They provide sufficient public methods to the outside world to play with the functionality of the object and to manipulate object data, i.e., state without actually knowing how class has been implemented internally."
},
{
"code": null,
"e": 108485,
"s": 108141,
"text": "For example, your program can make a call to the sort() function without knowing what algorithm the function actually uses to sort the given values. In fact, the underlying implementation of the sorting functionality could change between releases of the library, and as long as the interface stays the same, your function call will still work."
},
{
"code": null,
"e": 108644,
"s": 108485,
"text": "In C++, we use classes to define our own abstract data types (ADT). You can use the cout object of class ostream to stream data to standard output like this −"
},
{
"code": null,
"e": 108745,
"s": 108644,
"text": "#include <iostream>\nusing namespace std;\n\nint main() {\n cout << \"Hello C++\" <<endl;\n return 0;\n}"
},
{
"code": null,
"e": 108935,
"s": 108745,
"text": "Here, you don't need to understand how cout displays the text on the user's screen. You need to only know the public interface and the underlying implementation of ‘cout’ is free to change."
},
{
"code": null,
"e": 109060,
"s": 108935,
"text": "In C++, we use access labels to define the abstract interface to the class. A class may contain zero or more access labels −"
},
{
"code": null,
"e": 109210,
"s": 109060,
"text": "Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members."
},
{
"code": null,
"e": 109360,
"s": 109210,
"text": "Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members."
},
{
"code": null,
"e": 109520,
"s": 109360,
"text": "Members defined with a private label are not accessible to code that uses the class. The private sections hide the implementation from code that uses the type."
},
{
"code": null,
"e": 109680,
"s": 109520,
"text": "Members defined with a private label are not accessible to code that uses the class. The private sections hide the implementation from code that uses the type."
},
{
"code": null,
"e": 109972,
"s": 109680,
"text": "There are no restrictions on how often an access label may appear. Each access label specifies the access level of the succeeding member definitions. The specified access level remains in effect until the next access label is encountered or the closing right brace of the class body is seen."
},
{
"code": null,
"e": 110025,
"s": 109972,
"text": "Data abstraction provides two important advantages −"
},
{
"code": null,
"e": 110136,
"s": 110025,
"text": "Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object."
},
{
"code": null,
"e": 110247,
"s": 110136,
"text": "Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object."
},
{
"code": null,
"e": 110390,
"s": 110247,
"text": "The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code."
},
{
"code": null,
"e": 110533,
"s": 110390,
"text": "The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code."
},
{
"code": null,
"e": 110884,
"s": 110533,
"text": "By defining data members only in the private section of the class, the class author is free to make changes in the data. If the implementation changes, only the class code needs to be examined to see what affect the change may have. If data is public, then any function that directly access the data members of the old representation might be broken."
},
{
"code": null,
"e": 111028,
"s": 110884,
"text": "Any C++ program where you implement a class with public and private members is an example of data abstraction. Consider the following example −"
},
{
"code": null,
"e": 111596,
"s": 111028,
"text": "#include <iostream>\nusing namespace std;\n\nclass Adder {\n public:\n // constructor\n Adder(int i = 0) {\n total = i;\n }\n \n // interface to outside world\n void addNum(int number) {\n total += number;\n }\n \n // interface to outside world\n int getTotal() {\n return total;\n };\n \n private:\n // hidden data from outside world\n int total;\n};\n\nint main() {\n Adder a;\n \n a.addNum(10);\n a.addNum(20);\n a.addNum(30);\n\n cout << \"Total \" << a.getTotal() <<endl;\n return 0;\n}"
},
{
"code": null,
"e": 111677,
"s": 111596,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 111687,
"s": 111677,
"text": "Total 60\n"
},
{
"code": null,
"e": 112001,
"s": 111687,
"text": "Above class adds numbers together, and returns the sum. The public members - addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that the user doesn't need to know about, but is needed for the class to operate properly."
},
{
"code": null,
"e": 112240,
"s": 112001,
"text": "Abstraction separates code into interface and implementation. So while designing your component, you must keep interface independent of the implementation so that if you change underlying implementation then interface would remain intact."
},
{
"code": null,
"e": 112394,
"s": 112240,
"text": "In this case whatever programs are using these interfaces, they would not be impacted and would just need a recompilation with the latest implementation."
},
{
"code": null,
"e": 112468,
"s": 112394,
"text": "All C++ programs are composed of the following two fundamental elements −"
},
{
"code": null,
"e": 112579,
"s": 112468,
"text": "Program statements (code) − This is the part of a program that performs actions and they are called functions."
},
{
"code": null,
"e": 112690,
"s": 112579,
"text": "Program statements (code) − This is the part of a program that performs actions and they are called functions."
},
{
"code": null,
"e": 112794,
"s": 112690,
"text": "Program data − The data is the information of the program which gets affected by the program functions."
},
{
"code": null,
"e": 112898,
"s": 112794,
"text": "Program data − The data is the information of the program which gets affected by the program functions."
},
{
"code": null,
"e": 113154,
"s": 112898,
"text": "Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding."
},
{
"code": null,
"e": 113363,
"s": 113154,
"text": "Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user."
},
{
"code": null,
"e": 113641,
"s": 113363,
"text": "C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. For example −"
},
{
"code": null,
"e": 113899,
"s": 113641,
"text": "class Box {\n public:\n double getVolume(void) {\n return length * breadth * height;\n }\n\n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\n"
},
{
"code": null,
"e": 114117,
"s": 113899,
"text": "The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved."
},
{
"code": null,
"e": 114365,
"s": 114117,
"text": "To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program."
},
{
"code": null,
"e": 114565,
"s": 114365,
"text": "Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as many of the details of each class hidden from all other classes as possible."
},
{
"code": null,
"e": 114732,
"s": 114565,
"text": "Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example −"
},
{
"code": null,
"e": 115297,
"s": 114732,
"text": "#include <iostream>\nusing namespace std;\n\nclass Adder {\n public:\n // constructor\n Adder(int i = 0) {\n total = i;\n }\n \n // interface to outside world\n void addNum(int number) {\n total += number;\n }\n \n // interface to outside world\n int getTotal() {\n return total;\n };\n \n private:\n // hidden data from outside world\n int total;\n};\n\nint main() {\n Adder a;\n \n a.addNum(10);\n a.addNum(20);\n a.addNum(30);\n\n cout << \"Total \" << a.getTotal() <<endl;\n return 0;\n}"
},
{
"code": null,
"e": 115378,
"s": 115297,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 115388,
"s": 115378,
"text": "Total 60\n"
},
{
"code": null,
"e": 115698,
"s": 115388,
"text": "Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly."
},
{
"code": null,
"e": 115832,
"s": 115698,
"text": "Most of us have learnt to make class members private by default unless we really need to expose them. That's just good encapsulation."
},
{
"code": null,
"e": 115949,
"s": 115832,
"text": "This is applied most frequently to data members, but it applies equally to all members, including virtual functions."
},
{
"code": null,
"e": 116081,
"s": 115949,
"text": "An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class."
},
{
"code": null,
"e": 116295,
"s": 116081,
"text": "The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data."
},
{
"code": null,
"e": 116475,
"s": 116295,
"text": "A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing \"= 0\" in its declaration as follows −"
},
{
"code": null,
"e": 116726,
"s": 116475,
"text": "class Box {\n public:\n // pure virtual function\n virtual double getVolume() = 0;\n \n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\n"
},
{
"code": null,
"e": 117040,
"s": 116726,
"text": "The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error."
},
{
"code": null,
"e": 117354,
"s": 117040,
"text": "Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error."
},
{
"code": null,
"e": 117431,
"s": 117354,
"text": "Classes that can be used to instantiate objects are called concrete classes."
},
{
"code": null,
"e": 117565,
"s": 117431,
"text": "Consider the following example where parent class provides an interface to the base class to implement a function called getArea() −"
},
{
"code": null,
"e": 118531,
"s": 117565,
"text": "#include <iostream>\n \nusing namespace std;\n \n// Base class\nclass Shape {\n public:\n // pure virtual function providing interface framework.\n virtual int getArea() = 0;\n void setWidth(int w) {\n width = w;\n }\n \n void setHeight(int h) {\n height = h;\n }\n \n protected:\n int width;\n int height;\n};\n \n// Derived classes\nclass Rectangle: public Shape {\n public:\n int getArea() { \n return (width * height); \n }\n};\n\nclass Triangle: public Shape {\n public:\n int getArea() { \n return (width * height)/2; \n }\n};\n \nint main(void) {\n Rectangle Rect;\n Triangle Tri;\n \n Rect.setWidth(5);\n Rect.setHeight(7);\n \n // Print the area of the object.\n cout << \"Total Rectangle area: \" << Rect.getArea() << endl;\n\n Tri.setWidth(5);\n Tri.setHeight(7);\n \n // Print the area of the object.\n cout << \"Total Triangle area: \" << Tri.getArea() << endl; \n\n return 0;\n}"
},
{
"code": null,
"e": 118612,
"s": 118531,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 118662,
"s": 118612,
"text": "Total Rectangle area: 35\nTotal Triangle area: 17\n"
},
{
"code": null,
"e": 118861,
"s": 118662,
"text": "You can see how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape."
},
{
"code": null,
"e": 119122,
"s": 118861,
"text": "An object-oriented system might use an abstract base class to provide a common and standardized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that operate similarly."
},
{
"code": null,
"e": 119418,
"s": 119122,
"text": "The capabilities (i.e., the public functions) offered by the external applications are provided as pure virtual functions in the abstract base class. The implementations of these pure virtual functions are provided in the derived classes that correspond to the specific types of the application."
},
{
"code": null,
"e": 119537,
"s": 119418,
"text": "This architecture also allows new applications to be added to a system easily, even after the system has been defined."
},
{
"code": null,
"e": 119708,
"s": 119537,
"text": "So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively."
},
{
"code": null,
"e": 119868,
"s": 119708,
"text": "This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types −"
},
{
"code": null,
"e": 119877,
"s": 119868,
"text": "ofstream"
},
{
"code": null,
"e": 119989,
"s": 119877,
"text": "This data type represents the output file stream and is used to create files and to write information to files."
},
{
"code": null,
"e": 119998,
"s": 119989,
"text": "ifstream"
},
{
"code": null,
"e": 120091,
"s": 119998,
"text": "This data type represents the input file stream and is used to read information from files."
},
{
"code": null,
"e": 120099,
"s": 120091,
"text": "fstream"
},
{
"code": null,
"e": 120301,
"s": 120099,
"text": "This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files."
},
{
"code": null,
"e": 120416,
"s": 120301,
"text": "To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file."
},
{
"code": null,
"e": 120625,
"s": 120416,
"text": "A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only."
},
{
"code": null,
"e": 120741,
"s": 120625,
"text": "Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects."
},
{
"code": null,
"e": 120795,
"s": 120741,
"text": "void open(const char *filename, ios::openmode mode);\n"
},
{
"code": null,
"e": 120984,
"s": 120795,
"text": "Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened."
},
{
"code": null,
"e": 120993,
"s": 120984,
"text": "ios::app"
},
{
"code": null,
"e": 121057,
"s": 120993,
"text": "Append mode. All output to that file to be appended to the end."
},
{
"code": null,
"e": 121066,
"s": 121057,
"text": "ios::ate"
},
{
"code": null,
"e": 121145,
"s": 121066,
"text": "Open a file for output and move the read/write control to the end of the file."
},
{
"code": null,
"e": 121153,
"s": 121145,
"text": "ios::in"
},
{
"code": null,
"e": 121178,
"s": 121153,
"text": "Open a file for reading."
},
{
"code": null,
"e": 121187,
"s": 121178,
"text": "ios::out"
},
{
"code": null,
"e": 121212,
"s": 121187,
"text": "Open a file for writing."
},
{
"code": null,
"e": 121223,
"s": 121212,
"text": "ios::trunc"
},
{
"code": null,
"e": 121307,
"s": 121223,
"text": "If the file already exists, its contents will be truncated before opening the file."
},
{
"code": null,
"e": 121512,
"s": 121307,
"text": "You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −"
},
{
"code": null,
"e": 121581,
"s": 121512,
"text": "ofstream outfile;\noutfile.open(\"file.dat\", ios::out | ios::trunc );\n"
},
{
"code": null,
"e": 121659,
"s": 121581,
"text": "Similar way, you can open a file for reading and writing purpose as follows −"
},
{
"code": null,
"e": 121721,
"s": 121659,
"text": "fstream afile;\nafile.open(\"file.dat\", ios::out | ios::in );\n"
},
{
"code": null,
"e": 121972,
"s": 121721,
"text": "When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination."
},
{
"code": null,
"e": 122089,
"s": 121972,
"text": "Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects."
},
{
"code": null,
"e": 122104,
"s": 122089,
"text": "void close();\n"
},
{
"code": null,
"e": 122385,
"s": 122104,
"text": "While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object."
},
{
"code": null,
"e": 122641,
"s": 122385,
"text": "You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object."
},
{
"code": null,
"e": 122868,
"s": 122641,
"text": "Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen −"
},
{
"code": null,
"e": 123800,
"s": 122868,
"text": "#include <fstream>\n#include <iostream>\nusing namespace std;\n \nint main () {\n char data[100];\n\n // open a file in write mode.\n ofstream outfile;\n outfile.open(\"afile.dat\");\n\n cout << \"Writing to the file\" << endl;\n cout << \"Enter your name: \"; \n cin.getline(data, 100);\n\n // write inputted data into the file.\n outfile << data << endl;\n\n cout << \"Enter your age: \"; \n cin >> data;\n cin.ignore();\n \n // again write inputted data into the file.\n outfile << data << endl;\n\n // close the opened file.\n outfile.close();\n\n // open a file in read mode.\n ifstream infile; \n infile.open(\"afile.dat\"); \n \n cout << \"Reading from the file\" << endl; \n infile >> data; \n\n // write the data at the screen.\n cout << data << endl;\n \n // again read the data from the file and display it.\n infile >> data; \n cout << data << endl; \n\n // close the opened file.\n infile.close();\n\n return 0;\n}"
},
{
"code": null,
"e": 123898,
"s": 123800,
"text": "When the above code is compiled and executed, it produces the following sample input and output −"
},
{
"code": null,
"e": 123997,
"s": 123898,
"text": "$./a.out\nWriting to the file\nEnter your name: Zara\nEnter your age: 9\nReading from the file\nZara\n9\n"
},
{
"code": null,
"e": 124202,
"s": 123997,
"text": "Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement."
},
{
"code": null,
"e": 124391,
"s": 124202,
"text": "Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg (\"seek get\") for istream and seekp (\"seek put\") for ostream."
},
{
"code": null,
"e": 124753,
"s": 124391,
"text": "The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream."
},
{
"code": null,
"e": 124962,
"s": 124753,
"text": "The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file's starting location. Some examples of positioning the \"get\" file-position pointer are −"
},
{
"code": null,
"e": 125272,
"s": 124962,
"text": "// position to the nth byte of fileObject (assumes ios::beg)\nfileObject.seekg( n );\n\n// position n bytes forward in fileObject\nfileObject.seekg( n, ios::cur );\n\n// position n bytes back from end of fileObject\nfileObject.seekg( n, ios::end );\n\n// position at end of fileObject\nfileObject.seekg( 0, ios::end );\n"
},
{
"code": null,
"e": 125484,
"s": 125272,
"text": "An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero."
},
{
"code": null,
"e": 125644,
"s": 125484,
"text": "Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw."
},
{
"code": null,
"e": 125743,
"s": 125644,
"text": "throw − A program throws an exception when a problem shows up. This is done using a throw keyword."
},
{
"code": null,
"e": 125842,
"s": 125743,
"text": "throw − A program throws an exception when a problem shows up. This is done using a throw keyword."
},
{
"code": null,
"e": 126029,
"s": 125842,
"text": "catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception."
},
{
"code": null,
"e": 126216,
"s": 126029,
"text": "catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception."
},
{
"code": null,
"e": 126355,
"s": 126216,
"text": "try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks."
},
{
"code": null,
"e": 126494,
"s": 126355,
"text": "try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks."
},
{
"code": null,
"e": 126807,
"s": 126494,
"text": "Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows −"
},
{
"code": null,
"e": 126981,
"s": 126807,
"text": "try {\n // protected code\n} catch( ExceptionName e1 ) {\n // catch block\n} catch( ExceptionName e2 ) {\n // catch block\n} catch( ExceptionName eN ) {\n // catch block\n}\n"
},
{
"code": null,
"e": 127142,
"s": 126981,
"text": "You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations."
},
{
"code": null,
"e": 127403,
"s": 127142,
"text": "Exceptions can be thrown anywhere within a code block using throw statement. The operand of the throw statement determines a type for the exception and can be any expression and the type of the result of the expression determines the type of exception thrown."
},
{
"code": null,
"e": 127493,
"s": 127403,
"text": "Following is an example of throwing an exception when dividing by zero condition occurs −"
},
{
"code": null,
"e": 127611,
"s": 127493,
"text": "double division(int a, int b) {\n if( b == 0 ) {\n throw \"Division by zero condition!\";\n }\n return (a/b);\n}\n"
},
{
"code": null,
"e": 127840,
"s": 127611,
"text": "The catch block following the try block catches any exception. You can specify what type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the keyword catch."
},
{
"code": null,
"e": 127943,
"s": 127840,
"text": "try {\n // protected code\n} catch( ExceptionName e ) {\n // code to handle ExceptionName exception\n}\n"
},
{
"code": null,
"e": 128215,
"s": 127943,
"text": "Above code will catch an exception of ExceptionName type. If you want to specify that a catch block should handle any type of exception that is thrown in a try block, you must put an ellipsis, ..., between the parentheses enclosing the exception declaration as follows −"
},
{
"code": null,
"e": 128294,
"s": 128215,
"text": "try {\n // protected code\n} catch(...) {\n // code to handle any exception\n}\n"
},
{
"code": null,
"e": 128397,
"s": 128294,
"text": "The following is an example, which throws a division by zero exception and we catch it in catch block."
},
{
"code": null,
"e": 128757,
"s": 128397,
"text": "#include <iostream>\nusing namespace std;\n\ndouble division(int a, int b) {\n if( b == 0 ) {\n throw \"Division by zero condition!\";\n }\n return (a/b);\n}\n\nint main () {\n int x = 50;\n int y = 0;\n double z = 0;\n \n try {\n z = division(x, y);\n cout << z << endl;\n } catch (const char* msg) {\n cerr << msg << endl;\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 128967,
"s": 128757,
"text": "Because we are raising an exception of type const char*, so while catching this exception, we have to use const char* in catch block. If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 128996,
"s": 128967,
"text": "Division by zero condition!\n"
},
{
"code": null,
"e": 129164,
"s": 128996,
"text": "C++ provides a list of standard exceptions defined in <exception> which we can use in our programs. These are arranged in a parent-child class hierarchy shown below −"
},
{
"code": null,
"e": 129247,
"s": 129164,
"text": "Here is the small description of each exception mentioned in the above hierarchy −"
},
{
"code": null,
"e": 129262,
"s": 129247,
"text": "std::exception"
},
{
"code": null,
"e": 129328,
"s": 129262,
"text": "An exception and parent class of all the standard C++ exceptions."
},
{
"code": null,
"e": 129343,
"s": 129328,
"text": "std::bad_alloc"
},
{
"code": null,
"e": 129370,
"s": 129343,
"text": "This can be thrown by new."
},
{
"code": null,
"e": 129384,
"s": 129370,
"text": "std::bad_cast"
},
{
"code": null,
"e": 129420,
"s": 129384,
"text": "This can be thrown by dynamic_cast."
},
{
"code": null,
"e": 129439,
"s": 129420,
"text": "std::bad_exception"
},
{
"code": null,
"e": 129511,
"s": 129439,
"text": "This is useful device to handle unexpected exceptions in a C++ program."
},
{
"code": null,
"e": 129527,
"s": 129511,
"text": "std::bad_typeid"
},
{
"code": null,
"e": 129557,
"s": 129527,
"text": "This can be thrown by typeid."
},
{
"code": null,
"e": 129574,
"s": 129557,
"text": "std::logic_error"
},
{
"code": null,
"e": 129643,
"s": 129574,
"text": "An exception that theoretically can be detected by reading the code."
},
{
"code": null,
"e": 129661,
"s": 129643,
"text": "std::domain_error"
},
{
"code": null,
"e": 129735,
"s": 129661,
"text": "This is an exception thrown when a mathematically invalid domain is used."
},
{
"code": null,
"e": 129757,
"s": 129735,
"text": "std::invalid_argument"
},
{
"code": null,
"e": 129798,
"s": 129757,
"text": "This is thrown due to invalid arguments."
},
{
"code": null,
"e": 129816,
"s": 129798,
"text": "std::length_error"
},
{
"code": null,
"e": 129870,
"s": 129816,
"text": "This is thrown when a too big std::string is created."
},
{
"code": null,
"e": 129888,
"s": 129870,
"text": "std::out_of_range"
},
{
"code": null,
"e": 129986,
"s": 129888,
"text": "This can be thrown by the 'at' method, for example a std::vector and std::bitset<>::operator[]()."
},
{
"code": null,
"e": 130005,
"s": 129986,
"text": "std::runtime_error"
},
{
"code": null,
"e": 130077,
"s": 130005,
"text": "An exception that theoretically cannot be detected by reading the code."
},
{
"code": null,
"e": 130097,
"s": 130077,
"text": "std::overflow_error"
},
{
"code": null,
"e": 130147,
"s": 130097,
"text": "This is thrown if a mathematical overflow occurs."
},
{
"code": null,
"e": 130164,
"s": 130147,
"text": "std::range_error"
},
{
"code": null,
"e": 130234,
"s": 130164,
"text": "This is occurred when you try to store a value which is out of range."
},
{
"code": null,
"e": 130255,
"s": 130234,
"text": "std::underflow_error"
},
{
"code": null,
"e": 130306,
"s": 130255,
"text": "This is thrown if a mathematical underflow occurs."
},
{
"code": null,
"e": 130526,
"s": 130306,
"text": "You can define your own exceptions by inheriting and overriding exception class functionality. Following is the example, which shows how you can use std::exception class to implement your own exception in standard way −"
},
{
"code": null,
"e": 130944,
"s": 130526,
"text": "#include <iostream>\n#include <exception>\nusing namespace std;\n\nstruct MyException : public exception {\n const char * what () const throw () {\n return \"C++ Exception\";\n }\n};\n \nint main() {\n try {\n throw MyException();\n } catch(MyException& e) {\n std::cout << \"MyException caught\" << std::endl;\n std::cout << e.what() << std::endl;\n } catch(std::exception& e) {\n //Other errors\n }\n}"
},
{
"code": null,
"e": 130986,
"s": 130944,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 131020,
"s": 130986,
"text": "MyException caught\nC++ Exception\n"
},
{
"code": null,
"e": 131183,
"s": 131020,
"text": "Here, what() is a public method provided by exception class and it has been overridden by all the child exception classes. This returns the cause of an exception."
},
{
"code": null,
"e": 131349,
"s": 131183,
"text": "A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++ programmer. Memory in your C++ program is divided into two parts −"
},
{
"code": null,
"e": 131440,
"s": 131349,
"text": "The stack − All variables declared inside the function will take up memory from the stack."
},
{
"code": null,
"e": 131531,
"s": 131440,
"text": "The stack − All variables declared inside the function will take up memory from the stack."
},
{
"code": null,
"e": 131649,
"s": 131531,
"text": "The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs."
},
{
"code": null,
"e": 131767,
"s": 131649,
"text": "The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs."
},
{
"code": null,
"e": 131955,
"s": 131767,
"text": "Many times, you are not aware in advance how much memory you will need to store particular information in a defined variable and the size of required memory can be determined at run time."
},
{
"code": null,
"e": 132160,
"s": 131955,
"text": "You can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator."
},
{
"code": null,
"e": 132326,
"s": 132160,
"text": "If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-allocates memory that was previously allocated by new operator."
},
{
"code": null,
"e": 132430,
"s": 132326,
"text": "There is following generic syntax to use new operator to allocate memory dynamically for any data-type."
},
{
"code": null,
"e": 132446,
"s": 132430,
"text": "new data-type;\n"
},
{
"code": null,
"e": 132798,
"s": 132446,
"text": "Here, data-type could be any built-in data type including an array or any user defined data types include class or structure. Let us start with built-in data types. For example we can define a pointer to type double and then request that the memory be allocated at execution time. We can do this using the new operator with the following statements −"
},
{
"code": null,
"e": 132915,
"s": 132798,
"text": "double* pvalue = NULL; // Pointer initialized with null\npvalue = new double; // Request memory for the variable\n"
},
{
"code": null,
"e": 133117,
"s": 132915,
"text": "The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below −"
},
{
"code": null,
"e": 133231,
"s": 133117,
"text": "double* pvalue = NULL;\nif( !(pvalue = new double )) {\n cout << \"Error: out of memory.\" <<endl;\n exit(1);\n}\n"
},
{
"code": null,
"e": 133473,
"s": 133231,
"text": "The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn't just allocate memory, it constructs objects which is prime purpose of C++."
},
{
"code": null,
"e": 133675,
"s": 133473,
"text": "At any point, when you feel a variable that has been dynamically allocated is not anymore required, you can free up the memory that it occupies in the free store with the ‘delete’ operator as follows −"
},
{
"code": null,
"e": 133737,
"s": 133675,
"text": "delete pvalue; // Release memory pointed to by pvalue\n"
},
{
"code": null,
"e": 133832,
"s": 133737,
"text": "Let us put above concepts and form the following example to show how ‘new’ and ‘delete’ work −"
},
{
"code": null,
"e": 134193,
"s": 133832,
"text": "#include <iostream>\nusing namespace std;\n\nint main () {\n double* pvalue = NULL; // Pointer initialized with null\n pvalue = new double; // Request memory for the variable\n \n *pvalue = 29494.99; // Store value at allocated address\n cout << \"Value of pvalue : \" << *pvalue << endl;\n\n delete pvalue; // free up the memory.\n\n return 0;\n}"
},
{
"code": null,
"e": 134269,
"s": 134193,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 134294,
"s": 134269,
"text": "Value of pvalue : 29495\n"
},
{
"code": null,
"e": 134487,
"s": 134294,
"text": "Consider you want to allocate memory for an array of characters, i.e., string of 20 characters. Using the same syntax what we have used above we can allocate memory dynamically as shown below."
},
{
"code": null,
"e": 134616,
"s": 134487,
"text": "char* pvalue = NULL; // Pointer initialized with null\npvalue = new char[20]; // Request memory for the variable\n"
},
{
"code": null,
"e": 134699,
"s": 134616,
"text": "To remove the array that we have just created the statement would look like this −"
},
{
"code": null,
"e": 134767,
"s": 134699,
"text": "delete [] pvalue; // Delete array pointed to by pvalue\n"
},
{
"code": null,
"e": 134881,
"s": 134767,
"text": "Following the similar generic syntax of new operator, you can allocate for a multi-dimensional array as follows −"
},
{
"code": null,
"e": 135012,
"s": 134881,
"text": "double** pvalue = NULL; // Pointer initialized with null \npvalue = new double [3][4]; // Allocate memory for a 3x4 array \n"
},
{
"code": null,
"e": 135116,
"s": 135012,
"text": "However, the syntax to release the memory for multi-dimensional array will still remain same as above −"
},
{
"code": null,
"e": 135183,
"s": 135116,
"text": "delete [] pvalue; // Delete array pointed to by pvalue\n"
},
{
"code": null,
"e": 135344,
"s": 135183,
"text": "Objects are no different from simple data types. For example, consider the following code where we are going to use an array of objects to clarify the concept −"
},
{
"code": null,
"e": 135657,
"s": 135344,
"text": "#include <iostream>\nusing namespace std;\n\nclass Box {\n public:\n Box() { \n cout << \"Constructor called!\" <<endl; \n }\n ~Box() { \n cout << \"Destructor called!\" <<endl; \n }\n};\nint main() {\n Box* myBoxArray = new Box[4];\n delete [] myBoxArray; // Delete array\n\n return 0;\n}"
},
{
"code": null,
"e": 135858,
"s": 135657,
"text": "If you were to allocate an array of four Box objects, the Simple constructor would be called four times and similarly while deleting these objects, destructor will also be called same number of times."
},
{
"code": null,
"e": 135934,
"s": 135858,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 136091,
"s": 135934,
"text": "Constructor called!\nConstructor called!\nConstructor called!\nConstructor called!\nDestructor called!\nDestructor called!\nDestructor called!\nDestructor called!\n"
},
{
"code": null,
"e": 136399,
"s": 136091,
"text": "Consider a situation, when we have two persons with the same name, Zara, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother’s or father’s name, etc."
},
{
"code": null,
"e": 136718,
"s": 136399,
"text": "Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code."
},
{
"code": null,
"e": 137034,
"s": 136718,
"text": "A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope."
},
{
"code": null,
"e": 137135,
"s": 137034,
"text": "A namespace definition begins with the keyword namespace followed by the namespace name as follows −"
},
{
"code": null,
"e": 137189,
"s": 137135,
"text": "namespace namespace_name {\n // code declarations\n}\n"
},
{
"code": null,
"e": 137304,
"s": 137189,
"text": "To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows −"
},
{
"code": null,
"e": 137357,
"s": 137304,
"text": "name::code; // code could be variable or function.\n"
},
{
"code": null,
"e": 137436,
"s": 137357,
"text": "Let us see how namespace scope the entities including variable and functions −"
},
{
"code": null,
"e": 137880,
"s": 137436,
"text": "#include <iostream>\nusing namespace std;\n\n// first name space\nnamespace first_space {\n void func() {\n cout << \"Inside first_space\" << endl;\n }\n}\n\n// second name space\nnamespace second_space {\n void func() {\n cout << \"Inside second_space\" << endl;\n }\n}\n\nint main () {\n // Calls function from first name space.\n first_space::func();\n \n // Calls function from second name space.\n second_space::func(); \n\n return 0;\n}"
},
{
"code": null,
"e": 137956,
"s": 137880,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 137996,
"s": 137956,
"text": "Inside first_space\nInside second_space\n"
},
{
"code": null,
"e": 138241,
"s": 137996,
"text": "You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code −"
},
{
"code": null,
"e": 138634,
"s": 138241,
"text": "#include <iostream>\nusing namespace std;\n\n// first name space\nnamespace first_space {\n void func() {\n cout << \"Inside first_space\" << endl;\n }\n}\n\n// second name space\nnamespace second_space {\n void func() {\n cout << \"Inside second_space\" << endl;\n }\n}\n\nusing namespace first_space;\nint main () {\n // This calls function from first name space.\n func();\n \n return 0;\n}"
},
{
"code": null,
"e": 138710,
"s": 138634,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 138730,
"s": 138710,
"text": "Inside first_space\n"
},
{
"code": null,
"e": 138935,
"s": 138730,
"text": "The ‘using’ directive can also be used to refer to a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows −"
},
{
"code": null,
"e": 138953,
"s": 138935,
"text": "using std::cout;\n"
},
{
"code": null,
"e": 139103,
"s": 138953,
"text": "Subsequent code can refer to cout without prepending the namespace, but other items in the std namespace will still need to be explicit as follows −"
},
{
"code": null,
"e": 139229,
"s": 139103,
"text": "#include <iostream>\nusing std::cout;\n\nint main () {\n cout << \"std::endl is used with std!\" << std::endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 139305,
"s": 139229,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 139334,
"s": 139305,
"text": "std::endl is used with std!\n"
},
{
"code": null,
"e": 139578,
"s": 139334,
"text": "Names introduced in a using directive obey normal scope rules. The name is visible from the point of the using directive to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden."
},
{
"code": null,
"e": 139765,
"s": 139578,
"text": "A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files."
},
{
"code": null,
"e": 139987,
"s": 139765,
"text": "So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one −"
},
{
"code": null,
"e": 140041,
"s": 139987,
"text": "namespace namespace_name {\n // code declarations\n}\n"
},
{
"code": null,
"e": 140140,
"s": 140041,
"text": "Namespaces can be nested where you can define one namespace inside another name space as follows −"
},
{
"code": null,
"e": 140258,
"s": 140140,
"text": "namespace namespace_name1 {\n // code declarations\n namespace namespace_name2 {\n // code declarations\n }\n}\n"
},
{
"code": null,
"e": 140344,
"s": 140258,
"text": "You can access members of nested namespace by using resolution operators as follows −"
},
{
"code": null,
"e": 140509,
"s": 140344,
"text": "// to access members of namespace_name2\nusing namespace namespace_name1::namespace_name2;\n\n// to access members of namespace:name1\nusing namespace namespace_name1;\n"
},
{
"code": null,
"e": 140649,
"s": 140509,
"text": "In the above statements if you are using namespace_name1, then it will make elements of namespace_name2 available in the scope as follows −"
},
{
"code": null,
"e": 141078,
"s": 140649,
"text": "#include <iostream>\nusing namespace std;\n\n// first name space\nnamespace first_space {\n void func() {\n cout << \"Inside first_space\" << endl;\n }\n \n // second name space\n namespace second_space {\n void func() {\n cout << \"Inside second_space\" << endl;\n }\n }\n}\n\nusing namespace first_space::second_space;\nint main () {\n // This calls function from second name space.\n func();\n \n return 0;\n}"
},
{
"code": null,
"e": 141154,
"s": 141078,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 141175,
"s": 141154,
"text": "Inside second_space\n"
},
{
"code": null,
"e": 141309,
"s": 141175,
"text": "Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type."
},
{
"code": null,
"e": 141527,
"s": 141309,
"text": "A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept."
},
{
"code": null,
"e": 141687,
"s": 141527,
"text": "There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector <int> or vector <string>."
},
{
"code": null,
"e": 141776,
"s": 141687,
"text": "You can use templates to define functions as well as classes, let us see how they work −"
},
{
"code": null,
"e": 141843,
"s": 141776,
"text": "The general form of a template function definition is shown here −"
},
{
"code": null,
"e": 141929,
"s": 141843,
"text": "template <class type> ret-type func-name(parameter list) {\n // body of function\n} \n"
},
{
"code": null,
"e": 142054,
"s": 141929,
"text": "Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition."
},
{
"code": null,
"e": 142147,
"s": 142054,
"text": "The following is the example of a function template that returns the maximum of two values −"
},
{
"code": null,
"e": 142613,
"s": 142147,
"text": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\ntemplate <typename T>\ninline T const& Max (T const& a, T const& b) { \n return a < b ? b:a; \n}\n\nint main () {\n int i = 39;\n int j = 20;\n cout << \"Max(i, j): \" << Max(i, j) << endl; \n\n double f1 = 13.5; \n double f2 = 20.7; \n cout << \"Max(f1, f2): \" << Max(f1, f2) << endl; \n\n string s1 = \"Hello\"; \n string s2 = \"World\"; \n cout << \"Max(s1, s2): \" << Max(s1, s2) << endl; \n\n return 0;\n}"
},
{
"code": null,
"e": 142689,
"s": 142613,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 142741,
"s": 142689,
"text": "Max(i, j): 39\nMax(f1, f2): 20.7\nMax(s1, s2): World\n"
},
{
"code": null,
"e": 142883,
"s": 142741,
"text": "Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here −"
},
{
"code": null,
"e": 142942,
"s": 142883,
"text": "template <class type> class class-name {\n .\n .\n .\n}\n"
},
{
"code": null,
"e": 143118,
"s": 142942,
"text": "Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by using a comma-separated list."
},
{
"code": null,
"e": 143243,
"s": 143118,
"text": "Following is the example to define class Stack<> and implement generic methods to push and pop the elements from the stack −"
},
{
"code": null,
"e": 144762,
"s": 143243,
"text": "#include <iostream>\n#include <vector>\n#include <cstdlib>\n#include <string>\n#include <stdexcept>\n\nusing namespace std;\n\ntemplate <class T>\nclass Stack { \n private: \n vector<T> elems; // elements \n\n public: \n void push(T const&); // push element \n void pop(); // pop element \n T top() const; // return top element \n \n bool empty() const { // return true if empty.\n return elems.empty(); \n } \n}; \n\ntemplate <class T>\nvoid Stack<T>::push (T const& elem) { \n // append copy of passed element \n elems.push_back(elem); \n} \n\ntemplate <class T>\nvoid Stack<T>::pop () { \n if (elems.empty()) { \n throw out_of_range(\"Stack<>::pop(): empty stack\"); \n }\n \n // remove last element \n elems.pop_back(); \n} \n\ntemplate <class T>\nT Stack<T>::top () const { \n if (elems.empty()) { \n throw out_of_range(\"Stack<>::top(): empty stack\"); \n }\n \n // return copy of last element \n return elems.back(); \n} \n\nint main() { \n try {\n Stack<int> intStack; // stack of ints \n Stack<string> stringStack; // stack of strings \n\n // manipulate int stack \n intStack.push(7); \n cout << intStack.top() <<endl; \n\n // manipulate string stack \n stringStack.push(\"hello\"); \n cout << stringStack.top() << std::endl; \n stringStack.pop(); \n stringStack.pop(); \n } catch (exception const& ex) { \n cerr << \"Exception: \" << ex.what() <<endl; \n return -1;\n } \n} "
},
{
"code": null,
"e": 144838,
"s": 144762,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 144886,
"s": 144838,
"text": "7\nhello\nException: Stack<>::pop(): empty stack\n"
},
{
"code": null,
"e": 145028,
"s": 144886,
"text": "The preprocessors are the directives, which give instructions to the compiler to preprocess the information before actual compilation starts."
},
{
"code": null,
"e": 145243,
"s": 145028,
"text": "All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not C++ statements, so they do not end in a semicolon (;)."
},
{
"code": null,
"e": 145373,
"s": 145243,
"text": "You already have seen a #include directive in all the examples. This macro is used to include a header file into the source file."
},
{
"code": null,
"e": 145516,
"s": 145373,
"text": "There are number of preprocessor directives supported by C++ like #include, #define, #if, #else, #line, etc. Let us see important directives −"
},
{
"code": null,
"e": 145662,
"s": 145516,
"text": "The #define preprocessor directive creates symbolic constants. The symbolic constant is called a macro and the general form of the directive is −"
},
{
"code": null,
"e": 145700,
"s": 145662,
"text": "#define macro-name replacement-text \n"
},
{
"code": null,
"e": 145866,
"s": 145700,
"text": "When this line appears in a file, all subsequent occurrences of macro in that file will be replaced by replacement-text before the program is compiled. For example −"
},
{
"code": null,
"e": 146001,
"s": 145866,
"text": "#include <iostream>\nusing namespace std;\n\n#define PI 3.14159\n\nint main () {\n cout << \"Value of PI :\" << PI << endl; \n\n return 0;\n}"
},
{
"code": null,
"e": 146299,
"s": 146001,
"text": "Now, let us do the preprocessing of this code to see the result assuming we have the source code file. So let us compile it with -E option and redirect the result to test.p. Now, if you check test.p, it will have lots of information and at the bottom, you will find the value replaced as follows −"
},
{
"code": null,
"e": 146408,
"s": 146299,
"text": "$gcc -E test.cpp > test.p\n\n...\nint main () {\n cout << \"Value of PI :\" << 3.14159 << endl; \n return 0;\n}\n"
},
{
"code": null,
"e": 146484,
"s": 146408,
"text": "You can use #define to define a macro which will take argument as follows −"
},
{
"code": null,
"e": 146688,
"s": 146484,
"text": "#include <iostream>\nusing namespace std;\n\n#define MIN(a,b) (((a)<(b)) ? a : b)\n\nint main () {\n int i, j;\n \n i = 100;\n j = 30;\n \n cout <<\"The minimum is \" << MIN(i, j) << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 146764,
"s": 146688,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 146783,
"s": 146764,
"text": "The minimum is 30\n"
},
{
"code": null,
"e": 146940,
"s": 146783,
"text": "There are several directives, which can be used to compile selective portions of your program's source code. This process is called conditional compilation."
},
{
"code": null,
"e": 147065,
"s": 146940,
"text": "The conditional preprocessor construct is much like the ‘if’ selection structure. Consider the following preprocessor code −"
},
{
"code": null,
"e": 147104,
"s": 147065,
"text": "#ifndef NULL\n #define NULL 0\n#endif\n"
},
{
"code": null,
"e": 147229,
"s": 147104,
"text": "You can compile a program for debugging purpose. You can also turn on or off the debugging using a single macro as follows −"
},
{
"code": null,
"e": 147290,
"s": 147229,
"text": "#ifdef DEBUG\n cerr <<\"Variable x = \" << x << endl;\n#endif\n"
},
{
"code": null,
"e": 147510,
"s": 147290,
"text": "This causes the cerr statement to be compiled in the program if the symbolic constant DEBUG has been defined before directive #ifdef DEBUG. You can use #if 0 statment to comment out a portion of the program as follows −"
},
{
"code": null,
"e": 147557,
"s": 147510,
"text": "#if 0\n code prevented from compiling\n#endif\n"
},
{
"code": null,
"e": 147592,
"s": 147557,
"text": "Let us try the following example −"
},
{
"code": null,
"e": 148037,
"s": 147592,
"text": "#include <iostream>\nusing namespace std;\n#define DEBUG\n\n#define MIN(a,b) (((a)<(b)) ? a : b)\n\nint main () {\n int i, j;\n \n i = 100;\n j = 30;\n\n#ifdef DEBUG\n cerr <<\"Trace: Inside main function\" << endl;\n#endif\n\n#if 0\n /* This is commented part */\n cout << MKSTR(HELLO C++) << endl;\n#endif\n\n cout <<\"The minimum is \" << MIN(i, j) << endl;\n\n#ifdef DEBUG\n cerr <<\"Trace: Coming out of main function\" << endl;\n#endif\n\n return 0;\n}"
},
{
"code": null,
"e": 148113,
"s": 148037,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 148195,
"s": 148113,
"text": "The minimum is 30\nTrace: Inside main function\nTrace: Coming out of main function\n"
},
{
"code": null,
"e": 148366,
"s": 148195,
"text": "The # and ## preprocessor operators are available in C++ and ANSI/ISO C. The # operator causes a replacement-text token to be converted to a string surrounded by quotes. "
},
{
"code": null,
"e": 148408,
"s": 148366,
"text": "Consider the following macro definition −"
},
{
"code": null,
"e": 148541,
"s": 148408,
"text": "#include <iostream>\nusing namespace std;\n\n#define MKSTR( x ) #x\n\nint main () {\n\n cout << MKSTR(HELLO C++) << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 148617,
"s": 148541,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 148628,
"s": 148617,
"text": "HELLO C++\n"
},
{
"code": null,
"e": 148724,
"s": 148628,
"text": "Let us see how it worked. It is simple to understand that the C++ preprocessor turns the line −"
},
{
"code": null,
"e": 148759,
"s": 148724,
"text": "cout << MKSTR(HELLO C++) << endl;\n"
},
{
"code": null,
"e": 148811,
"s": 148759,
"text": "Above line will be turned into the following line −"
},
{
"code": null,
"e": 148841,
"s": 148811,
"text": "cout << \"HELLO C++\" << endl;\n"
},
{
"code": null,
"e": 148913,
"s": 148841,
"text": "The ## operator is used to concatenate two tokens. Here is an example −"
},
{
"code": null,
"e": 148945,
"s": 148913,
"text": "#define CONCAT( x, y ) x ## y\n"
},
{
"code": null,
"e": 149129,
"s": 148945,
"text": "When CONCAT appears in the program, its arguments are concatenated and used to replace the macro. For example, CONCAT(HELLO, C++) is replaced by \"HELLO C++\" in the program as follows."
},
{
"code": null,
"e": 149273,
"s": 149129,
"text": "#include <iostream>\nusing namespace std;\n\n#define concat(a, b) a ## b\nint main() {\n int xy = 100;\n \n cout << concat(x, y);\n return 0;\n}"
},
{
"code": null,
"e": 149349,
"s": 149273,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 149354,
"s": 149349,
"text": "100\n"
},
{
"code": null,
"e": 149446,
"s": 149354,
"text": "Let us see how it worked. It is simple to understand that the C++ preprocessor transforms −"
},
{
"code": null,
"e": 149469,
"s": 149446,
"text": "cout << concat(x, y);\n"
},
{
"code": null,
"e": 149526,
"s": 149469,
"text": "Above line will be transformed into the following line −"
},
{
"code": null,
"e": 149539,
"s": 149526,
"text": "cout << xy;\n"
},
{
"code": null,
"e": 149600,
"s": 149539,
"text": "C++ provides a number of predefined macros mentioned below −"
},
{
"code": null,
"e": 149609,
"s": 149600,
"text": "__LINE__"
},
{
"code": null,
"e": 149689,
"s": 149609,
"text": "This contains the current line number of the program when it is being compiled."
},
{
"code": null,
"e": 149698,
"s": 149689,
"text": "__FILE__"
},
{
"code": null,
"e": 149776,
"s": 149698,
"text": "This contains the current file name of the program when it is being compiled."
},
{
"code": null,
"e": 149785,
"s": 149776,
"text": "__DATE__"
},
{
"code": null,
"e": 149908,
"s": 149785,
"text": "This contains a string of the form month/day/year that is the date of the translation of the source file into object code."
},
{
"code": null,
"e": 149917,
"s": 149908,
"text": "__TIME__"
},
{
"code": null,
"e": 150023,
"s": 149917,
"text": "This contains a string of the form hour:minute:second that is the time at which the program was compiled."
},
{
"code": null,
"e": 150072,
"s": 150023,
"text": "Let us see an example for all the above macros −"
},
{
"code": null,
"e": 150364,
"s": 150072,
"text": "#include <iostream>\nusing namespace std;\n\nint main () {\n cout << \"Value of __LINE__ : \" << __LINE__ << endl;\n cout << \"Value of __FILE__ : \" << __FILE__ << endl;\n cout << \"Value of __DATE__ : \" << __DATE__ << endl;\n cout << \"Value of __TIME__ : \" << __TIME__ << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 150440,
"s": 150364,
"text": "If we compile and run above code, this would produce the following result −"
},
{
"code": null,
"e": 150553,
"s": 150440,
"text": "Value of __LINE__ : 6\nValue of __FILE__ : test.cpp\nValue of __DATE__ : Feb 28 2011\nValue of __TIME__ : 18:52:48\n"
},
{
"code": null,
"e": 150763,
"s": 150553,
"text": "Signals are the interrupts delivered to a process by the operating system which can terminate a program prematurely. You can generate interrupts by pressing Ctrl+C on a UNIX, LINUX, Mac OS X or Windows system."
},
{
"code": null,
"e": 151007,
"s": 150763,
"text": "There are signals which can not be caught by the program but there is a following list of signals which you can catch in your program and can take appropriate actions based on the signal. These signals are defined in C++ header file <csignal>."
},
{
"code": null,
"e": 151015,
"s": 151007,
"text": "SIGABRT"
},
{
"code": null,
"e": 151077,
"s": 151015,
"text": "Abnormal termination of the program, such as a call to abort."
},
{
"code": null,
"e": 151084,
"s": 151077,
"text": "SIGFPE"
},
{
"code": null,
"e": 151183,
"s": 151084,
"text": "An erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow."
},
{
"code": null,
"e": 151190,
"s": 151183,
"text": "SIGILL"
},
{
"code": null,
"e": 151227,
"s": 151190,
"text": "Detection of an illegal instruction."
},
{
"code": null,
"e": 151234,
"s": 151227,
"text": "SIGINT"
},
{
"code": null,
"e": 151278,
"s": 151234,
"text": "Receipt of an interactive attention signal."
},
{
"code": null,
"e": 151286,
"s": 151278,
"text": "SIGSEGV"
},
{
"code": null,
"e": 151316,
"s": 151286,
"text": "An invalid access to storage."
},
{
"code": null,
"e": 151324,
"s": 151316,
"text": "SIGTERM"
},
{
"code": null,
"e": 151367,
"s": 151324,
"text": "A termination request sent to the program."
},
{
"code": null,
"e": 151498,
"s": 151367,
"text": "C++ signal-handling library provides function signal to trap unexpected events. Following is the syntax of the signal() function −"
},
{
"code": null,
"e": 151550,
"s": 151498,
"text": "void (*signal (int sig, void (*func)(int)))(int); \n"
},
{
"code": null,
"e": 151733,
"s": 151550,
"text": "Keeping it simple, this function receives two arguments: first argument as an integer which represents signal number and second argument as a pointer to the signal-handling function."
},
{
"code": null,
"e": 152001,
"s": 151733,
"text": "Let us write a simple C++ program where we will catch SIGINT signal using signal() function. Whatever signal you want to catch in your program, you must register that signal using signal function and associate it with a signal handler. Examine the following example −"
},
{
"code": null,
"e": 152446,
"s": 152001,
"text": "#include <iostream>\n#include <csignal>\n\nusing namespace std;\n\nvoid signalHandler( int signum ) {\n cout << \"Interrupt signal (\" << signum << \") received.\\n\";\n\n // cleanup and close up stuff here \n // terminate program \n\n exit(signum); \n}\n\nint main () {\n // register signal SIGINT and signal handler \n signal(SIGINT, signalHandler); \n\n while(1) {\n cout << \"Going to sleep....\" << endl;\n sleep(1);\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 152527,
"s": 152446,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 152585,
"s": 152527,
"text": "Going to sleep....\nGoing to sleep....\nGoing to sleep....\n"
},
{
"code": null,
"e": 152739,
"s": 152585,
"text": "Now, press Ctrl+c to interrupt the program and you will see that your program will catch the signal and would come out by printing something as follows −"
},
{
"code": null,
"e": 152828,
"s": 152739,
"text": "Going to sleep....\nGoing to sleep....\nGoing to sleep....\nInterrupt signal (2) received.\n"
},
{
"code": null,
"e": 152956,
"s": 152828,
"text": "You can generate signals by function raise(), which takes an integer signal number as an argument and has the following syntax."
},
{
"code": null,
"e": 152981,
"s": 152956,
"text": "int raise (signal sig);\n"
},
{
"code": null,
"e": 153195,
"s": 152981,
"text": "Here, sig is the signal number to send any of the signals: SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Following is the example where we raise a signal internally using raise() function as follows −"
},
{
"code": null,
"e": 153710,
"s": 153195,
"text": "#include <iostream>\n#include <csignal>\n\nusing namespace std;\n\nvoid signalHandler( int signum ) {\n cout << \"Interrupt signal (\" << signum << \") received.\\n\";\n\n // cleanup and close up stuff here \n // terminate program \n\n exit(signum); \n}\n\nint main () {\n int i = 0;\n // register signal SIGINT and signal handler \n signal(SIGINT, signalHandler); \n\n while(++i) {\n cout << \"Going to sleep....\" << endl;\n if( i == 3 ) {\n raise( SIGINT);\n }\n sleep(1);\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 153824,
"s": 153710,
"text": "When the above code is compiled and executed, it produces the following result and would come out automatically −"
},
{
"code": null,
"e": 153913,
"s": 153824,
"text": "Going to sleep....\nGoing to sleep....\nGoing to sleep....\nInterrupt signal (2) received.\n"
},
{
"code": null,
"e": 154150,
"s": 153913,
"text": "Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based."
},
{
"code": null,
"e": 154316,
"s": 154150,
"text": "Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program."
},
{
"code": null,
"e": 154496,
"s": 154316,
"text": "A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution."
},
{
"code": null,
"e": 154651,
"s": 154496,
"text": "Before C++ 11, there is no built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature."
},
{
"code": null,
"e": 154923,
"s": 154651,
"text": "This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris."
},
{
"code": null,
"e": 154980,
"s": 154923,
"text": "The following routine is used to create a POSIX thread −"
},
{
"code": null,
"e": 155053,
"s": 154980,
"text": "#include <pthread.h>\npthread_create (thread, attr, start_routine, arg) \n"
},
{
"code": null,
"e": 155243,
"s": 155053,
"text": "Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters −"
},
{
"code": null,
"e": 155250,
"s": 155243,
"text": "thread"
},
{
"code": null,
"e": 155326,
"s": 155250,
"text": "An opaque, unique identifier for the new thread returned by the subroutine."
},
{
"code": null,
"e": 155331,
"s": 155326,
"text": "attr"
},
{
"code": null,
"e": 155477,
"s": 155331,
"text": "An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values."
},
{
"code": null,
"e": 155491,
"s": 155477,
"text": "start_routine"
},
{
"code": null,
"e": 155556,
"s": 155491,
"text": "The C++ routine that the thread will execute once it is created."
},
{
"code": null,
"e": 155560,
"s": 155556,
"text": "arg"
},
{
"code": null,
"e": 155727,
"s": 155560,
"text": "A single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed."
},
{
"code": null,
"e": 155943,
"s": 155727,
"text": "The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads."
},
{
"code": null,
"e": 156013,
"s": 155943,
"text": "There is following routine which we use to terminate a POSIX thread −"
},
{
"code": null,
"e": 156058,
"s": 156013,
"text": "#include <pthread.h>\npthread_exit (status) \n"
},
{
"code": null,
"e": 156235,
"s": 156058,
"text": "Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist."
},
{
"code": null,
"e": 156435,
"s": 156235,
"text": "If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes."
},
{
"code": null,
"e": 156443,
"s": 156435,
"text": "Example"
},
{
"code": null,
"e": 156618,
"s": 156443,
"text": "This simple example code creates 5 threads with the pthread_create() routine. Each thread prints a \"Hello World!\" message, and then terminates with a call to pthread_exit(). "
},
{
"code": null,
"e": 157262,
"s": 156618,
"text": "#include <iostream>\n#include <cstdlib>\n#include <pthread.h>\n\nusing namespace std;\n\n#define NUM_THREADS 5\n\nvoid *PrintHello(void *threadid) {\n long tid;\n tid = (long)threadid;\n cout << \"Hello World! Thread ID, \" << tid << endl;\n pthread_exit(NULL);\n}\n\nint main () {\n pthread_t threads[NUM_THREADS];\n int rc;\n int i;\n \n for( i = 0; i < NUM_THREADS; i++ ) {\n cout << \"main() : creating thread, \" << i << endl;\n rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);\n \n if (rc) {\n cout << \"Error:unable to create thread,\" << rc << endl;\n exit(-1);\n }\n }\n pthread_exit(NULL);\n}"
},
{
"code": null,
"e": 157329,
"s": 157262,
"text": "Compile the following program using -lpthread library as follows −"
},
{
"code": null,
"e": 157354,
"s": 157329,
"text": "$gcc test.cpp -lpthread\n"
},
{
"code": null,
"e": 157415,
"s": 157354,
"text": "Now, execute your program which gives the following output −"
},
{
"code": null,
"e": 157686,
"s": 157415,
"text": "main() : creating thread, 0\nmain() : creating thread, 1\nmain() : creating thread, 2\nmain() : creating thread, 3\nmain() : creating thread, 4\nHello World! Thread ID, 0\nHello World! Thread ID, 1\nHello World! Thread ID, 2\nHello World! Thread ID, 3\nHello World! Thread ID, 4\n"
},
{
"code": null,
"e": 157867,
"s": 157686,
"text": "This example shows how to pass multiple arguments via a structure. You can pass any data type in a thread callback because it points to void as explained in the following example −"
},
{
"code": null,
"e": 158775,
"s": 157867,
"text": "#include <iostream>\n#include <cstdlib>\n#include <pthread.h>\n\nusing namespace std;\n\n#define NUM_THREADS 5\n\nstruct thread_data {\n int thread_id;\n char *message;\n};\n\nvoid *PrintHello(void *threadarg) {\n struct thread_data *my_data;\n my_data = (struct thread_data *) threadarg;\n\n cout << \"Thread ID : \" << my_data->thread_id ;\n cout << \" Message : \" << my_data->message << endl;\n\n pthread_exit(NULL);\n}\n\nint main () {\n pthread_t threads[NUM_THREADS];\n struct thread_data td[NUM_THREADS];\n int rc;\n int i;\n\n for( i = 0; i < NUM_THREADS; i++ ) {\n cout <<\"main() : creating thread, \" << i << endl;\n td[i].thread_id = i;\n td[i].message = \"This is message\";\n rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]);\n \n if (rc) {\n cout << \"Error:unable to create thread,\" << rc << endl;\n exit(-1);\n }\n }\n pthread_exit(NULL);\n}"
},
{
"code": null,
"e": 158856,
"s": 158775,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 159197,
"s": 158856,
"text": "main() : creating thread, 0\nmain() : creating thread, 1\nmain() : creating thread, 2\nmain() : creating thread, 3\nmain() : creating thread, 4\nThread ID : 3 Message : This is message\nThread ID : 2 Message : This is message\nThread ID : 0 Message : This is message\nThread ID : 1 Message : This is message\nThread ID : 4 Message : This is message\n"
},
{
"code": null,
"e": 159275,
"s": 159197,
"text": "There are following two routines which we can use to join or detach threads −"
},
{
"code": null,
"e": 159336,
"s": 159275,
"text": "pthread_join (threadid, status) \npthread_detach (threadid) \n"
},
{
"code": null,
"e": 159651,
"s": 159336,
"text": "The pthread_join() subroutine blocks the calling thread until the specified 'threadid' thread terminates. When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined."
},
{
"code": null,
"e": 159747,
"s": 159651,
"text": "This example demonstrates how to wait for thread completions by using the Pthread join routine."
},
{
"code": null,
"e": 161078,
"s": 159747,
"text": "#include <iostream>\n#include <cstdlib>\n#include <pthread.h>\n#include <unistd.h>\n\nusing namespace std;\n\n#define NUM_THREADS 5\n\nvoid *wait(void *t) {\n int i;\n long tid;\n\n tid = (long)t;\n\n sleep(1);\n cout << \"Sleeping in thread \" << endl;\n cout << \"Thread with id : \" << tid << \" ...exiting \" << endl;\n pthread_exit(NULL);\n}\n\nint main () {\n int rc;\n int i;\n pthread_t threads[NUM_THREADS];\n pthread_attr_t attr;\n void *status;\n\n // Initialize and set thread joinable\n pthread_attr_init(&attr);\n pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n for( i = 0; i < NUM_THREADS; i++ ) {\n cout << \"main() : creating thread, \" << i << endl;\n rc = pthread_create(&threads[i], &attr, wait, (void *)i );\n\n \n if (rc) {\n cout << \"Error:unable to create thread,\" << rc << endl;\n exit(-1);\n }\n }\n\n // free attribute and wait for the other threads\n pthread_attr_destroy(&attr);\n for( i = 0; i < NUM_THREADS; i++ ) {\n rc = pthread_join(threads[i], &status);\n if (rc) {\n cout << \"Error:unable to join,\" << rc << endl;\n exit(-1);\n }\n \n cout << \"Main: completed thread id :\" << i ;\n cout << \" exiting with status :\" << status << endl;\n }\n\n cout << \"Main: program exiting.\" << endl;\n pthread_exit(NULL);\n}"
},
{
"code": null,
"e": 161159,
"s": 161078,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 161843,
"s": 161159,
"text": "main() : creating thread, 0\nmain() : creating thread, 1\nmain() : creating thread, 2\nmain() : creating thread, 3\nmain() : creating thread, 4\nSleeping in thread\nThread with id : 0 .... exiting\nSleeping in thread\nThread with id : 1 .... exiting\nSleeping in thread\nThread with id : 2 .... exiting\nSleeping in thread\nThread with id : 3 .... exiting\nSleeping in thread\nThread with id : 4 .... exiting\nMain: completed thread id :0 exiting with status :0\nMain: completed thread id :1 exiting with status :0\nMain: completed thread id :2 exiting with status :0\nMain: completed thread id :3 exiting with status :0\nMain: completed thread id :4 exiting with status :0\nMain: program exiting.\n"
},
{
"code": null,
"e": 161988,
"s": 161843,
"text": "The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script."
},
{
"code": null,
"e": 162133,
"s": 161988,
"text": "The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script."
},
{
"code": null,
"e": 162221,
"s": 162133,
"text": "The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows −"
},
{
"code": null,
"e": 162309,
"s": 162221,
"text": "The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows −"
},
{
"code": null,
"e": 162451,
"s": 162309,
"text": "The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers."
},
{
"code": null,
"e": 162593,
"s": 162451,
"text": "The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers."
},
{
"code": null,
"e": 162655,
"s": 162593,
"text": "The current version is CGI/1.1 and CGI/1.2 is under progress."
},
{
"code": null,
"e": 162717,
"s": 162655,
"text": "The current version is CGI/1.1 and CGI/1.2 is under progress."
},
{
"code": null,
"e": 162840,
"s": 162717,
"text": "To understand the concept of CGI, let's see what happens when we click a hyperlink to browse a particular web page or URL."
},
{
"code": null,
"e": 162919,
"s": 162840,
"text": "Your browser contacts the HTTP web server and demand for the URL ie. filename."
},
{
"code": null,
"e": 162998,
"s": 162919,
"text": "Your browser contacts the HTTP web server and demand for the URL ie. filename."
},
{
"code": null,
"e": 163221,
"s": 162998,
"text": "Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file."
},
{
"code": null,
"e": 163444,
"s": 163221,
"text": "Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file."
},
{
"code": null,
"e": 163574,
"s": 163444,
"text": "Web browser takes response from web server and displays either the received file or error message based on the received response."
},
{
"code": null,
"e": 163704,
"s": 163574,
"text": "Web browser takes response from web server and displays either the received file or error message based on the received response."
},
{
"code": null,
"e": 163969,
"s": 163704,
"text": "However, it is possible to set up the HTTP server in such a way that whenever a file in a certain directory is requested, that file is not sent back; instead it is executed as a program, and produced output from the program is sent back to your browser to display."
},
{
"code": null,
"e": 164211,
"s": 163969,
"text": "The Common Gateway Interface (CGI) is a standard protocol for enabling applications (called CGI programs or CGI scripts) to interact with Web servers and with clients. These CGI programs can be a written in Python, PERL, Shell, C or C++ etc."
},
{
"code": null,
"e": 164277,
"s": 164211,
"text": "The following simple program shows a simple architecture of CGI −"
},
{
"code": null,
"e": 164677,
"s": 164277,
"text": "Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /var/www/cgi-bin. By convention CGI files will have extension as .cgi, though they are C++ executable."
},
{
"code": null,
"e": 164892,
"s": 164677,
"text": "By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify any other directory to run your CGI scripts, you can modify the following section in the httpd.conf file −"
},
{
"code": null,
"e": 165076,
"s": 164892,
"text": "<Directory \"/var/www/cgi-bin\">\n AllowOverride None\n Options ExecCGI\n Order allow,deny\n Allow from all\n</Directory>\n \n<Directory \"/var/www/cgi-bin\">\n Options All\n</Directory>"
},
{
"code": null,
"e": 165214,
"s": 165076,
"text": "Here, I assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell etc."
},
{
"code": null,
"e": 165259,
"s": 165214,
"text": "Consider the following C++ Program content −"
},
{
"code": null,
"e": 165650,
"s": 165259,
"text": "#include <iostream>\nusing namespace std;\n\nint main () {\n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>Hello World - First CGI Program</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n cout << \"<h2>Hello World! This is my first CGI program</h2>\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 165935,
"s": 165650,
"text": "Compile above code and name the executable as cplusplus.cgi. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program make sure you have change mode of file using chmod 755 cplusplus.cgi UNIX command to make file executable."
},
{
"code": null,
"e": 166470,
"s": 165935,
"text": "The above C++ program is a simple program which is writing its output on STDOUT file i.e. screen. There is one important and extra feature available which is first line printing Content-type:text/html\\r\\n\\r\\n. This line is sent back to the browser and specify the content type to be displayed on the browser screen. Now you must have understood the basic concept of CGI and you can write many complicated CGI programs using Python. A C++ CGI program can interact with any other external system, such as RDBMS, to exchange information."
},
{
"code": null,
"e": 166644,
"s": 166470,
"text": "The line Content-type:text/html\\r\\n\\r\\n is a part of HTTP header, which is sent to the browser to understand the content. All the HTTP header will be in the following form −"
},
{
"code": null,
"e": 166722,
"s": 166644,
"text": "HTTP Field Name: Field Content\n \nFor Example\nContent-type: text/html\\r\\n\\r\\n\n"
},
{
"code": null,
"e": 166821,
"s": 166722,
"text": "There are few other important HTTP headers, which you will use frequently in your CGI Programming."
},
{
"code": null,
"e": 166835,
"s": 166821,
"text": "Content-type:"
},
{
"code": null,
"e": 166932,
"s": 166835,
"text": "A MIME string defining the format of the file being returned. Example is Content-type:text/html."
},
{
"code": null,
"e": 166946,
"s": 166932,
"text": "Expires: Date"
},
{
"code": null,
"e": 167138,
"s": 166946,
"text": "The date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT."
},
{
"code": null,
"e": 167152,
"s": 167138,
"text": "Location: URL"
},
{
"code": null,
"e": 167272,
"s": 167152,
"text": "The URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any file."
},
{
"code": null,
"e": 167292,
"s": 167272,
"text": "Last-modified: Date"
},
{
"code": null,
"e": 167339,
"s": 167292,
"text": "The date of last modification of the resource."
},
{
"code": null,
"e": 167357,
"s": 167339,
"text": "Content-length: N"
},
{
"code": null,
"e": 167485,
"s": 167357,
"text": "The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file."
},
{
"code": null,
"e": 167504,
"s": 167485,
"text": "Set-Cookie: String"
},
{
"code": null,
"e": 167546,
"s": 167504,
"text": "Set the cookie passed through the string."
},
{
"code": null,
"e": 167693,
"s": 167546,
"text": "All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program."
},
{
"code": null,
"e": 167706,
"s": 167693,
"text": "CONTENT_TYPE"
},
{
"code": null,
"e": 167829,
"s": 167706,
"text": "The data type of the content, used when the client is sending attached content to the server. For example file upload etc."
},
{
"code": null,
"e": 167844,
"s": 167829,
"text": "CONTENT_LENGTH"
},
{
"code": null,
"e": 167922,
"s": 167844,
"text": "The length of the query information that is available only for POST requests."
},
{
"code": null,
"e": 167934,
"s": 167922,
"text": "HTTP_COOKIE"
},
{
"code": null,
"e": 167991,
"s": 167934,
"text": "Returns the set cookies in the form of key & value pair."
},
{
"code": null,
"e": 168007,
"s": 167991,
"text": "HTTP_USER_AGENT"
},
{
"code": null,
"e": 168143,
"s": 168007,
"text": "The User-Agent request-header field contains information about the user agent originating the request. It is a name of the web browser."
},
{
"code": null,
"e": 168153,
"s": 168143,
"text": "PATH_INFO"
},
{
"code": null,
"e": 168182,
"s": 168153,
"text": "The path for the CGI script."
},
{
"code": null,
"e": 168195,
"s": 168182,
"text": "QUERY_STRING"
},
{
"code": null,
"e": 168261,
"s": 168195,
"text": "The URL-encoded information that is sent with GET method request."
},
{
"code": null,
"e": 168273,
"s": 168261,
"text": "REMOTE_ADDR"
},
{
"code": null,
"e": 168389,
"s": 168273,
"text": "The IP address of the remote host making the request. This can be useful for logging or for authentication purpose."
},
{
"code": null,
"e": 168401,
"s": 168389,
"text": "REMOTE_HOST"
},
{
"code": null,
"e": 168543,
"s": 168401,
"text": "The fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address."
},
{
"code": null,
"e": 168558,
"s": 168543,
"text": "REQUEST_METHOD"
},
{
"code": null,
"e": 168637,
"s": 168558,
"text": "The method used to make the request. The most common methods are GET and POST."
},
{
"code": null,
"e": 168653,
"s": 168637,
"text": "SCRIPT_FILENAME"
},
{
"code": null,
"e": 168686,
"s": 168653,
"text": "The full path to the CGI script."
},
{
"code": null,
"e": 168698,
"s": 168686,
"text": "SCRIPT_NAME"
},
{
"code": null,
"e": 168726,
"s": 168698,
"text": "The name of the CGI script."
},
{
"code": null,
"e": 168738,
"s": 168726,
"text": "SERVER_NAME"
},
{
"code": null,
"e": 168775,
"s": 168738,
"text": "The server's hostname or IP Address."
},
{
"code": null,
"e": 168791,
"s": 168775,
"text": "SERVER_SOFTWARE"
},
{
"code": null,
"e": 168851,
"s": 168791,
"text": "The name and version of the software the server is running."
},
{
"code": null,
"e": 168912,
"s": 168851,
"text": "Here is small CGI program to list out all the CGI variables."
},
{
"code": null,
"e": 170255,
"s": 168912,
"text": "#include <iostream>\n#include <stdlib.h>\nusing namespace std;\n\nconst string ENV[ 24 ] = {\n \"COMSPEC\", \"DOCUMENT_ROOT\", \"GATEWAY_INTERFACE\", \n \"HTTP_ACCEPT\", \"HTTP_ACCEPT_ENCODING\", \n \"HTTP_ACCEPT_LANGUAGE\", \"HTTP_CONNECTION\", \n \"HTTP_HOST\", \"HTTP_USER_AGENT\", \"PATH\", \n \"QUERY_STRING\", \"REMOTE_ADDR\", \"REMOTE_PORT\", \n \"REQUEST_METHOD\", \"REQUEST_URI\", \"SCRIPT_FILENAME\",\n \"SCRIPT_NAME\", \"SERVER_ADDR\", \"SERVER_ADMIN\", \n \"SERVER_NAME\",\"SERVER_PORT\",\"SERVER_PROTOCOL\", \n \"SERVER_SIGNATURE\",\"SERVER_SOFTWARE\" }; \n\nint main () {\n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>CGI Environment Variables</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n cout << \"<table border = \\\"0\\\" cellspacing = \\\"2\\\">\";\n\n for ( int i = 0; i < 24; i++ ) {\n cout << \"<tr><td>\" << ENV[ i ] << \"</td><td>\";\n \n // attempt to retrieve value of environment variable\n char *value = getenv( ENV[ i ].c_str() ); \n if ( value != 0 ) {\n cout << value; \n } else {\n cout << \"Environment variable does not exist.\";\n }\n cout << \"</td></tr>\\n\";\n }\n \n cout << \"</table><\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 170482,
"s": 170255,
"text": "For real examples, you would need to do many operations by your CGI program. There is a CGI library written for C++ program which you can download from ftp://ftp.gnu.org/gnu/cgicc/ and follow the steps to install the library −"
},
{
"code": null,
"e": 170578,
"s": 170482,
"text": "$tar xzf cgicc-X.X.X.tar.gz \n$cd cgicc-X.X.X/ \n$./configure --prefix=/usr \n$make\n$make install\n"
},
{
"code": null,
"e": 170655,
"s": 170578,
"text": "You can check related documentation available at ‘C++ CGI Lib Documentation."
},
{
"code": null,
"e": 170931,
"s": 170655,
"text": "You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently browser uses two methods to pass this information to web server. These methods are GET Method and POST Method."
},
{
"code": null,
"e": 171094,
"s": 170931,
"text": "The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows −"
},
{
"code": null,
"e": 171155,
"s": 171094,
"text": "http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2\n"
},
{
"code": null,
"e": 171510,
"s": 171155,
"text": "The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation and you can pass upto 1024 characters in a request string."
},
{
"code": null,
"e": 171672,
"s": 171510,
"text": "When using GET method, information is passed using QUERY_STRING http header and will be accessible in your CGI Program through QUERY_STRING environment variable."
},
{
"code": null,
"e": 171829,
"s": 171672,
"text": "You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM> tags to pass information using GET method."
},
{
"code": null,
"e": 171919,
"s": 171829,
"text": "Here is a simple URL which will pass two values to hello_get.py program using GET method."
},
{
"code": null,
"e": 172104,
"s": 171919,
"text": "Below is a program to generate cpp_get.cgi CGI program to handle input given by web browser. We are going to use C++ CGI library which makes it very easy to access passed information −"
},
{
"code": null,
"e": 173182,
"s": 172104,
"text": "#include <iostream>\n#include <vector> \n#include <string> \n#include <stdio.h> \n#include <stdlib.h> \n\n#include <cgicc/CgiDefs.h> \n#include <cgicc/Cgicc.h> \n#include <cgicc/HTTPHTMLHeader.h> \n#include <cgicc/HTMLClasses.h> \n\nusing namespace std;\nusing namespace cgicc;\n\nint main () {\n Cgicc formData;\n \n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>Using GET and POST Methods</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n\n form_iterator fi = formData.getElement(\"first_name\"); \n if( !fi->isEmpty() && fi != (*formData).end()) { \n cout << \"First name: \" << **fi << endl; \n } else {\n cout << \"No text entered for first name\" << endl; \n }\n \n cout << \"<br/>\\n\";\n fi = formData.getElement(\"last_name\"); \n if( !fi->isEmpty() &&fi != (*formData).end()) { \n cout << \"Last name: \" << **fi << endl; \n } else {\n cout << \"No text entered for last name\" << endl; \n }\n \n cout << \"<br/>\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 173226,
"s": 173182,
"text": "Now, compile the above program as follows −"
},
{
"code": null,
"e": 173267,
"s": 173226,
"text": "$g++ -o cpp_get.cgi cpp_get.cpp -lcgicc\n"
},
{
"code": null,
"e": 173362,
"s": 173267,
"text": "Generate cpp_get.cgi and put it in your CGI directory and try to access using following link −"
},
{
"code": null,
"e": 173401,
"s": 173362,
"text": "This would generate following result −"
},
{
"code": null,
"e": 173436,
"s": 173401,
"text": "First name: ZARA \nLast name: ALI \n"
},
{
"code": null,
"e": 173590,
"s": 173436,
"text": "Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same CGI script cpp_get.cgi to handle this input."
},
{
"code": null,
"e": 173822,
"s": 173590,
"text": "<form action = \"/cgi-bin/cpp_get.cgi\" method = \"get\">\n First Name: <input type = \"text\" name = \"first_name\"> <br />\n \n Last Name: <input type = \"text\" name = \"last_name\" />\n <input type = \"submit\" value = \"Submit\" />\n</form>"
},
{
"code": null,
"e": 173945,
"s": 173822,
"text": "Here is the actual output of the above form. You enter First and Last Name and\nthen click submit button to see the result."
},
{
"code": null,
"e": 174282,
"s": 173945,
"text": "A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input."
},
{
"code": null,
"e": 174481,
"s": 174282,
"text": "The same cpp_get.cgi program will handle POST method as well. Let us take same example as above, which passes two values using HTML FORM and submit button but this time with POST method as follows −"
},
{
"code": null,
"e": 174712,
"s": 174481,
"text": "<form action = \"/cgi-bin/cpp_get.cgi\" method = \"post\">\n First Name: <input type = \"text\" name = \"first_name\"><br />\n Last Name: <input type = \"text\" name = \"last_name\" />\n \n <input type = \"submit\" value = \"Submit\" />\n</form>"
},
{
"code": null,
"e": 174835,
"s": 174712,
"text": "Here is the actual output of the above form. You enter First and Last Name and\nthen click submit button to see the result."
},
{
"code": null,
"e": 174909,
"s": 174835,
"text": "Checkboxes are used when more than one option is required to be selected."
},
{
"code": null,
"e": 174968,
"s": 174909,
"text": "Here is example HTML code for a form with two checkboxes −"
},
{
"code": null,
"e": 175242,
"s": 174968,
"text": "<form action = \"/cgi-bin/cpp_checkbox.cgi\" method = \"POST\" target = \"_blank\">\n <input type = \"checkbox\" name = \"maths\" value = \"on\" /> Maths\n <input type = \"checkbox\" name = \"physics\" value = \"on\" /> Physics\n <input type = \"submit\" value = \"Select Subject\" />\n</form>"
},
{
"code": null,
"e": 175291,
"s": 175242,
"text": " The result of this code is the following form −"
},
{
"code": null,
"e": 175419,
"s": 175291,
"text": "Below is C++ program, which will generate cpp_checkbox.cgi script to handle input given by web browser through checkbox button."
},
{
"code": null,
"e": 176428,
"s": 175419,
"text": "#include <iostream>\n#include <vector> \n#include <string> \n#include <stdio.h> \n#include <stdlib.h> \n\n#include <cgicc/CgiDefs.h> \n#include <cgicc/Cgicc.h> \n#include <cgicc/HTTPHTMLHeader.h> \n#include <cgicc/HTMLClasses.h> \n\nusing namespace std;\nusing namespace cgicc;\n\nint main () {\n Cgicc formData;\n bool maths_flag, physics_flag;\n\n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>Checkbox Data to CGI</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n\n maths_flag = formData.queryCheckbox(\"maths\");\n if( maths_flag ) { \n cout << \"Maths Flag: ON \" << endl; \n } else {\n cout << \"Maths Flag: OFF \" << endl; \n }\n cout << \"<br/>\\n\";\n\n physics_flag = formData.queryCheckbox(\"physics\");\n if( physics_flag ) { \n cout << \"Physics Flag: ON \" << endl; \n } else {\n cout << \"Physics Flag: OFF \" << endl; \n }\n \n cout << \"<br/>\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 176500,
"s": 176428,
"text": "Radio Buttons are used when only one option is required to be selected."
},
{
"code": null,
"e": 176561,
"s": 176500,
"text": "Here is example HTML code for a form with two radio button −"
},
{
"code": null,
"e": 176862,
"s": 176561,
"text": "<form action = \"/cgi-bin/cpp_radiobutton.cgi\" method = \"post\" target = \"_blank\">\n <input type = \"radio\" name = \"subject\" value = \"maths\" checked = \"checked\"/> Maths \n <input type = \"radio\" name = \"subject\" value = \"physics\" /> Physics\n <input type = \"submit\" value = \"Select Subject\" />\n</form>"
},
{
"code": null,
"e": 176910,
"s": 176862,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 177039,
"s": 176910,
"text": "Below is C++ program, which will generate cpp_radiobutton.cgi script to handle input given by web browser through radio buttons."
},
{
"code": null,
"e": 177803,
"s": 177039,
"text": "#include <iostream>\n#include <vector> \n#include <string> \n#include <stdio.h> \n#include <stdlib.h> \n\n#include <cgicc/CgiDefs.h> \n#include <cgicc/Cgicc.h> \n#include <cgicc/HTTPHTMLHeader.h> \n#include <cgicc/HTMLClasses.h> \n\nusing namespace std;\nusing namespace cgicc;\n\nint main () {\n Cgicc formData;\n \n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>Radio Button Data to CGI</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n\n form_iterator fi = formData.getElement(\"subject\"); \n if( !fi->isEmpty() && fi != (*formData).end()) { \n cout << \"Radio box selected: \" << **fi << endl; \n }\n \n cout << \"<br/>\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 177885,
"s": 177803,
"text": "TEXTAREA element is used when multiline text has to be passed to the CGI Program."
},
{
"code": null,
"e": 177944,
"s": 177885,
"text": "Here is example HTML code for a form with a TEXTAREA box −"
},
{
"code": null,
"e": 178178,
"s": 177944,
"text": "<form action = \"/cgi-bin/cpp_textarea.cgi\" method = \"post\" target = \"_blank\">\n <textarea name = \"textcontent\" cols = \"40\" rows = \"4\">\n Type your text here...\n </textarea>\n <input type = \"submit\" value = \"Submit\" />\n</form>"
},
{
"code": null,
"e": 178226,
"s": 178178,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 178348,
"s": 178226,
"text": "Below is C++ program, which will generate cpp_textarea.cgi script to handle input given by web browser through text area."
},
{
"code": null,
"e": 179162,
"s": 178348,
"text": "#include <iostream>\n#include <vector> \n#include <string> \n#include <stdio.h> \n#include <stdlib.h> \n\n#include <cgicc/CgiDefs.h> \n#include <cgicc/Cgicc.h> \n#include <cgicc/HTTPHTMLHeader.h> \n#include <cgicc/HTMLClasses.h> \n\nusing namespace std;\nusing namespace cgicc;\n\nint main () {\n Cgicc formData;\n \n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>Text Area Data to CGI</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n\n form_iterator fi = formData.getElement(\"textcontent\"); \n if( !fi->isEmpty() && fi != (*formData).end()) { \n cout << \"Text Content: \" << **fi << endl; \n } else {\n cout << \"No text entered\" << endl; \n }\n \n cout << \"<br/>\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 179258,
"s": 179162,
"text": "Drop down Box is used when we have many options available but only one or two will be selected."
},
{
"code": null,
"e": 179320,
"s": 179258,
"text": "Here is example HTML code for a form with one drop down box −"
},
{
"code": null,
"e": 179601,
"s": 179320,
"text": "<form action = \"/cgi-bin/cpp_dropdown.cgi\" method = \"post\" target = \"_blank\">\n <select name = \"dropdown\">\n <option value = \"Maths\" selected>Maths</option>\n <option value = \"Physics\">Physics</option>\n </select>\n \n <input type = \"submit\" value = \"Submit\"/>\n</form>"
},
{
"code": null,
"e": 179650,
"s": 179601,
"text": " The result of this code is the following form −"
},
{
"code": null,
"e": 179776,
"s": 179650,
"text": "Below is C++ program, which will generate cpp_dropdown.cgi script to handle input given by web browser through drop down box."
},
{
"code": null,
"e": 180538,
"s": 179776,
"text": "#include <iostream>\n#include <vector> \n#include <string> \n#include <stdio.h> \n#include <stdlib.h> \n\n#include <cgicc/CgiDefs.h> \n#include <cgicc/Cgicc.h> \n#include <cgicc/HTTPHTMLHeader.h> \n#include <cgicc/HTMLClasses.h> \n\nusing namespace std;\nusing namespace cgicc;\n\nint main () {\n Cgicc formData;\n \n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>Drop Down Box Data to CGI</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n\n form_iterator fi = formData.getElement(\"dropdown\"); \n if( !fi->isEmpty() && fi != (*formData).end()) { \n cout << \"Value Selected: \" << **fi << endl; \n }\n \n cout << \"<br/>\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 180818,
"s": 180538,
"text": "HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after completing many pages. But how to maintain user's session information across all the web pages."
},
{
"code": null,
"e": 181027,
"s": 180818,
"text": "In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics."
},
{
"code": null,
"e": 181377,
"s": 181027,
"text": "Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored."
},
{
"code": null,
"e": 181444,
"s": 181377,
"text": "Cookies are a plain text data record of 5 variable-length fields −"
},
{
"code": null,
"e": 181571,
"s": 181444,
"text": "Expires − This shows date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 181698,
"s": 181571,
"text": "Expires − This shows date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 181744,
"s": 181698,
"text": "Domain − This shows domain name of your site."
},
{
"code": null,
"e": 181790,
"s": 181744,
"text": "Domain − This shows domain name of your site."
},
{
"code": null,
"e": 181944,
"s": 181790,
"text": "Path − This shows path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 182098,
"s": 181944,
"text": "Path − This shows path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 182260,
"s": 182098,
"text": "Secure − If this field contains the word \"secure\" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 182422,
"s": 182260,
"text": "Secure − If this field contains the word \"secure\" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 182504,
"s": 182422,
"text": "Name = Value − Cookies are set and retrieved in the form of key and value pairs."
},
{
"code": null,
"e": 182586,
"s": 182504,
"text": "Name = Value − Cookies are set and retrieved in the form of key and value pairs."
},
{
"code": null,
"e": 182811,
"s": 182586,
"text": "It is very easy to send cookies to browser. These cookies will be sent along with HTTP Header before the Content-type filed. Assuming you want to set UserID and Password as cookies. So cookies setting will be done as follows"
},
{
"code": null,
"e": 183379,
"s": 182811,
"text": "#include <iostream>\nusing namespace std;\n\nint main () {\n cout << \"Set-Cookie:UserID = XYZ;\\r\\n\";\n cout << \"Set-Cookie:Password = XYZ123;\\r\\n\";\n cout << \"Set-Cookie:Domain = www.tutorialspoint.com;\\r\\n\";\n cout << \"Set-Cookie:Path = /perl;\\n\";\n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>Cookies in CGI</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n\n cout << \"Setting cookies\" << endl; \n \n cout << \"<br/>\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 183489,
"s": 183379,
"text": "From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies."
},
{
"code": null,
"e": 183662,
"s": 183489,
"text": "Here, it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line \"Content-type:text/html\\r\\n\\r\\n."
},
{
"code": null,
"e": 183800,
"s": 183662,
"text": "Compile above program to produce setcookies.cgi, and try to set cookies using following link. It will set four cookies at your computer −"
},
{
"code": null,
"e": 183824,
"s": 183800,
"text": "/cgi-bin/setcookies.cgi"
},
{
"code": null,
"e": 183962,
"s": 183824,
"text": "It is easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form."
},
{
"code": null,
"e": 184011,
"s": 183962,
"text": "key1 = value1; key2 = value2; key3 = value3....\n"
},
{
"code": null,
"e": 184058,
"s": 184011,
"text": "Here is an example of how to retrieve cookies."
},
{
"code": null,
"e": 185088,
"s": 184058,
"text": "#include <iostream>\n#include <vector> \n#include <string> \n#include <stdio.h> \n#include <stdlib.h> \n\n#include <cgicc/CgiDefs.h> \n#include <cgicc/Cgicc.h> \n#include <cgicc/HTTPHTMLHeader.h> \n#include <cgicc/HTMLClasses.h>\n\nusing namespace std;\nusing namespace cgicc;\n\nint main () {\n Cgicc cgi;\n const_cookie_iterator cci;\n\n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>Cookies in CGI</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n cout << \"<table border = \\\"0\\\" cellspacing = \\\"2\\\">\";\n \n // get environment variables\n const CgiEnvironment& env = cgi.getEnvironment();\n\n for( cci = env.getCookieList().begin();\n cci != env.getCookieList().end(); \n ++cci ) {\n cout << \"<tr><td>\" << cci->getName() << \"</td><td>\";\n cout << cci->getValue(); \n cout << \"</td></tr>\\n\";\n }\n \n cout << \"</table><\\n\";\n cout << \"<br/>\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 185212,
"s": 185088,
"text": "Now, compile above program to produce getcookies.cgi, and try to get a list of all the cookies available at your computer −"
},
{
"code": null,
"e": 185236,
"s": 185212,
"text": "/cgi-bin/getcookies.cgi"
},
{
"code": null,
"e": 185354,
"s": 185236,
"text": "This will produce a list of all the four cookies set in previous section and all other cookies set in your computer −"
},
{
"code": null,
"e": 185427,
"s": 185354,
"text": "UserID XYZ \nPassword XYZ123 \nDomain www.tutorialspoint.com \nPath /perl \n"
},
{
"code": null,
"e": 185582,
"s": 185427,
"text": "To upload a file the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type will create a \"Browse\" button."
},
{
"code": null,
"e": 185864,
"s": 185582,
"text": "<html>\n <body>\n <form enctype = \"multipart/form-data\" action = \"/cgi-bin/cpp_uploadfile.cgi\"\n method = \"post\">\n <p>File: <input type = \"file\" name = \"userfile\" /></p>\n <p><input type = \"submit\" value = \"Upload\" /></p>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 185912,
"s": 185864,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 185919,
"s": 185912,
"text": "File: "
},
{
"code": null,
"e": 186063,
"s": 185919,
"text": "Note − Above example has been disabled intentionally to stop people uploading files on our server. But you can try above code with your server."
},
{
"code": null,
"e": 186125,
"s": 186063,
"text": "Here is the script cpp_uploadfile.cpp to handle file upload −"
},
{
"code": null,
"e": 187013,
"s": 186125,
"text": "#include <iostream>\n#include <vector> \n#include <string> \n#include <stdio.h> \n#include <stdlib.h> \n\n#include <cgicc/CgiDefs.h> \n#include <cgicc/Cgicc.h> \n#include <cgicc/HTTPHTMLHeader.h> \n#include <cgicc/HTMLClasses.h>\n\nusing namespace std;\nusing namespace cgicc;\n\nint main () {\n Cgicc cgi;\n\n cout << \"Content-type:text/html\\r\\n\\r\\n\";\n cout << \"<html>\\n\";\n cout << \"<head>\\n\";\n cout << \"<title>File Upload in CGI</title>\\n\";\n cout << \"</head>\\n\";\n cout << \"<body>\\n\";\n\n // get list of files to be uploaded\n const_file_iterator file = cgi.getFile(\"userfile\");\n if(file != cgi.getFiles().end()) {\n // send data type at cout.\n cout << HTTPContentHeader(file->getDataType());\n // write content at cout.\n file->writeToStream(cout);\n }\n cout << \"<File uploaded successfully>\\n\";\n cout << \"</body>\\n\";\n cout << \"</html>\\n\";\n \n return 0;\n}"
},
{
"code": null,
"e": 187172,
"s": 187013,
"text": "The above example is for writing content at cout stream but you can open your file stream and save the content of uploaded file in a file at desired location."
},
{
"code": null,
"e": 187247,
"s": 187172,
"text": "Hope you have enjoyed this tutorial. If yes, please send us your feedback."
},
{
"code": null,
"e": 187284,
"s": 187247,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 187303,
"s": 187284,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 187335,
"s": 187303,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 187358,
"s": 187335,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 187394,
"s": 187358,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 187411,
"s": 187394,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 187446,
"s": 187411,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 187463,
"s": 187446,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 187498,
"s": 187463,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 187515,
"s": 187498,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 187550,
"s": 187515,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 187567,
"s": 187550,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 187574,
"s": 187567,
"text": " Print"
},
{
"code": null,
"e": 187585,
"s": 187574,
"text": " Add Notes"
}
] |
Count occurrences of an element in a list in Python
|
In this article we are given a list and a string. We are required to find how many times the given string is present as an element in the list.
The counter function from collections module will give us the count of each element present in the list. From the counting result we can extract only that account fair the index matches with the value of the element we are searching for.
Live Demo
from collections import Counter
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
elem = 'Mon'
# Given list and element
print("Given list:\n", Alist)
print("Given element:\n",elem)
cnt = Counter(Alist)
print("Number of times the element is present in list:\n",cnt[elem])
Running the above code gives us the following result −
Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Given element:
Mon
Number of times the element is present in list:
2
The count function takes in in the given stream as a parameter and searches for that stream in the given list.
Live Demo
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
elem = 'Mon'
# Given list and element
print("Given list:\n", Alist)
print("Given element:\n",elem)
cnt = Alist.count('Mon')
print("Number of times the element is present in list:\n",cnt)
Running the above code gives us the following result −
Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Given element:
Mon
Number of times the element is present in list:
2
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "In this article we are given a list and a string. We are required to find how many times the given string is present as an element in the list."
},
{
"code": null,
"e": 1444,
"s": 1206,
"text": "The counter function from collections module will give us the count of each element present in the list. From the counting result we can extract only that account fair the index matches with the value of the element we are searching for."
},
{
"code": null,
"e": 1455,
"s": 1444,
"text": " Live Demo"
},
{
"code": null,
"e": 1720,
"s": 1455,
"text": "from collections import Counter\nAlist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']\nelem = 'Mon'\n# Given list and element\nprint(\"Given list:\\n\", Alist)\nprint(\"Given element:\\n\",elem)\ncnt = Counter(Alist)\nprint(\"Number of times the element is present in list:\\n\",cnt[elem])"
},
{
"code": null,
"e": 1775,
"s": 1720,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1892,
"s": 1775,
"text": "Given list:\n['Mon', 'Wed', 'Mon', 'Tue', 'Thu']\nGiven element:\nMon\nNumber of times the element is present in list:\n2"
},
{
"code": null,
"e": 2003,
"s": 1892,
"text": "The count function takes in in the given stream as a parameter and searches for that stream in the given list."
},
{
"code": null,
"e": 2014,
"s": 2003,
"text": " Live Demo"
},
{
"code": null,
"e": 2245,
"s": 2014,
"text": "Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']\nelem = 'Mon'\n# Given list and element\nprint(\"Given list:\\n\", Alist)\nprint(\"Given element:\\n\",elem)\ncnt = Alist.count('Mon')\nprint(\"Number of times the element is present in list:\\n\",cnt)"
},
{
"code": null,
"e": 2300,
"s": 2245,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2417,
"s": 2300,
"text": "Given list:\n['Mon', 'Wed', 'Mon', 'Tue', 'Thu']\nGiven element:\nMon\nNumber of times the element is present in list:\n2"
}
] |
CSS | Animation to Change the Hover State of a Button/Image - GeeksforGeeks
|
29 Jul, 2021
1. To change the color/size of the button in hover state.
Approach:
Set the animation and time duration of hover state
Set background color using @keyframes
Syntax:
button:hover {
animation-name: background-color;
animation-duration: 500ms;
}
@keyframes background-color {
100% {
background-color:#4065F3;
}
}
Examples:
HTML
<!DOCTYPE html><html> <head> Color Change of button on hovering</head><style> button { border-radius: 5px; color: white; background-color: #368508; padding: 5px 10px 8px 10px; } /*Button hover state*/ button:hover { animation-name: background-color; animation-duration: 500ms; } /*keyframes*/ @keyframes background-color { 100% { background-color: #4065F3; } }</style> <body> <br> <br> <button>GeeksforGeeks</button></body> </html>
Output:Initially, the button looks like this:
On hovering it changes to this:
2. To change the color/size of the image in the hover state
.Approach:
Set the animation and time duration of hover state
Set the image size using @keyframes
Syntax:
img:hover {
animation-name: breadth;
animation-duration: 500ms;
}
@keyframes breadth {
50% {
width: 400px;
}
100% {
width: 600px;
}
}
HTML
<!DOCTYPE html><html> <head> Size Change of image on hovering </head><style> img:hover { animation-name: breadth; animation-duration: 500ms; } @keyframes breadth { 50% { width: 400px; } 100% { width: 600px; } }</style> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png" alt="GeeksforGeeks Logo" /></body> </html>
Output:Initially, the size of image is this:
On hovering its size diminishes to this at half duration time:
And then again to original size on completion of duration of time:
kapoorsagar226
CSS-Misc
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24845,
"s": 24817,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 24903,
"s": 24845,
"text": "1. To change the color/size of the button in hover state."
},
{
"code": null,
"e": 24913,
"s": 24903,
"text": "Approach:"
},
{
"code": null,
"e": 24964,
"s": 24913,
"text": "Set the animation and time duration of hover state"
},
{
"code": null,
"e": 25002,
"s": 24964,
"text": "Set background color using @keyframes"
},
{
"code": null,
"e": 25010,
"s": 25002,
"text": "Syntax:"
},
{
"code": null,
"e": 25192,
"s": 25010,
"text": "button:hover {\n animation-name: background-color;\n animation-duration: 500ms;\n }\n\n @keyframes background-color {\n 100% {\n background-color:#4065F3;\n }\n}"
},
{
"code": null,
"e": 25202,
"s": 25192,
"text": "Examples:"
},
{
"code": null,
"e": 25207,
"s": 25202,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> Color Change of button on hovering</head><style> button { border-radius: 5px; color: white; background-color: #368508; padding: 5px 10px 8px 10px; } /*Button hover state*/ button:hover { animation-name: background-color; animation-duration: 500ms; } /*keyframes*/ @keyframes background-color { 100% { background-color: #4065F3; } }</style> <body> <br> <br> <button>GeeksforGeeks</button></body> </html>",
"e": 25748,
"s": 25207,
"text": null
},
{
"code": null,
"e": 25795,
"s": 25748,
"text": "Output:Initially, the button looks like this: "
},
{
"code": null,
"e": 25827,
"s": 25795,
"text": "On hovering it changes to this:"
},
{
"code": null,
"e": 25887,
"s": 25827,
"text": "2. To change the color/size of the image in the hover state"
},
{
"code": null,
"e": 25898,
"s": 25887,
"text": ".Approach:"
},
{
"code": null,
"e": 25949,
"s": 25898,
"text": "Set the animation and time duration of hover state"
},
{
"code": null,
"e": 25985,
"s": 25949,
"text": "Set the image size using @keyframes"
},
{
"code": null,
"e": 25993,
"s": 25985,
"text": "Syntax:"
},
{
"code": null,
"e": 26196,
"s": 25993,
"text": " img:hover {\n animation-name: breadth;\n animation-duration: 500ms;\n }\n\n @keyframes breadth {\n 50% {\n width: 400px;\n }\n 100% {\n width: 600px;\n }\n }"
},
{
"code": null,
"e": 26201,
"s": 26196,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> Size Change of image on hovering </head><style> img:hover { animation-name: breadth; animation-duration: 500ms; } @keyframes breadth { 50% { width: 400px; } 100% { width: 600px; } }</style> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\" alt=\"GeeksforGeeks Logo\" /></body> </html>",
"e": 26646,
"s": 26201,
"text": null
},
{
"code": null,
"e": 26691,
"s": 26646,
"text": "Output:Initially, the size of image is this:"
},
{
"code": null,
"e": 26754,
"s": 26691,
"text": "On hovering its size diminishes to this at half duration time:"
},
{
"code": null,
"e": 26822,
"s": 26754,
"text": "And then again to original size on completion of duration of time: "
},
{
"code": null,
"e": 26839,
"s": 26824,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 26848,
"s": 26839,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26852,
"s": 26848,
"text": "CSS"
},
{
"code": null,
"e": 26869,
"s": 26852,
"text": "Web Technologies"
},
{
"code": null,
"e": 26967,
"s": 26869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26976,
"s": 26967,
"text": "Comments"
},
{
"code": null,
"e": 26989,
"s": 26976,
"text": "Old Comments"
},
{
"code": null,
"e": 27026,
"s": 26989,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27067,
"s": 27026,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 27104,
"s": 27067,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27168,
"s": 27104,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 27229,
"s": 27168,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 27285,
"s": 27229,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27318,
"s": 27285,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27361,
"s": 27318,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27422,
"s": 27361,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Visualizing Output Of Machine Learning Model | by Himanshu Sharma | Towards Data Science
|
Interpreting a machine learning model is a difficult task because we don’t really know how the model is working inside that black box. Interpretation is required so that we can select the best model for our data and also make it robust.
Shap is an open-source python library that is used to explain models. It can create numerous types of visualizations which help in interpreting the model and explaining how the model is working.
In this article, we will see different types of machine learning model visualizations which can be created using Shap.
Let’s get started...
We will start by installing Shap using pip. The command given below will do that.
pip install shap
In this step, we will import the required libraries for loading the data, creating a model, and creating visualizations of that model.
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport shapfrom sklearn.model_selection import train_test_splitimport xgboost as xgb
In this step, we will create the machine learning model. For this article, I’m creating an XGBoost model but you can select any model of your choice. The dataset that we will be using for this model is the famous Diabetes dataset which can be downloaded from Kaggle.
df = pd.read_csv('/content/Diabetes.csv')features = ['Pregnancies', 'Glucose','BloodPressure','SkinThickness','Insulin','BMI','DiabetesPedigreeFunction','Age']Y = df['Outcome']X = df[features]X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 1234)xgb_model = xgb.XGBRegressor(random_state=42)xgb_model.fit(X_train, Y_train)
Now we will create the explainer for shap and find out the shape values for our model and create visualizations using them.
explainer = shap.Explainer(xgb_model)shap_values = explainer(X_test)
Bar Plot
Bar Plot
shap.plots.bar(shap_values, max_display=10)
2. Cohort Plot
shap.plots.bar(shap_values.cohorts(2).abs.mean(0))
3. Heatmap
shap.plots.heatmap(shap_values[1:100])
4. Waterfall Plot
shap.plots.waterfall(shap_values[0]) # For the first observation
5. Force Plot
For this plot, we need to initiate “js” also.
shap.initjs()explainer = shap.TreeExplainer(xgb_model)shap_values = explainer.shap_values(X_test)def p(j): return(shap.force_plot(explainer.expected_value, shap_values[j,:], X_test.iloc[j,:]))p(0)
6. Decision Plot
shap_values = explainer.shap_values(X_test)[1]print("The expected value is ", expected_value)print("The final prediction is ", xgb_model.predict(X_test)[1])shap.decision_plot(expected_value, shap_values, X_test)
This is how you can use Shap for creating visualizations related to machine learning models and analyze them. Go ahead and try this with different datasets and machine learning models and let me know your comment in the response section.
This article is in collaboration with Piyush Ingale.
Thanks for reading! If you want to get in touch with me, feel free to reach me at hmix13@gmail.com or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science.
|
[
{
"code": null,
"e": 409,
"s": 172,
"text": "Interpreting a machine learning model is a difficult task because we don’t really know how the model is working inside that black box. Interpretation is required so that we can select the best model for our data and also make it robust."
},
{
"code": null,
"e": 604,
"s": 409,
"text": "Shap is an open-source python library that is used to explain models. It can create numerous types of visualizations which help in interpreting the model and explaining how the model is working."
},
{
"code": null,
"e": 723,
"s": 604,
"text": "In this article, we will see different types of machine learning model visualizations which can be created using Shap."
},
{
"code": null,
"e": 744,
"s": 723,
"text": "Let’s get started..."
},
{
"code": null,
"e": 826,
"s": 744,
"text": "We will start by installing Shap using pip. The command given below will do that."
},
{
"code": null,
"e": 843,
"s": 826,
"text": "pip install shap"
},
{
"code": null,
"e": 978,
"s": 843,
"text": "In this step, we will import the required libraries for loading the data, creating a model, and creating visualizations of that model."
},
{
"code": null,
"e": 1131,
"s": 978,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport shapfrom sklearn.model_selection import train_test_splitimport xgboost as xgb"
},
{
"code": null,
"e": 1398,
"s": 1131,
"text": "In this step, we will create the machine learning model. For this article, I’m creating an XGBoost model but you can select any model of your choice. The dataset that we will be using for this model is the famous Diabetes dataset which can be downloaded from Kaggle."
},
{
"code": null,
"e": 1763,
"s": 1398,
"text": "df = pd.read_csv('/content/Diabetes.csv')features = ['Pregnancies', 'Glucose','BloodPressure','SkinThickness','Insulin','BMI','DiabetesPedigreeFunction','Age']Y = df['Outcome']X = df[features]X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 1234)xgb_model = xgb.XGBRegressor(random_state=42)xgb_model.fit(X_train, Y_train)"
},
{
"code": null,
"e": 1887,
"s": 1763,
"text": "Now we will create the explainer for shap and find out the shape values for our model and create visualizations using them."
},
{
"code": null,
"e": 1956,
"s": 1887,
"text": "explainer = shap.Explainer(xgb_model)shap_values = explainer(X_test)"
},
{
"code": null,
"e": 1965,
"s": 1956,
"text": "Bar Plot"
},
{
"code": null,
"e": 1974,
"s": 1965,
"text": "Bar Plot"
},
{
"code": null,
"e": 2018,
"s": 1974,
"text": "shap.plots.bar(shap_values, max_display=10)"
},
{
"code": null,
"e": 2033,
"s": 2018,
"text": "2. Cohort Plot"
},
{
"code": null,
"e": 2084,
"s": 2033,
"text": "shap.plots.bar(shap_values.cohorts(2).abs.mean(0))"
},
{
"code": null,
"e": 2095,
"s": 2084,
"text": "3. Heatmap"
},
{
"code": null,
"e": 2134,
"s": 2095,
"text": "shap.plots.heatmap(shap_values[1:100])"
},
{
"code": null,
"e": 2152,
"s": 2134,
"text": "4. Waterfall Plot"
},
{
"code": null,
"e": 2217,
"s": 2152,
"text": "shap.plots.waterfall(shap_values[0]) # For the first observation"
},
{
"code": null,
"e": 2231,
"s": 2217,
"text": "5. Force Plot"
},
{
"code": null,
"e": 2277,
"s": 2231,
"text": "For this plot, we need to initiate “js” also."
},
{
"code": null,
"e": 2477,
"s": 2277,
"text": "shap.initjs()explainer = shap.TreeExplainer(xgb_model)shap_values = explainer.shap_values(X_test)def p(j): return(shap.force_plot(explainer.expected_value, shap_values[j,:], X_test.iloc[j,:]))p(0)"
},
{
"code": null,
"e": 2494,
"s": 2477,
"text": "6. Decision Plot"
},
{
"code": null,
"e": 2706,
"s": 2494,
"text": "shap_values = explainer.shap_values(X_test)[1]print(\"The expected value is \", expected_value)print(\"The final prediction is \", xgb_model.predict(X_test)[1])shap.decision_plot(expected_value, shap_values, X_test)"
},
{
"code": null,
"e": 2944,
"s": 2706,
"text": "This is how you can use Shap for creating visualizations related to machine learning models and analyze them. Go ahead and try this with different datasets and machine learning models and let me know your comment in the response section."
},
{
"code": null,
"e": 2997,
"s": 2944,
"text": "This article is in collaboration with Piyush Ingale."
}
] |
Get second largest marks from a MySQL table using subquery?
|
Let us first create a table −
mysql> create table DemoTable(
Marks int
);
Query OK, 0 rows affected (1.34 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(78);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(67);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(76);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(86);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(89);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(99);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Marks |
+-------+
| 78 |
| 88 |
| 67 |
| 76 |
| 98 |
| 86 |
| 89 |
| 99 |
+-------+
8 rows in set (0.00 sec)
Following is the query to get a second-largest mark from MySQL table −
mysql> select Marks from DemoTable
where Marks=(select MAX(Marks) from DemoTable where Marks < (select MAX(Marks) from DemoTable));
This will produce the following output −
+-------+
| Marks |
+-------+
| 98 |
+-------+
1 row in set (0.03 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1176,
"s": 1092,
"text": "mysql> create table DemoTable(\n Marks int\n);\nQuery OK, 0 rows affected (1.34 sec)"
},
{
"code": null,
"e": 1232,
"s": 1176,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1848,
"s": 1232,
"text": "mysql> insert into DemoTable values(78);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(88);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(67);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(76);\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into DemoTable values(98);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(86);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values(89);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(99);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1908,
"s": 1848,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1939,
"s": 1908,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1980,
"s": 1939,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2125,
"s": 1980,
"text": "+-------+\n| Marks |\n+-------+\n| 78 |\n| 88 |\n| 67 |\n| 76 |\n| 98 |\n| 86 |\n| 89 |\n| 99 |\n+-------+\n8 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2196,
"s": 2125,
"text": "Following is the query to get a second-largest mark from MySQL table −"
},
{
"code": null,
"e": 2328,
"s": 2196,
"text": "mysql> select Marks from DemoTable\nwhere Marks=(select MAX(Marks) from DemoTable where Marks < (select MAX(Marks) from DemoTable));"
},
{
"code": null,
"e": 2369,
"s": 2328,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2443,
"s": 2369,
"text": "+-------+\n| Marks |\n+-------+\n| 98 |\n+-------+\n1 row in set (0.03 sec)"
}
] |
Java Connection getAutoCommit() method with example
|
If you commit a database, it saves all the changes that have been done till that particular point. By default, some databases commits/saves the changes done automatically. You can turn off/on the auto-commit using the setAutoCommit() method of the Connection interface.
The getAutocommit() method of the Connection interface is used to get the current value of the auto-commit in this connection.
To get the auto-commit value −
Register the driver using the registerDriver() method of the DriverManager class as −
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Get the connection using the getConnection() method of the DriverManager class as −
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
Turn off/on the auto-commit using the setAutoCommit() method as −
//Setting the auto commit on
con.setAutoCommit(true);
//Setting the auto commit off
con.setAutoCommit(false);
Get the current auto-commit value using the getAutoCommit() method as −
con.getAutoCommit();
Following JDBC program establishes a connection with the database and turns off the auto-commit and retrieves the current auto-commit value (which is false ).
import java.sql.Connection;
import java.sql.DriverManager;
public class Connection_getAutoCommit {
public static void main(String args[])throws Exception {
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Setting auto-commit false
con.setAutoCommit(false);
//Retrieving the current value of the auto-commit in this connection
boolean autoCommit = con.getAutoCommit();
System.out.println("Auto commit value is: "+autoCommit);
}
}
Connection established......
Auto commit value is: false
|
[
{
"code": null,
"e": 1332,
"s": 1062,
"text": "If you commit a database, it saves all the changes that have been done till that particular point. By default, some databases commits/saves the changes done automatically. You can turn off/on the auto-commit using the setAutoCommit() method of the Connection interface."
},
{
"code": null,
"e": 1459,
"s": 1332,
"text": "The getAutocommit() method of the Connection interface is used to get the current value of the auto-commit in this connection."
},
{
"code": null,
"e": 1490,
"s": 1459,
"text": "To get the auto-commit value −"
},
{
"code": null,
"e": 1576,
"s": 1490,
"text": "Register the driver using the registerDriver() method of the DriverManager class as −"
},
{
"code": null,
"e": 1660,
"s": 1576,
"text": "//Registering the Driver\nDriverManager.registerDriver(new com.mysql.jdbc.Driver());"
},
{
"code": null,
"e": 1744,
"s": 1660,
"text": "Get the connection using the getConnection() method of the DriverManager class as −"
},
{
"code": null,
"e": 1890,
"s": 1744,
"text": "//Getting the connection\nString url = \"jdbc:mysql://localhost/mydatabase\";\nConnection con = DriverManager.getConnection(url, \"root\", \"password\");"
},
{
"code": null,
"e": 1956,
"s": 1890,
"text": "Turn off/on the auto-commit using the setAutoCommit() method as −"
},
{
"code": null,
"e": 2066,
"s": 1956,
"text": "//Setting the auto commit on\ncon.setAutoCommit(true);\n//Setting the auto commit off\ncon.setAutoCommit(false);"
},
{
"code": null,
"e": 2138,
"s": 2066,
"text": "Get the current auto-commit value using the getAutoCommit() method as −"
},
{
"code": null,
"e": 2159,
"s": 2138,
"text": "con.getAutoCommit();"
},
{
"code": null,
"e": 2319,
"s": 2159,
"text": "Following JDBC program establishes a connection with the database and turns off the auto-commit and retrieves the current auto-commit value (which is false )."
},
{
"code": null,
"e": 2967,
"s": 2319,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\npublic class Connection_getAutoCommit {\n public static void main(String args[])throws Exception {\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Setting auto-commit false\n con.setAutoCommit(false);\n //Retrieving the current value of the auto-commit in this connection\n boolean autoCommit = con.getAutoCommit();\n System.out.println(\"Auto commit value is: \"+autoCommit);\n }\n}"
},
{
"code": null,
"e": 3024,
"s": 2967,
"text": "Connection established......\nAuto commit value is: false"
}
] |
Logistic Regression-Theory and Practice | by Gokul S Kumar | Towards Data Science
|
In this article, I will be explaining how to use the concept of regression, in specific logistic regression to the problems involving classification. Classification problems are everywhere around us, the classic ones would include mail classification, weather classification, etc. All these data, if needed can be used to train a Logistic regression model to predict the class of any future example.
This article is going to cover the following sub-topics:
Introduction to classification problems.Logistic regression and all its properties such as hypothesis, decision boundary, cost, cost function, gradient descent, and its necessary analysis.Developing a logistic regression model from scratch using python, pandas, matplotlib, and seaborn and training it on the Breast cancer dataset.Training an in-built Logistic regression model from sklearn using the Breast cancer dataset to verify the previous model.
Introduction to classification problems.
Logistic regression and all its properties such as hypothesis, decision boundary, cost, cost function, gradient descent, and its necessary analysis.
Developing a logistic regression model from scratch using python, pandas, matplotlib, and seaborn and training it on the Breast cancer dataset.
Training an in-built Logistic regression model from sklearn using the Breast cancer dataset to verify the previous model.
Classification problems can be explained based on the Breast Cancer dataset where there are two types of tumors (Benign and Malignant). It can be represented as:
where
This is a classification problem with 2 classes, 0 & 1. Generally, the classification problems have multiple classes say, 0,1,2 and 3.
The link to the Breast cancer dataset used in this article is given below:
www.kaggle.com
Let’s import the dataset to a pandas dataframe:
Let’s import the dataset to a pandas dataframe:
import pandas as pdread_df = pd.read_csv('breast_cancer.csv')df = read_df.copy()
2. The following dataframe is obtained:
df.head()
df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 569 entries, 0 to 568Data columns (total 33 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 569 non-null int64 1 diagnosis 569 non-null object 2 radius_mean 569 non-null float64 3 texture_mean 569 non-null float64 4 perimeter_mean 569 non-null float64 5 area_mean 569 non-null float64 6 smoothness_mean 569 non-null float64 7 compactness_mean 569 non-null float64 8 concavity_mean 569 non-null float64 9 concave points_mean 569 non-null float64 10 symmetry_mean 569 non-null float64 11 fractal_dimension_mean 569 non-null float64 12 radius_se 569 non-null float64 13 texture_se 569 non-null float64 14 perimeter_se 569 non-null float64 15 area_se 569 non-null float64 16 smoothness_se 569 non-null float64 17 compactness_se 569 non-null float64 18 concavity_se 569 non-null float64 19 concave points_se 569 non-null float64 20 symmetry_se 569 non-null float64 21 fractal_dimension_se 569 non-null float64 22 radius_worst 569 non-null float64 23 texture_worst 569 non-null float64 24 perimeter_worst 569 non-null float64 25 area_worst 569 non-null float64 26 smoothness_worst 569 non-null float64 27 compactness_worst 569 non-null float64 28 concavity_worst 569 non-null float64 29 concave points_worst 569 non-null float64 30 symmetry_worst 569 non-null float64 31 fractal_dimension_worst 569 non-null float64 32 Unnamed: 32 0 non-null float64dtypes: float64(31), int64(1), object(1)memory usage: 146.8+ KB
Let us plot the mean area of the clump and its classification and see if we can find a relation between them.
import matplotlib.pyplot as pltimport seaborn as snsfrom sklearn import preprocessinglabel_encoder = preprocessing.LabelEncoder()df.diagnosis = label_encoder.fit_transform(df.diagnosis)sns.set(style = 'whitegrid')sns.lmplot(x = 'area_mean', y = 'diagnosis', data = df, height = 10, aspect = 1.5, y_jitter = 0.1)
We can infer from the plot that most of the tumors having an area less than 500 are benign(represented by zero) and those having area more than 1000 are malignant(represented by 1). The tumors having a mean area between 500 to 1000 are both benign and malignant, therefore show that the classification depends on more factors other than mean area. A linear regression line is also plotted for further analysis.
If we are going to do predictions based on the linear regression line drawn, we could set the threshold classifier output value at say, 0.5.
This means that tumors having a mean area less than the threshold( the area corresponding to 0.5 in the y-axis) will be classified as benign and those having a mean area greater than the threshold will be classified as malignant.
But from the plot, we can state the following reasons for linear regression not being a perfect model.
For values of x having a corresponding hypothesis value less than 0.5, predicting it as 0(or malignant)and also vice-versa is inappropriate.We can also see that the hypothesis value is greater than 1 and less than 0 in some cases which can't be true(as there are only two classes 0 and 1).
For values of x having a corresponding hypothesis value less than 0.5, predicting it as 0(or malignant)and also vice-versa is inappropriate.
We can also see that the hypothesis value is greater than 1 and less than 0 in some cases which can't be true(as there are only two classes 0 and 1).
This is where logistic regression comes into the picture. Logistic regression is a regression model specifically used for classification problems i.e., where the output values are discrete.
We observed form the above part that, while using linear regression, the hypothesis value was not in the range of [0,1]. This is would be the basic requirement of Logistic regression.
This means that all the predictions are supposed to be between 0 and 1.
The hypothesis of linear regression is given by:
For logistic regression, the above hypothesis is modified a little:
where:
z is a real number. g(z) is called the Sigmoid function or Logistic function(which gives us the name Logistic regression).
Putting together both the equations given above:
Let’s see the shape of the logistic function:
def sigmoid(x): return 1/(1+ np.exp(-x))x = np.linspace(-10,10,num = 1000)fig = plt.figure(figsize = (10,10))sns.set(style = 'whitegrid')sns.lineplot(x = x, y = sigmoid(x))
We can infer the following from the graph:
It crosses the y-axis at 0.5.The logistic function asymptotes at 1 as z tends to infinity and at 0 as z tends to negative infinity.As g(z) take on values in the range of (0,1), the values of h(x) also lies between (0,1).
It crosses the y-axis at 0.5.
The logistic function asymptotes at 1 as z tends to infinity and at 0 as z tends to negative infinity.
As g(z) take on values in the range of (0,1), the values of h(x) also lies between (0,1).
So given the hypothesis:
we need to find the parameters which fit the training examples so that the hypothesis can be used to make predictions.
The output given by the hypothesis h(x) can be interpreted as the probability for y = 1 for a given input x.
Consider the breast cancer data set. The feature vector for the feature mean area can be formed as:
Assume the hypothesis h(x) gives us a value of 0.7 for the above feature vector. As we have denoted malignant with 1 and benign with 0 we can say that the probability of the tumor being malignant is 70%.
This can be mathematically represented as follows:
The RHS can be read as
probability that y=1, given x, parameterized by theta
Since this a classification problem, we know that y can be equal to only two values 0 or 1(in this case). This applies to both the training examples and also any future predictions that we make. So given the hypothesis h(x), we can compute the probability for y=0 also as follows:
Consider the logistic function that we plotted above:
Let’s understand better when the hypothesis makes predictions that y=1 and y=0.
Suppose the prediction y=1 happens when
From the plot, we notice that the above condition occurs as:
i.e., when z is positive, g(z) take on values greater than 0.5.
So considering our hypothesis h(x), we can say that:
Similarly, assume prediction y=0 happens when
By similar argument as above:
We can use the above conclusions to better understand how the hypothesis of logistic regression makes predictions.
Consider the simple training set shown below:
os = np.array([[0, 0.5], [0.5, 0.5], [1.5, 0.5], [1, 0.5], [0.5, 0.5], [0.5, 1.5], [0, 1.5], [0,2.5]])xs = np.array([[1.5, 3], [2, 3.5], [2, 3], [2, 2.5], [2.5, 3.5], [3, 3], [3, 1.5], [3, 2], [3, 1], [3.5, 1.5]])fig = plt.figure(figsize = (10,10))sns.set(style = 'whitegrid')ax = sns.scatterplot(x = os[:,0], y = os[:,1], marker = 's', s = 100, color = 'r')ax = sns.scatterplot(x = xs[:,0], y = xs[:,1], marker = 'x', s = 100, color = 'k')ax.set(xlabel = 'x1', ylabel = 'x2')
We will assume the X’s correspond to y = 1 and the squares correspond to y = 0. Consider its hypothesis to be:
where x1 and x2 are the two features.
Assume we end up choosing the parameters that fit the equation to be(the process of choosing the parameters will be discussed later):
The parameter vector is going to be:
Taking reference from the arguments in the above section, prediction y=1 happens when:
From the parameters that we ended up with, we get
Plotting the line x1+x2 = 3:
x = np.linspace(0, 3, num = 10)ax = sns.lineplot(x = x, y = 3-x)
We can see that the region to the right of the line corresponds to the condition x1+x2≥3 and the hypothesis would predict y=1 if it were in this region and vice-versa. This line that divides both the regions is called the decision boundary of this training dataset and it corresponds to h(x)=0.5 exactly.
To be very clear, the decision boundary and the region are the properties of the hypothesis and its parameters and not that of the training dataset.
Consider a somewhat complex data-set given below:
os = np.array([[0,0], [0,0.5], [0.5,0.5], [0.5,0], [-0.5,0.5], [-0.5,0], [-0.5,-0.5], [0,-0.5], [0.5, -0.5],])xs = np.array([[1,1], [-1,1], [1,-1], [-1,-1], [0,1.5], [-1.5,0], [0,-1.5], [1.5,0]])fig = plt.figure(figsize = (10,10))sns.set(style = ‘whitegrid’)ax = sns.scatterplot(os[:,0], os[:,1], marker = ‘s’, s = 100, color = ‘r’)ax = sns.scatterplot(xs[:,0], xs[:,1], marker = ‘x’, s = 100, color = ‘k’)
As in the above example, the X’s belong to the region y=1 and the squares belong to the region y=0. Let’s say our hypothesis looks like:
Assume we end up choosing the values of parameters as:
Then our parameter vector looks like:
As per our earlier discussion, the hypothesis will predict y=1 when:
We can see that the above equation corresponds to a circle of radius 1 centered at the origin.
Plotting the equation:
theta = np.linspace(0, 2*np.pi , 1000)r = np.sqrt(1)x = r*np.cos(theta)y = r*np.sin(theta)ax.plot(x,y, color = 'b')
The circle is our decision boundary and the region outside the circle corresponds to y=1 and inside the circle corresponds to y=0. We can see that the decision boundary doesn't necessarily have to be a straight line but also more complex shapes like a circle, ellipse, and any other irregular shapes. Again the decision boundary is a property of the hypothesis and its parameters and not that of the training dataset.
The cost of a logistic regression problem is given by:
where, as discussed before h(x) is the prediction of the hypothesis and y is the actual class label.
Let’s plot this function to see how it corresponds to each case. We need to set the limits to h(x) as [0,1] as it lies in that range for logistic regression.
If y=1
If y=1
x = np.linspace(0,1, num = 100)fig = plt.figure(figsize = (10,10))sns.set(style = 'whitegrid')ax = sns.lineplot(x = x, y = -np.log(x))ax.set(xlabel = 'h(x)', ylabel = 'cost')
The following inferences can be made from the plot:
a. Cost becomes zero as h(x)=1 and y=1. This is obvious since the hypothesis predicts y as 1 which is true, then the cost will be zero.
b. As h(x) approaches zero the cost tends to infinity. This happens as this plot is specific to y=1 but, when h(x) predicts it as 0 the cost tends to infinity.
2. If y=0
ax = sns.lineplot(x = x, y = -np.log(1-x))
As discussed above, the following can be inferred:
a. Cost becomes zero as h(x)=0 and y=0.
b. Cost tends to infinity as h(x) approaches 1 since y=0.
The cost function of logistic regression is given by:
The point to note is that y=0 or 1 always in a classification problem having 2 classes.
The cost can be represented in a single line as follows:
This is a more compact representation of the cost. Thereby the cost function can be written as follows:
We need to find the parameters so that the value of cost function is minimized. This can be mathematically represented as:
The differentiation term is given by:
Plugging it in the gradient descent equation:
Let’s use the above equations to execute Logistic Regression on the breast_cancer dataset.
x = df.area_meany = df.diagnosisx = preprocessing.scale(x)theta_0_gd = 0theta_1_gd = 0alpha = 0.01h_theta_0_gd = 1h_theta_1_gd = 1epoch = 0m = len(x)fig = plt.figure(figsize = (10,10))sns.set(style = 'whitegrid')ax = sns.scatterplot(x,y)while h_theta_0_gd != 0 or h_theta_0_gd != 0: if epoch > 5000: break h_theta_0_gd = 0 h_theta_1_gd = 0 for i in range(len(x)): h_theta_0_gd += ((1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))) - y[i]) h_theta_1_gd += (((1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))) - y[i]) * x[i]) h_theta_0_gd = (1/m) * h_theta_0_gd h_theta_1_gd = (1/m) * h_theta_1_gd theta_0_gd -= (alpha * h_theta_0_gd) theta_1_gd -= (alpha * h_theta_1_gd) epoch += 1ax = sns.lineplot(x,(1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x))))) , color = 'r', linewidth = 3)
The values of theta_0 and theta_1 are :
print(theta_0_gd, theta_1_gd)output>>-0.4173702618170074 3.0623106036104937
We could also plot the value of cost function after each epoch to check the convergence of the algorithm:
x = np.array(df.area_mean)y = np.array(df.diagnosis)x = preprocessing.scale(x)theta_0_gd = 0theta_1_gd = 0alpha = 0.01h_theta_0_gd = 1h_theta_1_gd = 1epoch = 0Epoch = []m = len(x)j = 0J = []fig = plt.figure(figsize = (20,10))ax1 = fig.add_subplot(1,2,1)ax2 = fig.add_subplot(1,2,2)style.use('ggplot')ax1.scatter(x,y)while h_theta_0_gd != 0 or h_theta_0_gd != 0: if epoch > 5000: break h_theta_0_gd = 0 h_theta_1_gd = 0 for i in range(len(x)): h_theta_0_gd += ((1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))) - y[i]) h_theta_1_gd += (((1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))) - y[i]) * x[i]) h_theta_0_gd = (1/m) * h_theta_0_gd h_theta_1_gd = (1/m) * h_theta_1_gd theta_0_gd -= (alpha * h_theta_0_gd) theta_1_gd -= (alpha * h_theta_1_gd) for i in range(m): j += ((y[i] * (np.log(1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))))) - ((1-y[i]) * np.log(1-(1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i])))))))) J.append((-1/m) * j) epoch += 1 Epoch.append(epoch)ax1.scatter(x,(1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x))))) , color = 'k')ax2.plot(Epoch,J)plt.show()
We can see that the algorithm converged at around 500 epochs where the cost function reached a minimum value of -30, after which it started increasing till 5000 epochs. This happened as the learning rate ( which is 0.01) is very large so the algorithm after a certain point starts diverging. Consider lowering the learning rate further.
The above plot corresponds to a learning rate of 0.001. We can see that the algorithm converges at around 6000 epochs at a cost function value of -375, after which it starts increasing again. We can conclude from this that decreasing the learning rate helps in fine-tuning the parameters to obtain the more minimized value of cost function, but the algorithm takes a larger no of epochs i.e., takes more time to converge.
Let’s check if the parameter values obtained in our model are on par with the sklearn model of Logistic regression
X = x.reshape(-1,1)x_train, x_test, y_train, y_test = model_selection.train_test_split(X, y, test_size = 0.33)clf = LogisticRegression(max_iter = 5000)clf.fit(x_train, y_train)clf.coef_output>> array([[3.5028]])clf.intercept_output>> array([-0.31180412])
As we can see, the parameters are having close enough values when compared. We could even plot the regression line using the parameters obtained to check if we are getting a similar plot.
Theta_1 = clf.coef_Theta_0 = clf.intercept_fig = plt.figure(figsize = (10,10))ax = sns.scatterplot(X,y)ax = sns.lineplot(X, (1/(1+np.exp(-(Theta_0 + (Theta_1[0] * X))))), color = 'r')
In this article, we have seen what is meant mathematically by a Classification problem, how linear regression is of little use in the case of a classification problem, Logistic regression and its hypothesis, cost, cost function, decision boundary, and gradient descent. We also built a Logistic regression model form scratch and trained it using the Breast cancer dataset. We also used the inbuilt model from sklearn for verification.
I am learning most of the concepts about Machine learning from this Youtube playlist. It is quite helpful and easy to understand too.
I am learning most of the concepts about Machine learning from this Youtube playlist. It is quite helpful and easy to understand too.
scikit-learn.org
2. Consider checking out the official docs of sklearn’s Logistic regression classified for further usability.
|
[
{
"code": null,
"e": 447,
"s": 47,
"text": "In this article, I will be explaining how to use the concept of regression, in specific logistic regression to the problems involving classification. Classification problems are everywhere around us, the classic ones would include mail classification, weather classification, etc. All these data, if needed can be used to train a Logistic regression model to predict the class of any future example."
},
{
"code": null,
"e": 504,
"s": 447,
"text": "This article is going to cover the following sub-topics:"
},
{
"code": null,
"e": 957,
"s": 504,
"text": "Introduction to classification problems.Logistic regression and all its properties such as hypothesis, decision boundary, cost, cost function, gradient descent, and its necessary analysis.Developing a logistic regression model from scratch using python, pandas, matplotlib, and seaborn and training it on the Breast cancer dataset.Training an in-built Logistic regression model from sklearn using the Breast cancer dataset to verify the previous model."
},
{
"code": null,
"e": 998,
"s": 957,
"text": "Introduction to classification problems."
},
{
"code": null,
"e": 1147,
"s": 998,
"text": "Logistic regression and all its properties such as hypothesis, decision boundary, cost, cost function, gradient descent, and its necessary analysis."
},
{
"code": null,
"e": 1291,
"s": 1147,
"text": "Developing a logistic regression model from scratch using python, pandas, matplotlib, and seaborn and training it on the Breast cancer dataset."
},
{
"code": null,
"e": 1413,
"s": 1291,
"text": "Training an in-built Logistic regression model from sklearn using the Breast cancer dataset to verify the previous model."
},
{
"code": null,
"e": 1575,
"s": 1413,
"text": "Classification problems can be explained based on the Breast Cancer dataset where there are two types of tumors (Benign and Malignant). It can be represented as:"
},
{
"code": null,
"e": 1581,
"s": 1575,
"text": "where"
},
{
"code": null,
"e": 1716,
"s": 1581,
"text": "This is a classification problem with 2 classes, 0 & 1. Generally, the classification problems have multiple classes say, 0,1,2 and 3."
},
{
"code": null,
"e": 1791,
"s": 1716,
"text": "The link to the Breast cancer dataset used in this article is given below:"
},
{
"code": null,
"e": 1806,
"s": 1791,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 1854,
"s": 1806,
"text": "Let’s import the dataset to a pandas dataframe:"
},
{
"code": null,
"e": 1902,
"s": 1854,
"text": "Let’s import the dataset to a pandas dataframe:"
},
{
"code": null,
"e": 1983,
"s": 1902,
"text": "import pandas as pdread_df = pd.read_csv('breast_cancer.csv')df = read_df.copy()"
},
{
"code": null,
"e": 2023,
"s": 1983,
"text": "2. The following dataframe is obtained:"
},
{
"code": null,
"e": 2033,
"s": 2023,
"text": "df.head()"
},
{
"code": null,
"e": 4063,
"s": 2033,
"text": "df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 569 entries, 0 to 568Data columns (total 33 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 569 non-null int64 1 diagnosis 569 non-null object 2 radius_mean 569 non-null float64 3 texture_mean 569 non-null float64 4 perimeter_mean 569 non-null float64 5 area_mean 569 non-null float64 6 smoothness_mean 569 non-null float64 7 compactness_mean 569 non-null float64 8 concavity_mean 569 non-null float64 9 concave points_mean 569 non-null float64 10 symmetry_mean 569 non-null float64 11 fractal_dimension_mean 569 non-null float64 12 radius_se 569 non-null float64 13 texture_se 569 non-null float64 14 perimeter_se 569 non-null float64 15 area_se 569 non-null float64 16 smoothness_se 569 non-null float64 17 compactness_se 569 non-null float64 18 concavity_se 569 non-null float64 19 concave points_se 569 non-null float64 20 symmetry_se 569 non-null float64 21 fractal_dimension_se 569 non-null float64 22 radius_worst 569 non-null float64 23 texture_worst 569 non-null float64 24 perimeter_worst 569 non-null float64 25 area_worst 569 non-null float64 26 smoothness_worst 569 non-null float64 27 compactness_worst 569 non-null float64 28 concavity_worst 569 non-null float64 29 concave points_worst 569 non-null float64 30 symmetry_worst 569 non-null float64 31 fractal_dimension_worst 569 non-null float64 32 Unnamed: 32 0 non-null float64dtypes: float64(31), int64(1), object(1)memory usage: 146.8+ KB"
},
{
"code": null,
"e": 4173,
"s": 4063,
"text": "Let us plot the mean area of the clump and its classification and see if we can find a relation between them."
},
{
"code": null,
"e": 4485,
"s": 4173,
"text": "import matplotlib.pyplot as pltimport seaborn as snsfrom sklearn import preprocessinglabel_encoder = preprocessing.LabelEncoder()df.diagnosis = label_encoder.fit_transform(df.diagnosis)sns.set(style = 'whitegrid')sns.lmplot(x = 'area_mean', y = 'diagnosis', data = df, height = 10, aspect = 1.5, y_jitter = 0.1)"
},
{
"code": null,
"e": 4896,
"s": 4485,
"text": "We can infer from the plot that most of the tumors having an area less than 500 are benign(represented by zero) and those having area more than 1000 are malignant(represented by 1). The tumors having a mean area between 500 to 1000 are both benign and malignant, therefore show that the classification depends on more factors other than mean area. A linear regression line is also plotted for further analysis."
},
{
"code": null,
"e": 5037,
"s": 4896,
"text": "If we are going to do predictions based on the linear regression line drawn, we could set the threshold classifier output value at say, 0.5."
},
{
"code": null,
"e": 5267,
"s": 5037,
"text": "This means that tumors having a mean area less than the threshold( the area corresponding to 0.5 in the y-axis) will be classified as benign and those having a mean area greater than the threshold will be classified as malignant."
},
{
"code": null,
"e": 5370,
"s": 5267,
"text": "But from the plot, we can state the following reasons for linear regression not being a perfect model."
},
{
"code": null,
"e": 5660,
"s": 5370,
"text": "For values of x having a corresponding hypothesis value less than 0.5, predicting it as 0(or malignant)and also vice-versa is inappropriate.We can also see that the hypothesis value is greater than 1 and less than 0 in some cases which can't be true(as there are only two classes 0 and 1)."
},
{
"code": null,
"e": 5801,
"s": 5660,
"text": "For values of x having a corresponding hypothesis value less than 0.5, predicting it as 0(or malignant)and also vice-versa is inappropriate."
},
{
"code": null,
"e": 5951,
"s": 5801,
"text": "We can also see that the hypothesis value is greater than 1 and less than 0 in some cases which can't be true(as there are only two classes 0 and 1)."
},
{
"code": null,
"e": 6141,
"s": 5951,
"text": "This is where logistic regression comes into the picture. Logistic regression is a regression model specifically used for classification problems i.e., where the output values are discrete."
},
{
"code": null,
"e": 6325,
"s": 6141,
"text": "We observed form the above part that, while using linear regression, the hypothesis value was not in the range of [0,1]. This is would be the basic requirement of Logistic regression."
},
{
"code": null,
"e": 6397,
"s": 6325,
"text": "This means that all the predictions are supposed to be between 0 and 1."
},
{
"code": null,
"e": 6446,
"s": 6397,
"text": "The hypothesis of linear regression is given by:"
},
{
"code": null,
"e": 6514,
"s": 6446,
"text": "For logistic regression, the above hypothesis is modified a little:"
},
{
"code": null,
"e": 6521,
"s": 6514,
"text": "where:"
},
{
"code": null,
"e": 6644,
"s": 6521,
"text": "z is a real number. g(z) is called the Sigmoid function or Logistic function(which gives us the name Logistic regression)."
},
{
"code": null,
"e": 6693,
"s": 6644,
"text": "Putting together both the equations given above:"
},
{
"code": null,
"e": 6739,
"s": 6693,
"text": "Let’s see the shape of the logistic function:"
},
{
"code": null,
"e": 6912,
"s": 6739,
"text": "def sigmoid(x): return 1/(1+ np.exp(-x))x = np.linspace(-10,10,num = 1000)fig = plt.figure(figsize = (10,10))sns.set(style = 'whitegrid')sns.lineplot(x = x, y = sigmoid(x))"
},
{
"code": null,
"e": 6955,
"s": 6912,
"text": "We can infer the following from the graph:"
},
{
"code": null,
"e": 7176,
"s": 6955,
"text": "It crosses the y-axis at 0.5.The logistic function asymptotes at 1 as z tends to infinity and at 0 as z tends to negative infinity.As g(z) take on values in the range of (0,1), the values of h(x) also lies between (0,1)."
},
{
"code": null,
"e": 7206,
"s": 7176,
"text": "It crosses the y-axis at 0.5."
},
{
"code": null,
"e": 7309,
"s": 7206,
"text": "The logistic function asymptotes at 1 as z tends to infinity and at 0 as z tends to negative infinity."
},
{
"code": null,
"e": 7399,
"s": 7309,
"text": "As g(z) take on values in the range of (0,1), the values of h(x) also lies between (0,1)."
},
{
"code": null,
"e": 7424,
"s": 7399,
"text": "So given the hypothesis:"
},
{
"code": null,
"e": 7543,
"s": 7424,
"text": "we need to find the parameters which fit the training examples so that the hypothesis can be used to make predictions."
},
{
"code": null,
"e": 7652,
"s": 7543,
"text": "The output given by the hypothesis h(x) can be interpreted as the probability for y = 1 for a given input x."
},
{
"code": null,
"e": 7752,
"s": 7652,
"text": "Consider the breast cancer data set. The feature vector for the feature mean area can be formed as:"
},
{
"code": null,
"e": 7956,
"s": 7752,
"text": "Assume the hypothesis h(x) gives us a value of 0.7 for the above feature vector. As we have denoted malignant with 1 and benign with 0 we can say that the probability of the tumor being malignant is 70%."
},
{
"code": null,
"e": 8007,
"s": 7956,
"text": "This can be mathematically represented as follows:"
},
{
"code": null,
"e": 8030,
"s": 8007,
"text": "The RHS can be read as"
},
{
"code": null,
"e": 8084,
"s": 8030,
"text": "probability that y=1, given x, parameterized by theta"
},
{
"code": null,
"e": 8365,
"s": 8084,
"text": "Since this a classification problem, we know that y can be equal to only two values 0 or 1(in this case). This applies to both the training examples and also any future predictions that we make. So given the hypothesis h(x), we can compute the probability for y=0 also as follows:"
},
{
"code": null,
"e": 8419,
"s": 8365,
"text": "Consider the logistic function that we plotted above:"
},
{
"code": null,
"e": 8499,
"s": 8419,
"text": "Let’s understand better when the hypothesis makes predictions that y=1 and y=0."
},
{
"code": null,
"e": 8539,
"s": 8499,
"text": "Suppose the prediction y=1 happens when"
},
{
"code": null,
"e": 8600,
"s": 8539,
"text": "From the plot, we notice that the above condition occurs as:"
},
{
"code": null,
"e": 8664,
"s": 8600,
"text": "i.e., when z is positive, g(z) take on values greater than 0.5."
},
{
"code": null,
"e": 8717,
"s": 8664,
"text": "So considering our hypothesis h(x), we can say that:"
},
{
"code": null,
"e": 8763,
"s": 8717,
"text": "Similarly, assume prediction y=0 happens when"
},
{
"code": null,
"e": 8793,
"s": 8763,
"text": "By similar argument as above:"
},
{
"code": null,
"e": 8908,
"s": 8793,
"text": "We can use the above conclusions to better understand how the hypothesis of logistic regression makes predictions."
},
{
"code": null,
"e": 8954,
"s": 8908,
"text": "Consider the simple training set shown below:"
},
{
"code": null,
"e": 9431,
"s": 8954,
"text": "os = np.array([[0, 0.5], [0.5, 0.5], [1.5, 0.5], [1, 0.5], [0.5, 0.5], [0.5, 1.5], [0, 1.5], [0,2.5]])xs = np.array([[1.5, 3], [2, 3.5], [2, 3], [2, 2.5], [2.5, 3.5], [3, 3], [3, 1.5], [3, 2], [3, 1], [3.5, 1.5]])fig = plt.figure(figsize = (10,10))sns.set(style = 'whitegrid')ax = sns.scatterplot(x = os[:,0], y = os[:,1], marker = 's', s = 100, color = 'r')ax = sns.scatterplot(x = xs[:,0], y = xs[:,1], marker = 'x', s = 100, color = 'k')ax.set(xlabel = 'x1', ylabel = 'x2')"
},
{
"code": null,
"e": 9542,
"s": 9431,
"text": "We will assume the X’s correspond to y = 1 and the squares correspond to y = 0. Consider its hypothesis to be:"
},
{
"code": null,
"e": 9580,
"s": 9542,
"text": "where x1 and x2 are the two features."
},
{
"code": null,
"e": 9714,
"s": 9580,
"text": "Assume we end up choosing the parameters that fit the equation to be(the process of choosing the parameters will be discussed later):"
},
{
"code": null,
"e": 9751,
"s": 9714,
"text": "The parameter vector is going to be:"
},
{
"code": null,
"e": 9838,
"s": 9751,
"text": "Taking reference from the arguments in the above section, prediction y=1 happens when:"
},
{
"code": null,
"e": 9888,
"s": 9838,
"text": "From the parameters that we ended up with, we get"
},
{
"code": null,
"e": 9917,
"s": 9888,
"text": "Plotting the line x1+x2 = 3:"
},
{
"code": null,
"e": 9982,
"s": 9917,
"text": "x = np.linspace(0, 3, num = 10)ax = sns.lineplot(x = x, y = 3-x)"
},
{
"code": null,
"e": 10287,
"s": 9982,
"text": "We can see that the region to the right of the line corresponds to the condition x1+x2≥3 and the hypothesis would predict y=1 if it were in this region and vice-versa. This line that divides both the regions is called the decision boundary of this training dataset and it corresponds to h(x)=0.5 exactly."
},
{
"code": null,
"e": 10436,
"s": 10287,
"text": "To be very clear, the decision boundary and the region are the properties of the hypothesis and its parameters and not that of the training dataset."
},
{
"code": null,
"e": 10486,
"s": 10436,
"text": "Consider a somewhat complex data-set given below:"
},
{
"code": null,
"e": 10893,
"s": 10486,
"text": "os = np.array([[0,0], [0,0.5], [0.5,0.5], [0.5,0], [-0.5,0.5], [-0.5,0], [-0.5,-0.5], [0,-0.5], [0.5, -0.5],])xs = np.array([[1,1], [-1,1], [1,-1], [-1,-1], [0,1.5], [-1.5,0], [0,-1.5], [1.5,0]])fig = plt.figure(figsize = (10,10))sns.set(style = ‘whitegrid’)ax = sns.scatterplot(os[:,0], os[:,1], marker = ‘s’, s = 100, color = ‘r’)ax = sns.scatterplot(xs[:,0], xs[:,1], marker = ‘x’, s = 100, color = ‘k’)"
},
{
"code": null,
"e": 11030,
"s": 10893,
"text": "As in the above example, the X’s belong to the region y=1 and the squares belong to the region y=0. Let’s say our hypothesis looks like:"
},
{
"code": null,
"e": 11085,
"s": 11030,
"text": "Assume we end up choosing the values of parameters as:"
},
{
"code": null,
"e": 11123,
"s": 11085,
"text": "Then our parameter vector looks like:"
},
{
"code": null,
"e": 11192,
"s": 11123,
"text": "As per our earlier discussion, the hypothesis will predict y=1 when:"
},
{
"code": null,
"e": 11287,
"s": 11192,
"text": "We can see that the above equation corresponds to a circle of radius 1 centered at the origin."
},
{
"code": null,
"e": 11310,
"s": 11287,
"text": "Plotting the equation:"
},
{
"code": null,
"e": 11426,
"s": 11310,
"text": "theta = np.linspace(0, 2*np.pi , 1000)r = np.sqrt(1)x = r*np.cos(theta)y = r*np.sin(theta)ax.plot(x,y, color = 'b')"
},
{
"code": null,
"e": 11844,
"s": 11426,
"text": "The circle is our decision boundary and the region outside the circle corresponds to y=1 and inside the circle corresponds to y=0. We can see that the decision boundary doesn't necessarily have to be a straight line but also more complex shapes like a circle, ellipse, and any other irregular shapes. Again the decision boundary is a property of the hypothesis and its parameters and not that of the training dataset."
},
{
"code": null,
"e": 11899,
"s": 11844,
"text": "The cost of a logistic regression problem is given by:"
},
{
"code": null,
"e": 12000,
"s": 11899,
"text": "where, as discussed before h(x) is the prediction of the hypothesis and y is the actual class label."
},
{
"code": null,
"e": 12158,
"s": 12000,
"text": "Let’s plot this function to see how it corresponds to each case. We need to set the limits to h(x) as [0,1] as it lies in that range for logistic regression."
},
{
"code": null,
"e": 12165,
"s": 12158,
"text": "If y=1"
},
{
"code": null,
"e": 12172,
"s": 12165,
"text": "If y=1"
},
{
"code": null,
"e": 12347,
"s": 12172,
"text": "x = np.linspace(0,1, num = 100)fig = plt.figure(figsize = (10,10))sns.set(style = 'whitegrid')ax = sns.lineplot(x = x, y = -np.log(x))ax.set(xlabel = 'h(x)', ylabel = 'cost')"
},
{
"code": null,
"e": 12399,
"s": 12347,
"text": "The following inferences can be made from the plot:"
},
{
"code": null,
"e": 12535,
"s": 12399,
"text": "a. Cost becomes zero as h(x)=1 and y=1. This is obvious since the hypothesis predicts y as 1 which is true, then the cost will be zero."
},
{
"code": null,
"e": 12695,
"s": 12535,
"text": "b. As h(x) approaches zero the cost tends to infinity. This happens as this plot is specific to y=1 but, when h(x) predicts it as 0 the cost tends to infinity."
},
{
"code": null,
"e": 12705,
"s": 12695,
"text": "2. If y=0"
},
{
"code": null,
"e": 12748,
"s": 12705,
"text": "ax = sns.lineplot(x = x, y = -np.log(1-x))"
},
{
"code": null,
"e": 12799,
"s": 12748,
"text": "As discussed above, the following can be inferred:"
},
{
"code": null,
"e": 12839,
"s": 12799,
"text": "a. Cost becomes zero as h(x)=0 and y=0."
},
{
"code": null,
"e": 12897,
"s": 12839,
"text": "b. Cost tends to infinity as h(x) approaches 1 since y=0."
},
{
"code": null,
"e": 12951,
"s": 12897,
"text": "The cost function of logistic regression is given by:"
},
{
"code": null,
"e": 13039,
"s": 12951,
"text": "The point to note is that y=0 or 1 always in a classification problem having 2 classes."
},
{
"code": null,
"e": 13096,
"s": 13039,
"text": "The cost can be represented in a single line as follows:"
},
{
"code": null,
"e": 13200,
"s": 13096,
"text": "This is a more compact representation of the cost. Thereby the cost function can be written as follows:"
},
{
"code": null,
"e": 13323,
"s": 13200,
"text": "We need to find the parameters so that the value of cost function is minimized. This can be mathematically represented as:"
},
{
"code": null,
"e": 13361,
"s": 13323,
"text": "The differentiation term is given by:"
},
{
"code": null,
"e": 13407,
"s": 13361,
"text": "Plugging it in the gradient descent equation:"
},
{
"code": null,
"e": 13498,
"s": 13407,
"text": "Let’s use the above equations to execute Logistic Regression on the breast_cancer dataset."
},
{
"code": null,
"e": 14328,
"s": 13498,
"text": "x = df.area_meany = df.diagnosisx = preprocessing.scale(x)theta_0_gd = 0theta_1_gd = 0alpha = 0.01h_theta_0_gd = 1h_theta_1_gd = 1epoch = 0m = len(x)fig = plt.figure(figsize = (10,10))sns.set(style = 'whitegrid')ax = sns.scatterplot(x,y)while h_theta_0_gd != 0 or h_theta_0_gd != 0: if epoch > 5000: break h_theta_0_gd = 0 h_theta_1_gd = 0 for i in range(len(x)): h_theta_0_gd += ((1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))) - y[i]) h_theta_1_gd += (((1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))) - y[i]) * x[i]) h_theta_0_gd = (1/m) * h_theta_0_gd h_theta_1_gd = (1/m) * h_theta_1_gd theta_0_gd -= (alpha * h_theta_0_gd) theta_1_gd -= (alpha * h_theta_1_gd) epoch += 1ax = sns.lineplot(x,(1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x))))) , color = 'r', linewidth = 3)"
},
{
"code": null,
"e": 14368,
"s": 14328,
"text": "The values of theta_0 and theta_1 are :"
},
{
"code": null,
"e": 14444,
"s": 14368,
"text": "print(theta_0_gd, theta_1_gd)output>>-0.4173702618170074 3.0623106036104937"
},
{
"code": null,
"e": 14550,
"s": 14444,
"text": "We could also plot the value of cost function after each epoch to check the convergence of the algorithm:"
},
{
"code": null,
"e": 15694,
"s": 14550,
"text": "x = np.array(df.area_mean)y = np.array(df.diagnosis)x = preprocessing.scale(x)theta_0_gd = 0theta_1_gd = 0alpha = 0.01h_theta_0_gd = 1h_theta_1_gd = 1epoch = 0Epoch = []m = len(x)j = 0J = []fig = plt.figure(figsize = (20,10))ax1 = fig.add_subplot(1,2,1)ax2 = fig.add_subplot(1,2,2)style.use('ggplot')ax1.scatter(x,y)while h_theta_0_gd != 0 or h_theta_0_gd != 0: if epoch > 5000: break h_theta_0_gd = 0 h_theta_1_gd = 0 for i in range(len(x)): h_theta_0_gd += ((1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))) - y[i]) h_theta_1_gd += (((1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))) - y[i]) * x[i]) h_theta_0_gd = (1/m) * h_theta_0_gd h_theta_1_gd = (1/m) * h_theta_1_gd theta_0_gd -= (alpha * h_theta_0_gd) theta_1_gd -= (alpha * h_theta_1_gd) for i in range(m): j += ((y[i] * (np.log(1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i]))))))) - ((1-y[i]) * np.log(1-(1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x[i])))))))) J.append((-1/m) * j) epoch += 1 Epoch.append(epoch)ax1.scatter(x,(1/(1+np.exp(-(theta_0_gd + (theta_1_gd * x))))) , color = 'k')ax2.plot(Epoch,J)plt.show()"
},
{
"code": null,
"e": 16031,
"s": 15694,
"text": "We can see that the algorithm converged at around 500 epochs where the cost function reached a minimum value of -30, after which it started increasing till 5000 epochs. This happened as the learning rate ( which is 0.01) is very large so the algorithm after a certain point starts diverging. Consider lowering the learning rate further."
},
{
"code": null,
"e": 16453,
"s": 16031,
"text": "The above plot corresponds to a learning rate of 0.001. We can see that the algorithm converges at around 6000 epochs at a cost function value of -375, after which it starts increasing again. We can conclude from this that decreasing the learning rate helps in fine-tuning the parameters to obtain the more minimized value of cost function, but the algorithm takes a larger no of epochs i.e., takes more time to converge."
},
{
"code": null,
"e": 16568,
"s": 16453,
"text": "Let’s check if the parameter values obtained in our model are on par with the sklearn model of Logistic regression"
},
{
"code": null,
"e": 16823,
"s": 16568,
"text": "X = x.reshape(-1,1)x_train, x_test, y_train, y_test = model_selection.train_test_split(X, y, test_size = 0.33)clf = LogisticRegression(max_iter = 5000)clf.fit(x_train, y_train)clf.coef_output>> array([[3.5028]])clf.intercept_output>> array([-0.31180412])"
},
{
"code": null,
"e": 17011,
"s": 16823,
"text": "As we can see, the parameters are having close enough values when compared. We could even plot the regression line using the parameters obtained to check if we are getting a similar plot."
},
{
"code": null,
"e": 17195,
"s": 17011,
"text": "Theta_1 = clf.coef_Theta_0 = clf.intercept_fig = plt.figure(figsize = (10,10))ax = sns.scatterplot(X,y)ax = sns.lineplot(X, (1/(1+np.exp(-(Theta_0 + (Theta_1[0] * X))))), color = 'r')"
},
{
"code": null,
"e": 17630,
"s": 17195,
"text": "In this article, we have seen what is meant mathematically by a Classification problem, how linear regression is of little use in the case of a classification problem, Logistic regression and its hypothesis, cost, cost function, decision boundary, and gradient descent. We also built a Logistic regression model form scratch and trained it using the Breast cancer dataset. We also used the inbuilt model from sklearn for verification."
},
{
"code": null,
"e": 17764,
"s": 17630,
"text": "I am learning most of the concepts about Machine learning from this Youtube playlist. It is quite helpful and easy to understand too."
},
{
"code": null,
"e": 17898,
"s": 17764,
"text": "I am learning most of the concepts about Machine learning from this Youtube playlist. It is quite helpful and easy to understand too."
},
{
"code": null,
"e": 17915,
"s": 17898,
"text": "scikit-learn.org"
}
] |
Maximum path sum in matrix | Practice | GeeksforGeeks
|
Given a NxN matrix of positive integers. There are only three possible moves from a cell Matrix[r][c].
Matrix [r+1] [c]
Matrix [r+1] [c-1]
Matrix [r+1] [c+1]
Matrix [r+1] [c]
Matrix [r+1] [c-1]
Matrix [r+1] [c+1]
Starting from any column in row 0 return the largest sum of any of the paths up to row N-1.
Example 1:
Input: N = 2
Matrix = {{348, 391},
{618, 193}}
Output: 1009
Explaination: The best path is 391 -> 618.
It gives the sum = 1009.
Example 2:
Input: N = 2
Matrix = {{2, 2},
{2, 2}}
Output: 4
Explaination: No matter which path is
chosen, the output is 4.
Your Task:
You do not need to read input or print anything. Your task is to complete the function maximumPath() which takes the size N and the Matrix as input parameters and returns the highest maximum path sum.
Expected Time Complexity: O(N*N)
Expected Auxiliary Space: O(N*N)
Constraints:
1 ≤ N ≤ 500
1 ≤ Matrix[i][j] ≤ 1000
0
patildhiren444 days ago
JAVA - 0.88
Memoization
class Solution{
static int memo(int i, int j, int[][]mat, int[][]dp){
if(j<0 || j>mat[0].length-1){
return 0;
}
if(i==mat.length-1){
return mat[i][j];
}
if(dp[i][j]!=-1){
return dp[i][j];
}
int a = mat[i][j]+ memo(i+1,j-1,mat,dp);
int b = mat[i][j]+ memo(i+1,j,mat,dp);
int c = mat[i][j]+ memo(i+1,j+1,mat,dp);
dp[i][j] =Math.max(a, Math.max(b, c));;
return Math.max(a, Math.max(b, c));
}
static int maximumPath(int n, int Matrix[][])
{
// code here
int[][]dp = new int[n][n];
for(int []row: dp){
Arrays.fill(row, -1);
}
int maxi=0;
for(int i=0; i<n; i++){
maxi = Math.max(maxi,memo(0, i, Matrix, dp));
}
return maxi;
}
}
0
vinaykush4 days ago
class Solution{
public:
int findAns(int N,vector<vector<int>>& Matrix,int r,int c,vector<vector<int>>& dp){
if(r>=N||c>=N||r<0||c<0)
{
return 0;
}
return Matrix[r][c]+max(max(dp[r+1][c]==0?dp[r+1][c]=findAns(N,Matrix,r+1,c,dp):dp[r+1][c],dp[r+1][c-1]==0?dp[r+1][c-1]=findAns(N,Matrix,r+1,c-1,dp):dp[r+1][c-1]),dp[r+1][c+1]==0?dp[r+1][c+1]=findAns(N,Matrix,r+1,c+1,dp):dp[r+1][c+1]);
}
int maximumPath(int N, vector<vector<int>> Matrix)
{
// code here
int ans=0;
vector<vector<int>> dp(N+1,vector<int>(N+1,0));
for(int i=0;i<N;i++){
ans=max(ans,findAns(N,Matrix,0,i,dp));
}
return ans;
}
};
0
milindprajapatmst192 weeks ago
class Solution{
public:
int maximumPath(int n, vector<vector<int>>& arr) {
int result = arr[0][0];
for (int i = 1; i < n; i++) {
for (int j = 0; j < n; j++) {
int x = (j == 0) ? 0 : arr[i - 1][j - 1];
int y = arr[i - 1][j];
int z = (j == n - 1) ? 0 : arr[i - 1][j + 1];
arr[i][j] += max({ x, y, z });
if (i == n - 1)
result = max(result, arr[i][j]);
}
}
return result;
}
};
0
jainmuskan5652 weeks ago
int solve(int i,int j, vector<vector<int>>& mat, vector<vector<int>>&dp){ int r= mat.size(), col= mat[0].size(); if(j<0 || j>col-1){ return 0; } if(i==r-1){ return mat[i][j]; } if(dp[i][j]!= -1){ return dp[i][j]; } int a= mat[i][j]+ solve(i+1,j-1,mat,dp); int b= mat[i][j]+ solve(i+1,j,mat,dp); int c= mat[i][j]+ solve(i+1,j+1,mat,dp); return dp[i][j]=max({a,b,c}); } int maximumPath(int N, vector<vector<int>> Matrix) { vector<vector<int>> dp(N+1,vector<int>(N+1,-1)); int ans= 0; for(int i=0;i<N;i++){ // check all the columns path then take max sum ans=max(ans,solve(0,i,Matrix,dp)); } return ans; }
0
bokonist2 weeks ago
C++ 0.24s solution with comments, O(n*n) time and space
int maximumPath(int n, vector<vector<int>> m)
{
// code here
int memo[n][n];
for(int i=0;i<n;i++)
fill(memo[i],memo[i]+n,0);
for(int i=0;i<n;i++)
{
memo[n-1][i] = m[n-1][i]; // the bottom row will be the same as maxsum path bc it has nowhere to move below
}
int down, downLeft, downRight;
for(int i=n-2;i>=0;i--) //populate the table from bottom up
{
for(int j=0;j<n;j++)
{
//check outofbounds and pick the max among the 3 options
if(j-1 < 0)
downLeft=0;
else
downLeft = memo[i+1][j-1];
if(j+1 > n-1)
downRight=0;
else
downRight= memo[i+1][j+1];
down = memo[i+1][j];
memo[i][j]= m[i][j] + max({down,downLeft,downRight});
}
}
int mx = INT_MIN;
for(int i=0;i<n;i++)
mx=max(mx,memo[0][i]);
return mx;
}
+1
gulashanshashishekhar293 weeks ago
int n = Matrix.size(), maxSum = Matrix[0][0];
for (int i = 1; i < n; i++) {
for (int j = 0; j < n; j++) {
int m = Matrix[i-1][j];
if (isValid(j-1, n)) m = max(m, Matrix[i-1][j-1]);
if (isValid(j+1, n)) m = max(m, Matrix[i-1][j+1]);
Matrix[i][j] += m;
maxSum = max(maxSum, Matrix[i][j]);
}
}
return maxSum;
0
2018eeb11381 month ago
int maximumPath(int n, vector<vector<int>> Matrix)
{
// code here
int i,j;
int dp[n+1][n+1];
for(i= 0 ; i<=n;i++)
for(j=0;j<=n;j++)
dp[i][j] = 0;
for(i= n-1 ; i>=0;i--)
{
for(j=n-1;j>=0;j--)
{
dp[i][j] = Matrix[i][j] + max({dp[i+1][j], dp[i+1][j-1], dp[i+1][j+1]});
}
}
int sol = -1;
for(i= 0 ; i<=n;i++)
{
sol = max(sol, dp[0][i]);
/*for(j=0;j<=n;j++)
{
cout << dp[i][j] << " ";
}*/
//cout << endl;
}
return sol;
}
0
khushiaggarwal09021 month ago
//Easiest Solution
//According to Aditya Verma approch
int maximumPath(int n, vector<vector<int>> mat) { int dp[n+1][n+1]; int ans=INT_MIN; for(int i=0;i<=n;i++) { for(int j=0;j<=n;j++) { if(i==0 || j==0) { dp[i][j]=0; } } } for(int i=1;i<n+1;i++) for(int j=1;j<n+1;j++) { int op1= mat[i-1][j-1]+ dp[i-1][j]; int op2= mat[i-1][j-1]+dp[i-1][j-1]; int op3= mat[i-1][j-1] + dp[i-1][j+1]; dp[i][j]=max({op1,op2,op3}); } for(int i=1;i<n+1;i++) for(int j=1;j<n+1;j++) { if(dp[i][j]>ans) { ans=dp[i][j]; } } return ans; }
0
guptatushar110411 month ago
C++ solution using memoization approach having time complexity as O(N*N) and space complexity as O(N*N) is as follows :-
Execution Time :- 0.3 / 3.4 sec
int dp[1001][1001]; int solve(int i,int j,vector<vector<int>>& matrix) { if(j<0 or j>=matrix[0].size()) { return 0; } if(i==0) return matrix[0][j]; if(dp[i][j]!=-1) return dp[i][j]; int up=matrix[i][j]+solve(i-1,j,matrix); int ld=matrix[i][j]+solve(i-1,j-1,matrix); int rd=matrix[i][j]+solve(i-1,j+1,matrix); return dp[i][j]=max(up,max(ld,rd));
} int maximumPath(int N, vector<vector<int>>&matrix) { memset(dp,-1,sizeof(dp)); // int m=matrix.size(),n=matrix[0].size(); int mini=INT_MIN; for(int i=0;i<N;i++) { mini=max(mini,solve(N-1,i,matrix)); } return mini; }
0
hamidnourashraf1 month ago
recursive and too slow:
import math
class Solution:
def rec_path(self, i, j, N, Matrix):
if i < 0 or i > N-1:
return -math.inf
if j < 0 or j > N-1:
return -math.inf
if i == N-1:
return Matrix[i][j]
case1 = self.rec_path(i+1, j, N, Matrix)
case2 = self.rec_path(i+1, j-1, N, Matrix)
case3 = self.rec_path(i+1, j+1, N, Matrix)
return Matrix[i][j] + max(case1, case2, case3)
def maximumPath(self, N, Matrix):
_max = -math.inf
for j in range(N):
_max = max(_max, self.rec_path(0, j, N, Matrix))
return _max
recursive with memorization
import math
class Solution:
def rec_path(self, i, j, N, Matrix, mem):
if i < 0 or i > N-1:
return -math.inf
if j < 0 or j > N-1:
return -math.inf
if i == N-1:
return Matrix[i][j]
if mem[i][j] != -1:
return mem[i][j]
case1 = self.rec_path(i+1, j, N, Matrix, mem)
case2 = self.rec_path(i+1, j-1, N, Matrix, mem)
case3 = self.rec_path(i+1, j+1, N, Matrix, mem)
mem[i][j] = Matrix[i][j] + max(case1, case2, case3)
return mem[i][j]
def maximumPath(self, N, Matrix):
mem = [[-1]*(N) for j in range(N)]
_max = -math.inf
for j in range(N):
_max = max(_max, self.rec_path(0, j, N, Matrix, mem))
return _max
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 341,
"s": 238,
"text": "Given a NxN matrix of positive integers. There are only three possible moves from a cell Matrix[r][c]."
},
{
"code": null,
"e": 398,
"s": 341,
"text": "\nMatrix [r+1] [c]\nMatrix [r+1] [c-1]\nMatrix [r+1] [c+1]\n"
},
{
"code": null,
"e": 415,
"s": 398,
"text": "Matrix [r+1] [c]"
},
{
"code": null,
"e": 434,
"s": 415,
"text": "Matrix [r+1] [c-1]"
},
{
"code": null,
"e": 453,
"s": 434,
"text": "Matrix [r+1] [c+1]"
},
{
"code": null,
"e": 557,
"s": 453,
"text": "Starting from any column in row 0 return the largest sum of any of the paths up to row N-1.\n\nExample 1:"
},
{
"code": null,
"e": 696,
"s": 557,
"text": "Input: N = 2\nMatrix = {{348, 391},\n {618, 193}}\nOutput: 1009\nExplaination: The best path is 391 -> 618. \nIt gives the sum = 1009."
},
{
"code": null,
"e": 708,
"s": 696,
"text": "\nExample 2:"
},
{
"code": null,
"e": 831,
"s": 708,
"text": "Input: N = 2\nMatrix = {{2, 2},\n {2, 2}}\nOutput: 4\nExplaination: No matter which path is \nchosen, the output is 4."
},
{
"code": null,
"e": 1044,
"s": 831,
"text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function maximumPath() which takes the size N and the Matrix as input parameters and returns the highest maximum path sum."
},
{
"code": null,
"e": 1111,
"s": 1044,
"text": "\nExpected Time Complexity: O(N*N)\nExpected Auxiliary Space: O(N*N)"
},
{
"code": null,
"e": 1161,
"s": 1111,
"text": "\nConstraints:\n1 ≤ N ≤ 500\n1 ≤ Matrix[i][j] ≤ 1000"
},
{
"code": null,
"e": 1163,
"s": 1161,
"text": "0"
},
{
"code": null,
"e": 1187,
"s": 1163,
"text": "patildhiren444 days ago"
},
{
"code": null,
"e": 1199,
"s": 1187,
"text": "JAVA - 0.88"
},
{
"code": null,
"e": 1211,
"s": 1199,
"text": "Memoization"
},
{
"code": null,
"e": 2138,
"s": 1211,
"text": "class Solution{\n \n static int memo(int i, int j, int[][]mat, int[][]dp){\n if(j<0 || j>mat[0].length-1){\n return 0;\n }\n \n if(i==mat.length-1){\n return mat[i][j];\n }\n \n if(dp[i][j]!=-1){\n return dp[i][j];\n }\n \n int a = mat[i][j]+ memo(i+1,j-1,mat,dp);\n int b = mat[i][j]+ memo(i+1,j,mat,dp);\n int c = mat[i][j]+ memo(i+1,j+1,mat,dp);\n \n dp[i][j] =Math.max(a, Math.max(b, c));;\n \n return Math.max(a, Math.max(b, c));\n }\n \n static int maximumPath(int n, int Matrix[][])\n {\n // code here\n int[][]dp = new int[n][n];\n \n for(int []row: dp){\n Arrays.fill(row, -1);\n }\n int maxi=0;\n for(int i=0; i<n; i++){\n maxi = Math.max(maxi,memo(0, i, Matrix, dp));\n }\n \n return maxi;\n }\n}"
},
{
"code": null,
"e": 2140,
"s": 2138,
"text": "0"
},
{
"code": null,
"e": 2160,
"s": 2140,
"text": "vinaykush4 days ago"
},
{
"code": null,
"e": 2883,
"s": 2160,
"text": "class Solution{\npublic:\n int findAns(int N,vector<vector<int>>& Matrix,int r,int c,vector<vector<int>>& dp){\n if(r>=N||c>=N||r<0||c<0)\n {\n return 0;\n }\n return Matrix[r][c]+max(max(dp[r+1][c]==0?dp[r+1][c]=findAns(N,Matrix,r+1,c,dp):dp[r+1][c],dp[r+1][c-1]==0?dp[r+1][c-1]=findAns(N,Matrix,r+1,c-1,dp):dp[r+1][c-1]),dp[r+1][c+1]==0?dp[r+1][c+1]=findAns(N,Matrix,r+1,c+1,dp):dp[r+1][c+1]);\n }\n int maximumPath(int N, vector<vector<int>> Matrix)\n {\n // code here\n int ans=0;\n vector<vector<int>> dp(N+1,vector<int>(N+1,0));\n for(int i=0;i<N;i++){\n ans=max(ans,findAns(N,Matrix,0,i,dp));\n }\n return ans;\n \n }\n};"
},
{
"code": null,
"e": 2885,
"s": 2883,
"text": "0"
},
{
"code": null,
"e": 2916,
"s": 2885,
"text": "milindprajapatmst192 weeks ago"
},
{
"code": null,
"e": 3454,
"s": 2916,
"text": "class Solution{\npublic:\n int maximumPath(int n, vector<vector<int>>& arr) {\n int result = arr[0][0];\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < n; j++) {\n int x = (j == 0) ? 0 : arr[i - 1][j - 1];\n int y = arr[i - 1][j];\n int z = (j == n - 1) ? 0 : arr[i - 1][j + 1];\n arr[i][j] += max({ x, y, z });\n if (i == n - 1)\n result = max(result, arr[i][j]);\n }\n }\n return result;\n }\n};"
},
{
"code": null,
"e": 3456,
"s": 3454,
"text": "0"
},
{
"code": null,
"e": 3481,
"s": 3456,
"text": "jainmuskan5652 weeks ago"
},
{
"code": null,
"e": 4238,
"s": 3481,
"text": "int solve(int i,int j, vector<vector<int>>& mat, vector<vector<int>>&dp){ int r= mat.size(), col= mat[0].size(); if(j<0 || j>col-1){ return 0; } if(i==r-1){ return mat[i][j]; } if(dp[i][j]!= -1){ return dp[i][j]; } int a= mat[i][j]+ solve(i+1,j-1,mat,dp); int b= mat[i][j]+ solve(i+1,j,mat,dp); int c= mat[i][j]+ solve(i+1,j+1,mat,dp); return dp[i][j]=max({a,b,c}); } int maximumPath(int N, vector<vector<int>> Matrix) { vector<vector<int>> dp(N+1,vector<int>(N+1,-1)); int ans= 0; for(int i=0;i<N;i++){ // check all the columns path then take max sum ans=max(ans,solve(0,i,Matrix,dp)); } return ans; }"
},
{
"code": null,
"e": 4240,
"s": 4238,
"text": "0"
},
{
"code": null,
"e": 4260,
"s": 4240,
"text": "bokonist2 weeks ago"
},
{
"code": null,
"e": 4316,
"s": 4260,
"text": "C++ 0.24s solution with comments, O(n*n) time and space"
},
{
"code": null,
"e": 5445,
"s": 4318,
"text": "int maximumPath(int n, vector<vector<int>> m)\n {\n // code here\n int memo[n][n];\n for(int i=0;i<n;i++)\n fill(memo[i],memo[i]+n,0);\n for(int i=0;i<n;i++)\n {\n memo[n-1][i] = m[n-1][i]; // the bottom row will be the same as maxsum path bc it has nowhere to move below\n }\n int down, downLeft, downRight;\n for(int i=n-2;i>=0;i--) //populate the table from bottom up\n {\n for(int j=0;j<n;j++)\n {\n //check outofbounds and pick the max among the 3 options\n if(j-1 < 0)\n downLeft=0;\n else\n downLeft = memo[i+1][j-1];\n \n if(j+1 > n-1)\n downRight=0;\n else\n downRight= memo[i+1][j+1];\n \n down = memo[i+1][j];\n \n memo[i][j]= m[i][j] + max({down,downLeft,downRight});\n }\n }\n int mx = INT_MIN;\n for(int i=0;i<n;i++)\n mx=max(mx,memo[0][i]);\n return mx;\n }"
},
{
"code": null,
"e": 5448,
"s": 5445,
"text": "+1"
},
{
"code": null,
"e": 5483,
"s": 5448,
"text": "gulashanshashishekhar293 weeks ago"
},
{
"code": null,
"e": 5837,
"s": 5483,
"text": "int n = Matrix.size(), maxSum = Matrix[0][0];\nfor (int i = 1; i < n; i++) {\n for (int j = 0; j < n; j++) {\n int m = Matrix[i-1][j];\n if (isValid(j-1, n)) m = max(m, Matrix[i-1][j-1]);\n if (isValid(j+1, n)) m = max(m, Matrix[i-1][j+1]);\n Matrix[i][j] += m;\n maxSum = max(maxSum, Matrix[i][j]);\n }\n}\nreturn maxSum;"
},
{
"code": null,
"e": 5839,
"s": 5837,
"text": "0"
},
{
"code": null,
"e": 5862,
"s": 5839,
"text": "2018eeb11381 month ago"
},
{
"code": null,
"e": 6556,
"s": 5862,
"text": "int maximumPath(int n, vector<vector<int>> Matrix)\n {\n // code here\n int i,j;\n int dp[n+1][n+1];\n for(i= 0 ; i<=n;i++)\n for(j=0;j<=n;j++)\n dp[i][j] = 0;\n \n for(i= n-1 ; i>=0;i--)\n {\n for(j=n-1;j>=0;j--)\n {\n dp[i][j] = Matrix[i][j] + max({dp[i+1][j], dp[i+1][j-1], dp[i+1][j+1]});\n }\n }\n int sol = -1;\n for(i= 0 ; i<=n;i++)\n {\n sol = max(sol, dp[0][i]);\n /*for(j=0;j<=n;j++)\n {\n cout << dp[i][j] << \" \";\n }*/\n //cout << endl;\n }\n \n return sol;\n }"
},
{
"code": null,
"e": 6558,
"s": 6556,
"text": "0"
},
{
"code": null,
"e": 6588,
"s": 6558,
"text": "khushiaggarwal09021 month ago"
},
{
"code": null,
"e": 6607,
"s": 6588,
"text": "//Easiest Solution"
},
{
"code": null,
"e": 6643,
"s": 6607,
"text": "//According to Aditya Verma approch"
},
{
"code": null,
"e": 7446,
"s": 6645,
"text": "int maximumPath(int n, vector<vector<int>> mat) { int dp[n+1][n+1]; int ans=INT_MIN; for(int i=0;i<=n;i++) { for(int j=0;j<=n;j++) { if(i==0 || j==0) { dp[i][j]=0; } } } for(int i=1;i<n+1;i++) for(int j=1;j<n+1;j++) { int op1= mat[i-1][j-1]+ dp[i-1][j]; int op2= mat[i-1][j-1]+dp[i-1][j-1]; int op3= mat[i-1][j-1] + dp[i-1][j+1]; dp[i][j]=max({op1,op2,op3}); } for(int i=1;i<n+1;i++) for(int j=1;j<n+1;j++) { if(dp[i][j]>ans) { ans=dp[i][j]; } } return ans; }"
},
{
"code": null,
"e": 7448,
"s": 7446,
"text": "0"
},
{
"code": null,
"e": 7476,
"s": 7448,
"text": "guptatushar110411 month ago"
},
{
"code": null,
"e": 7597,
"s": 7476,
"text": "C++ solution using memoization approach having time complexity as O(N*N) and space complexity as O(N*N) is as follows :-"
},
{
"code": null,
"e": 7631,
"s": 7599,
"text": "Execution Time :- 0.3 / 3.4 sec"
},
{
"code": null,
"e": 8083,
"s": 7633,
"text": "int dp[1001][1001]; int solve(int i,int j,vector<vector<int>>& matrix) { if(j<0 or j>=matrix[0].size()) { return 0; } if(i==0) return matrix[0][j]; if(dp[i][j]!=-1) return dp[i][j]; int up=matrix[i][j]+solve(i-1,j,matrix); int ld=matrix[i][j]+solve(i-1,j-1,matrix); int rd=matrix[i][j]+solve(i-1,j+1,matrix); return dp[i][j]=max(up,max(ld,rd));"
},
{
"code": null,
"e": 8372,
"s": 8083,
"text": " } int maximumPath(int N, vector<vector<int>>&matrix) { memset(dp,-1,sizeof(dp)); // int m=matrix.size(),n=matrix[0].size(); int mini=INT_MIN; for(int i=0;i<N;i++) { mini=max(mini,solve(N-1,i,matrix)); } return mini; }"
},
{
"code": null,
"e": 8374,
"s": 8372,
"text": "0"
},
{
"code": null,
"e": 8401,
"s": 8374,
"text": "hamidnourashraf1 month ago"
},
{
"code": null,
"e": 8425,
"s": 8401,
"text": "recursive and too slow:"
},
{
"code": null,
"e": 9049,
"s": 8425,
"text": "import math\nclass Solution:\n def rec_path(self, i, j, N, Matrix):\n if i < 0 or i > N-1:\n return -math.inf\n if j < 0 or j > N-1:\n return -math.inf\n if i == N-1:\n return Matrix[i][j]\n case1 = self.rec_path(i+1, j, N, Matrix)\n case2 = self.rec_path(i+1, j-1, N, Matrix)\n case3 = self.rec_path(i+1, j+1, N, Matrix)\n return Matrix[i][j] + max(case1, case2, case3)\n \n def maximumPath(self, N, Matrix):\n _max = -math.inf\n for j in range(N):\n _max = max(_max, self.rec_path(0, j, N, Matrix))\n return _max"
},
{
"code": null,
"e": 9077,
"s": 9049,
"text": "recursive with memorization"
},
{
"code": null,
"e": 9852,
"s": 9077,
"text": "import math\nclass Solution:\n def rec_path(self, i, j, N, Matrix, mem):\n if i < 0 or i > N-1:\n return -math.inf\n if j < 0 or j > N-1:\n return -math.inf\n if i == N-1:\n return Matrix[i][j]\n if mem[i][j] != -1:\n return mem[i][j]\n case1 = self.rec_path(i+1, j, N, Matrix, mem)\n case2 = self.rec_path(i+1, j-1, N, Matrix, mem)\n case3 = self.rec_path(i+1, j+1, N, Matrix, mem)\n mem[i][j] = Matrix[i][j] + max(case1, case2, case3)\n return mem[i][j]\n \n def maximumPath(self, N, Matrix):\n mem = [[-1]*(N) for j in range(N)]\n _max = -math.inf\n for j in range(N):\n _max = max(_max, self.rec_path(0, j, N, Matrix, mem))\n return _max"
},
{
"code": null,
"e": 9998,
"s": 9852,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 10034,
"s": 9998,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 10044,
"s": 10034,
"text": "\nProblem\n"
},
{
"code": null,
"e": 10054,
"s": 10044,
"text": "\nContest\n"
},
{
"code": null,
"e": 10117,
"s": 10054,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 10265,
"s": 10117,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 10473,
"s": 10265,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 10579,
"s": 10473,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.