title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
The essence of eigenvalues and eigenvectors in Machine Learning | by Ranjeet Singh | Towards Data Science | The word, Eigen is perhaps most usefully translated from German which means Characteristic. So when we talk about Eigenvalues and eigenvectors of a Matrix, we’re talking about finding the characteristics of the matrix.
Before diving deep into Eigenvectors, let's understand what is a matrix except being a rectangular array of numbers, What does it represent?
So a matrix is simply a linear transformation applied to a vector. There can be different types of transformation applied to a vector, for example-
Let's see some matrix transformations
img = cv2.imread(path_to_image,flags=cv2.IMREAD_UNCHANGED)img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)rows,cols,_ = img.shapeM = np.float32([[1, -np.sin(.1), 0],[0, np.cos(.1), 0]])out = cv2.warpAffine(img,M,(cols,rows))
What does this matrix M do with the image? It introduced a horizontal shear to every vector in the image.
#Let's try this oneM = cv2.getRotationMatrix2D((cols/2,rows/2),45,1)out = cv2.warpAffine(img,M,(cols,rows))print(M)=> [[ 0.70710678 0.70710678 -124.36235483] [ -0.70710678 0.70710678 501.76271632]]
So what has the matrix M has done to the images? So this linear transformation M rotates every vector in the image by 45 degrees.
M = [[ 1. 0. 100.] [ 0. 1. 100.]]out = cv2.warpAffine(img,M,(cols,rows))
It translates the image in both horizontal and vertical directions.
The rotation has no eigenevector[except the case of 180-degree rotation]. For pure shear, the horizontal vector is an eigenvector. The factor by which the length of vector changes is called eigenvalue.
The concept of eigenvalues and eigenvectors is used in many practical applications. I will discuss only a few of these.
PCA is a very popular classical dimensionality reduction technique which uses this concept to compress your data by reducing its dimensionality since curse of dimensionality has been very critical issue in classical Computer Vision to deal with images and even in Machine Learning, features with high dimensionality increase model capacity which in turn requires a large amount of data to train.
It is a method that uses simple matrix operations and statistics to calculate a projection of the original data into the same number or fewer dimensions.
Let the data matrix X be of n×p size, where n is the number of samples and p is the dimensionality of each sample. In PCA, essentially we diagonalize the covariance matrix of X by eigenvalue decomposition since the covariance matrix is symmetric-
C = VLVTIn Python-from numpy import covfrom numpy.linalg import eigX = array([[-2, -2], [0, 0], [2, 2]])C = cov(X)#To do eigendecomposition of Cvalues, vectors = eig(C)#Project data into pricipal directionsP = vectors.T.dot(X.T)print(P.T)Output-[[-2.82842712 0. ] [ 0. 0. ] [ 2.82842712 0. ]]
where V is a matrix of eigenvectors (each column is an eigenvector) and L is a diagonal matrix with eigenvalues λi in the decreasing order on the diagonal.
Eigenvectors of a symmetric matrix, covariance matrix here, are real and orthogonal.
The eigenvectors are called principal axes or principal directions of the data. Projections of the data on the principal axes are called principal components.
We reduce the dimensionality of data by projecting it in fewer principal directions than its original dimensionality.
K-Means is the most popular algorithm for clustering but it has several issues associated with it such as dependence upon cluster initialization and dimensionality of features. Also, it faces problems if your clusters are not spherical as seen below-
from sklearn.datasets import make_moonsX_mn, y_mn = make_moons(150, noise=.07, random_state=21)fig, ax = plt.subplots(figsize=(9,7))ax.set_title('Data with ground truth labels ', fontsize=18, fontweight='demi')ax.scatter(X_mn[:, 0], X_mn[:, 1],c=y_mn,s=50, cmap='viridis')
Spectral clustering is a family of methods to find K clusters using the eigenvectors of a matrix. It handles these issues and easily outperforms other algorithms for clustering.
Here data is represented in the form of a graph. Now clustering can be thought of making graph cuts where Cut(A,B) between 2 clusters A and B is defined as the sum of weight connections between two clusters. For example-
To find optimum clusters, we need MinCut and the objective of a MinCut method is to find two clusters A and B which have the minimum weight sum connections.
In spectral clustering, this min-cut objective is approximated using the Graph Laplacian matrix computed from the Adjacency and degree matrix of the graph. For proof, see this
Given: A graph with n vertices and edge weights Wij , number of desired clusters k
Construct (normalized) graph Laplacian L G V, E = D − W
Find the k eigenvectors corresponding to the k smallest eigenvalues of L
Let U be the n × k matrix of eigenvectors
Use k-means to find k clusters C′ letting xi ′ be the rows of U 5. Assign data point xi to the j’th cluster if xi ′ was assigned to cluster j
from sklearn.neighbors import radius_neighbors_graphfrom scipy.sparse import csgraphfrom sklearn.cluster import KMeans#Create adjacency matrix from the datasetA = radius_neighbors_graph(X_mn,0.4,mode='distance', metric='minkowski', p=2, metric_params=None, include_self=False)A = A.toarray()'''Next find out graph Laplacian matrix, which is defined as the L=D-A where A is our adjecency matrix we just saw and D is a diagonal degree matrix, every cell in the diagonal is the sum of the weights for that point'''L = csgraph.laplacian(A, normed=False)eigval, eigvec = np.linalg.eig(L)
Now, use k-means to find k clusters C letting xi be the rows of eigvec. Finally to assign data points into clusters, assign xi to the j’th cluster if xi was assigned to cluster j.
The second smallest eigenvector , also called Fiedler vector is used to recursively bi-partition the graph by finding the optimal splitting point.
See full example code here
Variants of spectral clustering are used in Region Proposal based Object Detection and Semantic Segmentation in Computer Vision.
At last, I will discuss my favorite field under AI, which is Computer Vision. In Computer Vision, Interest points in an image are the points which are unique in their neighborhood. Such points play a significant role in classical Computer Vision where these are used as features.
Corners are useful interest points along with other more complex image features such as SIFT, SURF, and HOG, etc. I would discuss one such method of corner detection.
Corners are easily recognized by looking through a small window.
Shifting the window should give a large change in intensity E if the window has a corner inside it.
The algorithm-
Compute image gradients over a small region
imggray = cv2.imread('checkerboard.png',0)i_x = cv2.Sobel(imggray,cv2.CV_64F,1,0,ksize=5)i_y = cv2.Sobel(imggray,cv2.CV_64F,0,1,ksize=5)
Compute the covariance matrix
# Calculate the product of derivates in each directioni_xx, i_xy, i_yy = multiply(i_x, i_x), multiply(i_x, i_y), multiply(i_y, i_y)# Calculate the sum of product of derivatess_xx, s_xy, s_yy = cv2.GaussianBlur(i_xx, (5,5), 0), cv2.GaussianBlur(i_xy, (5,5), 0), cv2.GaussianBlur(i_yy, (5,5), 0)
Compute eigenvectors and eigenvalues.
Harris described a way for a faster approximation — Avoid computing the eigenvalues, just compute Trace and Determinant. Combing these 2 properties, we calculate a measure of cornerness-R
Determinant of a matrix = Product of eigen values
Trace of a matrix = Sum of eigen values
# Compute the response of the detector at each pointk = .04 # Recommended value between .04 and .06det_h = multiply(s_xx, s_yy) - multiply(s_xy, s_xy)trace_h = s_xx + s_yyR = det_h - k*multiply(trace_h, trace_h)
Use threshold on eigenvalues to detect corners
ratio = .2 # Number to tweakthresh = abs(R) > ratio * abs(R).max()
If either eigenvalue is close to 0, then this is not a corner, so look for locations where both are large. E is almost constant in all directions.
λ2 >> λ1 or λ1 >> λ2 depicts an Edge
λ1 and λ2 are large, λ1 ~ λ2 E increases in all directions
See full example code here
Normalized Cuts and Image Segmentation. J. Shi and J. Malik, 2000
A Combined Combined and Edge Detector, Chris Harris & Mike Stephens, 1988
Algebraic Connectivity of Graph M. Fiedler, 1973 | [
{
"code": null,
"e": 391,
"s": 172,
"text": "The word, Eigen is perhaps most usefully translated from German which means Characteristic. So when we talk about Eigenvalues and eigenvectors of a Matrix, we’re talking about finding the characteristics of the matrix."
},
{
"code": null,
"e": 532,
"s": 391,
"text": "Before diving deep into Eigenvectors, let's understand what is a matrix except being a rectangular array of numbers, What does it represent?"
},
{
"code": null,
"e": 680,
"s": 532,
"text": "So a matrix is simply a linear transformation applied to a vector. There can be different types of transformation applied to a vector, for example-"
},
{
"code": null,
"e": 718,
"s": 680,
"text": "Let's see some matrix transformations"
},
{
"code": null,
"e": 937,
"s": 718,
"text": "img = cv2.imread(path_to_image,flags=cv2.IMREAD_UNCHANGED)img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)rows,cols,_ = img.shapeM = np.float32([[1, -np.sin(.1), 0],[0, np.cos(.1), 0]])out = cv2.warpAffine(img,M,(cols,rows))"
},
{
"code": null,
"e": 1043,
"s": 937,
"text": "What does this matrix M do with the image? It introduced a horizontal shear to every vector in the image."
},
{
"code": null,
"e": 1251,
"s": 1043,
"text": "#Let's try this oneM = cv2.getRotationMatrix2D((cols/2,rows/2),45,1)out = cv2.warpAffine(img,M,(cols,rows))print(M)=> [[ 0.70710678 0.70710678 -124.36235483] [ -0.70710678 0.70710678 501.76271632]]"
},
{
"code": null,
"e": 1381,
"s": 1251,
"text": "So what has the matrix M has done to the images? So this linear transformation M rotates every vector in the image by 45 degrees."
},
{
"code": null,
"e": 1460,
"s": 1381,
"text": "M = [[ 1. 0. 100.] [ 0. 1. 100.]]out = cv2.warpAffine(img,M,(cols,rows))"
},
{
"code": null,
"e": 1528,
"s": 1460,
"text": "It translates the image in both horizontal and vertical directions."
},
{
"code": null,
"e": 1730,
"s": 1528,
"text": "The rotation has no eigenevector[except the case of 180-degree rotation]. For pure shear, the horizontal vector is an eigenvector. The factor by which the length of vector changes is called eigenvalue."
},
{
"code": null,
"e": 1850,
"s": 1730,
"text": "The concept of eigenvalues and eigenvectors is used in many practical applications. I will discuss only a few of these."
},
{
"code": null,
"e": 2246,
"s": 1850,
"text": "PCA is a very popular classical dimensionality reduction technique which uses this concept to compress your data by reducing its dimensionality since curse of dimensionality has been very critical issue in classical Computer Vision to deal with images and even in Machine Learning, features with high dimensionality increase model capacity which in turn requires a large amount of data to train."
},
{
"code": null,
"e": 2400,
"s": 2246,
"text": "It is a method that uses simple matrix operations and statistics to calculate a projection of the original data into the same number or fewer dimensions."
},
{
"code": null,
"e": 2647,
"s": 2400,
"text": "Let the data matrix X be of n×p size, where n is the number of samples and p is the dimensionality of each sample. In PCA, essentially we diagonalize the covariance matrix of X by eigenvalue decomposition since the covariance matrix is symmetric-"
},
{
"code": null,
"e": 2972,
"s": 2647,
"text": "C = VLVTIn Python-from numpy import covfrom numpy.linalg import eigX = array([[-2, -2], [0, 0], [2, 2]])C = cov(X)#To do eigendecomposition of Cvalues, vectors = eig(C)#Project data into pricipal directionsP = vectors.T.dot(X.T)print(P.T)Output-[[-2.82842712 0. ] [ 0. 0. ] [ 2.82842712 0. ]]"
},
{
"code": null,
"e": 3128,
"s": 2972,
"text": "where V is a matrix of eigenvectors (each column is an eigenvector) and L is a diagonal matrix with eigenvalues λi in the decreasing order on the diagonal."
},
{
"code": null,
"e": 3213,
"s": 3128,
"text": "Eigenvectors of a symmetric matrix, covariance matrix here, are real and orthogonal."
},
{
"code": null,
"e": 3372,
"s": 3213,
"text": "The eigenvectors are called principal axes or principal directions of the data. Projections of the data on the principal axes are called principal components."
},
{
"code": null,
"e": 3490,
"s": 3372,
"text": "We reduce the dimensionality of data by projecting it in fewer principal directions than its original dimensionality."
},
{
"code": null,
"e": 3741,
"s": 3490,
"text": "K-Means is the most popular algorithm for clustering but it has several issues associated with it such as dependence upon cluster initialization and dimensionality of features. Also, it faces problems if your clusters are not spherical as seen below-"
},
{
"code": null,
"e": 4014,
"s": 3741,
"text": "from sklearn.datasets import make_moonsX_mn, y_mn = make_moons(150, noise=.07, random_state=21)fig, ax = plt.subplots(figsize=(9,7))ax.set_title('Data with ground truth labels ', fontsize=18, fontweight='demi')ax.scatter(X_mn[:, 0], X_mn[:, 1],c=y_mn,s=50, cmap='viridis')"
},
{
"code": null,
"e": 4192,
"s": 4014,
"text": "Spectral clustering is a family of methods to find K clusters using the eigenvectors of a matrix. It handles these issues and easily outperforms other algorithms for clustering."
},
{
"code": null,
"e": 4413,
"s": 4192,
"text": "Here data is represented in the form of a graph. Now clustering can be thought of making graph cuts where Cut(A,B) between 2 clusters A and B is defined as the sum of weight connections between two clusters. For example-"
},
{
"code": null,
"e": 4570,
"s": 4413,
"text": "To find optimum clusters, we need MinCut and the objective of a MinCut method is to find two clusters A and B which have the minimum weight sum connections."
},
{
"code": null,
"e": 4746,
"s": 4570,
"text": "In spectral clustering, this min-cut objective is approximated using the Graph Laplacian matrix computed from the Adjacency and degree matrix of the graph. For proof, see this"
},
{
"code": null,
"e": 4829,
"s": 4746,
"text": "Given: A graph with n vertices and edge weights Wij , number of desired clusters k"
},
{
"code": null,
"e": 4885,
"s": 4829,
"text": "Construct (normalized) graph Laplacian L G V, E = D − W"
},
{
"code": null,
"e": 4958,
"s": 4885,
"text": "Find the k eigenvectors corresponding to the k smallest eigenvalues of L"
},
{
"code": null,
"e": 5000,
"s": 4958,
"text": "Let U be the n × k matrix of eigenvectors"
},
{
"code": null,
"e": 5142,
"s": 5000,
"text": "Use k-means to find k clusters C′ letting xi ′ be the rows of U 5. Assign data point xi to the j’th cluster if xi ′ was assigned to cluster j"
},
{
"code": null,
"e": 5725,
"s": 5142,
"text": "from sklearn.neighbors import radius_neighbors_graphfrom scipy.sparse import csgraphfrom sklearn.cluster import KMeans#Create adjacency matrix from the datasetA = radius_neighbors_graph(X_mn,0.4,mode='distance', metric='minkowski', p=2, metric_params=None, include_self=False)A = A.toarray()'''Next find out graph Laplacian matrix, which is defined as the L=D-A where A is our adjecency matrix we just saw and D is a diagonal degree matrix, every cell in the diagonal is the sum of the weights for that point'''L = csgraph.laplacian(A, normed=False)eigval, eigvec = np.linalg.eig(L)"
},
{
"code": null,
"e": 5905,
"s": 5725,
"text": "Now, use k-means to find k clusters C letting xi be the rows of eigvec. Finally to assign data points into clusters, assign xi to the j’th cluster if xi was assigned to cluster j."
},
{
"code": null,
"e": 6052,
"s": 5905,
"text": "The second smallest eigenvector , also called Fiedler vector is used to recursively bi-partition the graph by finding the optimal splitting point."
},
{
"code": null,
"e": 6079,
"s": 6052,
"text": "See full example code here"
},
{
"code": null,
"e": 6208,
"s": 6079,
"text": "Variants of spectral clustering are used in Region Proposal based Object Detection and Semantic Segmentation in Computer Vision."
},
{
"code": null,
"e": 6488,
"s": 6208,
"text": "At last, I will discuss my favorite field under AI, which is Computer Vision. In Computer Vision, Interest points in an image are the points which are unique in their neighborhood. Such points play a significant role in classical Computer Vision where these are used as features."
},
{
"code": null,
"e": 6655,
"s": 6488,
"text": "Corners are useful interest points along with other more complex image features such as SIFT, SURF, and HOG, etc. I would discuss one such method of corner detection."
},
{
"code": null,
"e": 6720,
"s": 6655,
"text": "Corners are easily recognized by looking through a small window."
},
{
"code": null,
"e": 6820,
"s": 6720,
"text": "Shifting the window should give a large change in intensity E if the window has a corner inside it."
},
{
"code": null,
"e": 6835,
"s": 6820,
"text": "The algorithm-"
},
{
"code": null,
"e": 6879,
"s": 6835,
"text": "Compute image gradients over a small region"
},
{
"code": null,
"e": 7016,
"s": 6879,
"text": "imggray = cv2.imread('checkerboard.png',0)i_x = cv2.Sobel(imggray,cv2.CV_64F,1,0,ksize=5)i_y = cv2.Sobel(imggray,cv2.CV_64F,0,1,ksize=5)"
},
{
"code": null,
"e": 7046,
"s": 7016,
"text": "Compute the covariance matrix"
},
{
"code": null,
"e": 7340,
"s": 7046,
"text": "# Calculate the product of derivates in each directioni_xx, i_xy, i_yy = multiply(i_x, i_x), multiply(i_x, i_y), multiply(i_y, i_y)# Calculate the sum of product of derivatess_xx, s_xy, s_yy = cv2.GaussianBlur(i_xx, (5,5), 0), cv2.GaussianBlur(i_xy, (5,5), 0), cv2.GaussianBlur(i_yy, (5,5), 0)"
},
{
"code": null,
"e": 7378,
"s": 7340,
"text": "Compute eigenvectors and eigenvalues."
},
{
"code": null,
"e": 7566,
"s": 7378,
"text": "Harris described a way for a faster approximation — Avoid computing the eigenvalues, just compute Trace and Determinant. Combing these 2 properties, we calculate a measure of cornerness-R"
},
{
"code": null,
"e": 7616,
"s": 7566,
"text": "Determinant of a matrix = Product of eigen values"
},
{
"code": null,
"e": 7656,
"s": 7616,
"text": "Trace of a matrix = Sum of eigen values"
},
{
"code": null,
"e": 7868,
"s": 7656,
"text": "# Compute the response of the detector at each pointk = .04 # Recommended value between .04 and .06det_h = multiply(s_xx, s_yy) - multiply(s_xy, s_xy)trace_h = s_xx + s_yyR = det_h - k*multiply(trace_h, trace_h)"
},
{
"code": null,
"e": 7915,
"s": 7868,
"text": "Use threshold on eigenvalues to detect corners"
},
{
"code": null,
"e": 7982,
"s": 7915,
"text": "ratio = .2 # Number to tweakthresh = abs(R) > ratio * abs(R).max()"
},
{
"code": null,
"e": 8129,
"s": 7982,
"text": "If either eigenvalue is close to 0, then this is not a corner, so look for locations where both are large. E is almost constant in all directions."
},
{
"code": null,
"e": 8166,
"s": 8129,
"text": "λ2 >> λ1 or λ1 >> λ2 depicts an Edge"
},
{
"code": null,
"e": 8225,
"s": 8166,
"text": "λ1 and λ2 are large, λ1 ~ λ2 E increases in all directions"
},
{
"code": null,
"e": 8252,
"s": 8225,
"text": "See full example code here"
},
{
"code": null,
"e": 8318,
"s": 8252,
"text": "Normalized Cuts and Image Segmentation. J. Shi and J. Malik, 2000"
},
{
"code": null,
"e": 8392,
"s": 8318,
"text": "A Combined Combined and Edge Detector, Chris Harris & Mike Stephens, 1988"
}
] |
What does close() function do in Python? | The function close() closes an open file. For example:
f = open('my_file', 'r+')
my_file_data = f.read()
f.close()
The above code opens 'my_file'in read mode then stores the data it reads from my_file in my_file_data and closes the file. When you open a file, the operating system gives a file handle to read/write the file. You need to close it once you are done using the file. If your program encounters an error and doesn't call f.close(), you didn't release the file. To make sure it doesn't happen, you can use with open(...) as syntax as it automatically closes files regardless of whether an error was encountered:
with open('my_file', 'r+') as f:
my_file_data = f.read() | [
{
"code": null,
"e": 1118,
"s": 1062,
"text": "The function close() closes an open file. For example: "
},
{
"code": null,
"e": 1178,
"s": 1118,
"text": "f = open('my_file', 'r+')\nmy_file_data = f.read()\nf.close()"
},
{
"code": null,
"e": 1687,
"s": 1178,
"text": " The above code opens 'my_file'in read mode then stores the data it reads from my_file in my_file_data and closes the file. When you open a file, the operating system gives a file handle to read/write the file. You need to close it once you are done using the file. If your program encounters an error and doesn't call f.close(), you didn't release the file. To make sure it doesn't happen, you can use with open(...) as syntax as it automatically closes files regardless of whether an error was encountered:"
},
{
"code": null,
"e": 1749,
"s": 1687,
"text": " with open('my_file', 'r+') as f:\n my_file_data = f.read()"
}
] |
End to End Deep Learning: A Different Perspective | by Himanshu Dutta | Towards Data Science | Whenever there is an article on an end-to-end deep learning project, it consists of training a deep learning model, deploying a Flask API, and then making sure it works or it extensively consists of creating a web demo using Streamlit or something similar. The problem with this approach is that it talks about a straight-forward and typical path that has been tried and tested. It merely takes replacing a single piece of the puzzle with an equivalent, such as a sentiment analysis model with a classification model, etc, and a new project can be created, but the wireframe remains mostly the same. The approach is quite valid from an educational perspective since it teaches you about the domain, but a typical deep learning project, from an engineering perspective, can differ a lot.
Engineering is more about designing and building. Knowing the “how-to” is more important than following a set pattern, or a step-wise procedure to build a project. In 2021, when there are so many alternative frameworks to work with, multiple approaches to the same problem, varying ways to deploy models, and build a demo for them, it is important to know which to choose, and more importantly how to choose one out of the available options.
Note: For the rest of this article, project and deep learning projects are used interchangeably.
When one starts learning about deep learning concepts, projects are made to learn a specific technology, or sub-domain, such as NLP, or CV. Today, if you go to resources like https://paperswithcode.com/, you’ll find research over different problems, which have become inter-domain or have exceedingly become difficult to solve with the traditional supervised learning approaches and hence to tackle these problems, approaches such as self-supervised learning, semi-supervised learning, causal inference, etc are been experimented with. This leads to an important question, what is a good way to approach and work on a project? Should a domain be picked, and problems based on that be worked out, or should a problem be chosen, and learned what would involve solving it? Let's try and answer some of these questions in this article.
The rest of this article talks about the process of a specific project and some of its components might not be as familiar as others, but the point is to walk you through the process and specifically the thought process of working on such a project, rather than it acting as a tutorial for the specific project. And to resonate with the idea of not having any fixed path or set pattern, this article is one of how a project can be worked out, and it leaves out details that aren’t directly connected to the discussion.
Let’s take a look at the end product of this project and what it involves, before any further discussion.
This project consists of building an app, which when shown food ingredients, tells you which dishes these ingredients can be used in. The simple use case of the application is to capture an image of the ingredients, and the app would detect the ingredients itself, and present you with a list of detected ingredients along with the probable recipes in which the ingredients can be used.
The project is broken down into three different parts. The first part consists of working with a deep learning model to detect the food ingredients, the second part consists of creating an endpoint to deploy it as a service, and the third part consists of actually using it in a native application.
At this point, you must be wondering, how is this different from any other smooth sailing project walkthrough, or demo, but as you’ll keep reading, the difference will become more and more apparent. The purpose of this article is not to spoon-feed a step-by-step procedure to create such a project, but rather to give you intuition as to what is involved in coming up with one, and what active decisions may involve at various stages.
At this point, it would be pleonasm to say that there is no set formula for approaching a problem or working on a project but there is something that always helps.
“Choose something that excites you. Choose something that encourages you to work hard.”
- Abhishek Thakur
Knowing what you are working on is important, but it’s equally important to know why you are working on it. It can be extremely helpful when things aren’t working as you want or expect them to(it happens, a lot!). It keeps you encouraged and gives you a clear perspective on the project. But that’s it. That’s the only pseudo-set piece of the puzzle. The rest can be looked into as we go along with the project.
Let’s talk a little about the motivation for this project then. I am a huge fan of Masterchef(most of them), and for those who are living under a rock and haven’t watched it ever, just know that it’s about cooking. There is this one segment on the show, called, Mystery Box Challenge, which involves the contestants having to work up a dish given some mystery ingredients. It made me think about how I would tackle this problem while remaining in my comfort zone of deep learning and software engineering. And the light bulb went off, and so was born the idea of the MBC App.
Taking a small segue at this point, it would be good to talk about how close this process is to a real-life project. More often than not, it happens so that there is either an existing product or a new product is in the works, and using any kind of AI is one of the alternatives, and in today’s time, from a startup to large tech giants, all put AI as their first option for a solution, hence our thought process conforms to some degree with that of the industry.
Now that we have the motivation resolved, and we have decided not to follow any particular path to solving the problem, do we not think of a solution at all? Well, that’s too bold for even us deep learning aficionados. There needs to be a clear distinction between a process and a methodology. “Process” is a broad term that describes what needs to be done to solve the problem, whereas the methodology of doing it could differ a lot, whereas a methodology talks of the steps in getting something particular done. For example, knowing whether to approach a problem as regression or classification, can be part of the process, whereas which specific backbone to choose from ResNet, EfficientNet, VGG can consist of the specific methodology.
So, let’s talk about the process that would be involved in solving the problem at hand. We need a way to get the ingredients. It could be as simple as asking the user to type in the names, but why wouldn’t they just google that instead of using the app we are so passionately building? So could it be a multiclass problem, where the user would simply either click or upload a picture of the ingredients and the app would recommend recipes based on that? Could be a good alternative, but sounds like too safe an option to experiment with. So what are the alternatives to this? We could use object detection to detect different ingredients. Even that could be a choice, whether to approach it from a supervised perspective or use some self-supervised localization technique for it. The latter however is out of the scope of our discussion, so we’ll stick with using object detection.
Now that that’s settled, how do we want to create this application? Should it be a script, which users would run on their systems after installing all the dependencies or should it be a web deployment? Both the alternatives sound charmingly wrong for the problem that we are trying to solve, rather creating a native application that can be used at the get-go sounds both user-friendly and right for the task.
Now let’s dive into the three different parts constituting this project and talk about their working individually.
We decided to use an object detection model to detect different ingredients as part of the process, but what we didn’t decide then is how this would be accomplished, and what specifications to choose for it, from the various available options. There are various popular object detection models out there, such as Faster-RCNN, Mask-RCNN, SSD, YOLO, etc. You can find papers with a comprehensive comparison of these models, but we would rather keep it short and simple, and justify our choice than focusing on the ones we didn’t choose.
YOLO v5 is one of the latest additions to the list of these object detection models. It outperforms all the recent models, in terms of both prediction speed on GPU, as well as, COCO metric(ranging from 0 to 1). It has a well-written code base, and it provides various alternatives to choose from, depending on the scale and requirement of the project. Along with that, it provides a good amount of portability. Although written in Pytorch, it can be converted to formats, such as Onnx, CoreML, TFLite, and Torchscript(which we’ll be using). Also, its ability to convert into Onnx itself opens a lot of possibilities. Hence due to its well-written code base and good portability, we choose YOLOv5 as our object detection model, and specifically YOLOv5m, as a good trade-off between speed and average precision(AP).
Great! Now, all we need to do is to train the object detection model and we are good to go, right? To burst the bubble, no. We talked plenty about the process, but we didn’t talk about the data itself, which is one of the main elements of any Data Science pipeline. So let’s put a pin on the model and process, and talk about data.
Let’s talk about another big distinction at this point, first. We always hear terms and phrases like, “Big Data”, “Data is the new gold”, “Data in abundance”, but the fact of the matter is that unstructured and unprocessed data is in abundance. And again, when we start learning about Deep Learning and Data Science in general, we come across datasets like Iris or MNIST, etc. These are well-processed data, and it takes effort to do that. This effort goes unrealized most of the time, but consider curating a dataset with 70,000 images of different digits, of different handwriting, or something even bigger and more relevant to the project, such as the COCO dataset. Collecting and processing such large-scale datasets is neither easy nor cheap. Most of the time in professional scenarios, the data relevant to the task is not available and rather needs to be collected, curated, and processed well before even considering starting the whole training-testing-experimentation cycle.
And such is our case. We need a dataset of food ingredients, with bounding box information of different labels across all these images. And spoiler alert, such a dataset is not readily available, and hence we need to put in the extra effort to prepare the dataset ourselves, which is more of a manual boring task than a fun coding challenge, but again, a very crucial part of the whole lifecycle.
This step in the project lifecycle involves us collecting data, annotating it with bounding box information, structuring it before it can then be passed on to the model for training. For the sake of simplicity, we rather choose to work with 10–20 ingredients than a whole bunch of ingredients, sleepless nights, and a jug full of coffee. The ingredients are chosen as per their frequency in different dishes in the Indian Food 101 dataset. As of now, only 10 ingredients are chosen. This dataset will also be important in a later part when we would have to predict dishes from the recognized ingredients, but more on that later.
Curry leaves, Garam masala, Ghee, Ginger, Jaggery, Milk, Rice flour, Sugar, Tomato, Urad dal
Now that we have our list of top 10 dishes that we want to work with, we need a way to collect this data, and that too in a well-structured way. There could be multiple ways of doing this. One can go around flaunting their photography skills and get images of these 10 ingredients, but that sounds too much manual labor. Engineering is also about being crafty and lazy, which leads to smart alternatives to painstaking work. Hence, an easy alternative to this would be to download the data from different free sources and web searches. But an even smarter approach would be to write a web scraper to get the data automatically from different free sources.
We choose the third option. Writing a web scraper to do the task for us, is better than clicking and collecting images manually ourselves. We collect the data in a manner that for each label(food ingredient) there is a separate folder, and we can control the number of images we want to scrape.
food-ingredients/ |--curry-leaves/ |--garam-masala/ . . . |--urad-dal/
There remains one task left before getting back to the model itself, and with fewer alternatives than the previous one. The task of annotating and creating bounding boxes on each of the images. Either we can do this manually using tools like LabelImg or we can choose some entirely different approach, such as Semi-supervised object localization, but let’s refrain from talking about the latter since it’s out of the scope for this discussion. Let’s stay on this track and manually annotate the data. The YOLO v5 project expects a very particular directory structure for the data:
And hence we convert the above data to replicate the above folder structure with the following piece of code:
After this using the LabelImg tool we generate the bounding boxes for each of the images in the train and val splits. And here is when we go back to our initial motivation and remind ourselves why we were working on this project in the first place.
Great! Now that the labeling is done and the data is properly structured, we can go ahead and train the YOLO v5 model on our custom dataset. We’ll use the yolov5m and write our configuration for the data, which would look something like this:
Since everything is well prepared now, all that remains is to train and export our model in the desired format, for later use. Since it involves running a few scripts either locally or over services like Google Colab, it can easily be skipped here, and the reference for the training and entire part 1 can be found here:
github.com
There is a variety of options available when it comes to serving a machine learning or deep learning model. Ranging from more familiar ones like Streamlit and Flask to slightly less talked about, “deployment on the edge”, and new options that keep on emerging, like FastAPI(which I am yet to play with).
We need to choose the option that best suits our purpose. Since we decided to create a native application for the project, we can either choose to deploy the model natively, with options like Onnxjs or TensorFlow.js. The problem with this option is, Onnx doesn’t properly work with React Native(since the application will be built using that), and even though TF.js has a compatible framework for React Native, it has some bugs that need to be worked out. This restricts our options to create an API endpoint. For this purpose, we choose TorchServe, which inherently uses C++ bindings for deploying a Torchscript model. The reason for choosing TorchServe is the pythonic style in which the endpoints can be written, along with its Torchscript deployment, which accounts for the speed.
The endpoint handler consists of the methods which would be part of your codebase(in our case YOLOv5 codebase) anyway. It consists of the following methods:
__init__: Used to initialize the endpoint, can be image transforms, or encoders for text, etc.preprocess: Method used to process the input batch before feeding it to the model and making inference, such as given an input image, transforming it in the desired way.inferencce: This method is where the actual inference happens. The preprocessed input is passed to the model, and output is obtained from it. Other smaller changes to the output can also be performed here.postprocess: After the inference is made the output is passed to this method, where the output can be packaged in the desired way, before the response is made for the given input, such as converting class index to label names, etc.Note: Although the method names are predefined, what is actually done inside these methods is completely upto us. Above are the suggeested best practices.
Now that we have our endpoint handler in place, all that’s needed is the actual endpoint function, which simply does what we have described in our handler, preprocess the data, makes inference on it, and postprocesses to return a response.
The endpoint can be deployed using a command similar to this:
The above script simply archives our saved model to a compatible “model archive” file packing all the necessary scripts, model graphs, and weights, which is then passed to the TorchServe command to start the endpoint.
The third part is very specific to the project. There are multiple ways to demo or create a full-fledged frontend for a project. Sometimes it is good to package your work as a library or framework, at other times, it can be a complete web or native application. And there are also options like Streamlit, which are genuinely a boon for when you have to demo something really quick and easy. But being from an engineering background, learning something new is what needs to be done.
For the specific project, writing a native application makes the most sense. But for the sake of discussion, let’s consider other options. A close alternative can be deploying a simple web application. Since we are working in React Native, a lot of the code itself is reusable if we consider working in React later, so the codebase has good reusability. Other than that, web applications don’t feel as user-friendly as a native application would, hence we will go ahead with a native application.
Although we have already decided on the use case of the application, we are yet to figure out what needs to be done for the use case to materialize. There can be two good options for this:
We can either let the user point the camera to the food ingredients, and the app will keep on making async calls to our endpoints and depending on the response keep on suggesting the recipes. For this alternative to work, our endpoint must be highly responsive, which at times won’t be possible since the endpoint might be running on a CPU. Along with this, an API call would have to be made continuously which is redundant for the use case.
Another way to do this is to let the user click an image of the food ingredients, and then make an API call to get the inference, based on which the recipes can be suggested.
Since the latter option is more feasible, we proceed with it. After deciding on the preferred way of making an inference, we now need to decide on the UI and components needed for the application. We’ll definitely require a Camera component and an Image component(to display still images), along with that it would require some buttons for the user to click images, flip the camera, etc, and a section where the ingredients and the recipes can be listed. It would also be nice to have bounding boxes drawn around the detected ingredients. Most of these elements are already built-in React Native, but we’ll have to build the “bounding box” component ourselves.
The “bounding box” component is a transparent rectangle box with a Text component on the top left corner, which renders over the Image component directly. Now that all our components are ready, we need to assemble them into a working application, which itself will be a single screen application that looks like the image we went over at the start. The code to make inference would look something like this:
It simply sends an image as a Base64 string and structures the response into a suitable format to be passed on to different components for rendering and further processing. It also makes sure that the predicted bounding boxes and labels for the ingredients have a confidence level above the set threshold.
Now we need to suggest some recipes based on the detected ingredients, which could range anywhere from making an external API call to some existing service to having a record of recipes within the app itself. For the sake of simplicity, we’ll use the list of recipes we extracted from the “Indian Food 101” dataset, and use that to suggest recipes based on the detected ingredients.
Now it is up to us how interactive and user-friendly we want this application to be. We can even add more use cases and features if we want to. But since the application we have worked on so far conforms with the initial idea that we had, we will stop here.
Hopefully, this article provides you with a good motivation to research and find your own way of working on projects, than following any set pattern. Each project has some learning to bestow, but what’s important is to use that learning for future endeavors, both the technical and non-technical ones.
[1] https://github.com/himanshu-dutta/mbc-object-detection-yolov5
[2] https://github.com/himanshu-dutta/mystery-box-challenge-app
[1] Yolo v5
[2] TorchServe & Pytorch
[3] React Native | [
{
"code": null,
"e": 959,
"s": 172,
"text": "Whenever there is an article on an end-to-end deep learning project, it consists of training a deep learning model, deploying a Flask API, and then making sure it works or it extensively consists of creating a web demo using Streamlit or something similar. The problem with this approach is that it talks about a straight-forward and typical path that has been tried and tested. It merely takes replacing a single piece of the puzzle with an equivalent, such as a sentiment analysis model with a classification model, etc, and a new project can be created, but the wireframe remains mostly the same. The approach is quite valid from an educational perspective since it teaches you about the domain, but a typical deep learning project, from an engineering perspective, can differ a lot."
},
{
"code": null,
"e": 1401,
"s": 959,
"text": "Engineering is more about designing and building. Knowing the “how-to” is more important than following a set pattern, or a step-wise procedure to build a project. In 2021, when there are so many alternative frameworks to work with, multiple approaches to the same problem, varying ways to deploy models, and build a demo for them, it is important to know which to choose, and more importantly how to choose one out of the available options."
},
{
"code": null,
"e": 1498,
"s": 1401,
"text": "Note: For the rest of this article, project and deep learning projects are used interchangeably."
},
{
"code": null,
"e": 2330,
"s": 1498,
"text": "When one starts learning about deep learning concepts, projects are made to learn a specific technology, or sub-domain, such as NLP, or CV. Today, if you go to resources like https://paperswithcode.com/, you’ll find research over different problems, which have become inter-domain or have exceedingly become difficult to solve with the traditional supervised learning approaches and hence to tackle these problems, approaches such as self-supervised learning, semi-supervised learning, causal inference, etc are been experimented with. This leads to an important question, what is a good way to approach and work on a project? Should a domain be picked, and problems based on that be worked out, or should a problem be chosen, and learned what would involve solving it? Let's try and answer some of these questions in this article."
},
{
"code": null,
"e": 2849,
"s": 2330,
"text": "The rest of this article talks about the process of a specific project and some of its components might not be as familiar as others, but the point is to walk you through the process and specifically the thought process of working on such a project, rather than it acting as a tutorial for the specific project. And to resonate with the idea of not having any fixed path or set pattern, this article is one of how a project can be worked out, and it leaves out details that aren’t directly connected to the discussion."
},
{
"code": null,
"e": 2955,
"s": 2849,
"text": "Let’s take a look at the end product of this project and what it involves, before any further discussion."
},
{
"code": null,
"e": 3342,
"s": 2955,
"text": "This project consists of building an app, which when shown food ingredients, tells you which dishes these ingredients can be used in. The simple use case of the application is to capture an image of the ingredients, and the app would detect the ingredients itself, and present you with a list of detected ingredients along with the probable recipes in which the ingredients can be used."
},
{
"code": null,
"e": 3641,
"s": 3342,
"text": "The project is broken down into three different parts. The first part consists of working with a deep learning model to detect the food ingredients, the second part consists of creating an endpoint to deploy it as a service, and the third part consists of actually using it in a native application."
},
{
"code": null,
"e": 4076,
"s": 3641,
"text": "At this point, you must be wondering, how is this different from any other smooth sailing project walkthrough, or demo, but as you’ll keep reading, the difference will become more and more apparent. The purpose of this article is not to spoon-feed a step-by-step procedure to create such a project, but rather to give you intuition as to what is involved in coming up with one, and what active decisions may involve at various stages."
},
{
"code": null,
"e": 4240,
"s": 4076,
"text": "At this point, it would be pleonasm to say that there is no set formula for approaching a problem or working on a project but there is something that always helps."
},
{
"code": null,
"e": 4328,
"s": 4240,
"text": "“Choose something that excites you. Choose something that encourages you to work hard.”"
},
{
"code": null,
"e": 4346,
"s": 4328,
"text": "- Abhishek Thakur"
},
{
"code": null,
"e": 4758,
"s": 4346,
"text": "Knowing what you are working on is important, but it’s equally important to know why you are working on it. It can be extremely helpful when things aren’t working as you want or expect them to(it happens, a lot!). It keeps you encouraged and gives you a clear perspective on the project. But that’s it. That’s the only pseudo-set piece of the puzzle. The rest can be looked into as we go along with the project."
},
{
"code": null,
"e": 5334,
"s": 4758,
"text": "Let’s talk a little about the motivation for this project then. I am a huge fan of Masterchef(most of them), and for those who are living under a rock and haven’t watched it ever, just know that it’s about cooking. There is this one segment on the show, called, Mystery Box Challenge, which involves the contestants having to work up a dish given some mystery ingredients. It made me think about how I would tackle this problem while remaining in my comfort zone of deep learning and software engineering. And the light bulb went off, and so was born the idea of the MBC App."
},
{
"code": null,
"e": 5798,
"s": 5334,
"text": "Taking a small segue at this point, it would be good to talk about how close this process is to a real-life project. More often than not, it happens so that there is either an existing product or a new product is in the works, and using any kind of AI is one of the alternatives, and in today’s time, from a startup to large tech giants, all put AI as their first option for a solution, hence our thought process conforms to some degree with that of the industry."
},
{
"code": null,
"e": 6538,
"s": 5798,
"text": "Now that we have the motivation resolved, and we have decided not to follow any particular path to solving the problem, do we not think of a solution at all? Well, that’s too bold for even us deep learning aficionados. There needs to be a clear distinction between a process and a methodology. “Process” is a broad term that describes what needs to be done to solve the problem, whereas the methodology of doing it could differ a lot, whereas a methodology talks of the steps in getting something particular done. For example, knowing whether to approach a problem as regression or classification, can be part of the process, whereas which specific backbone to choose from ResNet, EfficientNet, VGG can consist of the specific methodology."
},
{
"code": null,
"e": 7420,
"s": 6538,
"text": "So, let’s talk about the process that would be involved in solving the problem at hand. We need a way to get the ingredients. It could be as simple as asking the user to type in the names, but why wouldn’t they just google that instead of using the app we are so passionately building? So could it be a multiclass problem, where the user would simply either click or upload a picture of the ingredients and the app would recommend recipes based on that? Could be a good alternative, but sounds like too safe an option to experiment with. So what are the alternatives to this? We could use object detection to detect different ingredients. Even that could be a choice, whether to approach it from a supervised perspective or use some self-supervised localization technique for it. The latter however is out of the scope of our discussion, so we’ll stick with using object detection."
},
{
"code": null,
"e": 7830,
"s": 7420,
"text": "Now that that’s settled, how do we want to create this application? Should it be a script, which users would run on their systems after installing all the dependencies or should it be a web deployment? Both the alternatives sound charmingly wrong for the problem that we are trying to solve, rather creating a native application that can be used at the get-go sounds both user-friendly and right for the task."
},
{
"code": null,
"e": 7945,
"s": 7830,
"text": "Now let’s dive into the three different parts constituting this project and talk about their working individually."
},
{
"code": null,
"e": 8480,
"s": 7945,
"text": "We decided to use an object detection model to detect different ingredients as part of the process, but what we didn’t decide then is how this would be accomplished, and what specifications to choose for it, from the various available options. There are various popular object detection models out there, such as Faster-RCNN, Mask-RCNN, SSD, YOLO, etc. You can find papers with a comprehensive comparison of these models, but we would rather keep it short and simple, and justify our choice than focusing on the ones we didn’t choose."
},
{
"code": null,
"e": 9294,
"s": 8480,
"text": "YOLO v5 is one of the latest additions to the list of these object detection models. It outperforms all the recent models, in terms of both prediction speed on GPU, as well as, COCO metric(ranging from 0 to 1). It has a well-written code base, and it provides various alternatives to choose from, depending on the scale and requirement of the project. Along with that, it provides a good amount of portability. Although written in Pytorch, it can be converted to formats, such as Onnx, CoreML, TFLite, and Torchscript(which we’ll be using). Also, its ability to convert into Onnx itself opens a lot of possibilities. Hence due to its well-written code base and good portability, we choose YOLOv5 as our object detection model, and specifically YOLOv5m, as a good trade-off between speed and average precision(AP)."
},
{
"code": null,
"e": 9626,
"s": 9294,
"text": "Great! Now, all we need to do is to train the object detection model and we are good to go, right? To burst the bubble, no. We talked plenty about the process, but we didn’t talk about the data itself, which is one of the main elements of any Data Science pipeline. So let’s put a pin on the model and process, and talk about data."
},
{
"code": null,
"e": 10610,
"s": 9626,
"text": "Let’s talk about another big distinction at this point, first. We always hear terms and phrases like, “Big Data”, “Data is the new gold”, “Data in abundance”, but the fact of the matter is that unstructured and unprocessed data is in abundance. And again, when we start learning about Deep Learning and Data Science in general, we come across datasets like Iris or MNIST, etc. These are well-processed data, and it takes effort to do that. This effort goes unrealized most of the time, but consider curating a dataset with 70,000 images of different digits, of different handwriting, or something even bigger and more relevant to the project, such as the COCO dataset. Collecting and processing such large-scale datasets is neither easy nor cheap. Most of the time in professional scenarios, the data relevant to the task is not available and rather needs to be collected, curated, and processed well before even considering starting the whole training-testing-experimentation cycle."
},
{
"code": null,
"e": 11007,
"s": 10610,
"text": "And such is our case. We need a dataset of food ingredients, with bounding box information of different labels across all these images. And spoiler alert, such a dataset is not readily available, and hence we need to put in the extra effort to prepare the dataset ourselves, which is more of a manual boring task than a fun coding challenge, but again, a very crucial part of the whole lifecycle."
},
{
"code": null,
"e": 11636,
"s": 11007,
"text": "This step in the project lifecycle involves us collecting data, annotating it with bounding box information, structuring it before it can then be passed on to the model for training. For the sake of simplicity, we rather choose to work with 10–20 ingredients than a whole bunch of ingredients, sleepless nights, and a jug full of coffee. The ingredients are chosen as per their frequency in different dishes in the Indian Food 101 dataset. As of now, only 10 ingredients are chosen. This dataset will also be important in a later part when we would have to predict dishes from the recognized ingredients, but more on that later."
},
{
"code": null,
"e": 11729,
"s": 11636,
"text": "Curry leaves, Garam masala, Ghee, Ginger, Jaggery, Milk, Rice flour, Sugar, Tomato, Urad dal"
},
{
"code": null,
"e": 12385,
"s": 11729,
"text": "Now that we have our list of top 10 dishes that we want to work with, we need a way to collect this data, and that too in a well-structured way. There could be multiple ways of doing this. One can go around flaunting their photography skills and get images of these 10 ingredients, but that sounds too much manual labor. Engineering is also about being crafty and lazy, which leads to smart alternatives to painstaking work. Hence, an easy alternative to this would be to download the data from different free sources and web searches. But an even smarter approach would be to write a web scraper to get the data automatically from different free sources."
},
{
"code": null,
"e": 12680,
"s": 12385,
"text": "We choose the third option. Writing a web scraper to do the task for us, is better than clicking and collecting images manually ourselves. We collect the data in a manner that for each label(food ingredient) there is a separate folder, and we can control the number of images we want to scrape."
},
{
"code": null,
"e": 12781,
"s": 12680,
"text": "food-ingredients/ |--curry-leaves/ |--garam-masala/ . . . |--urad-dal/"
},
{
"code": null,
"e": 13362,
"s": 12781,
"text": "There remains one task left before getting back to the model itself, and with fewer alternatives than the previous one. The task of annotating and creating bounding boxes on each of the images. Either we can do this manually using tools like LabelImg or we can choose some entirely different approach, such as Semi-supervised object localization, but let’s refrain from talking about the latter since it’s out of the scope for this discussion. Let’s stay on this track and manually annotate the data. The YOLO v5 project expects a very particular directory structure for the data:"
},
{
"code": null,
"e": 13472,
"s": 13362,
"text": "And hence we convert the above data to replicate the above folder structure with the following piece of code:"
},
{
"code": null,
"e": 13721,
"s": 13472,
"text": "After this using the LabelImg tool we generate the bounding boxes for each of the images in the train and val splits. And here is when we go back to our initial motivation and remind ourselves why we were working on this project in the first place."
},
{
"code": null,
"e": 13964,
"s": 13721,
"text": "Great! Now that the labeling is done and the data is properly structured, we can go ahead and train the YOLO v5 model on our custom dataset. We’ll use the yolov5m and write our configuration for the data, which would look something like this:"
},
{
"code": null,
"e": 14285,
"s": 13964,
"text": "Since everything is well prepared now, all that remains is to train and export our model in the desired format, for later use. Since it involves running a few scripts either locally or over services like Google Colab, it can easily be skipped here, and the reference for the training and entire part 1 can be found here:"
},
{
"code": null,
"e": 14296,
"s": 14285,
"text": "github.com"
},
{
"code": null,
"e": 14600,
"s": 14296,
"text": "There is a variety of options available when it comes to serving a machine learning or deep learning model. Ranging from more familiar ones like Streamlit and Flask to slightly less talked about, “deployment on the edge”, and new options that keep on emerging, like FastAPI(which I am yet to play with)."
},
{
"code": null,
"e": 15385,
"s": 14600,
"text": "We need to choose the option that best suits our purpose. Since we decided to create a native application for the project, we can either choose to deploy the model natively, with options like Onnxjs or TensorFlow.js. The problem with this option is, Onnx doesn’t properly work with React Native(since the application will be built using that), and even though TF.js has a compatible framework for React Native, it has some bugs that need to be worked out. This restricts our options to create an API endpoint. For this purpose, we choose TorchServe, which inherently uses C++ bindings for deploying a Torchscript model. The reason for choosing TorchServe is the pythonic style in which the endpoints can be written, along with its Torchscript deployment, which accounts for the speed."
},
{
"code": null,
"e": 15542,
"s": 15385,
"text": "The endpoint handler consists of the methods which would be part of your codebase(in our case YOLOv5 codebase) anyway. It consists of the following methods:"
},
{
"code": null,
"e": 16396,
"s": 15542,
"text": "__init__: Used to initialize the endpoint, can be image transforms, or encoders for text, etc.preprocess: Method used to process the input batch before feeding it to the model and making inference, such as given an input image, transforming it in the desired way.inferencce: This method is where the actual inference happens. The preprocessed input is passed to the model, and output is obtained from it. Other smaller changes to the output can also be performed here.postprocess: After the inference is made the output is passed to this method, where the output can be packaged in the desired way, before the response is made for the given input, such as converting class index to label names, etc.Note: Although the method names are predefined, what is actually done inside these methods is completely upto us. Above are the suggeested best practices."
},
{
"code": null,
"e": 16636,
"s": 16396,
"text": "Now that we have our endpoint handler in place, all that’s needed is the actual endpoint function, which simply does what we have described in our handler, preprocess the data, makes inference on it, and postprocesses to return a response."
},
{
"code": null,
"e": 16698,
"s": 16636,
"text": "The endpoint can be deployed using a command similar to this:"
},
{
"code": null,
"e": 16916,
"s": 16698,
"text": "The above script simply archives our saved model to a compatible “model archive” file packing all the necessary scripts, model graphs, and weights, which is then passed to the TorchServe command to start the endpoint."
},
{
"code": null,
"e": 17398,
"s": 16916,
"text": "The third part is very specific to the project. There are multiple ways to demo or create a full-fledged frontend for a project. Sometimes it is good to package your work as a library or framework, at other times, it can be a complete web or native application. And there are also options like Streamlit, which are genuinely a boon for when you have to demo something really quick and easy. But being from an engineering background, learning something new is what needs to be done."
},
{
"code": null,
"e": 17895,
"s": 17398,
"text": "For the specific project, writing a native application makes the most sense. But for the sake of discussion, let’s consider other options. A close alternative can be deploying a simple web application. Since we are working in React Native, a lot of the code itself is reusable if we consider working in React later, so the codebase has good reusability. Other than that, web applications don’t feel as user-friendly as a native application would, hence we will go ahead with a native application."
},
{
"code": null,
"e": 18084,
"s": 17895,
"text": "Although we have already decided on the use case of the application, we are yet to figure out what needs to be done for the use case to materialize. There can be two good options for this:"
},
{
"code": null,
"e": 18526,
"s": 18084,
"text": "We can either let the user point the camera to the food ingredients, and the app will keep on making async calls to our endpoints and depending on the response keep on suggesting the recipes. For this alternative to work, our endpoint must be highly responsive, which at times won’t be possible since the endpoint might be running on a CPU. Along with this, an API call would have to be made continuously which is redundant for the use case."
},
{
"code": null,
"e": 18701,
"s": 18526,
"text": "Another way to do this is to let the user click an image of the food ingredients, and then make an API call to get the inference, based on which the recipes can be suggested."
},
{
"code": null,
"e": 19362,
"s": 18701,
"text": "Since the latter option is more feasible, we proceed with it. After deciding on the preferred way of making an inference, we now need to decide on the UI and components needed for the application. We’ll definitely require a Camera component and an Image component(to display still images), along with that it would require some buttons for the user to click images, flip the camera, etc, and a section where the ingredients and the recipes can be listed. It would also be nice to have bounding boxes drawn around the detected ingredients. Most of these elements are already built-in React Native, but we’ll have to build the “bounding box” component ourselves."
},
{
"code": null,
"e": 19770,
"s": 19362,
"text": "The “bounding box” component is a transparent rectangle box with a Text component on the top left corner, which renders over the Image component directly. Now that all our components are ready, we need to assemble them into a working application, which itself will be a single screen application that looks like the image we went over at the start. The code to make inference would look something like this:"
},
{
"code": null,
"e": 20076,
"s": 19770,
"text": "It simply sends an image as a Base64 string and structures the response into a suitable format to be passed on to different components for rendering and further processing. It also makes sure that the predicted bounding boxes and labels for the ingredients have a confidence level above the set threshold."
},
{
"code": null,
"e": 20459,
"s": 20076,
"text": "Now we need to suggest some recipes based on the detected ingredients, which could range anywhere from making an external API call to some existing service to having a record of recipes within the app itself. For the sake of simplicity, we’ll use the list of recipes we extracted from the “Indian Food 101” dataset, and use that to suggest recipes based on the detected ingredients."
},
{
"code": null,
"e": 20717,
"s": 20459,
"text": "Now it is up to us how interactive and user-friendly we want this application to be. We can even add more use cases and features if we want to. But since the application we have worked on so far conforms with the initial idea that we had, we will stop here."
},
{
"code": null,
"e": 21019,
"s": 20717,
"text": "Hopefully, this article provides you with a good motivation to research and find your own way of working on projects, than following any set pattern. Each project has some learning to bestow, but what’s important is to use that learning for future endeavors, both the technical and non-technical ones."
},
{
"code": null,
"e": 21085,
"s": 21019,
"text": "[1] https://github.com/himanshu-dutta/mbc-object-detection-yolov5"
},
{
"code": null,
"e": 21149,
"s": 21085,
"text": "[2] https://github.com/himanshu-dutta/mystery-box-challenge-app"
},
{
"code": null,
"e": 21161,
"s": 21149,
"text": "[1] Yolo v5"
},
{
"code": null,
"e": 21186,
"s": 21161,
"text": "[2] TorchServe & Pytorch"
}
] |
W3.CSS - Forms | W3.CSS has a very beautiful and responsive CSS for form designing. The following CSS are used −
w3-group
Represents a bordered container. Can be used to group a label and input.
w3-input
Beautifies an input control.
w3-label
Beautifies a label.
w3-checkbox w3-checkmark
Beautify a checkbox/ radio button.
<html>
<head>
<title>The W3.CSS Forms</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://www.w3schools.com/lib/w3.css">
</head>
<body>
<form class = "w3-container w3-card-8">
<div class = "w3-group">
<input class = "w3-input" type = "text" style = "width:90%" required>
<label class = "w3-label">User Name</label>
</div>
<div class = "w3-group">
<input class = "w3-input" type = "text" style = "width:90%" required>
<label class = "w3-label">Email</label>
</div>
<div class = "w3-group">
<textarea class = "w3-input" style = "width:90%" required></textarea>
<label class = "w3-label">Comments</label>
</div>
<div class = "w3-row">
<div class = "w3-half">
<label class = "w3-checkbox">
<input type = "checkbox" checked = "checked">
<div class = "w3-checkmark"></div> Married
</label>
<br>
<label class = "w3-checkbox">
<input type = "checkbox">
<div class = "w3-checkmark"></div> Single
</label>
<br>
<label class = "w3-checkbox">
<input type = "checkbox" disabled>
<div class = "w3-checkmark"></div> Don't know (Disabled)
</label>
<br>
<br>
</div>
<div class = "w3-half">
<label class = "w3-checkbox">
<input type = "radio" name = "gender" value = "male" checked>
<div class = "w3-checkmark"></div> Male
</label>
<br>
<label class = "w3-checkbox">
<input type = "radio" name = "gender" value = "female">
<div class = "w3-checkmark"></div> Female
</label>
<br>
<label class = "w3-checkbox">
<input type = "radio" name = "gender" value = "female" disabled>
<div class = "w3-checkmark"></div> Don't know (Disabled)
</label>
</div>
</div>
</form>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2005,
"s": 1909,
"text": "W3.CSS has a very beautiful and responsive CSS for form designing. The following CSS are used −"
},
{
"code": null,
"e": 2014,
"s": 2005,
"text": "w3-group"
},
{
"code": null,
"e": 2087,
"s": 2014,
"text": "Represents a bordered container. Can be used to group a label and input."
},
{
"code": null,
"e": 2096,
"s": 2087,
"text": "w3-input"
},
{
"code": null,
"e": 2125,
"s": 2096,
"text": "Beautifies an input control."
},
{
"code": null,
"e": 2134,
"s": 2125,
"text": "w3-label"
},
{
"code": null,
"e": 2154,
"s": 2134,
"text": "Beautifies a label."
},
{
"code": null,
"e": 2179,
"s": 2154,
"text": "w3-checkbox w3-checkmark"
},
{
"code": null,
"e": 2214,
"s": 2179,
"text": "Beautify a checkbox/ radio button."
},
{
"code": null,
"e": 4605,
"s": 2214,
"text": "<html>\n <head>\n <title>The W3.CSS Forms</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://www.w3schools.com/lib/w3.css\">\n </head>\n \n <body>\n <form class = \"w3-container w3-card-8\">\n <div class = \"w3-group\">\n <input class = \"w3-input\" type = \"text\" style = \"width:90%\" required>\n <label class = \"w3-label\">User Name</label>\n </div>\n \n <div class = \"w3-group\">\n <input class = \"w3-input\" type = \"text\" style = \"width:90%\" required>\n <label class = \"w3-label\">Email</label>\n </div>\n \n <div class = \"w3-group\">\n <textarea class = \"w3-input\" style = \"width:90%\" required></textarea>\n <label class = \"w3-label\">Comments</label>\n </div>\n <div class = \"w3-row\">\n <div class = \"w3-half\">\n <label class = \"w3-checkbox\">\n <input type = \"checkbox\" checked = \"checked\">\n <div class = \"w3-checkmark\"></div> Married\n </label>\n <br>\n <label class = \"w3-checkbox\">\n <input type = \"checkbox\">\n <div class = \"w3-checkmark\"></div> Single\n </label>\n <br>\n <label class = \"w3-checkbox\">\n <input type = \"checkbox\" disabled>\n <div class = \"w3-checkmark\"></div> Don't know (Disabled)\n </label>\n <br>\n <br>\n </div>\n \n <div class = \"w3-half\">\n <label class = \"w3-checkbox\">\n <input type = \"radio\" name = \"gender\" value = \"male\" checked>\n <div class = \"w3-checkmark\"></div> Male\n </label>\n <br>\n <label class = \"w3-checkbox\">\n <input type = \"radio\" name = \"gender\" value = \"female\">\n <div class = \"w3-checkmark\"></div> Female\n </label>\n <br>\n <label class = \"w3-checkbox\">\n <input type = \"radio\" name = \"gender\" value = \"female\" disabled>\n <div class = \"w3-checkmark\"></div> Don't know (Disabled)\n </label>\n </div>\n </div>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 4624,
"s": 4605,
"text": "Verify the result."
},
{
"code": null,
"e": 4631,
"s": 4624,
"text": " Print"
},
{
"code": null,
"e": 4642,
"s": 4631,
"text": " Add Notes"
}
] |
String to Number Conversion in Julia - GeeksforGeeks | 25 Aug, 2020
Julia is a flexible, dynamic, and high-level programming language that can be used to write any application. Also, many of its features can be used for numerical analysis and computational science. Julia is being widely used in machine learning, visualization, and data science. Julia allows type conversion for compatible datatypes. Julia has an inbuilt parse method that allows conversion of string to numeric datatype.
A string can be converted to the desired numeric datatype until it’s an invalid string. We can also specify the base for conversion like decimal, binary, octal or hexadecimal.
Syntax: parse(T::Type, str, base=Int)
Parameters: Type: Specifies the datatype to which the String is to be converted. str: It is the String that is to be converted to the specified datatype. base: This is optional. Required only if the String must be converted to a Number of specific bases.
Following are the ways for conversion from String to Number in Julia:
The string input is taken from the user using the readline() method of Julia. Next, the parse() method is used to convert the String into Integer datatype. The typeof() method outputs the datatype of the resulting integer.
Julia
# reads the string a = readline() # prints the string println(a) # parsing the string to integer print(typeof(parse(Int64, a)))
Output :
The string input is taken from the user using the readline() method of Julia. Next, the parse() method is used to convert the String into Integer datatype with the given base(here octal). The typeof() method outputs the datatype of the resulting integer.
Julia
# Taking User Inputprintln("Enter the number") a = readline() println("Entered the number: "a) # 8 is the octal base println(parse(Int64, a, 8)) # Getting Type of dataprint(typeof(parse(Int64, a, 8)))
Output :
The string input and required base are taken from the user using the readline() method of Julia. The parse() method converts the base into Integer(Int64). Next, the parse() method is used to convert the String into Integer datatype with the given base(here hexadecimal). The typeof() method outputs the datatype of the resulting integer.
Julia
# Taking String from userprintln("Enter the number") a = readline() println("Entered the number: "a) # Taking base from userprintln("Enter the base(10,8,16,2)") base = readline() println("Entered base: "base) # Converting to Numberprintln(parse(Int64, a, parse(Int64,base))) print(typeof(parse(Int64, a, parse(Int64,base))))
Output :
The string input is taken from the user using the readline() method of Julia. Next, the parse() method is used to convert the String into Float datatype. The typeof() method outputs the datatype of the resulting float value.
Julia
# parsing string into float println(parse(Float64, "123.345")) print(typeof(parse(Float64, "123.345")))
Output :
Since the given string cannot be converted into Float type the parse() method throws an error.
Julia
# error will be thrown as string# is not a valid float representation print(parse(Float64, "123.345a"))
Output :
julia-basic-methods
Picked
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Storing Output on a File in Julia
Getting rounded value of a number in Julia - round() Method
Reshaping array dimensions in Julia | Array reshape() Method
Comments in Julia
Creating array with repeated elements in Julia - repeat() Method
Get array dimensions and size of a dimension in Julia - size() Method
Manipulating matrices in Julia
while loop in Julia
Tuples in Julia | [
{
"code": null,
"e": 24180,
"s": 24152,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 24603,
"s": 24180,
"text": "Julia is a flexible, dynamic, and high-level programming language that can be used to write any application. Also, many of its features can be used for numerical analysis and computational science. Julia is being widely used in machine learning, visualization, and data science. Julia allows type conversion for compatible datatypes. Julia has an inbuilt parse method that allows conversion of string to numeric datatype. "
},
{
"code": null,
"e": 24780,
"s": 24603,
"text": "A string can be converted to the desired numeric datatype until it’s an invalid string. We can also specify the base for conversion like decimal, binary, octal or hexadecimal. "
},
{
"code": null,
"e": 24818,
"s": 24780,
"text": "Syntax: parse(T::Type, str, base=Int)"
},
{
"code": null,
"e": 25074,
"s": 24818,
"text": "Parameters: Type: Specifies the datatype to which the String is to be converted. str: It is the String that is to be converted to the specified datatype. base: This is optional. Required only if the String must be converted to a Number of specific bases. "
},
{
"code": null,
"e": 25145,
"s": 25074,
"text": "Following are the ways for conversion from String to Number in Julia: "
},
{
"code": null,
"e": 25369,
"s": 25145,
"text": "The string input is taken from the user using the readline() method of Julia. Next, the parse() method is used to convert the String into Integer datatype. The typeof() method outputs the datatype of the resulting integer. "
},
{
"code": null,
"e": 25375,
"s": 25369,
"text": "Julia"
},
{
"code": "# reads the string a = readline() # prints the string println(a) # parsing the string to integer print(typeof(parse(Int64, a)))",
"e": 25507,
"s": 25375,
"text": null
},
{
"code": null,
"e": 25516,
"s": 25507,
"text": "Output :"
},
{
"code": null,
"e": 25772,
"s": 25516,
"text": "The string input is taken from the user using the readline() method of Julia. Next, the parse() method is used to convert the String into Integer datatype with the given base(here octal). The typeof() method outputs the datatype of the resulting integer. "
},
{
"code": null,
"e": 25778,
"s": 25772,
"text": "Julia"
},
{
"code": "# Taking User Inputprintln(\"Enter the number\") a = readline() println(\"Entered the number: \"a) # 8 is the octal base println(parse(Int64, a, 8)) # Getting Type of dataprint(typeof(parse(Int64, a, 8)))",
"e": 25983,
"s": 25778,
"text": null
},
{
"code": null,
"e": 25992,
"s": 25983,
"text": "Output :"
},
{
"code": null,
"e": 26331,
"s": 25992,
"text": "The string input and required base are taken from the user using the readline() method of Julia. The parse() method converts the base into Integer(Int64). Next, the parse() method is used to convert the String into Integer datatype with the given base(here hexadecimal). The typeof() method outputs the datatype of the resulting integer. "
},
{
"code": null,
"e": 26337,
"s": 26331,
"text": "Julia"
},
{
"code": "# Taking String from userprintln(\"Enter the number\") a = readline() println(\"Entered the number: \"a) # Taking base from userprintln(\"Enter the base(10,8,16,2)\") base = readline() println(\"Entered base: \"base) # Converting to Numberprintln(parse(Int64, a, parse(Int64,base))) print(typeof(parse(Int64, a, parse(Int64,base))))",
"e": 26666,
"s": 26337,
"text": null
},
{
"code": null,
"e": 26675,
"s": 26666,
"text": "Output :"
},
{
"code": null,
"e": 26901,
"s": 26675,
"text": "The string input is taken from the user using the readline() method of Julia. Next, the parse() method is used to convert the String into Float datatype. The typeof() method outputs the datatype of the resulting float value. "
},
{
"code": null,
"e": 26907,
"s": 26901,
"text": "Julia"
},
{
"code": "# parsing string into float println(parse(Float64, \"123.345\")) print(typeof(parse(Float64, \"123.345\")))",
"e": 27011,
"s": 26907,
"text": null
},
{
"code": null,
"e": 27020,
"s": 27011,
"text": "Output :"
},
{
"code": null,
"e": 27116,
"s": 27020,
"text": "Since the given string cannot be converted into Float type the parse() method throws an error. "
},
{
"code": null,
"e": 27122,
"s": 27116,
"text": "Julia"
},
{
"code": "# error will be thrown as string# is not a valid float representation print(parse(Float64, \"123.345a\"))",
"e": 27226,
"s": 27122,
"text": null
},
{
"code": null,
"e": 27235,
"s": 27226,
"text": "Output :"
},
{
"code": null,
"e": 27255,
"s": 27235,
"text": "julia-basic-methods"
},
{
"code": null,
"e": 27262,
"s": 27255,
"text": "Picked"
},
{
"code": null,
"e": 27268,
"s": 27262,
"text": "Julia"
},
{
"code": null,
"e": 27366,
"s": 27268,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27383,
"s": 27366,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 27417,
"s": 27383,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 27477,
"s": 27417,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 27538,
"s": 27477,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 27556,
"s": 27538,
"text": "Comments in Julia"
},
{
"code": null,
"e": 27621,
"s": 27556,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 27691,
"s": 27621,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 27722,
"s": 27691,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 27742,
"s": 27722,
"text": "while loop in Julia"
}
] |
All Pandas qcut() you should know for binning numerical data based on sample quantiles | by B. Chen | Towards Data Science | Numerical data is common in data analysis. Often you have numerical data that is continuous, very large scales, or highly skewed. Sometimes, it can be easier to bin those data into discrete intervals. This is very helpful to perform descriptive statistics when values are divided into meaningful categories. For example, age group instead of the exact age, weight class instead of the exact weight, grade level instead of the exact score.
Pandas has 2 built-in functions cut() and qcut() for transforming numerical data into categorical data.
cut() bins data into discrete intervals based on bin edges
qcut() bins data into discrete intervals based on sample quantiles
In the previous article, we have introduced the cut() function.
towardsdatascience.com
In this article, you’ll learn how to use qcut() to bin numerical data based on sample quantiles. This article is structured as follows:
Discretizing into equal-sized bucketsDiscretizing into buckets with a list of quantilesAdding custom labelsReturning bins with retbins=TrueConfiguring the bin precision
Discretizing into equal-sized buckets
Discretizing into buckets with a list of quantiles
Adding custom labels
Returning bins with retbins=True
Configuring the bin precision
Please check out Notebook for source code.
Visit Github Repo for other tutorials
Similar to Pandas cut(), the simplest usage of qcut() must have a column and an integer as input. It discretizes values into equal-sized buckets:
df = pd.DataFrame({ 'age': [2, 67, 40, 32, 4, 15, 82, 99, 26, 30, 50, 78]})df['age_group'] = pd.qcut(df['age'], 3)
Let’s count that how many values fall into each bin.
df['age_group'].value_counts()(1.999, 28.667] 4(28.667, 55.667] 4(55.667, 99.0] 4Name: age_group, dtype: int64
We can see bins have been chosen so that the result has the same number of records in each bin (Known as equal-sized buckets).
In addition, you may notice those interval values are having a round bracket at the start and a square bracket at the end, for example (1.999, 28.667]. It basically means any value on the side of the round bracket is not included in the interval and any value on the side of the square bracket is included (It is known as open and closed intervals in Math).
Now, let’s take a look at the new column age_group.
It shows dtype: category with 3 label values: (1.999, 28.667] , (28.667, 55.667] , and (55.667, 99.0]. Those label values are ordered as indicated with the symbol <. Let’s sort the DataFrame by the column age_group:
df.sort_values('age_group')
One of the problems with the previous approach is that the result always has the same number of records in each bin. In another word, each bin has the same proportion/percentage. For example:
pd.qcut(df['age'], 2) Result: |<- 50% ->|<- 50% ->|pd.qcut(df['age'], 3) Result: |<- 33.3% ->|<- 33.3% ->|<- 33.3% ->|pd.qcut(df['age'], 4)Result: |<- 25% ->|<- 25% ->|<- 25% ->|<- 25% ->|pd.qcut(df['age'], 5)Result: |<- 20% ->|<- 20% ->|<- 20% ->|<- 20% ->|<- 20% ->|
In some cases, you may want to explicitly choose the proportions other than equal-sized buckets, for instance:
10%, 40%, 50%
To do that, we can pass a list of quantiles to the 2nd argument.
df['age_group'] = pd.qcut(df['age'], [0, .1, .5, 1])df.sort_values('age_group')
Note that 4 values [0, .1, .5, 1] are used to produce the 3 proportions/percentages 10%, 40%, and 50%
To verify the result, let’s sort and count the number of values in each bin as follows:
df.sort_values('age_group')['age_group'].value_counts()(36.0, 99.0] 6(5.1, 36.0] 4(1.999, 5.1] 2Name: age_group, dtype: int64
It is more descriptive to label these age_group values as ‘Millennial’, ‘Gen X’, ‘Boomer’, ‘Greatest’. To do that, we can simply pass those values in a list to the argument labels
labels=['Millennial', 'Gen X', 'Boomer', 'Greatest']df['age_group'] = pd.qcut(df['age'], [0, .1, 0.3, .6, 1], labels=labels)
Now, when we looking into the column, it shows the label instead
df['age_group']0 Millennial1 Greatest2 Boomer3 Boomer4 Millennial5 Gen X6 Greatest7 Greatest8 Gen X9 Boomer10 Greatest11 GreatestName: age_group, dtype: categoryCategories (4, object): ['Millennial' < 'Gen X' < 'Boomer' < 'Greatest']
Similarly, it’s showing label when sorting and counting
df.sort_values('age_group')
df['age_group'].value_counts().sort_index()Millennial 2Gen X 2Boomer 3Greatest 5Name: age_group, dtype: int64
There is an argument called retbin to return the bins. If it’s set to True, the result will return the bins. It’s useful when the 2nd argument q is passed as a single number value.
result, bins = pd.qcut( df['age'], 5, # A single number value retbins=True)# Print out bins valuebinsarray([ 2. , 17.2, 30.8, 46. , 75.8, 99. ])
You may notice all the bin interval values we have made so far have some decimal points, for example pd.qcut(df['age'], 3)
pd.qcut(df['age'], 3)0 (1.999, 28.667]1 (55.667, 99.0]2 (28.667, 55.667]3 (28.667, 55.667]4 (1.999, 28.667]5 (1.999, 28.667]6 (55.667, 99.0]7 (55.667, 99.0]8 (1.999, 28.667]9 (28.667, 55.667]10 (28.667, 55.667]11 (55.667, 99.0]Name: age, dtype: categoryCategories (3, interval[float64]): [(1.999, 28.667] < (28.667, 55.667] < (55.667, 99.0]]
Generally, the age group interval doesn’t use decimal places. Luckily, there is an argument called precision to define how many decimal points to use while calculating bin precision. We can set the precision to 0 to avoid any decimal place.
pd.qcut(df['age'], 3, precision=0)0 (1.0, 29.0]1 (56.0, 99.0]2 (29.0, 56.0]3 (29.0, 56.0]4 (1.0, 29.0]5 (1.0, 29.0]6 (56.0, 99.0]7 (56.0, 99.0]8 (1.0, 29.0]9 (29.0, 56.0]10 (29.0, 56.0]11 (56.0, 99.0]Name: age, dtype: categoryCategories (3, interval[float64]): [(1.0, 29.0] < (29.0, 56.0] < (56.0, 99.0]]
You can also set it to any other value, for instance precision=1 for 1 decimal place.
pd.qcut(df['age'], 3, precision=1)0 (1.9, 28.7]1 (55.7, 99.0]2 (28.7, 55.7]3 (28.7, 55.7]4 (1.9, 28.7]5 (1.9, 28.7]6 (55.7, 99.0]7 (55.7, 99.0]8 (1.9, 28.7]9 (28.7, 55.7]10 (28.7, 55.7]11 (55.7, 99.0]Name: age, dtype: categoryCategories (3, interval[float64]): [(1.9, 28.7] < (28.7, 55.7] < (55.7, 99.0]]
Pandas qcut() function is a quick and convenient way for binning numerical data based on sample quantiles.
I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the qcut() API and to know about other things you can do.
Thanks for reading. Please check out the Notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning.
A Practical Introduction to Pandas Series
Using Pandas method chaining to improve code readability
How to do a Custom Sort on Pandas DataFrame
All the Pandas shift() you should know for data analysis
When to use Pandas transform() function
Pandas concat() tricks you should know
Difference between apply() and transform() in Pandas
All the Pandas merge() you should know
Working with datetime in Pandas DataFrame
Pandas read_csv() tricks you should know
4 tricks you should know to parse date columns with Pandas read_csv()
More tutorials can be found on my Github | [
{
"code": null,
"e": 610,
"s": 171,
"text": "Numerical data is common in data analysis. Often you have numerical data that is continuous, very large scales, or highly skewed. Sometimes, it can be easier to bin those data into discrete intervals. This is very helpful to perform descriptive statistics when values are divided into meaningful categories. For example, age group instead of the exact age, weight class instead of the exact weight, grade level instead of the exact score."
},
{
"code": null,
"e": 714,
"s": 610,
"text": "Pandas has 2 built-in functions cut() and qcut() for transforming numerical data into categorical data."
},
{
"code": null,
"e": 773,
"s": 714,
"text": "cut() bins data into discrete intervals based on bin edges"
},
{
"code": null,
"e": 840,
"s": 773,
"text": "qcut() bins data into discrete intervals based on sample quantiles"
},
{
"code": null,
"e": 904,
"s": 840,
"text": "In the previous article, we have introduced the cut() function."
},
{
"code": null,
"e": 927,
"s": 904,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1063,
"s": 927,
"text": "In this article, you’ll learn how to use qcut() to bin numerical data based on sample quantiles. This article is structured as follows:"
},
{
"code": null,
"e": 1232,
"s": 1063,
"text": "Discretizing into equal-sized bucketsDiscretizing into buckets with a list of quantilesAdding custom labelsReturning bins with retbins=TrueConfiguring the bin precision"
},
{
"code": null,
"e": 1270,
"s": 1232,
"text": "Discretizing into equal-sized buckets"
},
{
"code": null,
"e": 1321,
"s": 1270,
"text": "Discretizing into buckets with a list of quantiles"
},
{
"code": null,
"e": 1342,
"s": 1321,
"text": "Adding custom labels"
},
{
"code": null,
"e": 1375,
"s": 1342,
"text": "Returning bins with retbins=True"
},
{
"code": null,
"e": 1405,
"s": 1375,
"text": "Configuring the bin precision"
},
{
"code": null,
"e": 1448,
"s": 1405,
"text": "Please check out Notebook for source code."
},
{
"code": null,
"e": 1486,
"s": 1448,
"text": "Visit Github Repo for other tutorials"
},
{
"code": null,
"e": 1632,
"s": 1486,
"text": "Similar to Pandas cut(), the simplest usage of qcut() must have a column and an integer as input. It discretizes values into equal-sized buckets:"
},
{
"code": null,
"e": 1749,
"s": 1632,
"text": "df = pd.DataFrame({ 'age': [2, 67, 40, 32, 4, 15, 82, 99, 26, 30, 50, 78]})df['age_group'] = pd.qcut(df['age'], 3)"
},
{
"code": null,
"e": 1802,
"s": 1749,
"text": "Let’s count that how many values fall into each bin."
},
{
"code": null,
"e": 1925,
"s": 1802,
"text": "df['age_group'].value_counts()(1.999, 28.667] 4(28.667, 55.667] 4(55.667, 99.0] 4Name: age_group, dtype: int64"
},
{
"code": null,
"e": 2052,
"s": 1925,
"text": "We can see bins have been chosen so that the result has the same number of records in each bin (Known as equal-sized buckets)."
},
{
"code": null,
"e": 2410,
"s": 2052,
"text": "In addition, you may notice those interval values are having a round bracket at the start and a square bracket at the end, for example (1.999, 28.667]. It basically means any value on the side of the round bracket is not included in the interval and any value on the side of the square bracket is included (It is known as open and closed intervals in Math)."
},
{
"code": null,
"e": 2462,
"s": 2410,
"text": "Now, let’s take a look at the new column age_group."
},
{
"code": null,
"e": 2678,
"s": 2462,
"text": "It shows dtype: category with 3 label values: (1.999, 28.667] , (28.667, 55.667] , and (55.667, 99.0]. Those label values are ordered as indicated with the symbol <. Let’s sort the DataFrame by the column age_group:"
},
{
"code": null,
"e": 2706,
"s": 2678,
"text": "df.sort_values('age_group')"
},
{
"code": null,
"e": 2898,
"s": 2706,
"text": "One of the problems with the previous approach is that the result always has the same number of records in each bin. In another word, each bin has the same proportion/percentage. For example:"
},
{
"code": null,
"e": 3167,
"s": 2898,
"text": "pd.qcut(df['age'], 2) Result: |<- 50% ->|<- 50% ->|pd.qcut(df['age'], 3) Result: |<- 33.3% ->|<- 33.3% ->|<- 33.3% ->|pd.qcut(df['age'], 4)Result: |<- 25% ->|<- 25% ->|<- 25% ->|<- 25% ->|pd.qcut(df['age'], 5)Result: |<- 20% ->|<- 20% ->|<- 20% ->|<- 20% ->|<- 20% ->|"
},
{
"code": null,
"e": 3278,
"s": 3167,
"text": "In some cases, you may want to explicitly choose the proportions other than equal-sized buckets, for instance:"
},
{
"code": null,
"e": 3292,
"s": 3278,
"text": "10%, 40%, 50%"
},
{
"code": null,
"e": 3357,
"s": 3292,
"text": "To do that, we can pass a list of quantiles to the 2nd argument."
},
{
"code": null,
"e": 3437,
"s": 3357,
"text": "df['age_group'] = pd.qcut(df['age'], [0, .1, .5, 1])df.sort_values('age_group')"
},
{
"code": null,
"e": 3539,
"s": 3437,
"text": "Note that 4 values [0, .1, .5, 1] are used to produce the 3 proportions/percentages 10%, 40%, and 50%"
},
{
"code": null,
"e": 3627,
"s": 3539,
"text": "To verify the result, let’s sort and count the number of values in each bin as follows:"
},
{
"code": null,
"e": 3763,
"s": 3627,
"text": "df.sort_values('age_group')['age_group'].value_counts()(36.0, 99.0] 6(5.1, 36.0] 4(1.999, 5.1] 2Name: age_group, dtype: int64"
},
{
"code": null,
"e": 3943,
"s": 3763,
"text": "It is more descriptive to label these age_group values as ‘Millennial’, ‘Gen X’, ‘Boomer’, ‘Greatest’. To do that, we can simply pass those values in a list to the argument labels"
},
{
"code": null,
"e": 4068,
"s": 3943,
"text": "labels=['Millennial', 'Gen X', 'Boomer', 'Greatest']df['age_group'] = pd.qcut(df['age'], [0, .1, 0.3, .6, 1], labels=labels)"
},
{
"code": null,
"e": 4133,
"s": 4068,
"text": "Now, when we looking into the column, it shows the label instead"
},
{
"code": null,
"e": 4445,
"s": 4133,
"text": "df['age_group']0 Millennial1 Greatest2 Boomer3 Boomer4 Millennial5 Gen X6 Greatest7 Greatest8 Gen X9 Boomer10 Greatest11 GreatestName: age_group, dtype: categoryCategories (4, object): ['Millennial' < 'Gen X' < 'Boomer' < 'Greatest']"
},
{
"code": null,
"e": 4501,
"s": 4445,
"text": "Similarly, it’s showing label when sorting and counting"
},
{
"code": null,
"e": 4529,
"s": 4501,
"text": "df.sort_values('age_group')"
},
{
"code": null,
"e": 4662,
"s": 4529,
"text": "df['age_group'].value_counts().sort_index()Millennial 2Gen X 2Boomer 3Greatest 5Name: age_group, dtype: int64"
},
{
"code": null,
"e": 4843,
"s": 4662,
"text": "There is an argument called retbin to return the bins. If it’s set to True, the result will return the bins. It’s useful when the 2nd argument q is passed as a single number value."
},
{
"code": null,
"e": 5015,
"s": 4843,
"text": "result, bins = pd.qcut( df['age'], 5, # A single number value retbins=True)# Print out bins valuebinsarray([ 2. , 17.2, 30.8, 46. , 75.8, 99. ])"
},
{
"code": null,
"e": 5138,
"s": 5015,
"text": "You may notice all the bin interval values we have made so far have some decimal points, for example pd.qcut(df['age'], 3)"
},
{
"code": null,
"e": 5538,
"s": 5138,
"text": "pd.qcut(df['age'], 3)0 (1.999, 28.667]1 (55.667, 99.0]2 (28.667, 55.667]3 (28.667, 55.667]4 (1.999, 28.667]5 (1.999, 28.667]6 (55.667, 99.0]7 (55.667, 99.0]8 (1.999, 28.667]9 (28.667, 55.667]10 (28.667, 55.667]11 (55.667, 99.0]Name: age, dtype: categoryCategories (3, interval[float64]): [(1.999, 28.667] < (28.667, 55.667] < (55.667, 99.0]]"
},
{
"code": null,
"e": 5779,
"s": 5538,
"text": "Generally, the age group interval doesn’t use decimal places. Luckily, there is an argument called precision to define how many decimal points to use while calculating bin precision. We can set the precision to 0 to avoid any decimal place."
},
{
"code": null,
"e": 6134,
"s": 5779,
"text": "pd.qcut(df['age'], 3, precision=0)0 (1.0, 29.0]1 (56.0, 99.0]2 (29.0, 56.0]3 (29.0, 56.0]4 (1.0, 29.0]5 (1.0, 29.0]6 (56.0, 99.0]7 (56.0, 99.0]8 (1.0, 29.0]9 (29.0, 56.0]10 (29.0, 56.0]11 (56.0, 99.0]Name: age, dtype: categoryCategories (3, interval[float64]): [(1.0, 29.0] < (29.0, 56.0] < (56.0, 99.0]]"
},
{
"code": null,
"e": 6220,
"s": 6134,
"text": "You can also set it to any other value, for instance precision=1 for 1 decimal place."
},
{
"code": null,
"e": 6575,
"s": 6220,
"text": "pd.qcut(df['age'], 3, precision=1)0 (1.9, 28.7]1 (55.7, 99.0]2 (28.7, 55.7]3 (28.7, 55.7]4 (1.9, 28.7]5 (1.9, 28.7]6 (55.7, 99.0]7 (55.7, 99.0]8 (1.9, 28.7]9 (28.7, 55.7]10 (28.7, 55.7]11 (55.7, 99.0]Name: age, dtype: categoryCategories (3, interval[float64]): [(1.9, 28.7] < (28.7, 55.7] < (55.7, 99.0]]"
},
{
"code": null,
"e": 6682,
"s": 6575,
"text": "Pandas qcut() function is a quick and convenient way for binning numerical data based on sample quantiles."
},
{
"code": null,
"e": 6858,
"s": 6682,
"text": "I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the qcut() API and to know about other things you can do."
},
{
"code": null,
"e": 7010,
"s": 6858,
"text": "Thanks for reading. Please check out the Notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning."
},
{
"code": null,
"e": 7052,
"s": 7010,
"text": "A Practical Introduction to Pandas Series"
},
{
"code": null,
"e": 7109,
"s": 7052,
"text": "Using Pandas method chaining to improve code readability"
},
{
"code": null,
"e": 7153,
"s": 7109,
"text": "How to do a Custom Sort on Pandas DataFrame"
},
{
"code": null,
"e": 7210,
"s": 7153,
"text": "All the Pandas shift() you should know for data analysis"
},
{
"code": null,
"e": 7250,
"s": 7210,
"text": "When to use Pandas transform() function"
},
{
"code": null,
"e": 7289,
"s": 7250,
"text": "Pandas concat() tricks you should know"
},
{
"code": null,
"e": 7342,
"s": 7289,
"text": "Difference between apply() and transform() in Pandas"
},
{
"code": null,
"e": 7381,
"s": 7342,
"text": "All the Pandas merge() you should know"
},
{
"code": null,
"e": 7423,
"s": 7381,
"text": "Working with datetime in Pandas DataFrame"
},
{
"code": null,
"e": 7464,
"s": 7423,
"text": "Pandas read_csv() tricks you should know"
},
{
"code": null,
"e": 7534,
"s": 7464,
"text": "4 tricks you should know to parse date columns with Pandas read_csv()"
}
] |
Design and Analysis Introduction | An algorithm is a set of steps of operations to solve a problem performing calculation, data processing, and automated reasoning tasks. An algorithm is an efficient method that can be expressed within finite amount of time and space.
An algorithm is the best way to represent the solution of a particular problem in a very simple and efficient way. If we have an algorithm for a specific problem, then we can implement it in any programming language, meaning that the algorithm is independent from any programming languages.
The important aspects of algorithm design include creating an efficient algorithm to solve a problem in an efficient way using minimum time and space.
To solve a problem, different approaches can be followed. Some of them can be efficient with respect to time consumption, whereas other approaches may be memory efficient. However, one has to keep in mind that both time consumption and memory usage cannot be optimized simultaneously. If we require an algorithm to run in lesser time, we have to invest in more memory and if we require an algorithm to run with lesser memory, we need to have more time.
The following steps are involved in solving computational problems.
Problem definition
Development of a model
Specification of an Algorithm
Designing an Algorithm
Checking the correctness of an Algorithm
Analysis of an Algorithm
Implementation of an Algorithm
Program testing
Documentation
The main characteristics of algorithms are as follows −
Algorithms must have a unique name
Algorithms must have a unique name
Algorithms should have explicitly defined set of inputs and outputs
Algorithms should have explicitly defined set of inputs and outputs
Algorithms are well-ordered with unambiguous operations
Algorithms are well-ordered with unambiguous operations
Algorithms halt in a finite amount of time. Algorithms should not run for infinity, i.e., an algorithm must end at some point
Algorithms halt in a finite amount of time. Algorithms should not run for infinity, i.e., an algorithm must end at some point
Pseudocode gives a high-level description of an algorithm without the ambiguity associated with plain text but also without the need to know the syntax of a particular programming language.
The running time can be estimated in a more general manner by using Pseudocode to represent the algorithm as a set of fundamental operations which can then be counted.
An algorithm is a formal definition with some specific characteristics that describes a process, which could be executed by a Turing-complete computer machine to perform a specific task. Generally, the word "algorithm" can be used to describe any high level task in computer science.
On the other hand, pseudocode is an informal and (often rudimentary) human readable description of an algorithm leaving many granular details of it. Writing a pseudocode has no restriction of styles and its only objective is to describe the high level steps of algorithm in a much realistic manner in natural language.
For example, following is an algorithm for Insertion Sort.
Algorithm: Insertion-Sort
Input: A list L of integers of length n
Output: A sorted list L1 containing those integers present in L
Step 1: Keep a sorted list L1 which starts off empty
Step 2: Perform Step 3 for each element in the original list L
Step 3: Insert it into the correct position in the sorted list L1.
Step 4: Return the sorted list
Step 5: Stop
Here is a pseudocode which describes how the high level abstract process mentioned above in the algorithm Insertion-Sort could be described in a more realistic way.
for i <- 1 to length(A)
x <- A[i]
j <- i
while j > 0 and A[j-1] > x
A[j] <- A[j-1]
j <- j - 1
A[j] <- x
In this tutorial, algorithms will be presented in the form of pseudocode, that is similar in many respects to C, C++, Java, Python, and other programming languages.
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2833,
"s": 2599,
"text": "An algorithm is a set of steps of operations to solve a problem performing calculation, data processing, and automated reasoning tasks. An algorithm is an efficient method that can be expressed within finite amount of time and space."
},
{
"code": null,
"e": 3124,
"s": 2833,
"text": "An algorithm is the best way to represent the solution of a particular problem in a very simple and efficient way. If we have an algorithm for a specific problem, then we can implement it in any programming language, meaning that the algorithm is independent from any programming languages."
},
{
"code": null,
"e": 3275,
"s": 3124,
"text": "The important aspects of algorithm design include creating an efficient algorithm to solve a problem in an efficient way using minimum time and space."
},
{
"code": null,
"e": 3728,
"s": 3275,
"text": "To solve a problem, different approaches can be followed. Some of them can be efficient with respect to time consumption, whereas other approaches may be memory efficient. However, one has to keep in mind that both time consumption and memory usage cannot be optimized simultaneously. If we require an algorithm to run in lesser time, we have to invest in more memory and if we require an algorithm to run with lesser memory, we need to have more time."
},
{
"code": null,
"e": 3796,
"s": 3728,
"text": "The following steps are involved in solving computational problems."
},
{
"code": null,
"e": 3815,
"s": 3796,
"text": "Problem definition"
},
{
"code": null,
"e": 3838,
"s": 3815,
"text": "Development of a model"
},
{
"code": null,
"e": 3868,
"s": 3838,
"text": "Specification of an Algorithm"
},
{
"code": null,
"e": 3891,
"s": 3868,
"text": "Designing an Algorithm"
},
{
"code": null,
"e": 3932,
"s": 3891,
"text": "Checking the correctness of an Algorithm"
},
{
"code": null,
"e": 3957,
"s": 3932,
"text": "Analysis of an Algorithm"
},
{
"code": null,
"e": 3988,
"s": 3957,
"text": "Implementation of an Algorithm"
},
{
"code": null,
"e": 4004,
"s": 3988,
"text": "Program testing"
},
{
"code": null,
"e": 4018,
"s": 4004,
"text": "Documentation"
},
{
"code": null,
"e": 4074,
"s": 4018,
"text": "The main characteristics of algorithms are as follows −"
},
{
"code": null,
"e": 4109,
"s": 4074,
"text": "Algorithms must have a unique name"
},
{
"code": null,
"e": 4144,
"s": 4109,
"text": "Algorithms must have a unique name"
},
{
"code": null,
"e": 4212,
"s": 4144,
"text": "Algorithms should have explicitly defined set of inputs and outputs"
},
{
"code": null,
"e": 4280,
"s": 4212,
"text": "Algorithms should have explicitly defined set of inputs and outputs"
},
{
"code": null,
"e": 4336,
"s": 4280,
"text": "Algorithms are well-ordered with unambiguous operations"
},
{
"code": null,
"e": 4392,
"s": 4336,
"text": "Algorithms are well-ordered with unambiguous operations"
},
{
"code": null,
"e": 4518,
"s": 4392,
"text": "Algorithms halt in a finite amount of time. Algorithms should not run for infinity, i.e., an algorithm must end at some point"
},
{
"code": null,
"e": 4644,
"s": 4518,
"text": "Algorithms halt in a finite amount of time. Algorithms should not run for infinity, i.e., an algorithm must end at some point"
},
{
"code": null,
"e": 4834,
"s": 4644,
"text": "Pseudocode gives a high-level description of an algorithm without the ambiguity associated with plain text but also without the need to know the syntax of a particular programming language."
},
{
"code": null,
"e": 5002,
"s": 4834,
"text": "The running time can be estimated in a more general manner by using Pseudocode to represent the algorithm as a set of fundamental operations which can then be counted."
},
{
"code": null,
"e": 5286,
"s": 5002,
"text": "An algorithm is a formal definition with some specific characteristics that describes a process, which could be executed by a Turing-complete computer machine to perform a specific task. Generally, the word \"algorithm\" can be used to describe any high level task in computer science."
},
{
"code": null,
"e": 5605,
"s": 5286,
"text": "On the other hand, pseudocode is an informal and (often rudimentary) human readable description of an algorithm leaving many granular details of it. Writing a pseudocode has no restriction of styles and its only objective is to describe the high level steps of algorithm in a much realistic manner in natural language."
},
{
"code": null,
"e": 5664,
"s": 5605,
"text": "For example, following is an algorithm for Insertion Sort."
},
{
"code": null,
"e": 6033,
"s": 5664,
"text": "Algorithm: Insertion-Sort \nInput: A list L of integers of length n \nOutput: A sorted list L1 containing those integers present in L \nStep 1: Keep a sorted list L1 which starts off empty \nStep 2: Perform Step 3 for each element in the original list L \nStep 3: Insert it into the correct position in the sorted list L1. \nStep 4: Return the sorted list \nStep 5: Stop\n"
},
{
"code": null,
"e": 6198,
"s": 6033,
"text": "Here is a pseudocode which describes how the high level abstract process mentioned above in the algorithm Insertion-Sort could be described in a more realistic way."
},
{
"code": null,
"e": 6333,
"s": 6198,
"text": "for i <- 1 to length(A) \n x <- A[i] \n j <- i \n while j > 0 and A[j-1] > x \n A[j] <- A[j-1] \n j <- j - 1 \n A[j] <- x\n"
},
{
"code": null,
"e": 6498,
"s": 6333,
"text": "In this tutorial, algorithms will be presented in the form of pseudocode, that is similar in many respects to C, C++, Java, Python, and other programming languages."
},
{
"code": null,
"e": 6533,
"s": 6498,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6552,
"s": 6533,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6585,
"s": 6552,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6604,
"s": 6585,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6637,
"s": 6604,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6656,
"s": 6637,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6691,
"s": 6656,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6704,
"s": 6691,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 6736,
"s": 6704,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6749,
"s": 6736,
"text": " Zach Miller"
},
{
"code": null,
"e": 6782,
"s": 6749,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6796,
"s": 6782,
"text": " Sasha Miller"
},
{
"code": null,
"e": 6803,
"s": 6796,
"text": " Print"
},
{
"code": null,
"e": 6814,
"s": 6803,
"text": " Add Notes"
}
] |
Difference between the | and || or operator in php | '|' operator is a bitwise OR operator and is used to set the bit to 1 if any of the corresponding bit is 1.
'||' is a logical Or operator and works on complete operands as whole.
Following example, shows usage of '|' vs '||' operators.
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<?php
$x = 1; // 0001
$y = 2; // 0010
print('$x | $y = ');
echo $x | $y;
print("<br/>");
print('$x || $y = ');
echo $x || $y;
?>
</body>
</html>
$x | $y = 3
$x || $y = 1 | [
{
"code": null,
"e": 1170,
"s": 1062,
"text": "'|' operator is a bitwise OR operator and is used to set the bit to 1 if any of the corresponding bit is 1."
},
{
"code": null,
"e": 1241,
"s": 1170,
"text": "'||' is a logical Or operator and works on complete operands as whole."
},
{
"code": null,
"e": 1298,
"s": 1241,
"text": "Following example, shows usage of '|' vs '||' operators."
},
{
"code": null,
"e": 1309,
"s": 1298,
"text": " Live Demo"
},
{
"code": null,
"e": 1578,
"s": 1309,
"text": "<!DOCTYPE html>\n<html>\n<head>\n <title>PHP Example</title>\n</head>\n<body>\n <?php\n $x = 1; // 0001\n $y = 2; // 0010\n\n print('$x | $y = ');\n echo $x | $y;\n print(\"<br/>\");\n print('$x || $y = ');\n echo $x || $y;\n ?>\n</body>\n</html>"
},
{
"code": null,
"e": 1603,
"s": 1578,
"text": "$x | $y = 3\n$x || $y = 1"
}
] |
C# | ToLower() Method - GeeksforGeeks | 31 Jan, 2019
In C#, ToLower() is a string method. It converts every character to lowercase (if there is a lowercase character). If a character does not have a lowercase equivalent, it remains unchanged. For example, special symbols remain unchanged. This method can be overloaded by passing the different type of arguments to it.
String.ToLower() Method
String.ToLower(CultureInfo) Method
This method is used to return a copy of the current string converted to lowercase.
Syntax:
public string ToLower ();
Return Type: It return the string value, which is the lowercase equivalent of the string of type System.String.
Example:
Input : str = "GeeksForGeeks"
str.ToLower()
Output: geeksforgeeks
Input : str = "This is C# Program xsdD_$#%"
str.ToLower()
Output: this is c# program xsdd_$#%
Below Programs illustrate the use ToLower() Method:
Example 1:// C# program to desmonstrate the // use of ToLower() method using System; class Program { // Main Method public static void Main() { // original string string str1 = "GeeksForGeeks"; // string converted to lower case string lowerstr1 = str1.ToLower(); Console.WriteLine(lowerstr1); }}Output:geeksforgeeks
// C# program to desmonstrate the // use of ToLower() method using System; class Program { // Main Method public static void Main() { // original string string str1 = "GeeksForGeeks"; // string converted to lower case string lowerstr1 = str1.ToLower(); Console.WriteLine(lowerstr1); }}
Output:
geeksforgeeks
Example 2:// C# program to desmonstrate the // use of ToLower() method using System; class Program { // Main Method public static void Main() { // original string containing the special // symbol. Here special symbol will remain // unchange string str2 = "This is C# Program xsdD_$#%"; // string converted to lower case string lowerstr2 = str2.ToLower(); Console.WriteLine(lowerstr2); }}Output:this is c# program xsdd_$#%
// C# program to desmonstrate the // use of ToLower() method using System; class Program { // Main Method public static void Main() { // original string containing the special // symbol. Here special symbol will remain // unchange string str2 = "This is C# Program xsdD_$#%"; // string converted to lower case string lowerstr2 = str2.ToLower(); Console.WriteLine(lowerstr2); }}
Output:
this is c# program xsdd_$#%
This method is used to return a copy of the current string converted to lowercase, using the casing rules of the specified culture.
Syntax:
public string ToLower (System.Globalization.CultureInfo culture);
Parameter:
culture: It is the required object which supplies culture-specific casing rules.
Return Type: This method returns the lowercase equivalent of the current string of type System.String.
Exception: This method can give ArgumentNullException if the value of culture is null.
Example:
// C# program to desmonstrate the // use of ToLower(CultureInfo) method using System;using System.Globalization; class Program { // Main Method public static void Main() { // original string string str2 = "THIS IS C# PROGRAM XSDD_$#%"; // string converted to lowercase by // using English-United States culture string lowerstr2 = str2.ToLower(new CultureInfo("en-US", false)); Console.WriteLine(lowerstr2); }}
Output:
this is c# program xsdd_$#%
Note: These methods will not modify the value of the current instance. Instead, returns a new string in which all characters in the current instance will convert to lowercase.
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.tolower?view=netframework-4.7.2
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Method Overriding
C# Dictionary with examples
C# | Delegates
Difference between Ref and Out keywords in C#
Destructors in C#
Extension Method in C#
C# | Constructors
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object | [
{
"code": null,
"e": 24436,
"s": 24408,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 24753,
"s": 24436,
"text": "In C#, ToLower() is a string method. It converts every character to lowercase (if there is a lowercase character). If a character does not have a lowercase equivalent, it remains unchanged. For example, special symbols remain unchanged. This method can be overloaded by passing the different type of arguments to it."
},
{
"code": null,
"e": 24777,
"s": 24753,
"text": "String.ToLower() Method"
},
{
"code": null,
"e": 24812,
"s": 24777,
"text": "String.ToLower(CultureInfo) Method"
},
{
"code": null,
"e": 24895,
"s": 24812,
"text": "This method is used to return a copy of the current string converted to lowercase."
},
{
"code": null,
"e": 24903,
"s": 24895,
"text": "Syntax:"
},
{
"code": null,
"e": 24930,
"s": 24903,
"text": "public string ToLower ();\n"
},
{
"code": null,
"e": 25042,
"s": 24930,
"text": "Return Type: It return the string value, which is the lowercase equivalent of the string of type System.String."
},
{
"code": null,
"e": 25051,
"s": 25042,
"text": "Example:"
},
{
"code": null,
"e": 25231,
"s": 25051,
"text": "Input : str = \"GeeksForGeeks\"\n str.ToLower()\nOutput: geeksforgeeks\n\nInput : str = \"This is C# Program xsdD_$#%\"\n str.ToLower()\nOutput: this is c# program xsdd_$#%\n"
},
{
"code": null,
"e": 25283,
"s": 25231,
"text": "Below Programs illustrate the use ToLower() Method:"
},
{
"code": null,
"e": 25656,
"s": 25283,
"text": "Example 1:// C# program to desmonstrate the // use of ToLower() method using System; class Program { // Main Method public static void Main() { // original string string str1 = \"GeeksForGeeks\"; // string converted to lower case string lowerstr1 = str1.ToLower(); Console.WriteLine(lowerstr1); }}Output:geeksforgeeks\n"
},
{
"code": "// C# program to desmonstrate the // use of ToLower() method using System; class Program { // Main Method public static void Main() { // original string string str1 = \"GeeksForGeeks\"; // string converted to lower case string lowerstr1 = str1.ToLower(); Console.WriteLine(lowerstr1); }}",
"e": 25998,
"s": 25656,
"text": null
},
{
"code": null,
"e": 26006,
"s": 25998,
"text": "Output:"
},
{
"code": null,
"e": 26021,
"s": 26006,
"text": "geeksforgeeks\n"
},
{
"code": null,
"e": 26515,
"s": 26021,
"text": "Example 2:// C# program to desmonstrate the // use of ToLower() method using System; class Program { // Main Method public static void Main() { // original string containing the special // symbol. Here special symbol will remain // unchange string str2 = \"This is C# Program xsdD_$#%\"; // string converted to lower case string lowerstr2 = str2.ToLower(); Console.WriteLine(lowerstr2); }}Output:this is c# program xsdd_$#%\n"
},
{
"code": "// C# program to desmonstrate the // use of ToLower() method using System; class Program { // Main Method public static void Main() { // original string containing the special // symbol. Here special symbol will remain // unchange string str2 = \"This is C# Program xsdD_$#%\"; // string converted to lower case string lowerstr2 = str2.ToLower(); Console.WriteLine(lowerstr2); }}",
"e": 26964,
"s": 26515,
"text": null
},
{
"code": null,
"e": 26972,
"s": 26964,
"text": "Output:"
},
{
"code": null,
"e": 27001,
"s": 26972,
"text": "this is c# program xsdd_$#%\n"
},
{
"code": null,
"e": 27133,
"s": 27001,
"text": "This method is used to return a copy of the current string converted to lowercase, using the casing rules of the specified culture."
},
{
"code": null,
"e": 27141,
"s": 27133,
"text": "Syntax:"
},
{
"code": null,
"e": 27208,
"s": 27141,
"text": "public string ToLower (System.Globalization.CultureInfo culture);\n"
},
{
"code": null,
"e": 27219,
"s": 27208,
"text": "Parameter:"
},
{
"code": null,
"e": 27300,
"s": 27219,
"text": "culture: It is the required object which supplies culture-specific casing rules."
},
{
"code": null,
"e": 27403,
"s": 27300,
"text": "Return Type: This method returns the lowercase equivalent of the current string of type System.String."
},
{
"code": null,
"e": 27490,
"s": 27403,
"text": "Exception: This method can give ArgumentNullException if the value of culture is null."
},
{
"code": null,
"e": 27499,
"s": 27490,
"text": "Example:"
},
{
"code": "// C# program to desmonstrate the // use of ToLower(CultureInfo) method using System;using System.Globalization; class Program { // Main Method public static void Main() { // original string string str2 = \"THIS IS C# PROGRAM XSDD_$#%\"; // string converted to lowercase by // using English-United States culture string lowerstr2 = str2.ToLower(new CultureInfo(\"en-US\", false)); Console.WriteLine(lowerstr2); }}",
"e": 27970,
"s": 27499,
"text": null
},
{
"code": null,
"e": 27978,
"s": 27970,
"text": "Output:"
},
{
"code": null,
"e": 28007,
"s": 27978,
"text": "this is c# program xsdd_$#%\n"
},
{
"code": null,
"e": 28183,
"s": 28007,
"text": "Note: These methods will not modify the value of the current instance. Instead, returns a new string in which all characters in the current instance will convert to lowercase."
},
{
"code": null,
"e": 28284,
"s": 28183,
"text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.tolower?view=netframework-4.7.2"
},
{
"code": null,
"e": 28298,
"s": 28284,
"text": "CSharp-method"
},
{
"code": null,
"e": 28312,
"s": 28298,
"text": "CSharp-string"
},
{
"code": null,
"e": 28315,
"s": 28312,
"text": "C#"
},
{
"code": null,
"e": 28413,
"s": 28315,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28436,
"s": 28413,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28464,
"s": 28436,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28479,
"s": 28464,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28525,
"s": 28479,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28543,
"s": 28525,
"text": "Destructors in C#"
},
{
"code": null,
"e": 28566,
"s": 28543,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28584,
"s": 28566,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28615,
"s": 28584,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28637,
"s": 28615,
"text": "C# | Abstract Classes"
}
] |
MySQL - AVG Function | MySQL AVG function is used to find out the average of a field in various records.
To understand AVG function, consider an employee_tbl table, which is having following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, suppose based on the above table you want to calculate average of all the dialy_typing_pages, then you can do so by using the following command −
mysql> SELECT AVG(daily_typing_pages)
-> FROM employee_tbl;
+-------------------------+
| AVG(daily_typing_pages) |
+-------------------------+
| 230.0000 |
+-------------------------+
1 row in set (0.03 sec)
You can take average of various records set using GROUP BY clause. Following example will take average all the records related to a single person and you will have average typed pages by every person.
mysql> SELECT name, AVG(daily_typing_pages)
-> FROM employee_tbl GROUP BY name;
+------+-------------------------+
| name | AVG(daily_typing_pages) |
+------+-------------------------+
| Jack | 135.0000 |
| Jill | 220.0000 |
| John | 250.0000 |
| Ram | 220.0000 |
| Zara | 325.0000 |
+------+-------------------------+
5 rows in set (0.20 sec)
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2415,
"s": 2333,
"text": "MySQL AVG function is used to find out the average of a field in various records."
},
{
"code": null,
"e": 2511,
"s": 2415,
"text": "To understand AVG function, consider an employee_tbl table, which is having following records −"
},
{
"code": null,
"e": 3121,
"s": 2511,
"text": "mysql> SELECT * FROM employee_tbl;\n+------+------+------------+--------------------+\n| id | name | work_date | daily_typing_pages |\n+------+------+------------+--------------------+\n| 1 | John | 2007-01-24 | 250 |\n| 2 | Ram | 2007-05-27 | 220 |\n| 3 | Jack | 2007-05-06 | 170 |\n| 3 | Jack | 2007-04-06 | 100 |\n| 4 | Jill | 2007-04-06 | 220 |\n| 5 | Zara | 2007-06-06 | 300 |\n| 5 | Zara | 2007-02-06 | 350 |\n+------+------+------------+--------------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3272,
"s": 3121,
"text": "Now, suppose based on the above table you want to calculate average of all the dialy_typing_pages, then you can do so by using the following command −"
},
{
"code": null,
"e": 3499,
"s": 3272,
"text": "mysql> SELECT AVG(daily_typing_pages)\n -> FROM employee_tbl;\n+-------------------------+\n| AVG(daily_typing_pages) |\n+-------------------------+\n| 230.0000 |\n+-------------------------+\n1 row in set (0.03 sec)"
},
{
"code": null,
"e": 3700,
"s": 3499,
"text": "You can take average of various records set using GROUP BY clause. Following example will take average all the records related to a single person and you will have average typed pages by every person."
},
{
"code": null,
"e": 4123,
"s": 3700,
"text": "mysql> SELECT name, AVG(daily_typing_pages)\n -> FROM employee_tbl GROUP BY name;\n+------+-------------------------+\n| name | AVG(daily_typing_pages) |\n+------+-------------------------+\n| Jack | 135.0000 |\n| Jill | 220.0000 |\n| John | 250.0000 |\n| Ram | 220.0000 |\n| Zara | 325.0000 |\n+------+-------------------------+\n5 rows in set (0.20 sec)"
},
{
"code": null,
"e": 4156,
"s": 4123,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4184,
"s": 4156,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4219,
"s": 4184,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4236,
"s": 4219,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4270,
"s": 4236,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4305,
"s": 4270,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 4339,
"s": 4305,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4367,
"s": 4339,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4400,
"s": 4367,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4420,
"s": 4400,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4453,
"s": 4420,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4471,
"s": 4453,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 4478,
"s": 4471,
"text": " Print"
},
{
"code": null,
"e": 4489,
"s": 4478,
"text": " Add Notes"
}
] |
Different ways to update Python list - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
There are several ways to update the List in Python, let’s see them.
Python list provides the following methods to modify the data.
list.append(value) # Append a value
list.extend(iterable) # Append a series of values
list.insert(index, value) # At index, insert value
list.remove(value) # Remove first instance of value
list.clear() # Remove all elements
If you like to add a single element to the python list then list.append(value) is the best fit for you. The list.append(value) always adds the value to the end of existing list.
a_list = [1, 2, 3, 4]
a_list.append(5)
print(a_list)
Output:
[1, 2, 3, 4, 5]
The append and extend methods have a similar purpose: to add data to the end of a list. The difference is that the append method adds a single element to the end of the list, whereas the extend method appends a series of elements from a collection or iterable.
a_list = [1, 2, 3, 4]
a_list.extend([5, 6, 7])
print(a_list)
Output:
[1, 2, 3, 4, 5, 6, 7]
The insert() method similar to the append() method, however insert method inserts the value at the given index position, where as append() always add the element at the end of the list.
a_list = [10, 20, 40]
a_list.insert(2, 30 ) # At index 2, insert 30.
print(a_list)
Output:
[10, 20, 30, 40]
If the provided index out of range, then the insert() method adds the new value at the end of the list, and it inserts the new value to the beginning of the list if the given index is too low.
a_list = [10, 20, 30]
a_list.insert(100, 40)
print(a_list)
a_list.insert(-50, 1)
print(a_list)
Output:
[10, 20, 30, 40]
[1, 10, 20, 30, 40]
The remove(value) method removes the first occurrence of the given value from the list. There must be one occurrence of the provided value, otherwise the Python raises ValueError.
a_list = [1, 2, 3, 4, 5, 4]
a_list.remove(4)
print(a_list)
Output:
[1, 2, 3, 5, 4]
Removing min and max values from the list.
a_list = [1, 2, 3, 4, 5, 4, 7, 9 , -1]
a_list.remove(max(a_list)) # removed the max element from the list
a_list.remove(min(a_list)) # removed the min element from the list
print(a_list)
Output:
[1, 2, 3, 4, 5, 4, 7]
The clear() method used to remove all the elements from the list. The same we can also do with del list[:]
a_list = [10, 20, 30, 40]
a_list.clear()
print(a_list)
Output:
[]
Python List Data structure in Depth
More on Python list methods
Happy Learning 🙂
Python List Data Structure In Depth
Python – How to remove duplicate elements from List
How to remove empty lists from a Python List
Different ways to use Lambdas in Python
How to clear all elements from List in Python
Different ways to do String formatting in Python
Python List comprehension usage and advantages
Implementing Stack in Python
What are the different ways to Sort Objects in Python ?
How to Remove Spaces from String in Python
How to access for loop index in Python
Ways to create constructors In Python
How to Create or Delete Directories in Python ?
How to Convert Python List Of Objects to CSV File
Python – Update Records in MySQL Data Database
Python List Data Structure In Depth
Python – How to remove duplicate elements from List
How to remove empty lists from a Python List
Different ways to use Lambdas in Python
How to clear all elements from List in Python
Different ways to do String formatting in Python
Python List comprehension usage and advantages
Implementing Stack in Python
What are the different ways to Sort Objects in Python ?
How to Remove Spaces from String in Python
How to access for loop index in Python
Ways to create constructors In Python
How to Create or Delete Directories in Python ?
How to Convert Python List Of Objects to CSV File
Python – Update Records in MySQL Data Database
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 467,
"s": 398,
"text": "There are several ways to update the List in Python, let’s see them."
},
{
"code": null,
"e": 530,
"s": 467,
"text": "Python list provides the following methods to modify the data."
},
{
"code": null,
"e": 566,
"s": 530,
"text": "list.append(value) # Append a value"
},
{
"code": null,
"e": 616,
"s": 566,
"text": "list.extend(iterable) # Append a series of values"
},
{
"code": null,
"e": 667,
"s": 616,
"text": "list.insert(index, value) # At index, insert value"
},
{
"code": null,
"e": 719,
"s": 667,
"text": "list.remove(value) # Remove first instance of value"
},
{
"code": null,
"e": 754,
"s": 719,
"text": "list.clear() # Remove all elements"
},
{
"code": null,
"e": 932,
"s": 754,
"text": "If you like to add a single element to the python list then list.append(value) is the best fit for you. The list.append(value) always adds the value to the end of existing list."
},
{
"code": null,
"e": 987,
"s": 932,
"text": "a_list = [1, 2, 3, 4]\n\na_list.append(5)\n\nprint(a_list)"
},
{
"code": null,
"e": 995,
"s": 987,
"text": "Output:"
},
{
"code": null,
"e": 1011,
"s": 995,
"text": "[1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 1272,
"s": 1011,
"text": "The append and extend methods have a similar purpose: to add data to the end of a list. The difference is that the append method adds a single element to the end of the list, whereas the extend method appends a series of elements from a collection or iterable."
},
{
"code": null,
"e": 1335,
"s": 1272,
"text": "a_list = [1, 2, 3, 4]\n\na_list.extend([5, 6, 7])\n\nprint(a_list)"
},
{
"code": null,
"e": 1343,
"s": 1335,
"text": "Output:"
},
{
"code": null,
"e": 1365,
"s": 1343,
"text": "[1, 2, 3, 4, 5, 6, 7]"
},
{
"code": null,
"e": 1551,
"s": 1365,
"text": "The insert() method similar to the append() method, however insert method inserts the value at the given index position, where as append() always add the element at the end of the list."
},
{
"code": null,
"e": 1637,
"s": 1551,
"text": "a_list = [10, 20, 40] \na_list.insert(2, 30 ) # At index 2, insert 30.\n\nprint(a_list)"
},
{
"code": null,
"e": 1645,
"s": 1637,
"text": "Output:"
},
{
"code": null,
"e": 1662,
"s": 1645,
"text": "[10, 20, 30, 40]"
},
{
"code": null,
"e": 1855,
"s": 1662,
"text": "If the provided index out of range, then the insert() method adds the new value at the end of the list, and it inserts the new value to the beginning of the list if the given index is too low."
},
{
"code": null,
"e": 1950,
"s": 1855,
"text": "a_list = [10, 20, 30]\na_list.insert(100, 40)\nprint(a_list)\na_list.insert(-50, 1)\nprint(a_list)"
},
{
"code": null,
"e": 1958,
"s": 1950,
"text": "Output:"
},
{
"code": null,
"e": 1997,
"s": 1958,
"text": "[10, 20, 30, 40] \n\n[1, 10, 20, 30, 40]"
},
{
"code": null,
"e": 2177,
"s": 1997,
"text": "The remove(value) method removes the first occurrence of the given value from the list. There must be one occurrence of the provided value, otherwise the Python raises ValueError."
},
{
"code": null,
"e": 2239,
"s": 2177,
"text": "a_list = [1, 2, 3, 4, 5, 4] \n\na_list.remove(4)\n\nprint(a_list)"
},
{
"code": null,
"e": 2247,
"s": 2239,
"text": "Output:"
},
{
"code": null,
"e": 2263,
"s": 2247,
"text": "[1, 2, 3, 5, 4]"
},
{
"code": null,
"e": 2306,
"s": 2263,
"text": "Removing min and max values from the list."
},
{
"code": null,
"e": 2496,
"s": 2306,
"text": "a_list = [1, 2, 3, 4, 5, 4, 7, 9 , -1] \n\na_list.remove(max(a_list)) # removed the max element from the list\na_list.remove(min(a_list)) # removed the min element from the list\n\nprint(a_list)"
},
{
"code": null,
"e": 2504,
"s": 2496,
"text": "Output:"
},
{
"code": null,
"e": 2526,
"s": 2504,
"text": "[1, 2, 3, 4, 5, 4, 7]"
},
{
"code": null,
"e": 2633,
"s": 2526,
"text": "The clear() method used to remove all the elements from the list. The same we can also do with del list[:]"
},
{
"code": null,
"e": 2690,
"s": 2633,
"text": "a_list = [10, 20, 30, 40]\n\na_list.clear()\n\nprint(a_list)"
},
{
"code": null,
"e": 2698,
"s": 2690,
"text": "Output:"
},
{
"code": null,
"e": 2701,
"s": 2698,
"text": "[]"
},
{
"code": null,
"e": 2737,
"s": 2701,
"text": "Python List Data structure in Depth"
},
{
"code": null,
"e": 2765,
"s": 2737,
"text": "More on Python list methods"
},
{
"code": null,
"e": 2782,
"s": 2765,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 3449,
"s": 2782,
"text": "\nPython List Data Structure In Depth\nPython – How to remove duplicate elements from List\nHow to remove empty lists from a Python List\nDifferent ways to use Lambdas in Python\nHow to clear all elements from List in Python\nDifferent ways to do String formatting in Python\nPython List comprehension usage and advantages\nImplementing Stack in Python\nWhat are the different ways to Sort Objects in Python ?\nHow to Remove Spaces from String in Python\nHow to access for loop index in Python\nWays to create constructors In Python\nHow to Create or Delete Directories in Python ?\nHow to Convert Python List Of Objects to CSV File\nPython – Update Records in MySQL Data Database\n"
},
{
"code": null,
"e": 3485,
"s": 3449,
"text": "Python List Data Structure In Depth"
},
{
"code": null,
"e": 3537,
"s": 3485,
"text": "Python – How to remove duplicate elements from List"
},
{
"code": null,
"e": 3582,
"s": 3537,
"text": "How to remove empty lists from a Python List"
},
{
"code": null,
"e": 3622,
"s": 3582,
"text": "Different ways to use Lambdas in Python"
},
{
"code": null,
"e": 3668,
"s": 3622,
"text": "How to clear all elements from List in Python"
},
{
"code": null,
"e": 3717,
"s": 3668,
"text": "Different ways to do String formatting in Python"
},
{
"code": null,
"e": 3764,
"s": 3717,
"text": "Python List comprehension usage and advantages"
},
{
"code": null,
"e": 3793,
"s": 3764,
"text": "Implementing Stack in Python"
},
{
"code": null,
"e": 3849,
"s": 3793,
"text": "What are the different ways to Sort Objects in Python ?"
},
{
"code": null,
"e": 3892,
"s": 3849,
"text": "How to Remove Spaces from String in Python"
},
{
"code": null,
"e": 3931,
"s": 3892,
"text": "How to access for loop index in Python"
},
{
"code": null,
"e": 3969,
"s": 3931,
"text": "Ways to create constructors In Python"
},
{
"code": null,
"e": 4017,
"s": 3969,
"text": "How to Create or Delete Directories in Python ?"
},
{
"code": null,
"e": 4067,
"s": 4017,
"text": "How to Convert Python List Of Objects to CSV File"
},
{
"code": null,
"e": 4114,
"s": 4067,
"text": "Python – Update Records in MySQL Data Database"
},
{
"code": null,
"e": 4120,
"s": 4118,
"text": "Δ"
},
{
"code": null,
"e": 4143,
"s": 4120,
"text": " Python – Introduction"
},
{
"code": null,
"e": 4162,
"s": 4143,
"text": " Python – Features"
},
{
"code": null,
"e": 4191,
"s": 4162,
"text": " Python – Install on Windows"
},
{
"code": null,
"e": 4218,
"s": 4191,
"text": " Python – Modes of Program"
},
{
"code": null,
"e": 4242,
"s": 4218,
"text": " Python – Number System"
},
{
"code": null,
"e": 4264,
"s": 4242,
"text": " Python – Identifiers"
},
{
"code": null,
"e": 4284,
"s": 4264,
"text": " Python – Operators"
},
{
"code": null,
"e": 4311,
"s": 4284,
"text": " Python – Ternary Operator"
},
{
"code": null,
"e": 4344,
"s": 4311,
"text": " Python – Command Line Arguments"
},
{
"code": null,
"e": 4363,
"s": 4344,
"text": " Python – Keywords"
},
{
"code": null,
"e": 4384,
"s": 4363,
"text": " Python – Data Types"
},
{
"code": null,
"e": 4413,
"s": 4384,
"text": " Python – Upgrade Python PIP"
},
{
"code": null,
"e": 4443,
"s": 4413,
"text": " Python – Virtual Environment"
},
{
"code": null,
"e": 4466,
"s": 4443,
"text": " Pyhton – Type Casting"
},
{
"code": null,
"e": 4490,
"s": 4466,
"text": " Python – String to Int"
},
{
"code": null,
"e": 4523,
"s": 4490,
"text": " Python – Conditional Statements"
},
{
"code": null,
"e": 4546,
"s": 4523,
"text": " Python – if statement"
},
{
"code": null,
"e": 4575,
"s": 4546,
"text": " Python – *args and **kwargs"
},
{
"code": null,
"e": 4601,
"s": 4575,
"text": " Python – Date Formatting"
},
{
"code": null,
"e": 4636,
"s": 4601,
"text": " Python – Read input from keyboard"
},
{
"code": null,
"e": 4656,
"s": 4636,
"text": " Python – raw_input"
},
{
"code": null,
"e": 4680,
"s": 4656,
"text": " Python – List In Depth"
},
{
"code": null,
"e": 4709,
"s": 4680,
"text": " Python – List Comprehension"
},
{
"code": null,
"e": 4732,
"s": 4709,
"text": " Python – Set in Depth"
},
{
"code": null,
"e": 4762,
"s": 4732,
"text": " Python – Dictionary in Depth"
},
{
"code": null,
"e": 4787,
"s": 4762,
"text": " Python – Tuple in Depth"
},
{
"code": null,
"e": 4817,
"s": 4787,
"text": " Python – Stack Datastructure"
},
{
"code": null,
"e": 4847,
"s": 4817,
"text": " Python – Classes and Objects"
},
{
"code": null,
"e": 4870,
"s": 4847,
"text": " Python – Constructors"
},
{
"code": null,
"e": 4901,
"s": 4870,
"text": " Python – Object Introspection"
},
{
"code": null,
"e": 4923,
"s": 4901,
"text": " Python – Inheritance"
},
{
"code": null,
"e": 4944,
"s": 4923,
"text": " Python – Decorators"
},
{
"code": null,
"e": 4980,
"s": 4944,
"text": " Python – Serialization with Pickle"
},
{
"code": null,
"e": 5010,
"s": 4980,
"text": " Python – Exceptions Handling"
},
{
"code": null,
"e": 5044,
"s": 5010,
"text": " Python – User defined Exceptions"
},
{
"code": null,
"e": 5070,
"s": 5044,
"text": " Python – Multiprocessing"
},
{
"code": null,
"e": 5108,
"s": 5070,
"text": " Python – Default function parameters"
},
{
"code": null,
"e": 5136,
"s": 5108,
"text": " Python – Lambdas Functions"
},
{
"code": null,
"e": 5160,
"s": 5136,
"text": " Python – NumPy Library"
},
{
"code": null,
"e": 5186,
"s": 5160,
"text": " Python – MySQL Connector"
},
{
"code": null,
"e": 5218,
"s": 5186,
"text": " Python – MySQL Create Database"
},
{
"code": null,
"e": 5244,
"s": 5218,
"text": " Python – MySQL Read Data"
},
{
"code": null,
"e": 5272,
"s": 5244,
"text": " Python – MySQL Insert Data"
},
{
"code": null,
"e": 5303,
"s": 5272,
"text": " Python – MySQL Update Records"
},
{
"code": null,
"e": 5334,
"s": 5303,
"text": " Python – MySQL Delete Records"
},
{
"code": null,
"e": 5367,
"s": 5334,
"text": " Python – String Case Conversion"
},
{
"code": null,
"e": 5402,
"s": 5367,
"text": " Howto – Find biggest of 2 numbers"
},
{
"code": null,
"e": 5439,
"s": 5402,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 5477,
"s": 5439,
"text": " Howto – Convert any Number to Binary"
},
{
"code": null,
"e": 5503,
"s": 5477,
"text": " Howto – Merge two Lists"
},
{
"code": null,
"e": 5528,
"s": 5503,
"text": " Howto – Merge two dicts"
},
{
"code": null,
"e": 5568,
"s": 5528,
"text": " Howto – Get Characters Count in a File"
},
{
"code": null,
"e": 5603,
"s": 5568,
"text": " Howto – Get Words Count in a File"
},
{
"code": null,
"e": 5638,
"s": 5603,
"text": " Howto – Remove Spaces from String"
},
{
"code": null,
"e": 5667,
"s": 5638,
"text": " Howto – Read Env variables"
},
{
"code": null,
"e": 5693,
"s": 5667,
"text": " Howto – Read a text File"
},
{
"code": null,
"e": 5719,
"s": 5693,
"text": " Howto – Read a JSON File"
},
{
"code": null,
"e": 5751,
"s": 5719,
"text": " Howto – Read Config.ini files"
},
{
"code": null,
"e": 5779,
"s": 5751,
"text": " Howto – Iterate Dictionary"
},
{
"code": null,
"e": 5819,
"s": 5779,
"text": " Howto – Convert List Of Objects to CSV"
},
{
"code": null,
"e": 5853,
"s": 5819,
"text": " Howto – Merge two dict in Python"
},
{
"code": null,
"e": 5878,
"s": 5853,
"text": " Howto – create Zip File"
},
{
"code": null,
"e": 5899,
"s": 5878,
"text": " Howto – Get OS info"
},
{
"code": null,
"e": 5930,
"s": 5899,
"text": " Howto – Get size of Directory"
},
{
"code": null,
"e": 5967,
"s": 5930,
"text": " Howto – Check whether a file exists"
},
{
"code": null,
"e": 6004,
"s": 5967,
"text": " Howto – Remove key from dictionary"
},
{
"code": null,
"e": 6026,
"s": 6004,
"text": " Howto – Sort Objects"
},
{
"code": null,
"e": 6064,
"s": 6026,
"text": " Howto – Create or Delete Directories"
},
{
"code": null,
"e": 6087,
"s": 6064,
"text": " Howto – Read CSV File"
},
{
"code": null,
"e": 6125,
"s": 6087,
"text": " Howto – Create Python Iterable class"
},
{
"code": null,
"e": 6156,
"s": 6125,
"text": " Howto – Access for loop index"
},
{
"code": null,
"e": 6194,
"s": 6156,
"text": " Howto – Clear all elements from List"
},
{
"code": null,
"e": 6234,
"s": 6194,
"text": " Howto – Remove empty lists from a List"
},
{
"code": null,
"e": 6281,
"s": 6234,
"text": " Howto – Remove special characters from String"
},
{
"code": null,
"e": 6313,
"s": 6281,
"text": " Howto – Sort dictionary by key"
}
] |
Create gradient translucent windows in Java Swing | With JDK 7, we can create a gradient based translucent window using swing very easily. Following are the steps needed to make a gradient-based translucent window.
Make the background of JFrame transparent first.
frame.setBackground(new Color(0,0,0,0));
Create a gradient paint, and fill the panel.
JPanel panel = new javax.swing.JPanel() {
protected void paintComponent(Graphics g) {
Paint p = new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),
getWidth(), getHeight(), new Color(R, G, B, 255), true);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(p);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
Assign the panel as a content pane to the frame.
frame.setContentPane(panel);
See the example below of a window with gradient-based translucency.
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Paint;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UnsupportedLookAndFeelException;
public class Tester {
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, UnsupportedLookAndFeelException {
JFrame.setDefaultLookAndFeelDecorated(true);
// Create the GUI on the event-dispatching thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createWindow();
}
});
}
private static void createWindow() {
JFrame frame = new JFrame("Translucent Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setVisible(true);
}
private static void createUI(JFrame frame){
frame.setLayout(new GridBagLayout());
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setBackground(new Color(0,0,0,0));
JPanel panel = new javax.swing.JPanel() {
protected void paintComponent(Graphics g) {
if (g instanceof Graphics2D) {
final int R = 100;
final int G = 100;
final int B = 100;
Paint p =
new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),
getWidth(), getHeight(), new Color(R, G, B, 255), true);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(p);
g2d.fillRect(0, 0, getWidth(), getHeight());
} else {
super.paintComponent(g);
}
}
};
panel.setLayout(new GridBagLayout());
panel.add(new JButton("Hello World"));
frame.setContentPane(panel);
}
} | [
{
"code": null,
"e": 1225,
"s": 1062,
"text": "With JDK 7, we can create a gradient based translucent window using swing very easily. Following are the steps needed to make a gradient-based translucent window."
},
{
"code": null,
"e": 1275,
"s": 1225,
"text": " Make the background of JFrame transparent first."
},
{
"code": null,
"e": 1316,
"s": 1275,
"text": "frame.setBackground(new Color(0,0,0,0));"
},
{
"code": null,
"e": 1362,
"s": 1316,
"text": " Create a gradient paint, and fill the panel."
},
{
"code": null,
"e": 1703,
"s": 1362,
"text": "JPanel panel = new javax.swing.JPanel() {\n protected void paintComponent(Graphics g) {\n Paint p = new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),\n getWidth(), getHeight(), new Color(R, G, B, 255), true);\n Graphics2D g2d = (Graphics2D)g;\n g2d.setPaint(p);\n g2d.fillRect(0, 0, getWidth(), getHeight());\n }\n}"
},
{
"code": null,
"e": 1753,
"s": 1703,
"text": " Assign the panel as a content pane to the frame."
},
{
"code": null,
"e": 1782,
"s": 1753,
"text": "frame.setContentPane(panel);"
},
{
"code": null,
"e": 1850,
"s": 1782,
"text": "See the example below of a window with gradient-based translucency."
},
{
"code": null,
"e": 3933,
"s": 1850,
"text": "import java.awt.Color;\nimport java.awt.GradientPaint;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.GridBagLayout;\nimport java.awt.Paint;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.SwingUtilities;\nimport javax.swing.UnsupportedLookAndFeelException;\n\npublic class Tester {\n public static void main(String[] args) \n throws ClassNotFoundException, InstantiationException, \n IllegalAccessException, UnsupportedLookAndFeelException {\n \n JFrame.setDefaultLookAndFeelDecorated(true);\n // Create the GUI on the event-dispatching thread\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n createWindow(); \n }\n });\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Translucent Window\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n createUI(frame);\n frame.setVisible(true); \n }\n\n private static void createUI(JFrame frame){\n frame.setLayout(new GridBagLayout());\n frame.setSize(200, 200); \n frame.setLocationRelativeTo(null);\n frame.setBackground(new Color(0,0,0,0));\n\n JPanel panel = new javax.swing.JPanel() {\n protected void paintComponent(Graphics g) {\n if (g instanceof Graphics2D) {\n final int R = 100;\n final int G = 100;\n final int B = 100; \n Paint p =\n new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),\n getWidth(), getHeight(), new Color(R, G, B, 255), true);\n Graphics2D g2d = (Graphics2D)g;\n g2d.setPaint(p);\n g2d.fillRect(0, 0, getWidth(), getHeight());\n } else {\n super.paintComponent(g);\n }\n }\n };\n panel.setLayout(new GridBagLayout());\n panel.add(new JButton(\"Hello World\"));\n frame.setContentPane(panel);\n }\n}"
}
] |
Test Environment | Test Environment consists of elements that support test execution with software, hardware and network configured. Test environment configuration must mimic the production environment in order to uncover any environment/configuration related issues.
Determine if test environment needs archiving in order to take back ups.
Determine if test environment needs archiving in order to take back ups.
Verify the network configuration.
Verify the network configuration.
Identify the required server operating system, databases and other components.
Identify the required server operating system, databases and other components.
Identify the number of license required by the test team.
Identify the number of license required by the test team.
It is the combination of hardware and software environment on which the tests will be executed. It includes hardware configuration, operating system settings, software configuration, test terminals and other support to perform the test.
A typical Environmental Configuration for a web-based application is given below:
Web Server - IIS/Apache
Database - MS SQL
OS - Windows/ Linux
Browser - IE/FireFox
Java version : version 6
80 Lectures
7.5 hours
Arnab Chakraborty
10 Lectures
1 hours
Zach Miller
17 Lectures
1.5 hours
Zach Miller
60 Lectures
5 hours
John Shea
99 Lectures
10 hours
Daniel IT
62 Lectures
5 hours
GlobalETraining
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 5994,
"s": 5745,
"text": "Test Environment consists of elements that support test execution with software, hardware and network configured. Test environment configuration must mimic the production environment in order to uncover any environment/configuration related issues."
},
{
"code": null,
"e": 6067,
"s": 5994,
"text": "Determine if test environment needs archiving in order to take back ups."
},
{
"code": null,
"e": 6140,
"s": 6067,
"text": "Determine if test environment needs archiving in order to take back ups."
},
{
"code": null,
"e": 6174,
"s": 6140,
"text": "Verify the network configuration."
},
{
"code": null,
"e": 6208,
"s": 6174,
"text": "Verify the network configuration."
},
{
"code": null,
"e": 6287,
"s": 6208,
"text": "Identify the required server operating system, databases and other components."
},
{
"code": null,
"e": 6366,
"s": 6287,
"text": "Identify the required server operating system, databases and other components."
},
{
"code": null,
"e": 6424,
"s": 6366,
"text": "Identify the number of license required by the test team."
},
{
"code": null,
"e": 6482,
"s": 6424,
"text": "Identify the number of license required by the test team."
},
{
"code": null,
"e": 6719,
"s": 6482,
"text": "It is the combination of hardware and software environment on which the tests will be executed. It includes hardware configuration, operating system settings, software configuration, test terminals and other support to perform the test."
},
{
"code": null,
"e": 6801,
"s": 6719,
"text": "A typical Environmental Configuration for a web-based application is given below:"
},
{
"code": null,
"e": 6909,
"s": 6801,
"text": "Web Server - IIS/Apache\nDatabase - MS SQL\nOS - Windows/ Linux\nBrowser - IE/FireFox\nJava version : version 6"
},
{
"code": null,
"e": 6944,
"s": 6909,
"text": "\n 80 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6963,
"s": 6944,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6996,
"s": 6963,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7009,
"s": 6996,
"text": " Zach Miller"
},
{
"code": null,
"e": 7044,
"s": 7009,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7057,
"s": 7044,
"text": " Zach Miller"
},
{
"code": null,
"e": 7090,
"s": 7057,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7101,
"s": 7090,
"text": " John Shea"
},
{
"code": null,
"e": 7135,
"s": 7101,
"text": "\n 99 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 7146,
"s": 7135,
"text": " Daniel IT"
},
{
"code": null,
"e": 7179,
"s": 7146,
"text": "\n 62 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7196,
"s": 7179,
"text": " GlobalETraining"
},
{
"code": null,
"e": 7203,
"s": 7196,
"text": " Print"
},
{
"code": null,
"e": 7214,
"s": 7203,
"text": " Add Notes"
}
] |
How do I check to see if a column name exists in a CachedRowSet in JDBC? | CachedRowSet interface does not provide any methods to determine whether a particular column exists.
Therefore, to find whether a RowSet contains a specific column, you need to compare the name of each column in the RowSet with the required name. To do so −
Retrieve the ResultSetMetaData object from the RowSet using the getMetaData() method.
ResultSetMetaData meta = rowSet.getMetaData();
Get the number of columns in the RowSet using the getColumnCount() method.
int columnCount = meta.getColumnCount();
The getColumnName() method returns the name of the column of the specified index. Using this method retrieve the column names of the RowSet from index 1 to column count and compare name of the each column, with the required column name.
boolean flag = false;
for (int i = 1; i <=columnCount; i++) {
if(meta.getColumnName(i).equals("ProductName")) {
flag = true;
}
}
Let us create a table with name sales in MySQL database, with one of the columns as auto-incremented, using CREATE statement as shown below −
CREATE TABLE Sales(
ID INT PRIMARY KEY AUTO_INCREMENT,
ProductName VARCHAR (20),
CustomerName VARCHAR (20),
DispatchDate date,
DeliveryTime time,
Price INT,
Location VARCHAR(20)
);
Now, we will insert 5 records in sales table using INSERT statements −
insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'India');
insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');
insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');
insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');
insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');
Following JDBC program establishes connection with the database, retrieves the contents of the Sales table into the RowSet and finds out whether the it contains the column named ProductName.
import java.sql.DriverManager;
import java.sql.ResultSetMetaData;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
public class CachedRowSetExample {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Creating the RowSet object
RowSetFactory factory = RowSetProvider.newFactory();
CachedRowSet rowSet = factory.createCachedRowSet();
//Setting the URL
String mysqlUrl = "jdbc:mysql://localhost/SampleDB";
rowSet.setUrl(mysqlUrl);
//Setting the user name
rowSet.setUsername("root");
//Setting the password
rowSet.setPassword("password");
//Setting the query/command
rowSet.setCommand("select * from Sales");
//Executing the command
rowSet.execute();
//Retrieving the ResultSetMetaData object
ResultSetMetaData meta = rowSet.getMetaData();
int columnCount = meta.getColumnCount();
boolean flag = false;
for (int i = 1; i <=columnCount; i++) {
if(meta.getColumnName(i).equals("ProductName")){
flag = true;
}
}
if(flag) {
System.out.println("Specified column exist");
} else {
System.out.println("Specified column does not exists");
}
System.out.println("Contents of the row set");
while(rowSet.next()) {
System.out.print("ID: "+rowSet.getInt("ID")+", ");
System.out.print("Product Name: "+rowSet.getString("ProductName")+", ");
System.out.print("Customer Name: "+rowSet.getString("CustomerName")+", ");
System.out.print("Dispatch Date: "+rowSet.getDate("DispatchDate")+", ");
System.out.print("Delivery Time: "+rowSet.getTime("DeliveryTime")+", "););
System.out.print("Price: "+rowSet.getString("Price")+", ");
System.out.print("Location: "+rowSet.getString("Location"));
System.out.println("");
}
}
}
Specified column exists
Contents of the row set
ID: 1, Product Name: Key-Board, Customer Name: Raja, Dispatch Date: 2019-09-01, Delivery Time: 05:30:00, Price: 2000, Location: Hyderabad
ID: 2, Product Name: Earphones, Customer Name: Roja, Dispatch Date: 2019-05-01, Delivery Time: 05:30:00, Price: 2000, Location: Vishakhapatnam
ID: 3, Product Name: Mouse, Customer Name: Puja, Dispatch Date: 2019-03-01, Delivery Time: 05:29:59, Price: 3000, Location: Vijayawada
ID: 4, Product Name: Mobile, Customer Name: Vanaja, Dispatch Date: 2019-03-01, Delivery Time: 04:40:52, Price: 9000, Location: Chennai
ID: 5, Product Name: Headset, Customer Name: Jalaja, Dispatch Date: 2019-04-06, Delivery Time: 18:38:59, Price: 6000, Location: Goa | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "CachedRowSet interface does not provide any methods to determine whether a particular column exists."
},
{
"code": null,
"e": 1320,
"s": 1163,
"text": "Therefore, to find whether a RowSet contains a specific column, you need to compare the name of each column in the RowSet with the required name. To do so −"
},
{
"code": null,
"e": 1406,
"s": 1320,
"text": "Retrieve the ResultSetMetaData object from the RowSet using the getMetaData() method."
},
{
"code": null,
"e": 1453,
"s": 1406,
"text": "ResultSetMetaData meta = rowSet.getMetaData();"
},
{
"code": null,
"e": 1528,
"s": 1453,
"text": "Get the number of columns in the RowSet using the getColumnCount() method."
},
{
"code": null,
"e": 1569,
"s": 1528,
"text": "int columnCount = meta.getColumnCount();"
},
{
"code": null,
"e": 1806,
"s": 1569,
"text": "The getColumnName() method returns the name of the column of the specified index. Using this method retrieve the column names of the RowSet from index 1 to column count and compare name of the each column, with the required column name."
},
{
"code": null,
"e": 1947,
"s": 1806,
"text": "boolean flag = false;\nfor (int i = 1; i <=columnCount; i++) {\n if(meta.getColumnName(i).equals(\"ProductName\")) {\n flag = true;\n }\n}"
},
{
"code": null,
"e": 2089,
"s": 1947,
"text": "Let us create a table with name sales in MySQL database, with one of the columns as auto-incremented, using CREATE statement as shown below −"
},
{
"code": null,
"e": 2291,
"s": 2089,
"text": "CREATE TABLE Sales(\n ID INT PRIMARY KEY AUTO_INCREMENT,\n ProductName VARCHAR (20),\n CustomerName VARCHAR (20),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(20)\n);"
},
{
"code": null,
"e": 2362,
"s": 2291,
"text": "Now, we will insert 5 records in sales table using INSERT statements −"
},
{
"code": null,
"e": 3236,
"s": 2362,
"text": "insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'India');\ninsert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');\ninsert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');\ninsert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');\ninsert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');"
},
{
"code": null,
"e": 3427,
"s": 3236,
"text": "Following JDBC program establishes connection with the database, retrieves the contents of the Sales table into the RowSet and finds out whether the it contains the column named ProductName."
},
{
"code": null,
"e": 5483,
"s": 3427,
"text": "import java.sql.DriverManager;\nimport java.sql.ResultSetMetaData;\nimport javax.sql.rowset.CachedRowSet;\nimport javax.sql.rowset.RowSetFactory;\nimport javax.sql.rowset.RowSetProvider;\npublic class CachedRowSetExample {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Creating the RowSet object\n RowSetFactory factory = RowSetProvider.newFactory();\n CachedRowSet rowSet = factory.createCachedRowSet();\n //Setting the URL\n String mysqlUrl = \"jdbc:mysql://localhost/SampleDB\";\n rowSet.setUrl(mysqlUrl);\n //Setting the user name\n rowSet.setUsername(\"root\");\n //Setting the password\n rowSet.setPassword(\"password\");\n //Setting the query/command\n rowSet.setCommand(\"select * from Sales\");\n //Executing the command\n rowSet.execute();\n //Retrieving the ResultSetMetaData object\n ResultSetMetaData meta = rowSet.getMetaData();\n int columnCount = meta.getColumnCount();\n boolean flag = false;\n for (int i = 1; i <=columnCount; i++) {\n if(meta.getColumnName(i).equals(\"ProductName\")){\n flag = true;\n }\n }\n if(flag) {\n System.out.println(\"Specified column exist\");\n } else {\n System.out.println(\"Specified column does not exists\");\n }\n System.out.println(\"Contents of the row set\");\n while(rowSet.next()) {\n System.out.print(\"ID: \"+rowSet.getInt(\"ID\")+\", \");\n System.out.print(\"Product Name: \"+rowSet.getString(\"ProductName\")+\", \");\n System.out.print(\"Customer Name: \"+rowSet.getString(\"CustomerName\")+\", \");\n System.out.print(\"Dispatch Date: \"+rowSet.getDate(\"DispatchDate\")+\", \");\n System.out.print(\"Delivery Time: \"+rowSet.getTime(\"DeliveryTime\")+\", \"););\n System.out.print(\"Price: \"+rowSet.getString(\"Price\")+\", \");\n System.out.print(\"Location: \"+rowSet.getString(\"Location\"));\n System.out.println(\"\");\n }\n }\n}"
},
{
"code": null,
"e": 6214,
"s": 5483,
"text": "Specified column exists\nContents of the row set\nID: 1, Product Name: Key-Board, Customer Name: Raja, Dispatch Date: 2019-09-01, Delivery Time: 05:30:00, Price: 2000, Location: Hyderabad\nID: 2, Product Name: Earphones, Customer Name: Roja, Dispatch Date: 2019-05-01, Delivery Time: 05:30:00, Price: 2000, Location: Vishakhapatnam\nID: 3, Product Name: Mouse, Customer Name: Puja, Dispatch Date: 2019-03-01, Delivery Time: 05:29:59, Price: 3000, Location: Vijayawada\nID: 4, Product Name: Mobile, Customer Name: Vanaja, Dispatch Date: 2019-03-01, Delivery Time: 04:40:52, Price: 9000, Location: Chennai\nID: 5, Product Name: Headset, Customer Name: Jalaja, Dispatch Date: 2019-04-06, Delivery Time: 18:38:59, Price: 6000, Location: Goa"
}
] |
Python Pandas - Convert the Timedelta to a NumPy timedelta64 | To convert the Timedelta to a NumPy timedelta64, use the timedelta.to_timedelta64() method.
At first, import the required libraries −
import pandas as pd
Create a Timedelta object −
timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')
Display the Timedelta −
print("Timedelta...\n", timedelta)
Convert the Timedelta to a NumPy timedelta64 −
timedelta.to_timedelta64()
Following is the code −
import pandas as pd
# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# create a Timedelta object
timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')
# display the Timedelta
print("Timedelta...\n", timedelta)
# Convert the Timedelta to a NumPy timedelta64.
res = timedelta.to_timedelta64()
# Return the result
print("\nConverting the Timedelta to a NumPy timedelta64....\n", res)
This will produce the following code −
Timedelta...
2 days 11:22:25.050000045
Converting the Timedelta to a NumPy timedelta64....
213745050000045 nanoseconds | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To convert the Timedelta to a NumPy timedelta64, use the timedelta.to_timedelta64() method."
},
{
"code": null,
"e": 1196,
"s": 1154,
"text": "At first, import the required libraries −"
},
{
"code": null,
"e": 1216,
"s": 1196,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1244,
"s": 1216,
"text": "Create a Timedelta object −"
},
{
"code": null,
"e": 1313,
"s": 1244,
"text": "timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')\n"
},
{
"code": null,
"e": 1337,
"s": 1313,
"text": "Display the Timedelta −"
},
{
"code": null,
"e": 1372,
"s": 1337,
"text": "print(\"Timedelta...\\n\", timedelta)"
},
{
"code": null,
"e": 1419,
"s": 1372,
"text": "Convert the Timedelta to a NumPy timedelta64 −"
},
{
"code": null,
"e": 1447,
"s": 1419,
"text": "timedelta.to_timedelta64()\n"
},
{
"code": null,
"e": 1471,
"s": 1447,
"text": "Following is the code −"
},
{
"code": null,
"e": 1916,
"s": 1471,
"text": "import pandas as pd\n\n# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s\n# create a Timedelta object\ntimedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')\n\n# display the Timedelta\nprint(\"Timedelta...\\n\", timedelta)\n\n# Convert the Timedelta to a NumPy timedelta64.\nres = timedelta.to_timedelta64()\n\n# Return the result\nprint(\"\\nConverting the Timedelta to a NumPy timedelta64....\\n\", res)"
},
{
"code": null,
"e": 1955,
"s": 1916,
"text": "This will produce the following code −"
},
{
"code": null,
"e": 2075,
"s": 1955,
"text": "Timedelta...\n2 days 11:22:25.050000045\n\nConverting the Timedelta to a NumPy timedelta64....\n213745050000045 nanoseconds"
}
] |
jQuery | unbind() Method | 20 Feb, 2019
The unbind() Method is an inbuilt method in jQuery which is used to remove any selected event handlers. This method can be used to remove particular event handler, or stop specific functions. It works on any event handler using an event object.
Note: If no parameters are provided, the method works on all event handlers from the specified element.Syntax:
$(selector).unbind(event, function, eventObj)
Parameters: This method accepts three parameters as mentioned above and described below:
event: It is an optional parameter which is used to specify events (one or more) to remove them from the elements.
function: It is an optional parameter which is used to specify the name of the function to unbind from the specified event for the element.
eventObj: It is an optional parameter which is used to specify the event object to remove from the event binding function.
Example 1: This example describes the unbind() method to remove event handler from selected element.
<!DOCTYPE html> <html> <head> <title> jQuery unbind() Method </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <button> Click Here </button> <!-- Script to illustrates unbind() method --> <script> $(document).ready(function() { $("h1").click(function() { $(this).slideToggle(); }); $("button").click(function() { $("h1").unbind(); }); }); </script></body> </html>
Output:
Before click anywhere:
After clicking on the element h1:
After clicking on the button event will not work:
Example 2: This example describes the unbind() method to remove event handler from selected element.
<!DOCTYPE html> <html> <head> <title> jQuery unbind() Method </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <style> h1 { border: 1px solid black; height: 100px; padding-top: 35px; background: green; color: white; } </style></head> <body style = "text-align:center;"> <h1>GeeksForGeeks</h1> <button> Remove event handler from geeks for geeks </button> <!-- Script to illustrates unbind() method --> <script> $(document).ready(function() { $("h1").click(function() { $(this).slideToggle(); }); $("button").click(function() { $("h1").unbind(); }); }); </script></body> </html>
Output:
Before click anywhere:
After clicking on the element h1:
After clicking on the button event will not work:
jQuery-Events
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Feb, 2019"
},
{
"code": null,
"e": 273,
"s": 28,
"text": "The unbind() Method is an inbuilt method in jQuery which is used to remove any selected event handlers. This method can be used to remove particular event handler, or stop specific functions. It works on any event handler using an event object."
},
{
"code": null,
"e": 384,
"s": 273,
"text": "Note: If no parameters are provided, the method works on all event handlers from the specified element.Syntax:"
},
{
"code": null,
"e": 430,
"s": 384,
"text": "$(selector).unbind(event, function, eventObj)"
},
{
"code": null,
"e": 519,
"s": 430,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 634,
"s": 519,
"text": "event: It is an optional parameter which is used to specify events (one or more) to remove them from the elements."
},
{
"code": null,
"e": 774,
"s": 634,
"text": "function: It is an optional parameter which is used to specify the name of the function to unbind from the specified event for the element."
},
{
"code": null,
"e": 897,
"s": 774,
"text": "eventObj: It is an optional parameter which is used to specify the event object to remove from the event binding function."
},
{
"code": null,
"e": 998,
"s": 897,
"text": "Example 1: This example describes the unbind() method to remove event handler from selected element."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> jQuery unbind() Method </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <button> Click Here </button> <!-- Script to illustrates unbind() method --> <script> $(document).ready(function() { $(\"h1\").click(function() { $(this).slideToggle(); }); $(\"button\").click(function() { $(\"h1\").unbind(); }); }); </script></body> </html> ",
"e": 1726,
"s": 998,
"text": null
},
{
"code": null,
"e": 1734,
"s": 1726,
"text": "Output:"
},
{
"code": null,
"e": 1757,
"s": 1734,
"text": "Before click anywhere:"
},
{
"code": null,
"e": 1791,
"s": 1757,
"text": "After clicking on the element h1:"
},
{
"code": null,
"e": 1841,
"s": 1791,
"text": "After clicking on the button event will not work:"
},
{
"code": null,
"e": 1942,
"s": 1841,
"text": "Example 2: This example describes the unbind() method to remove event handler from selected element."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> jQuery unbind() Method </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <style> h1 { border: 1px solid black; height: 100px; padding-top: 35px; background: green; color: white; } </style></head> <body style = \"text-align:center;\"> <h1>GeeksForGeeks</h1> <button> Remove event handler from geeks for geeks </button> <!-- Script to illustrates unbind() method --> <script> $(document).ready(function() { $(\"h1\").click(function() { $(this).slideToggle(); }); $(\"button\").click(function() { $(\"h1\").unbind(); }); }); </script></body> </html> ",
"e": 2847,
"s": 1942,
"text": null
},
{
"code": null,
"e": 2855,
"s": 2847,
"text": "Output:"
},
{
"code": null,
"e": 2878,
"s": 2855,
"text": "Before click anywhere:"
},
{
"code": null,
"e": 2912,
"s": 2878,
"text": "After clicking on the element h1:"
},
{
"code": null,
"e": 2962,
"s": 2912,
"text": "After clicking on the button event will not work:"
},
{
"code": null,
"e": 2976,
"s": 2962,
"text": "jQuery-Events"
},
{
"code": null,
"e": 2983,
"s": 2976,
"text": "Picked"
},
{
"code": null,
"e": 2990,
"s": 2983,
"text": "JQuery"
},
{
"code": null,
"e": 3007,
"s": 2990,
"text": "Web Technologies"
}
] |
Strings in C++ and How to Create them? | 13 Nov, 2019
Strings in C++ are used to store text or sequence of characters. In C++ strings can be stored in one of the two following ways:
C style string (using characters)
String class
Each of the above methods is discussed below:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C style string: In C, strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. In C, the string is actually represented as an array of characters terminated by a null string. Therefore the size of the character array is always one more than that of the number of characters in the actual string. This thing continues to be supported in C++ too. The C++ compiler automatically sets “\0” at the end of the string, during initialization of the array.Initializing a String in C++:1. char str[] = "Geeks";
2. char str[6] = "Geeks";
3. char str[] = {'G', 'e', 'e', 'k', 's', '\0'};
4. char str[6] = {'G', 'e', 'e', 'k', 's', '\0'};
Below is the memory representation of a string “Geeks” in C++.Let’s look at some examples to better understand the string representation in C++, using C style:// C++ program to demonstrate// Strings using C style #include <iostream>using namespace std; int main(){ // Declare and initialize string char str[] = "Geeks"; // Print string cout << str; return 0;}Output:Geeks
Standard String representation and String Class: In C++, one can directly store the collection of characters or text in a string variable, surrounded by double-quotes. C++ provides string class, which supports various operations like copying strings, concatenating strings etc.Initializing string in C++:1. string str1 = "Geeks";
2. string str2 = "Welcome to GeeksforGeeks!";
Example:// C++ program to demonstrate String// using Standard String representation #include <iostream>#include <string>using namespace std; int main(){ // Declare and initialize the string string str1 = "Welcome to GeeksforGeeks!"; // Initialization by raw string string str2("A Computer Science Portal"); // Print string cout << str1 << endl << str2; return 0;}Output:Welcome to GeeksforGeeks!
A Computer Science Portal
C style string: In C, strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. In C, the string is actually represented as an array of characters terminated by a null string. Therefore the size of the character array is always one more than that of the number of characters in the actual string. This thing continues to be supported in C++ too. The C++ compiler automatically sets “\0” at the end of the string, during initialization of the array.Initializing a String in C++:1. char str[] = "Geeks";
2. char str[6] = "Geeks";
3. char str[] = {'G', 'e', 'e', 'k', 's', '\0'};
4. char str[6] = {'G', 'e', 'e', 'k', 's', '\0'};
Below is the memory representation of a string “Geeks” in C++.Let’s look at some examples to better understand the string representation in C++, using C style:// C++ program to demonstrate// Strings using C style #include <iostream>using namespace std; int main(){ // Declare and initialize string char str[] = "Geeks"; // Print string cout << str; return 0;}Output:Geeks
Initializing a String in C++:
1. char str[] = "Geeks";
2. char str[6] = "Geeks";
3. char str[] = {'G', 'e', 'e', 'k', 's', '\0'};
4. char str[6] = {'G', 'e', 'e', 'k', 's', '\0'};
Below is the memory representation of a string “Geeks” in C++.
Let’s look at some examples to better understand the string representation in C++, using C style:
// C++ program to demonstrate// Strings using C style #include <iostream>using namespace std; int main(){ // Declare and initialize string char str[] = "Geeks"; // Print string cout << str; return 0;}
Geeks
Standard String representation and String Class: In C++, one can directly store the collection of characters or text in a string variable, surrounded by double-quotes. C++ provides string class, which supports various operations like copying strings, concatenating strings etc.Initializing string in C++:1. string str1 = "Geeks";
2. string str2 = "Welcome to GeeksforGeeks!";
Example:// C++ program to demonstrate String// using Standard String representation #include <iostream>#include <string>using namespace std; int main(){ // Declare and initialize the string string str1 = "Welcome to GeeksforGeeks!"; // Initialization by raw string string str2("A Computer Science Portal"); // Print string cout << str1 << endl << str2; return 0;}Output:Welcome to GeeksforGeeks!
A Computer Science Portal
Initializing string in C++:
1. string str1 = "Geeks";
2. string str2 = "Welcome to GeeksforGeeks!";
Example:
// C++ program to demonstrate String// using Standard String representation #include <iostream>#include <string>using namespace std; int main(){ // Declare and initialize the string string str1 = "Welcome to GeeksforGeeks!"; // Initialization by raw string string str2("A Computer Science Portal"); // Print string cout << str1 << endl << str2; return 0;}
Welcome to GeeksforGeeks!
A Computer Science Portal
Related Articles:
C++ string class and its applications | Set 1
C++ string class and its applications | Set 2
cpp-strings
C++
cpp-strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Nov, 2019"
},
{
"code": null,
"e": 180,
"s": 52,
"text": "Strings in C++ are used to store text or sequence of characters. In C++ strings can be stored in one of the two following ways:"
},
{
"code": null,
"e": 214,
"s": 180,
"text": "C style string (using characters)"
},
{
"code": null,
"e": 227,
"s": 214,
"text": "String class"
},
{
"code": null,
"e": 273,
"s": 227,
"text": "Each of the above methods is discussed below:"
},
{
"code": null,
"e": 282,
"s": 273,
"text": "Chapters"
},
{
"code": null,
"e": 309,
"s": 282,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 359,
"s": 309,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 382,
"s": 359,
"text": "captions off, selected"
},
{
"code": null,
"e": 390,
"s": 382,
"text": "English"
},
{
"code": null,
"e": 414,
"s": 390,
"text": "This is a modal window."
},
{
"code": null,
"e": 483,
"s": 414,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 505,
"s": 483,
"text": "End of dialog window."
},
{
"code": null,
"e": 2459,
"s": 505,
"text": "C style string: In C, strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\\0’. In C, the string is actually represented as an array of characters terminated by a null string. Therefore the size of the character array is always one more than that of the number of characters in the actual string. This thing continues to be supported in C++ too. The C++ compiler automatically sets “\\0” at the end of the string, during initialization of the array.Initializing a String in C++:1. char str[] = \"Geeks\";\n2. char str[6] = \"Geeks\";\n3. char str[] = {'G', 'e', 'e', 'k', 's', '\\0'};\n4. char str[6] = {'G', 'e', 'e', 'k', 's', '\\0'};\nBelow is the memory representation of a string “Geeks” in C++.Let’s look at some examples to better understand the string representation in C++, using C style:// C++ program to demonstrate// Strings using C style #include <iostream>using namespace std; int main(){ // Declare and initialize string char str[] = \"Geeks\"; // Print string cout << str; return 0;}Output:Geeks\nStandard String representation and String Class: In C++, one can directly store the collection of characters or text in a string variable, surrounded by double-quotes. C++ provides string class, which supports various operations like copying strings, concatenating strings etc.Initializing string in C++:1. string str1 = \"Geeks\";\n2. string str2 = \"Welcome to GeeksforGeeks!\";\nExample:// C++ program to demonstrate String// using Standard String representation #include <iostream>#include <string>using namespace std; int main(){ // Declare and initialize the string string str1 = \"Welcome to GeeksforGeeks!\"; // Initialization by raw string string str2(\"A Computer Science Portal\"); // Print string cout << str1 << endl << str2; return 0;}Output:Welcome to GeeksforGeeks!\nA Computer Science Portal\n"
},
{
"code": null,
"e": 3584,
"s": 2459,
"text": "C style string: In C, strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\\0’. In C, the string is actually represented as an array of characters terminated by a null string. Therefore the size of the character array is always one more than that of the number of characters in the actual string. This thing continues to be supported in C++ too. The C++ compiler automatically sets “\\0” at the end of the string, during initialization of the array.Initializing a String in C++:1. char str[] = \"Geeks\";\n2. char str[6] = \"Geeks\";\n3. char str[] = {'G', 'e', 'e', 'k', 's', '\\0'};\n4. char str[6] = {'G', 'e', 'e', 'k', 's', '\\0'};\nBelow is the memory representation of a string “Geeks” in C++.Let’s look at some examples to better understand the string representation in C++, using C style:// C++ program to demonstrate// Strings using C style #include <iostream>using namespace std; int main(){ // Declare and initialize string char str[] = \"Geeks\"; // Print string cout << str; return 0;}Output:Geeks\n"
},
{
"code": null,
"e": 3614,
"s": 3584,
"text": "Initializing a String in C++:"
},
{
"code": null,
"e": 3765,
"s": 3614,
"text": "1. char str[] = \"Geeks\";\n2. char str[6] = \"Geeks\";\n3. char str[] = {'G', 'e', 'e', 'k', 's', '\\0'};\n4. char str[6] = {'G', 'e', 'e', 'k', 's', '\\0'};\n"
},
{
"code": null,
"e": 3828,
"s": 3765,
"text": "Below is the memory representation of a string “Geeks” in C++."
},
{
"code": null,
"e": 3926,
"s": 3828,
"text": "Let’s look at some examples to better understand the string representation in C++, using C style:"
},
{
"code": "// C++ program to demonstrate// Strings using C style #include <iostream>using namespace std; int main(){ // Declare and initialize string char str[] = \"Geeks\"; // Print string cout << str; return 0;}",
"e": 4150,
"s": 3926,
"text": null
},
{
"code": null,
"e": 4157,
"s": 4150,
"text": "Geeks\n"
},
{
"code": null,
"e": 4987,
"s": 4157,
"text": "Standard String representation and String Class: In C++, one can directly store the collection of characters or text in a string variable, surrounded by double-quotes. C++ provides string class, which supports various operations like copying strings, concatenating strings etc.Initializing string in C++:1. string str1 = \"Geeks\";\n2. string str2 = \"Welcome to GeeksforGeeks!\";\nExample:// C++ program to demonstrate String// using Standard String representation #include <iostream>#include <string>using namespace std; int main(){ // Declare and initialize the string string str1 = \"Welcome to GeeksforGeeks!\"; // Initialization by raw string string str2(\"A Computer Science Portal\"); // Print string cout << str1 << endl << str2; return 0;}Output:Welcome to GeeksforGeeks!\nA Computer Science Portal\n"
},
{
"code": null,
"e": 5015,
"s": 4987,
"text": "Initializing string in C++:"
},
{
"code": null,
"e": 5088,
"s": 5015,
"text": "1. string str1 = \"Geeks\";\n2. string str2 = \"Welcome to GeeksforGeeks!\";\n"
},
{
"code": null,
"e": 5097,
"s": 5088,
"text": "Example:"
},
{
"code": "// C++ program to demonstrate String// using Standard String representation #include <iostream>#include <string>using namespace std; int main(){ // Declare and initialize the string string str1 = \"Welcome to GeeksforGeeks!\"; // Initialization by raw string string str2(\"A Computer Science Portal\"); // Print string cout << str1 << endl << str2; return 0;}",
"e": 5484,
"s": 5097,
"text": null
},
{
"code": null,
"e": 5537,
"s": 5484,
"text": "Welcome to GeeksforGeeks!\nA Computer Science Portal\n"
},
{
"code": null,
"e": 5555,
"s": 5537,
"text": "Related Articles:"
},
{
"code": null,
"e": 5601,
"s": 5555,
"text": "C++ string class and its applications | Set 1"
},
{
"code": null,
"e": 5647,
"s": 5601,
"text": "C++ string class and its applications | Set 2"
},
{
"code": null,
"e": 5659,
"s": 5647,
"text": "cpp-strings"
},
{
"code": null,
"e": 5663,
"s": 5659,
"text": "C++"
},
{
"code": null,
"e": 5675,
"s": 5663,
"text": "cpp-strings"
},
{
"code": null,
"e": 5679,
"s": 5675,
"text": "CPP"
}
] |
Python – Downloading captions from YouTube | 13 Jul, 2022
Python provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Transcript API is very simple to use provides various features.
In this article, we will learn how to download captions or subtitles from a YouTube video. The subtitles can be auto-generated by YouTube or can be manually added by the mentor, in case it has both types available we would take a look at how to get specifically manual or automatic captions too. We would also explore how to get captions of specific languages and translate captions from one language to another. Then we would also see how to write the transcript in a text file.
youtube_transcript_api: This module is used for getting the captions/subtitles from a YouTube Video. It can be installed using:
pip install youtube-transcript-api # for windows
or
pip3 install youtube-transcript-api # for Linux and MacOs
Before starting with the process we would like to explain how we can get the video id of a YouTube video. For Example, if a YouTube video has the following URL
https://youtu.be/SW14tOda_kI
Then the video id for this video would be “SW14tOda_kI”, i.e. all the phrases after the ?v= counts as the video id. This is unique for each video on YouTube.
Now we would start with the basics, In the first code snippet, we are trying to get the transcript of the video id using the .get_transcript() function.
It returns us a list of dictionaries in which each dictionary contains 3 key-value pair inside it, the first one being the content, the second one being the time instant from which the caption sentence/phrase start to be spoken and the third one being the duration in seconds that is taken to speak the sentence or phrase completely.
First-line basically imports the required packages and the next line assigns a variable to store the list of dictionaries and finally on the 3rd line it prints out the variable.
Python3
from youtube_transcript_api import YouTubeTranscriptApi # assigning srt variable with the list# of dictonaries obtained by the get_transcript() functionsrt = YouTubeTranscriptApi.get_transcript("SW14tOda_kI") # prints the resultprint(srt)
Output:
For getting transcripts of more than one video we can pass them using commas, as in YouTubeTranscriptApi.get_transcript(videoid1, Videoid2, ....), in this case, we would have a list of lists and gain inside each inner list we would have a dictionary.
Now if we want to get the transcript of a specific language, we can mention the language as a parameter. In the next code snippet, we aim to do the same. All the code and working would be the same as the previous example with the difference that this time it will get only the transcripts in English and ignore subtitles if any exists.
Python3
from youtube_transcript_api import YouTubeTranscriptApi # assigning srt variable with the list of dictonaries# obtained by the .get_transcript() function# and this time it gets only the subtitles that# are of english langauge.srt = YouTubeTranscriptApi.get_transcript("SW14tOda_kI", languages=['en']) # prints the resultprint(srt)
Output:
Since the video we are considering for this example, only has English subtitles so both the examples gave us the same answer.
Now to get the list of all transcripts of a video we can use the .list_transcripts() function. This function returns us all the transcripts of all the languages available for the video. It returns the TranscriptList object which is iterable and provides methods to filter the list of transcripts for specific languages and types.
Next, we use functions to fetch some data about the transcript from the metadata obtained.transcript.video_id returns us the video ID of the videotranscript.language returns us the language of the transcripttranscript.language_code returns us the language cod of the transcript, for example, “en” for English, etc.transcript.is_generated tell us whether it has been manually created or generated by YouTubetranscript.is_translatable tells whether this transcript can be translated or nottranscript.translation_languages which give us a list of languages the transcript can be translated to.
transcript.video_id returns us the video ID of the video
transcript.language returns us the language of the transcript
transcript.language_code returns us the language cod of the transcript, for example, “en” for English, etc.
transcript.is_generated tell us whether it has been manually created or generated by YouTube
transcript.is_translatable tells whether this transcript can be translated or not
transcript.translation_languages which give us a list of languages the transcript can be translated to.
Then we use .fetch() function to fetch the actual transcript.
Then we also showed how to use the .translate() function to convert/translate the caption from one language to another if at all it’s translatable (since we have only English subtitles for this language it might be not evident in this case, but this translation is very useful if there are transcripts of more than one language in the video).
Next line we have the .find_transcript() function that helps us to get the actual transcript of the video we are wanting along with the metadata.
Finally, we used the .find_manually_created_transcript() function to specifically find manual subscripts, similar to this we have .find_generated_transcript() which we have not used in this example since there are no generated captions, and we have only manual captions here.
Python3
# importing the modulefrom youtube_transcript_api import YouTubeTranscriptApi # retrieve the available transcriptstranscript_list = YouTubeTranscriptApi.list_transcripts('SW14tOda_kI') # iterate over all available transcriptsfor transcript in transcript_list: # the Transcript object provides metadata # properties print( transcript.video_id, transcript.language, transcript.language_code, # whether it has been manually created or # generated by YouTube transcript.is_generated, # whether this transcript can be translated # or not transcript.is_translatable, # a list of languages the transcript can be # translated to transcript.translation_languages, ) # fetch the actual transcript data print(transcript.fetch()) # translating the transcript will return another # transcript object print(transcript.translate('en').fetch()) # you can also directly filter for the language you are# looking for, using the transcript listtranscript = transcript_list.find_transcript(['en']) # or just filter for manually created transcriptstranscript = transcript_list.find_manually_created_transcript(['en'])
Output:
Now we would see how can we can write subtitles of a YouTube video in a text file. For that first, we would import the modules and then get the transcript or caption using the .get_transcript() function and store it into a variable. Then we would use the built-in file reader of python. The line uses a context manager so that we need not worry to close the file after our work is done. We open a file named subtitles.txt in write mode and then inside it we would iterate through each element of the list and then write it to the file. The code is as follows:
Python3
# importing modulesfrom youtube_transcript_api import YouTubeTranscriptApi # using the srt variable with the list of dictonaries# obtained by the .get_transcript() functionsrt = YouTubeTranscriptApi.get_transcript("SW14tOda_kI") # creating or overwriting a file "subtitles.txt" with# the info inside the context managerwith open("subtitles.txt", "w") as f: # iterating through each element of list srt for i in srt: # writing each element of srt on a new line f.write("{}\n".format(i))
Output:
The file would be created in the same directory as that of the .py file if you just enter the name of the file in the context manager, to create/save it at a different location we need to give it’s absolute or relative path. Also, the program can generate error for unknown characters in the caption. However, the subtitle file will be created with known characters.
sweetyty
sagar0719kumar
simmytarika5
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jul, 2022"
},
{
"code": null,
"e": 254,
"s": 28,
"text": "Python provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Transcript API is very simple to use provides various features."
},
{
"code": null,
"e": 734,
"s": 254,
"text": "In this article, we will learn how to download captions or subtitles from a YouTube video. The subtitles can be auto-generated by YouTube or can be manually added by the mentor, in case it has both types available we would take a look at how to get specifically manual or automatic captions too. We would also explore how to get captions of specific languages and translate captions from one language to another. Then we would also see how to write the transcript in a text file."
},
{
"code": null,
"e": 862,
"s": 734,
"text": "youtube_transcript_api: This module is used for getting the captions/subtitles from a YouTube Video. It can be installed using:"
},
{
"code": null,
"e": 974,
"s": 862,
"text": "pip install youtube-transcript-api # for windows\nor \npip3 install youtube-transcript-api # for Linux and MacOs "
},
{
"code": null,
"e": 1134,
"s": 974,
"text": "Before starting with the process we would like to explain how we can get the video id of a YouTube video. For Example, if a YouTube video has the following URL"
},
{
"code": null,
"e": 1163,
"s": 1134,
"text": "https://youtu.be/SW14tOda_kI"
},
{
"code": null,
"e": 1321,
"s": 1163,
"text": "Then the video id for this video would be “SW14tOda_kI”, i.e. all the phrases after the ?v= counts as the video id. This is unique for each video on YouTube."
},
{
"code": null,
"e": 1474,
"s": 1321,
"text": "Now we would start with the basics, In the first code snippet, we are trying to get the transcript of the video id using the .get_transcript() function."
},
{
"code": null,
"e": 1808,
"s": 1474,
"text": "It returns us a list of dictionaries in which each dictionary contains 3 key-value pair inside it, the first one being the content, the second one being the time instant from which the caption sentence/phrase start to be spoken and the third one being the duration in seconds that is taken to speak the sentence or phrase completely."
},
{
"code": null,
"e": 1986,
"s": 1808,
"text": "First-line basically imports the required packages and the next line assigns a variable to store the list of dictionaries and finally on the 3rd line it prints out the variable."
},
{
"code": null,
"e": 1994,
"s": 1986,
"text": "Python3"
},
{
"code": "from youtube_transcript_api import YouTubeTranscriptApi # assigning srt variable with the list# of dictonaries obtained by the get_transcript() functionsrt = YouTubeTranscriptApi.get_transcript(\"SW14tOda_kI\") # prints the resultprint(srt)",
"e": 2235,
"s": 1994,
"text": null
},
{
"code": null,
"e": 2246,
"s": 2238,
"text": "Output:"
},
{
"code": null,
"e": 2501,
"s": 2250,
"text": "For getting transcripts of more than one video we can pass them using commas, as in YouTubeTranscriptApi.get_transcript(videoid1, Videoid2, ....), in this case, we would have a list of lists and gain inside each inner list we would have a dictionary."
},
{
"code": null,
"e": 2842,
"s": 2505,
"text": "Now if we want to get the transcript of a specific language, we can mention the language as a parameter. In the next code snippet, we aim to do the same. All the code and working would be the same as the previous example with the difference that this time it will get only the transcripts in English and ignore subtitles if any exists. "
},
{
"code": null,
"e": 2852,
"s": 2844,
"text": "Python3"
},
{
"code": "from youtube_transcript_api import YouTubeTranscriptApi # assigning srt variable with the list of dictonaries# obtained by the .get_transcript() function# and this time it gets only the subtitles that# are of english langauge.srt = YouTubeTranscriptApi.get_transcript(\"SW14tOda_kI\", languages=['en']) # prints the resultprint(srt)",
"e": 3224,
"s": 2852,
"text": null
},
{
"code": null,
"e": 3232,
"s": 3224,
"text": "Output:"
},
{
"code": null,
"e": 3359,
"s": 3232,
"text": "Since the video we are considering for this example, only has English subtitles so both the examples gave us the same answer. "
},
{
"code": null,
"e": 3689,
"s": 3359,
"text": "Now to get the list of all transcripts of a video we can use the .list_transcripts() function. This function returns us all the transcripts of all the languages available for the video. It returns the TranscriptList object which is iterable and provides methods to filter the list of transcripts for specific languages and types."
},
{
"code": null,
"e": 4280,
"s": 3689,
"text": "Next, we use functions to fetch some data about the transcript from the metadata obtained.transcript.video_id returns us the video ID of the videotranscript.language returns us the language of the transcripttranscript.language_code returns us the language cod of the transcript, for example, “en” for English, etc.transcript.is_generated tell us whether it has been manually created or generated by YouTubetranscript.is_translatable tells whether this transcript can be translated or nottranscript.translation_languages which give us a list of languages the transcript can be translated to."
},
{
"code": null,
"e": 4337,
"s": 4280,
"text": "transcript.video_id returns us the video ID of the video"
},
{
"code": null,
"e": 4399,
"s": 4337,
"text": "transcript.language returns us the language of the transcript"
},
{
"code": null,
"e": 4507,
"s": 4399,
"text": "transcript.language_code returns us the language cod of the transcript, for example, “en” for English, etc."
},
{
"code": null,
"e": 4600,
"s": 4507,
"text": "transcript.is_generated tell us whether it has been manually created or generated by YouTube"
},
{
"code": null,
"e": 4682,
"s": 4600,
"text": "transcript.is_translatable tells whether this transcript can be translated or not"
},
{
"code": null,
"e": 4786,
"s": 4682,
"text": "transcript.translation_languages which give us a list of languages the transcript can be translated to."
},
{
"code": null,
"e": 4848,
"s": 4786,
"text": "Then we use .fetch() function to fetch the actual transcript."
},
{
"code": null,
"e": 5191,
"s": 4848,
"text": "Then we also showed how to use the .translate() function to convert/translate the caption from one language to another if at all it’s translatable (since we have only English subtitles for this language it might be not evident in this case, but this translation is very useful if there are transcripts of more than one language in the video)."
},
{
"code": null,
"e": 5337,
"s": 5191,
"text": "Next line we have the .find_transcript() function that helps us to get the actual transcript of the video we are wanting along with the metadata."
},
{
"code": null,
"e": 5613,
"s": 5337,
"text": "Finally, we used the .find_manually_created_transcript() function to specifically find manual subscripts, similar to this we have .find_generated_transcript() which we have not used in this example since there are no generated captions, and we have only manual captions here."
},
{
"code": null,
"e": 5621,
"s": 5613,
"text": "Python3"
},
{
"code": "# importing the modulefrom youtube_transcript_api import YouTubeTranscriptApi # retrieve the available transcriptstranscript_list = YouTubeTranscriptApi.list_transcripts('SW14tOda_kI') # iterate over all available transcriptsfor transcript in transcript_list: # the Transcript object provides metadata # properties print( transcript.video_id, transcript.language, transcript.language_code, # whether it has been manually created or # generated by YouTube transcript.is_generated, # whether this transcript can be translated # or not transcript.is_translatable, # a list of languages the transcript can be # translated to transcript.translation_languages, ) # fetch the actual transcript data print(transcript.fetch()) # translating the transcript will return another # transcript object print(transcript.translate('en').fetch()) # you can also directly filter for the language you are# looking for, using the transcript listtranscript = transcript_list.find_transcript(['en']) # or just filter for manually created transcriptstranscript = transcript_list.find_manually_created_transcript(['en'])",
"e": 6856,
"s": 5621,
"text": null
},
{
"code": null,
"e": 6864,
"s": 6856,
"text": "Output:"
},
{
"code": null,
"e": 7424,
"s": 6864,
"text": "Now we would see how can we can write subtitles of a YouTube video in a text file. For that first, we would import the modules and then get the transcript or caption using the .get_transcript() function and store it into a variable. Then we would use the built-in file reader of python. The line uses a context manager so that we need not worry to close the file after our work is done. We open a file named subtitles.txt in write mode and then inside it we would iterate through each element of the list and then write it to the file. The code is as follows:"
},
{
"code": null,
"e": 7432,
"s": 7424,
"text": "Python3"
},
{
"code": "# importing modulesfrom youtube_transcript_api import YouTubeTranscriptApi # using the srt variable with the list of dictonaries# obtained by the .get_transcript() functionsrt = YouTubeTranscriptApi.get_transcript(\"SW14tOda_kI\") # creating or overwriting a file \"subtitles.txt\" with# the info inside the context managerwith open(\"subtitles.txt\", \"w\") as f: # iterating through each element of list srt for i in srt: # writing each element of srt on a new line f.write(\"{}\\n\".format(i))",
"e": 7945,
"s": 7432,
"text": null
},
{
"code": null,
"e": 7953,
"s": 7945,
"text": "Output:"
},
{
"code": null,
"e": 8320,
"s": 7953,
"text": "The file would be created in the same directory as that of the .py file if you just enter the name of the file in the context manager, to create/save it at a different location we need to give it’s absolute or relative path. Also, the program can generate error for unknown characters in the caption. However, the subtitle file will be created with known characters."
},
{
"code": null,
"e": 8329,
"s": 8320,
"text": "sweetyty"
},
{
"code": null,
"e": 8344,
"s": 8329,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 8357,
"s": 8344,
"text": "simmytarika5"
},
{
"code": null,
"e": 8364,
"s": 8357,
"text": "Picked"
},
{
"code": null,
"e": 8379,
"s": 8364,
"text": "python-utility"
},
{
"code": null,
"e": 8386,
"s": 8379,
"text": "Python"
}
] |
Null Cipher | 09 Sep, 2021
A null cipher, also known as concealment cipher, is an ancient form of encryption where the plaintext is mixed with a large amount of non-cipher material. Today it is regarded as a simple form of steganography, which can be used to hide ciphertext.There are various options of using the Null Cipher. Here we are taking the first letter from each word successively. The pattern can be chosen to increase the cryptography level Other options can be:
Taking last letters from each word.
Taking the letter from the particular position
Using the pattern (1, 2, 3, 1, 2, 3 [each letter in each word]). You can use some other pattern also.
Positing of the significant letters next to or at certain intervals from punctuation marks or particular characters.
Null Cipher taking the first letter from each word successively
More Examples of messages containing null ciphers:
Input will be one paragraph or sentence without any newline.
Input : News Eight Weather: Tonight increasing snow.
Unexpected precipitation smothers eastern
towns. Be extremely cautious and use snowtires
especially heading east. The [highway is not]
knowingly slippery. Highway evacuation is
suspected. Police report emergency situations
in downtown ending near Tuesday.
Explanation:
Taking the first letter in each word successively yields
the real message.
Here we are converting decoded message to lowercase.
News Eight Weather: Tonight Increasing Snow.
Unexpected Precipitation Smothers Eastern
Towns. Be Extremely Cautious And Use Snowtires
Especially Heading East. The [Highway Is Not]
Knowingly Slippery. Highway Evacuation Is
Suspected. Police Report Emergency Situations
In Downtown Ending Near Tuesday.
Output :
After Deciphered : newtisupsetbecausehethinksheispresident
After breaking the words manually the output will be:
Newt is upset because he thinks he is President
C++
Java
Python3
C#
Javascript
// CPP program to decode NULL CIPHER#include <bits/stdc++.h>using namespace std;string decode(string str){ // Store the decoded string. string res = ""; // found variable is used to tell that the encoded // encoded character is found in that particular word. bool found = false; for (int i = 0; i < str.size(); i++) { // Set found variable to false whenever we find // whitespace, meaning that encoded character for // new word is not found if (str[i] == ' ') { found = false; continue; } if (!found) { if (str[i] >= 'A' && str[i] <= 'Z') { res += str[i] + 32; found = true; } else if (str[i] >= 'a' && str[i] <= 'z') { res += str[i]; found = true; } } } return res;}// Driver codeint main(){ string in; in = "A Step by Step Guide for Placement Preparation by GeeksforGeeks"; cout << "Enciphered Message: "; // Function call cout << decode(in) << endl; return 0;}
// Java program to decode NULL CIPHERclass GFG{ // Function to decode the message. static String decode(String str) { // Store the decoded string String res = ""; // found variable is used // to tell that the encoded // encoded character is // found in that particular word. boolean found = false; for (int i = 0; i < str.length(); i++) { // Set found variable to false // whenever we find // whitespace, meaning that // encoded character for // new word is not found if (str.charAt(i) == ' ') { found = false; continue; } if (!found) { if ((str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') || (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')) { res += Character.toString(str.charAt(i)); found = true; } } } return res.toLowerCase(); } // Driver Code public static void main(String[] args) { String in; in = "A Step by Step Guide for Placement Preparation by GeeksforGeeks"; System.out.println("Enciphered Message: " + decode(in)); }} // This code is contributed by Vivek Kumar Singh
# Python program to decode NULL CIPHER # Function to decode the message.def decode(string): # Store the decoded string res = "" # found variable is used # to tell that the encoded # encoded character is # found in that particular word. found = False for character in string: # Set found variable to false # whenever we find # whitespace, meaning that # encoded character for # new word is not found if character == ' ': found = False continue if not found: if character>='A' and character<='Z' or character>='a' and character<='z': res += character found = True return res.lower() # Driver codeif __name__ == "__main__": input = "A Step by Step Guide for Placement Preparation by GeeksforGeeks" print("Enciphered Message:",decode(input)) # This code is contributed by Vivek Kumar Singh
// A C# program to decode NULL CIPHERusing System; class GFG{ // Function to decode the message. static String decode(String str) { // Store the decoded string String res = ""; // found variable is used // to tell that the encoded // encoded character is // found in that particular word. Boolean found = false; for (int i = 0; i < str.Length; i++) { // Set found variable to false whenever we find // whitespace, meaning that encoded character for // new word is not found if (str[i] == ' ') { found = false; continue; } if (!found) { if (str[i] >= 'A' && str[i] <= 'Z') { res += (char)(str[i] + 32); found = true; } else if (str[i] >= 'a' && str[i] <= 'z') { res += (char)str[i]; found = true; } } } return res; } // Driver Code public static void Main(String[] args) { String str; str = "A Step by Step Guide for Placement Preparation by GeeksforGeeks"; Console.WriteLine("Enciphered Message: " + decode(str)); }} // This code has been contributed by 29AjayKumar
<script>// Javascript program to decode NULL CIPHER // Function to decode the message.function decode(str){ // Store the decoded string let res = ""; // found variable is used // to tell that the encoded // encoded character is // found in that particular word. let found = false; for (let i = 0; i < str.length; i++) { // Set found variable to false // whenever we find // whitespace, meaning that // encoded character for // new word is not found if (str[i] == ' ') { found = false; continue; } if (!found) { if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) { res += (str[i]); found = true; } } } return res.toLowerCase();} // Driver Codelet In = "A Step by Step Guide for Placement Preparation by GeeksforGeeks";document.write("Enciphered Message: " + decode(In)); // This code is contributed by rag2127</script>
Output:
Enciphered Message: asbsgfppbg
This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Vivekkumar Singh
29AjayKumar
rag2127
anikakapoor
cryptography
Strings
Strings
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Find the smallest window in a string containing all characters of another string
Program to count occurrence of a given character in a string
Convert character array to string in C++
Return maximum occurring character in an input string | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 501,
"s": 52,
"text": "A null cipher, also known as concealment cipher, is an ancient form of encryption where the plaintext is mixed with a large amount of non-cipher material. Today it is regarded as a simple form of steganography, which can be used to hide ciphertext.There are various options of using the Null Cipher. Here we are taking the first letter from each word successively. The pattern can be chosen to increase the cryptography level Other options can be: "
},
{
"code": null,
"e": 537,
"s": 501,
"text": "Taking last letters from each word."
},
{
"code": null,
"e": 584,
"s": 537,
"text": "Taking the letter from the particular position"
},
{
"code": null,
"e": 686,
"s": 584,
"text": "Using the pattern (1, 2, 3, 1, 2, 3 [each letter in each word]). You can use some other pattern also."
},
{
"code": null,
"e": 803,
"s": 686,
"text": "Positing of the significant letters next to or at certain intervals from punctuation marks or particular characters."
},
{
"code": null,
"e": 868,
"s": 803,
"text": "Null Cipher taking the first letter from each word successively "
},
{
"code": null,
"e": 921,
"s": 868,
"text": "More Examples of messages containing null ciphers: "
},
{
"code": null,
"e": 1959,
"s": 921,
"text": "Input will be one paragraph or sentence without any newline.\n\nInput : News Eight Weather: Tonight increasing snow.\n Unexpected precipitation smothers eastern\n towns. Be extremely cautious and use snowtires\n especially heading east. The [highway is not]\n knowingly slippery. Highway evacuation is \n suspected. Police report emergency situations\n in downtown ending near Tuesday.\n\nExplanation:\nTaking the first letter in each word successively yields\nthe real message.\nHere we are converting decoded message to lowercase.\n\nNews Eight Weather: Tonight Increasing Snow.\nUnexpected Precipitation Smothers Eastern\nTowns. Be Extremely Cautious And Use Snowtires\nEspecially Heading East. The [Highway Is Not]\nKnowingly Slippery. Highway Evacuation Is\nSuspected. Police Report Emergency Situations\nIn Downtown Ending Near Tuesday.\n\nOutput :\nAfter Deciphered : newtisupsetbecausehethinksheispresident\n\nAfter breaking the words manually the output will be:\n Newt is upset because he thinks he is President"
},
{
"code": null,
"e": 1963,
"s": 1959,
"text": "C++"
},
{
"code": null,
"e": 1968,
"s": 1963,
"text": "Java"
},
{
"code": null,
"e": 1976,
"s": 1968,
"text": "Python3"
},
{
"code": null,
"e": 1979,
"s": 1976,
"text": "C#"
},
{
"code": null,
"e": 1990,
"s": 1979,
"text": "Javascript"
},
{
"code": "// CPP program to decode NULL CIPHER#include <bits/stdc++.h>using namespace std;string decode(string str){ // Store the decoded string. string res = \"\"; // found variable is used to tell that the encoded // encoded character is found in that particular word. bool found = false; for (int i = 0; i < str.size(); i++) { // Set found variable to false whenever we find // whitespace, meaning that encoded character for // new word is not found if (str[i] == ' ') { found = false; continue; } if (!found) { if (str[i] >= 'A' && str[i] <= 'Z') { res += str[i] + 32; found = true; } else if (str[i] >= 'a' && str[i] <= 'z') { res += str[i]; found = true; } } } return res;}// Driver codeint main(){ string in; in = \"A Step by Step Guide for Placement Preparation by GeeksforGeeks\"; cout << \"Enciphered Message: \"; // Function call cout << decode(in) << endl; return 0;}",
"e": 3113,
"s": 1990,
"text": null
},
{
"code": "// Java program to decode NULL CIPHERclass GFG{ // Function to decode the message. static String decode(String str) { // Store the decoded string String res = \"\"; // found variable is used // to tell that the encoded // encoded character is // found in that particular word. boolean found = false; for (int i = 0; i < str.length(); i++) { // Set found variable to false // whenever we find // whitespace, meaning that // encoded character for // new word is not found if (str.charAt(i) == ' ') { found = false; continue; } if (!found) { if ((str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') || (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')) { res += Character.toString(str.charAt(i)); found = true; } } } return res.toLowerCase(); } // Driver Code public static void main(String[] args) { String in; in = \"A Step by Step Guide for Placement Preparation by GeeksforGeeks\"; System.out.println(\"Enciphered Message: \" + decode(in)); }} // This code is contributed by Vivek Kumar Singh",
"e": 4470,
"s": 3113,
"text": null
},
{
"code": "# Python program to decode NULL CIPHER # Function to decode the message.def decode(string): # Store the decoded string res = \"\" # found variable is used # to tell that the encoded # encoded character is # found in that particular word. found = False for character in string: # Set found variable to false # whenever we find # whitespace, meaning that # encoded character for # new word is not found if character == ' ': found = False continue if not found: if character>='A' and character<='Z' or character>='a' and character<='z': res += character found = True return res.lower() # Driver codeif __name__ == \"__main__\": input = \"A Step by Step Guide for Placement Preparation by GeeksforGeeks\" print(\"Enciphered Message:\",decode(input)) # This code is contributed by Vivek Kumar Singh",
"e": 5411,
"s": 4470,
"text": null
},
{
"code": "// A C# program to decode NULL CIPHERusing System; class GFG{ // Function to decode the message. static String decode(String str) { // Store the decoded string String res = \"\"; // found variable is used // to tell that the encoded // encoded character is // found in that particular word. Boolean found = false; for (int i = 0; i < str.Length; i++) { // Set found variable to false whenever we find // whitespace, meaning that encoded character for // new word is not found if (str[i] == ' ') { found = false; continue; } if (!found) { if (str[i] >= 'A' && str[i] <= 'Z') { res += (char)(str[i] + 32); found = true; } else if (str[i] >= 'a' && str[i] <= 'z') { res += (char)str[i]; found = true; } } } return res; } // Driver Code public static void Main(String[] args) { String str; str = \"A Step by Step Guide for Placement Preparation by GeeksforGeeks\"; Console.WriteLine(\"Enciphered Message: \" + decode(str)); }} // This code has been contributed by 29AjayKumar",
"e": 6705,
"s": 5411,
"text": null
},
{
"code": "<script>// Javascript program to decode NULL CIPHER // Function to decode the message.function decode(str){ // Store the decoded string let res = \"\"; // found variable is used // to tell that the encoded // encoded character is // found in that particular word. let found = false; for (let i = 0; i < str.length; i++) { // Set found variable to false // whenever we find // whitespace, meaning that // encoded character for // new word is not found if (str[i] == ' ') { found = false; continue; } if (!found) { if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) { res += (str[i]); found = true; } } } return res.toLowerCase();} // Driver Codelet In = \"A Step by Step Guide for Placement Preparation by GeeksforGeeks\";document.write(\"Enciphered Message: \" + decode(In)); // This code is contributed by rag2127</script>",
"e": 7880,
"s": 6705,
"text": null
},
{
"code": null,
"e": 7889,
"s": 7880,
"text": "Output: "
},
{
"code": null,
"e": 7920,
"s": 7889,
"text": "Enciphered Message: asbsgfppbg"
},
{
"code": null,
"e": 8341,
"s": 7920,
"text": "This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 8358,
"s": 8341,
"text": "Vivekkumar Singh"
},
{
"code": null,
"e": 8370,
"s": 8358,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8378,
"s": 8370,
"text": "rag2127"
},
{
"code": null,
"e": 8390,
"s": 8378,
"text": "anikakapoor"
},
{
"code": null,
"e": 8403,
"s": 8390,
"text": "cryptography"
},
{
"code": null,
"e": 8411,
"s": 8403,
"text": "Strings"
},
{
"code": null,
"e": 8419,
"s": 8411,
"text": "Strings"
},
{
"code": null,
"e": 8432,
"s": 8419,
"text": "cryptography"
},
{
"code": null,
"e": 8530,
"s": 8432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8575,
"s": 8530,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 8639,
"s": 8575,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 8684,
"s": 8639,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 8719,
"s": 8684,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 8784,
"s": 8719,
"text": "A Program to check if strings are rotations of each other or not"
},
{
"code": null,
"e": 8813,
"s": 8784,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 8894,
"s": 8813,
"text": "Find the smallest window in a string containing all characters of another string"
},
{
"code": null,
"e": 8955,
"s": 8894,
"text": "Program to count occurrence of a given character in a string"
},
{
"code": null,
"e": 8996,
"s": 8955,
"text": "Convert character array to string in C++"
}
] |
C# | Check if two List objects are equal | 27 Jan, 2019
Equals(Object) Method which is inherited from the Object class is used to check if a specified List<T> object is equal to another List<T> object or not.
Syntax:
public virtual bool Equals (object obj);
Here, obj is the object which is to be compared with the current object.
Return Value: This method return true if the specified object is equal to the current object otherwise it returns false.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# program to if a List object// is equal to another List objectusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(19); firstlist.Add(21); firstlist.Add(9); firstlist.Add(75); firstlist.Add(19); firstlist.Add(73); // Checking whether firstlist is // equal to itself or not Console.WriteLine(firstlist.Equals(firstlist)); }}
True
Example 2:
// C# program to if a List object// is equal to another List objectusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of strings List<string> list1 = new List<string>(); // Inserting elements in List list1.Add("DS"); list1.Add("C++"); list1.Add("Java"); list1.Add("JavaScript"); // Creating an List<T> of Integers List<int> list2 = new List<int>(); // Adding elements to List list2.Add(78); list2.Add(44); list2.Add(27); list2.Add(98); list2.Add(74); // Checking whether list1 is // equal to list2 or not Console.WriteLine(list1.Equals(list2)); // Creating a List of integers List<int> list3 = new List<int>(); // Assigning list2 to list3 list3 = list2; // Checking whether list3 is // equal to list2 or not Console.WriteLine(list3.Equals(list2)); }}
False
True
Note: If the current instance is a reference type, the Equals(Object) method checks for reference equality.
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Class and Object
C# | Constructors
C# | Replace() Method
C# | Encapsulation
Extension Method in C# | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Jan, 2019"
},
{
"code": null,
"e": 207,
"s": 54,
"text": "Equals(Object) Method which is inherited from the Object class is used to check if a specified List<T> object is equal to another List<T> object or not."
},
{
"code": null,
"e": 215,
"s": 207,
"text": "Syntax:"
},
{
"code": null,
"e": 256,
"s": 215,
"text": "public virtual bool Equals (object obj);"
},
{
"code": null,
"e": 329,
"s": 256,
"text": "Here, obj is the object which is to be compared with the current object."
},
{
"code": null,
"e": 450,
"s": 329,
"text": "Return Value: This method return true if the specified object is equal to the current object otherwise it returns false."
},
{
"code": null,
"e": 511,
"s": 450,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 522,
"s": 511,
"text": "Example 1:"
},
{
"code": "// C# program to if a List object// is equal to another List objectusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(19); firstlist.Add(21); firstlist.Add(9); firstlist.Add(75); firstlist.Add(19); firstlist.Add(73); // Checking whether firstlist is // equal to itself or not Console.WriteLine(firstlist.Equals(firstlist)); }}",
"e": 1161,
"s": 522,
"text": null
},
{
"code": null,
"e": 1167,
"s": 1161,
"text": "True\n"
},
{
"code": null,
"e": 1178,
"s": 1167,
"text": "Example 2:"
},
{
"code": "// C# program to if a List object// is equal to another List objectusing System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of strings List<string> list1 = new List<string>(); // Inserting elements in List list1.Add(\"DS\"); list1.Add(\"C++\"); list1.Add(\"Java\"); list1.Add(\"JavaScript\"); // Creating an List<T> of Integers List<int> list2 = new List<int>(); // Adding elements to List list2.Add(78); list2.Add(44); list2.Add(27); list2.Add(98); list2.Add(74); // Checking whether list1 is // equal to list2 or not Console.WriteLine(list1.Equals(list2)); // Creating a List of integers List<int> list3 = new List<int>(); // Assigning list2 to list3 list3 = list2; // Checking whether list3 is // equal to list2 or not Console.WriteLine(list3.Equals(list2)); }}",
"e": 2220,
"s": 1178,
"text": null
},
{
"code": null,
"e": 2232,
"s": 2220,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 2340,
"s": 2232,
"text": "Note: If the current instance is a reference type, the Equals(Object) method checks for reference equality."
},
{
"code": null,
"e": 2360,
"s": 2340,
"text": "CSharp-Generic-List"
},
{
"code": null,
"e": 2385,
"s": 2360,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 2399,
"s": 2385,
"text": "CSharp-method"
},
{
"code": null,
"e": 2402,
"s": 2399,
"text": "C#"
},
{
"code": null,
"e": 2500,
"s": 2402,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2543,
"s": 2500,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2574,
"s": 2543,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 2589,
"s": 2574,
"text": "C# | Delegates"
},
{
"code": null,
"e": 2638,
"s": 2589,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2654,
"s": 2638,
"text": "C# | Data Types"
},
{
"code": null,
"e": 2676,
"s": 2654,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 2694,
"s": 2676,
"text": "C# | Constructors"
},
{
"code": null,
"e": 2716,
"s": 2694,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 2735,
"s": 2716,
"text": "C# | Encapsulation"
}
] |
BigDecimal divide() Method in Java with Examples | 17 Jun, 2019
The java.math.BigDecimal.divide(BigDecimal divisor) is used to calculate the Quotient of two BigDecimals. The Quotient is given by (this / divisor). This method performs an operation upon the current BigDecimal by which this method is called and the BigDecimal passed as the parameter.
There are five overloads of divide method available in Java which is listed below:
divide(BigDecimal divisor)
divide(BigDecimal divisor, MathContext mc)
divide(BigDecimal divisor, RoundingMode roundingMode)
divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
divide(BigDecimal divisor, int roundingMode)
Note: The method divide(BigDecimal divisor, int roundingMode) is deprecated since Java 9.
The Quotient is given by (this / divisor) and whose preferred scale is (this.scale() – divisor.scale()).Syntax:
public BigDecimal divide(BigDecimal divisor)
Parameters: This method accepts a parameter divisor by which this BigDecimal is to be divided for obtaining quotient.Return value: This method returns a BigDecimal which holds the result (this / divisor).Exception: If parameter divisor is 0 or the exact quotient does not have a terminating decimal expansion then Arithmetic Exception is thrown.
Below programs is used to illustrate the divide() method of BigDecimal.
// Java program to demonstrate// divide() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values String input1 = "204800000"; String input2 = "256"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal divisor = new BigDecimal(input2); // Using divide() method res = a.divide(divisor); // Display the result in BigDecimal System.out.println(res); }}
800000
Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divide(java.math.BigDecimal)
This method is used to calculate the quotient of two BigDecimals whose value is (this / divisor), with rounding according to the context settings.Syntax:
public BigDecimal divide(BigDecimal divisor,
MathContext mc)
Parameters: This method accepts two parameters:
divisor by which this BigDecimal is to be divided
mc of type MathContext for context settings.
Return value: This method returns a BigDecimal which holds the result (this / divisor) and rounded as necessary.
Exception: The method throws Arithmetic Exception if the result is inexact but the rounding mode is UNNECESSARY or mc.precision == 0 and the quotient has a non-terminating decimal expansion.
Below programs is used to illustrate the divide() method of BigDecimal.
// Java program to demonstrate// divide() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values String input1 = "24536482"; String input2 = "264"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal divisor = new BigDecimal(input2); // Set precision to 5 MathContext mc = new MathContext(5); // Using divide() method res = a.divide(divisor, mc); // Display the result in BigDecimal System.out.println(res); }}
92941
Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divide(java.math.BigDecimal, java.math.MathContext)
The Quotient is given by (this / divisor) and whose preferred scale is this.scale(). The specific rounding mode is applied if rounding is needed to generate result with the given scale.Syntax:
public BigDecimal divide(BigDecimal divisor,
RoundingMode roundingMode)
Parameters: This method accepts two parameters:
divisor by which this BigDecimal is to be divided
roundingMode of type RoundingMode that tells which rounding mode to apply.
Return value: This method returns a BigDecimal which holds the result (this / divisor).Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and this.scale() is insufficient to represent the result of the division exactly or Divisor is 0.
Below programs is used to illustrate the divide() method of BigDecimal.
// Java program to demonstrate// divide() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values String input1 = "2453648454542"; String input2 = "264"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal divisor = new BigDecimal(input2); // Using divide() method // Using RoundingMode.CEILING res = a.divide(divisor, RoundingMode.CEILING); // Display the result in BigDecimal System.out.println(res); }}
9294122934
Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divide(java.math.BigDecimal, java.math.RoundingMode)
The Quotient is given by (this / divisor) whose preferred scale is specified. If rounding is required to generate a result with the specified scale, the specified rounding mode is applied.Syntax:
public BigDecimal divide(BigDecimal divisor,
int scale,
RoundingMode roundingMode)
Parameters: This method accepts three parameters:
divisor by which this BigDecimal is to be divided
roundingMode of type RoundingMode that tells which rounding mode to apply
scale which sets the scale of the quotient.
Return value: This method returns a BigDecimal which holds the result (this / divisor).Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and the specified scale is insufficient to represent the result of the division exactly or Divisor is 0.
Below programs is used to illustrate the divide() method of BigDecimal.
// Java program to demonstrate// divide() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values String input1 = "2453648454542"; String input2 = "264"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal divisor = new BigDecimal(input2); // Using scale = 4 int scale = 4; // Using divide() method // Using RoundingMode.CEILING res = a.divide(divisor, scale, RoundingMode.CEILING); // Display the result in BigDecimal System.out.println(res); }}
9294122933.8713
Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divide(java.math.BigDecimal, int, java.math.RoundingMode)
Java-BigDecimal
Java-Functions
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2019"
},
{
"code": null,
"e": 314,
"s": 28,
"text": "The java.math.BigDecimal.divide(BigDecimal divisor) is used to calculate the Quotient of two BigDecimals. The Quotient is given by (this / divisor). This method performs an operation upon the current BigDecimal by which this method is called and the BigDecimal passed as the parameter."
},
{
"code": null,
"e": 397,
"s": 314,
"text": "There are five overloads of divide method available in Java which is listed below:"
},
{
"code": null,
"e": 424,
"s": 397,
"text": "divide(BigDecimal divisor)"
},
{
"code": null,
"e": 467,
"s": 424,
"text": "divide(BigDecimal divisor, MathContext mc)"
},
{
"code": null,
"e": 521,
"s": 467,
"text": "divide(BigDecimal divisor, RoundingMode roundingMode)"
},
{
"code": null,
"e": 586,
"s": 521,
"text": "divide(BigDecimal divisor, int scale, RoundingMode roundingMode)"
},
{
"code": null,
"e": 631,
"s": 586,
"text": "divide(BigDecimal divisor, int roundingMode)"
},
{
"code": null,
"e": 721,
"s": 631,
"text": "Note: The method divide(BigDecimal divisor, int roundingMode) is deprecated since Java 9."
},
{
"code": null,
"e": 833,
"s": 721,
"text": "The Quotient is given by (this / divisor) and whose preferred scale is (this.scale() – divisor.scale()).Syntax:"
},
{
"code": null,
"e": 879,
"s": 833,
"text": "public BigDecimal divide(BigDecimal divisor)\n"
},
{
"code": null,
"e": 1225,
"s": 879,
"text": "Parameters: This method accepts a parameter divisor by which this BigDecimal is to be divided for obtaining quotient.Return value: This method returns a BigDecimal which holds the result (this / divisor).Exception: If parameter divisor is 0 or the exact quotient does not have a terminating decimal expansion then Arithmetic Exception is thrown."
},
{
"code": null,
"e": 1297,
"s": 1225,
"text": "Below programs is used to illustrate the divide() method of BigDecimal."
},
{
"code": "// Java program to demonstrate// divide() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values String input1 = \"204800000\"; String input2 = \"256\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal divisor = new BigDecimal(input2); // Using divide() method res = a.divide(divisor); // Display the result in BigDecimal System.out.println(res); }}",
"e": 2072,
"s": 1297,
"text": null
},
{
"code": null,
"e": 2080,
"s": 2072,
"text": "800000\n"
},
{
"code": null,
"e": 2207,
"s": 2080,
"text": "Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divide(java.math.BigDecimal)"
},
{
"code": null,
"e": 2361,
"s": 2207,
"text": "This method is used to calculate the quotient of two BigDecimals whose value is (this / divisor), with rounding according to the context settings.Syntax:"
},
{
"code": null,
"e": 2448,
"s": 2361,
"text": "public BigDecimal divide(BigDecimal divisor,\n MathContext mc)\n"
},
{
"code": null,
"e": 2496,
"s": 2448,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 2546,
"s": 2496,
"text": "divisor by which this BigDecimal is to be divided"
},
{
"code": null,
"e": 2591,
"s": 2546,
"text": "mc of type MathContext for context settings."
},
{
"code": null,
"e": 2704,
"s": 2591,
"text": "Return value: This method returns a BigDecimal which holds the result (this / divisor) and rounded as necessary."
},
{
"code": null,
"e": 2895,
"s": 2704,
"text": "Exception: The method throws Arithmetic Exception if the result is inexact but the rounding mode is UNNECESSARY or mc.precision == 0 and the quotient has a non-terminating decimal expansion."
},
{
"code": null,
"e": 2967,
"s": 2895,
"text": "Below programs is used to illustrate the divide() method of BigDecimal."
},
{
"code": "// Java program to demonstrate// divide() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values String input1 = \"24536482\"; String input2 = \"264\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal divisor = new BigDecimal(input2); // Set precision to 5 MathContext mc = new MathContext(5); // Using divide() method res = a.divide(divisor, mc); // Display the result in BigDecimal System.out.println(res); }}",
"e": 3822,
"s": 2967,
"text": null
},
{
"code": null,
"e": 3829,
"s": 3822,
"text": "92941\n"
},
{
"code": null,
"e": 3979,
"s": 3829,
"text": "Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divide(java.math.BigDecimal, java.math.MathContext)"
},
{
"code": null,
"e": 4172,
"s": 3979,
"text": "The Quotient is given by (this / divisor) and whose preferred scale is this.scale(). The specific rounding mode is applied if rounding is needed to generate result with the given scale.Syntax:"
},
{
"code": null,
"e": 4270,
"s": 4172,
"text": "public BigDecimal divide(BigDecimal divisor,\n RoundingMode roundingMode)\n"
},
{
"code": null,
"e": 4318,
"s": 4270,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 4368,
"s": 4318,
"text": "divisor by which this BigDecimal is to be divided"
},
{
"code": null,
"e": 4443,
"s": 4368,
"text": "roundingMode of type RoundingMode that tells which rounding mode to apply."
},
{
"code": null,
"e": 4709,
"s": 4443,
"text": "Return value: This method returns a BigDecimal which holds the result (this / divisor).Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and this.scale() is insufficient to represent the result of the division exactly or Divisor is 0."
},
{
"code": null,
"e": 4781,
"s": 4709,
"text": "Below programs is used to illustrate the divide() method of BigDecimal."
},
{
"code": "// Java program to demonstrate// divide() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values String input1 = \"2453648454542\"; String input2 = \"264\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal divisor = new BigDecimal(input2); // Using divide() method // Using RoundingMode.CEILING res = a.divide(divisor, RoundingMode.CEILING); // Display the result in BigDecimal System.out.println(res); }}",
"e": 5610,
"s": 4781,
"text": null
},
{
"code": null,
"e": 5622,
"s": 5610,
"text": "9294122934\n"
},
{
"code": null,
"e": 5773,
"s": 5622,
"text": "Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divide(java.math.BigDecimal, java.math.RoundingMode)"
},
{
"code": null,
"e": 5969,
"s": 5773,
"text": "The Quotient is given by (this / divisor) whose preferred scale is specified. If rounding is required to generate a result with the specified scale, the specified rounding mode is applied.Syntax:"
},
{
"code": null,
"e": 6105,
"s": 5969,
"text": "public BigDecimal divide(BigDecimal divisor, \n int scale, \n RoundingMode roundingMode)\n"
},
{
"code": null,
"e": 6155,
"s": 6105,
"text": "Parameters: This method accepts three parameters:"
},
{
"code": null,
"e": 6205,
"s": 6155,
"text": "divisor by which this BigDecimal is to be divided"
},
{
"code": null,
"e": 6279,
"s": 6205,
"text": "roundingMode of type RoundingMode that tells which rounding mode to apply"
},
{
"code": null,
"e": 6323,
"s": 6279,
"text": "scale which sets the scale of the quotient."
},
{
"code": null,
"e": 6596,
"s": 6323,
"text": "Return value: This method returns a BigDecimal which holds the result (this / divisor).Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and the specified scale is insufficient to represent the result of the division exactly or Divisor is 0."
},
{
"code": null,
"e": 6668,
"s": 6596,
"text": "Below programs is used to illustrate the divide() method of BigDecimal."
},
{
"code": "// Java program to demonstrate// divide() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values String input1 = \"2453648454542\"; String input2 = \"264\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal divisor = new BigDecimal(input2); // Using scale = 4 int scale = 4; // Using divide() method // Using RoundingMode.CEILING res = a.divide(divisor, scale, RoundingMode.CEILING); // Display the result in BigDecimal System.out.println(res); }}",
"e": 7576,
"s": 6668,
"text": null
},
{
"code": null,
"e": 7593,
"s": 7576,
"text": "9294122933.8713\n"
},
{
"code": null,
"e": 7749,
"s": 7593,
"text": "Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divide(java.math.BigDecimal, int, java.math.RoundingMode)"
},
{
"code": null,
"e": 7765,
"s": 7749,
"text": "Java-BigDecimal"
},
{
"code": null,
"e": 7780,
"s": 7765,
"text": "Java-Functions"
},
{
"code": null,
"e": 7798,
"s": 7780,
"text": "Java-math-package"
},
{
"code": null,
"e": 7803,
"s": 7798,
"text": "Java"
},
{
"code": null,
"e": 7808,
"s": 7803,
"text": "Java"
}
] |
What is Scrambling in Digital Electronics ? | 31 May, 2022
A computer network is designed to send information from one point to another. Data that we send can either be digital or analog. Also, signals that represent data can also be digital or analog. Thus to send data by using signals, we must be able to convert the data into signals, this conversion can be Analog to Analog, Analog to Digital, Digital to Analog, or Digital to Digital. Digital to Digital conversion involves three techniques – Line Coding, Block Coding, and Scrambling. Line Coding is always needed, whereas Block Coding and Scrambling may or may not be needed depending upon the need. Scrambling is a technique that does not increase the number of bits and does provide synchronization. The problem with techniques like Bipolar AMI(Alternate Mark Inversion) is that continuous sequence of zero’s create synchronization problems one solution to this is Scrambling.
Prerequisite: Block Coding, Line Coding
There are two common scrambling techniques:
B8ZS(Bipolar with 8-zero substitution)HDB3(High-density bipolar3-zero)
B8ZS(Bipolar with 8-zero substitution)
HDB3(High-density bipolar3-zero)
B8ZS(Bipolar with 8-zero substitution): This technique is similar to Bipolar AMI except when eight consecutive zero-level voltages are encountered they are replaced by the sequence, “000VB0VB”.
Note:
V(Violation), is a non-zero voltage which means the signal has the same polarity as the previous non-zero voltage. Thus it is a violation of the general AMI technique.
B(Bipolar), is also a non-zero voltage level that is in accordance with the AMI rule (i.e., opposite polarity from the previous non-zero voltage).
Example: Data = 100000000
Note: Both figures (left and right one) are correct, depending upon the last non-zero voltage signal of the previous data sequence (i.e., sequence before current data sequence “100000000”).
HDB3(High-density bipolar3-zero): In this technique, four consecutive zero-level voltages are replaced with a sequence “000V” or “B00V”. Rules for using these sequences:
If the number of nonzero pulses after the last substitution is odd, the substitution pattern will be “000V”, this helps in maintaining a total number of nonzero pulses even.
If the number of nonzero pulses after the last substitution is even, the substitution pattern will be “B00V”. Hence even the number of nonzero pulses is maintained again.
Example: Data = 1100001000000000
Output explanation: After representing the first two 1’s of data we encounter four consecutive zeros. Since our last substitutions were two 1’s(thus the number of non-zero pulses is even). So, we substitute four zeros with “B00V”.
Note: Zero non-zero pulses are also even.
singhankitasingh066
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 931,
"s": 52,
"text": "A computer network is designed to send information from one point to another. Data that we send can either be digital or analog. Also, signals that represent data can also be digital or analog. Thus to send data by using signals, we must be able to convert the data into signals, this conversion can be Analog to Analog, Analog to Digital, Digital to Analog, or Digital to Digital. Digital to Digital conversion involves three techniques – Line Coding, Block Coding, and Scrambling. Line Coding is always needed, whereas Block Coding and Scrambling may or may not be needed depending upon the need. Scrambling is a technique that does not increase the number of bits and does provide synchronization. The problem with techniques like Bipolar AMI(Alternate Mark Inversion) is that continuous sequence of zero’s create synchronization problems one solution to this is Scrambling. "
},
{
"code": null,
"e": 972,
"s": 931,
"text": "Prerequisite: Block Coding, Line Coding "
},
{
"code": null,
"e": 1016,
"s": 972,
"text": "There are two common scrambling techniques:"
},
{
"code": null,
"e": 1087,
"s": 1016,
"text": "B8ZS(Bipolar with 8-zero substitution)HDB3(High-density bipolar3-zero)"
},
{
"code": null,
"e": 1126,
"s": 1087,
"text": "B8ZS(Bipolar with 8-zero substitution)"
},
{
"code": null,
"e": 1159,
"s": 1126,
"text": "HDB3(High-density bipolar3-zero)"
},
{
"code": null,
"e": 1354,
"s": 1159,
"text": "B8ZS(Bipolar with 8-zero substitution): This technique is similar to Bipolar AMI except when eight consecutive zero-level voltages are encountered they are replaced by the sequence, “000VB0VB”. "
},
{
"code": null,
"e": 1360,
"s": 1354,
"text": "Note:"
},
{
"code": null,
"e": 1528,
"s": 1360,
"text": "V(Violation), is a non-zero voltage which means the signal has the same polarity as the previous non-zero voltage. Thus it is a violation of the general AMI technique."
},
{
"code": null,
"e": 1675,
"s": 1528,
"text": "B(Bipolar), is also a non-zero voltage level that is in accordance with the AMI rule (i.e., opposite polarity from the previous non-zero voltage)."
},
{
"code": null,
"e": 1701,
"s": 1675,
"text": "Example: Data = 100000000"
},
{
"code": null,
"e": 1895,
"s": 1704,
"text": "Note: Both figures (left and right one) are correct, depending upon the last non-zero voltage signal of the previous data sequence (i.e., sequence before current data sequence “100000000”). "
},
{
"code": null,
"e": 2065,
"s": 1895,
"text": "HDB3(High-density bipolar3-zero): In this technique, four consecutive zero-level voltages are replaced with a sequence “000V” or “B00V”. Rules for using these sequences:"
},
{
"code": null,
"e": 2239,
"s": 2065,
"text": "If the number of nonzero pulses after the last substitution is odd, the substitution pattern will be “000V”, this helps in maintaining a total number of nonzero pulses even."
},
{
"code": null,
"e": 2410,
"s": 2239,
"text": "If the number of nonzero pulses after the last substitution is even, the substitution pattern will be “B00V”. Hence even the number of nonzero pulses is maintained again."
},
{
"code": null,
"e": 2444,
"s": 2410,
"text": "Example: Data = 1100001000000000 "
},
{
"code": null,
"e": 2676,
"s": 2444,
"text": "Output explanation: After representing the first two 1’s of data we encounter four consecutive zeros. Since our last substitutions were two 1’s(thus the number of non-zero pulses is even). So, we substitute four zeros with “B00V”. "
},
{
"code": null,
"e": 2718,
"s": 2676,
"text": "Note: Zero non-zero pulses are also even."
},
{
"code": null,
"e": 2738,
"s": 2718,
"text": "singhankitasingh066"
},
{
"code": null,
"e": 2773,
"s": 2738,
"text": "Digital Electronics & Logic Design"
}
] |
XOR two binary strings of unequal lengths | 06 Jul, 2021
Given two binary string of unequal lengths A and B, the task is to print the binary string which is the XOR of A and B.Examples:
Input: A = “11001”, B = “111111” Output: 100110Input: A = “11111”, B = “0” Output: 11111
Approach: The idea is to first make both the strings of equal length and then perform the XOR of each character one by one and store it in the resultant string.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to insert n 0s in the// beginning of the given stringvoid addZeros(string& str, int n){ for (int i = 0; i < n; i++) { str = "0" + str; }} // Function to return the XOR// of the given stringsstring getXOR(string a, string b){ // Lengths of the given strings int aLen = a.length(); int bLen = b.length(); // Make both the strings of equal lengths // by inserting 0s in the beginning if (aLen > bLen) { addZeros(b, aLen - bLen); } else if (bLen > aLen) { addZeros(a, bLen - aLen); } // Updated length int len = max(aLen, bLen); // To store the resultant XOR string res = ""; for (int i = 0; i < len; i++) { if (a[i] == b[i]) res += "0"; else res += "1"; } return res;} // Driver codeint main(){ string a = "11001", b = "111111"; cout << getXOR(a, b); return 0;}
// Java implementation of the approachclass GFG{ // Function to insert n 0s in the // beginning of the given string static String addZeros(String str, int n) { for (int i = 0; i < n; i++) { str = "0" + str; } return str; } // Function to return the XOR // of the given strings static String getXOR(String a, String b) { // Lengths of the given strings int aLen = a.length(); int bLen = b.length(); // Make both the strings of equal lengths // by inserting 0s in the beginning if (aLen > bLen) { a = addZeros(b, aLen - bLen); } else if (bLen > aLen) { a = addZeros(a, bLen - aLen); } // Updated length int len = Math.max(aLen, bLen); // To store the resultant XOR String res = ""; for (int i = 0; i < len; i++) { if (a.charAt(i) == b.charAt(i)) res += "0"; else res += "1"; } return res; } // Driver code public static void main (String[] args) { String a = "11001", b = "111111"; System.out.println(getXOR(a, b)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach # Function to insert n 0s in the# beginning of the given stringdef addZeros(strr, n): for i in range(n): strr = "0" + strr return strr # Function to return the XOR# of the given stringsdef getXOR(a, b): # Lengths of the given strings aLen = len(a) bLen = len(b) # Make both the strings of equal lengths # by inserting 0s in the beginning if (aLen > bLen): b = addZeros(b, aLen - bLen) elif (bLen > aLen): a = addZeros(a, bLen - aLen) # Updated length lenn = max(aLen, bLen); # To store the resultant XOR res = "" for i in range(lenn): if (a[i] == b[i]): res += "0" else: res += "1" return res # Driver codea = "11001"b = "111111" print(getXOR(a, b)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ // Function to insert n 0s in the // beginning of the given string static String addZeros(String str, int n) { for (int i = 0; i < n; i++) { str = "0" + str; } return str; } // Function to return the XOR // of the given strings static String getXOR(String a, String b) { // Lengths of the given strings int aLen = a.Length; int bLen = b.Length; // Make both the strings of equal lengths // by inserting 0s in the beginning if (aLen > bLen) { a = addZeros(b, aLen - bLen); } else if (bLen > aLen) { a = addZeros(a, bLen - aLen); } // Updated length int len = Math.Max(aLen, bLen); // To store the resultant XOR String res = ""; for (int i = 0; i < len; i++) { if (a[i] == b[i]) res += "0"; else res += "1"; } return res; } // Driver code public static void Main(String[] args) { String a = "11001", b = "111111"; Console.WriteLine(getXOR(a, b)); }} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach // Function to insert n 0s in the // beginning of the given string function addZeros(str, n) { for (let i = 0; i < n; i++) { str = "0" + str; } return str; } // Function to return the XOR // of the given strings function getXOR(a, b) { // Lengths of the given strings let aLen = a.length; let bLen = b.length; // Make both the strings of equal lengths // by inserting 0s in the beginning if (aLen > bLen) { a = addZeros(b, aLen - bLen); } else if (bLen > aLen) { a = addZeros(a, bLen - aLen); } // Updated length let len = Math.max(aLen, bLen); // To store the resultant XOR let res = ""; for (let i = 0; i < len; i++) { if (a[i] == b[i]) res += "0"; else res += "1"; } return res; } let a = "11001", b = "111111"; document.write(getXOR(a, b)); // This code is contributed by divyeshrabadiya07.</script>
100110
Time Complexity: O(len), len=Max(length a,length b)
Auxiliary Space: O(len)
mohit kumar 29
ankthon
Rajput-Ji
aditya7409
divyeshrabadiya07
ruhelaa48
binary-string
Bitwise-XOR
Competitive Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 182,
"s": 52,
"text": "Given two binary string of unequal lengths A and B, the task is to print the binary string which is the XOR of A and B.Examples: "
},
{
"code": null,
"e": 272,
"s": 182,
"text": "Input: A = “11001”, B = “111111” Output: 100110Input: A = “11111”, B = “0” Output: 11111 "
},
{
"code": null,
"e": 485,
"s": 272,
"text": "Approach: The idea is to first make both the strings of equal length and then perform the XOR of each character one by one and store it in the resultant string.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 489,
"s": 485,
"text": "C++"
},
{
"code": null,
"e": 494,
"s": 489,
"text": "Java"
},
{
"code": null,
"e": 502,
"s": 494,
"text": "Python3"
},
{
"code": null,
"e": 505,
"s": 502,
"text": "C#"
},
{
"code": null,
"e": 516,
"s": 505,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to insert n 0s in the// beginning of the given stringvoid addZeros(string& str, int n){ for (int i = 0; i < n; i++) { str = \"0\" + str; }} // Function to return the XOR// of the given stringsstring getXOR(string a, string b){ // Lengths of the given strings int aLen = a.length(); int bLen = b.length(); // Make both the strings of equal lengths // by inserting 0s in the beginning if (aLen > bLen) { addZeros(b, aLen - bLen); } else if (bLen > aLen) { addZeros(a, bLen - aLen); } // Updated length int len = max(aLen, bLen); // To store the resultant XOR string res = \"\"; for (int i = 0; i < len; i++) { if (a[i] == b[i]) res += \"0\"; else res += \"1\"; } return res;} // Driver codeint main(){ string a = \"11001\", b = \"111111\"; cout << getXOR(a, b); return 0;}",
"e": 1496,
"s": 516,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to insert n 0s in the // beginning of the given string static String addZeros(String str, int n) { for (int i = 0; i < n; i++) { str = \"0\" + str; } return str; } // Function to return the XOR // of the given strings static String getXOR(String a, String b) { // Lengths of the given strings int aLen = a.length(); int bLen = b.length(); // Make both the strings of equal lengths // by inserting 0s in the beginning if (aLen > bLen) { a = addZeros(b, aLen - bLen); } else if (bLen > aLen) { a = addZeros(a, bLen - aLen); } // Updated length int len = Math.max(aLen, bLen); // To store the resultant XOR String res = \"\"; for (int i = 0; i < len; i++) { if (a.charAt(i) == b.charAt(i)) res += \"0\"; else res += \"1\"; } return res; } // Driver code public static void main (String[] args) { String a = \"11001\", b = \"111111\"; System.out.println(getXOR(a, b)); }} // This code is contributed by AnkitRai01",
"e": 2806,
"s": 1496,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to insert n 0s in the# beginning of the given stringdef addZeros(strr, n): for i in range(n): strr = \"0\" + strr return strr # Function to return the XOR# of the given stringsdef getXOR(a, b): # Lengths of the given strings aLen = len(a) bLen = len(b) # Make both the strings of equal lengths # by inserting 0s in the beginning if (aLen > bLen): b = addZeros(b, aLen - bLen) elif (bLen > aLen): a = addZeros(a, bLen - aLen) # Updated length lenn = max(aLen, bLen); # To store the resultant XOR res = \"\" for i in range(lenn): if (a[i] == b[i]): res += \"0\" else: res += \"1\" return res # Driver codea = \"11001\"b = \"111111\" print(getXOR(a, b)) # This code is contributed by Mohit Kumar",
"e": 3646,
"s": 2806,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to insert n 0s in the // beginning of the given string static String addZeros(String str, int n) { for (int i = 0; i < n; i++) { str = \"0\" + str; } return str; } // Function to return the XOR // of the given strings static String getXOR(String a, String b) { // Lengths of the given strings int aLen = a.Length; int bLen = b.Length; // Make both the strings of equal lengths // by inserting 0s in the beginning if (aLen > bLen) { a = addZeros(b, aLen - bLen); } else if (bLen > aLen) { a = addZeros(a, bLen - aLen); } // Updated length int len = Math.Max(aLen, bLen); // To store the resultant XOR String res = \"\"; for (int i = 0; i < len; i++) { if (a[i] == b[i]) res += \"0\"; else res += \"1\"; } return res; } // Driver code public static void Main(String[] args) { String a = \"11001\", b = \"111111\"; Console.WriteLine(getXOR(a, b)); }} // This code is contributed by Rajput-Ji",
"e": 4947,
"s": 3646,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to insert n 0s in the // beginning of the given string function addZeros(str, n) { for (let i = 0; i < n; i++) { str = \"0\" + str; } return str; } // Function to return the XOR // of the given strings function getXOR(a, b) { // Lengths of the given strings let aLen = a.length; let bLen = b.length; // Make both the strings of equal lengths // by inserting 0s in the beginning if (aLen > bLen) { a = addZeros(b, aLen - bLen); } else if (bLen > aLen) { a = addZeros(a, bLen - aLen); } // Updated length let len = Math.max(aLen, bLen); // To store the resultant XOR let res = \"\"; for (let i = 0; i < len; i++) { if (a[i] == b[i]) res += \"0\"; else res += \"1\"; } return res; } let a = \"11001\", b = \"111111\"; document.write(getXOR(a, b)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 6156,
"s": 4947,
"text": null
},
{
"code": null,
"e": 6163,
"s": 6156,
"text": "100110"
},
{
"code": null,
"e": 6217,
"s": 6165,
"text": "Time Complexity: O(len), len=Max(length a,length b)"
},
{
"code": null,
"e": 6241,
"s": 6217,
"text": "Auxiliary Space: O(len)"
},
{
"code": null,
"e": 6256,
"s": 6241,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 6264,
"s": 6256,
"text": "ankthon"
},
{
"code": null,
"e": 6274,
"s": 6264,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6285,
"s": 6274,
"text": "aditya7409"
},
{
"code": null,
"e": 6303,
"s": 6285,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 6313,
"s": 6303,
"text": "ruhelaa48"
},
{
"code": null,
"e": 6327,
"s": 6313,
"text": "binary-string"
},
{
"code": null,
"e": 6339,
"s": 6327,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 6363,
"s": 6339,
"text": "Competitive Programming"
},
{
"code": null,
"e": 6371,
"s": 6363,
"text": "Strings"
},
{
"code": null,
"e": 6379,
"s": 6371,
"text": "Strings"
}
] |
Python – Initialize empty array of given length | 06 Dec, 2019
Prerequisite: List in Python
As we know Array is a collection of items stored at contiguous memory locations. In Python, List (Dynamic Array) can be treated as Array. In this article, we will learn how to initialize an empty array of some given size.
Let’s see different Pythonic ways to do this task.
Method 1 –
Syntax:
list1 = [0] * size
list2 = [None] * size
# initializes all the 10 spaces with 0’sa = [0] * 10 # initializes all the 10 spaces with Noneb = [None] * 10 # initializes all the 10 spaces with A'sc = ['A'] * 5 # empty list which is not null, it's just empty.d = [] print (a, "\n", b, "\n", c, "\n", d);
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[None, None, None, None, None, None, None, None, None, None]
['A', 'A', 'A', 'A', 'A']
[]
Method 2 – Use loops just like C and assign the size.
Syntax:
a = [0 for x in range(size)] #using loops
a = []b = [] # initialize the spaces with 0’s with # the help of list comprehensionsa = [0 for x in range(10)]print(a) # initialize multi-array b = [ [ None for y in range( 2 ) ] for x in range( 2 ) ] print(b)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[[None, None], [None, None]]
Method 3 – Using Numpy to create empty array.
import numpy # create a simple array with numpy empty()a = numpy.empty(5, dtype=object)print(a) # create multi-dim array by providing shapematrix = numpy.empty(shape=(2,5),dtype='object')print(matrix)
Output:
[None None None None None]
[[None None None None None]
[None None None None None]]
Picked
Python list-programs
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 82,
"s": 53,
"text": "Prerequisite: List in Python"
},
{
"code": null,
"e": 304,
"s": 82,
"text": "As we know Array is a collection of items stored at contiguous memory locations. In Python, List (Dynamic Array) can be treated as Array. In this article, we will learn how to initialize an empty array of some given size."
},
{
"code": null,
"e": 355,
"s": 304,
"text": "Let’s see different Pythonic ways to do this task."
},
{
"code": null,
"e": 366,
"s": 355,
"text": "Method 1 –"
},
{
"code": null,
"e": 374,
"s": 366,
"text": "Syntax:"
},
{
"code": null,
"e": 416,
"s": 374,
"text": "list1 = [0] * size\nlist2 = [None] * size\n"
},
{
"code": "# initializes all the 10 spaces with 0’sa = [0] * 10 # initializes all the 10 spaces with Noneb = [None] * 10 # initializes all the 10 spaces with A'sc = ['A'] * 5 # empty list which is not null, it's just empty.d = [] print (a, \"\\n\", b, \"\\n\", c, \"\\n\", d);",
"e": 681,
"s": 416,
"text": null
},
{
"code": null,
"e": 806,
"s": 681,
"text": "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] \n[None, None, None, None, None, None, None, None, None, None] \n['A', 'A', 'A', 'A', 'A'] \n[]\n"
},
{
"code": null,
"e": 861,
"s": 806,
"text": " Method 2 – Use loops just like C and assign the size."
},
{
"code": null,
"e": 869,
"s": 861,
"text": "Syntax:"
},
{
"code": null,
"e": 912,
"s": 869,
"text": "a = [0 for x in range(size)] #using loops\n"
},
{
"code": "a = []b = [] # initialize the spaces with 0’s with # the help of list comprehensionsa = [0 for x in range(10)]print(a) # initialize multi-array b = [ [ None for y in range( 2 ) ] for x in range( 2 ) ] print(b)",
"e": 1150,
"s": 912,
"text": null
},
{
"code": null,
"e": 1212,
"s": 1150,
"text": "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n[[None, None], [None, None]]\n"
},
{
"code": null,
"e": 1259,
"s": 1212,
"text": " Method 3 – Using Numpy to create empty array."
},
{
"code": "import numpy # create a simple array with numpy empty()a = numpy.empty(5, dtype=object)print(a) # create multi-dim array by providing shapematrix = numpy.empty(shape=(2,5),dtype='object')print(matrix)",
"e": 1462,
"s": 1259,
"text": null
},
{
"code": null,
"e": 1470,
"s": 1462,
"text": "Output:"
},
{
"code": null,
"e": 1556,
"s": 1470,
"text": "[None None None None None]\n\n[[None None None None None]\n [None None None None None]]\n"
},
{
"code": null,
"e": 1563,
"s": 1556,
"text": "Picked"
},
{
"code": null,
"e": 1584,
"s": 1563,
"text": "Python list-programs"
},
{
"code": null,
"e": 1591,
"s": 1584,
"text": "Python"
},
{
"code": null,
"e": 1607,
"s": 1591,
"text": "Python Programs"
},
{
"code": null,
"e": 1626,
"s": 1607,
"text": "Technical Scripter"
}
] |
Java Program to Convert Byte Array to String | 03 May, 2022
A byte is 8 bits of binary data so do byte array is an array of bytes used to store the collection of binary data. There are multiple ways to change byte array to String in Java, you can either use methods from JDK, or you can use open-source complementary APIs like Apache commons and Google Guava. These APIs provide at least two sets of methods to create a String from a byte array; one, which uses default platform encoding, and the other which takes character encoding.
Using UTF-8 encodingUsing String Class Constructor
Using UTF-8 encoding
Using String Class Constructor
It’s also one of the best practices for specifying character encoding while converting bytes to the character in any programming language. It might be possible that your byte array contains non-printable ASCII characters. Let’s first see JDK’s way of converting byte[] to a string. Some programmers, also recommend using Charset over String for specifying character encoding, e.g. instead of “UTF-8” use StandardCharsets.UTF_8 mainly to avoid Unsupported Encoding Exception in the worst case.
Case 1: Without character encoding
We can convert the byte array to String for the ASCII character set without even specifying the character encoding. The idea is to pass the byte[] to the string. It is as shown in the below example which is as follows:
Example:
Java
// Java Program to Convert Byte Array to String// Without character encoding // Importing required classesimport java.io.IOException;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Getting bytes from the custom input string // using getBytes() method and // storing it in a byte array byte[] bytes = "Geeksforgeeks".getBytes(); System.out.println(Arrays.toString(bytes)); // Creating a string from the byte array // without specifying character encoding String string = new String(bytes); // Printing the string System.out.println(string); }}
[71, 101, 101, 107, 115, 102, 111, 114, 103, 101, 101, 107, 115]
Geeksforgeeks
Case 2: With character encoding
We know that a byte holds 8 bits, which can have up to 256 distinct values. This works fine for the ASCII character set, where only the first 7 bits are used. For character sets with more than 256 values, we should explicitly specify the encoding, which tells how to encode characters into sequences of bytes.
Note: Here we are using StandardCharsets.UTF_8 to specify the encoding. Before Java 7, we can use the Charset. for Name(“UTF-8”).
Example 2:
Java
// Java Program to Convert Byte Array to String// With character encoding // Importing required classesimport java.io.IOException;import java.nio.charset.StandardCharsets; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Custom input string is converted into array of // bytes and stored byte[] bytes = "Geeksforgeeks".getBytes( StandardCharsets.UTF_8); // Creating a string from the byte array with // "UTF-8" encoding String string = new String(bytes, StandardCharsets.UTF_8); // Print and display the string System.out.println(string); }}
Geeksforgeeks
Java
// Java Program to Illustrate Conversion of// Byte Array to String// Using String Class Constructor // Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Getting bytes of input byte array // using getBytes() method byte[] input = "GeeksforGeeks".getBytes(); // Creating a corresponding string String str = new String(input); // Printing the above string System.out.println(str); } // Catch block to handle exceptions catch (Exception e) { // Display exceptions along with line number // using printStackTrace() method e.printStackTrace(); } }}
GeeksforGeeks
Conclusion: We should focus on the type of input data when working with conversion between byte[] array and String in Java.
Use String class when you input data is string or text content.
Use Base64 class when you input data in a byte array.
AshokJaiswal
solankimayank
Java-Array-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 May, 2022"
},
{
"code": null,
"e": 527,
"s": 52,
"text": "A byte is 8 bits of binary data so do byte array is an array of bytes used to store the collection of binary data. There are multiple ways to change byte array to String in Java, you can either use methods from JDK, or you can use open-source complementary APIs like Apache commons and Google Guava. These APIs provide at least two sets of methods to create a String from a byte array; one, which uses default platform encoding, and the other which takes character encoding."
},
{
"code": null,
"e": 580,
"s": 527,
"text": "Using UTF-8 encodingUsing String Class Constructor "
},
{
"code": null,
"e": 601,
"s": 580,
"text": "Using UTF-8 encoding"
},
{
"code": null,
"e": 634,
"s": 601,
"text": "Using String Class Constructor "
},
{
"code": null,
"e": 1127,
"s": 634,
"text": "It’s also one of the best practices for specifying character encoding while converting bytes to the character in any programming language. It might be possible that your byte array contains non-printable ASCII characters. Let’s first see JDK’s way of converting byte[] to a string. Some programmers, also recommend using Charset over String for specifying character encoding, e.g. instead of “UTF-8” use StandardCharsets.UTF_8 mainly to avoid Unsupported Encoding Exception in the worst case."
},
{
"code": null,
"e": 1162,
"s": 1127,
"text": "Case 1: Without character encoding"
},
{
"code": null,
"e": 1381,
"s": 1162,
"text": "We can convert the byte array to String for the ASCII character set without even specifying the character encoding. The idea is to pass the byte[] to the string. It is as shown in the below example which is as follows:"
},
{
"code": null,
"e": 1390,
"s": 1381,
"text": "Example:"
},
{
"code": null,
"e": 1395,
"s": 1390,
"text": "Java"
},
{
"code": "// Java Program to Convert Byte Array to String// Without character encoding // Importing required classesimport java.io.IOException;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Getting bytes from the custom input string // using getBytes() method and // storing it in a byte array byte[] bytes = \"Geeksforgeeks\".getBytes(); System.out.println(Arrays.toString(bytes)); // Creating a string from the byte array // without specifying character encoding String string = new String(bytes); // Printing the string System.out.println(string); }}",
"e": 2122,
"s": 1395,
"text": null
},
{
"code": null,
"e": 2201,
"s": 2122,
"text": "[71, 101, 101, 107, 115, 102, 111, 114, 103, 101, 101, 107, 115]\nGeeksforgeeks"
},
{
"code": null,
"e": 2233,
"s": 2201,
"text": "Case 2: With character encoding"
},
{
"code": null,
"e": 2544,
"s": 2233,
"text": "We know that a byte holds 8 bits, which can have up to 256 distinct values. This works fine for the ASCII character set, where only the first 7 bits are used. For character sets with more than 256 values, we should explicitly specify the encoding, which tells how to encode characters into sequences of bytes. "
},
{
"code": null,
"e": 2674,
"s": 2544,
"text": "Note: Here we are using StandardCharsets.UTF_8 to specify the encoding. Before Java 7, we can use the Charset. for Name(“UTF-8”)."
},
{
"code": null,
"e": 2685,
"s": 2674,
"text": "Example 2:"
},
{
"code": null,
"e": 2690,
"s": 2685,
"text": "Java"
},
{
"code": "// Java Program to Convert Byte Array to String// With character encoding // Importing required classesimport java.io.IOException;import java.nio.charset.StandardCharsets; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Custom input string is converted into array of // bytes and stored byte[] bytes = \"Geeksforgeeks\".getBytes( StandardCharsets.UTF_8); // Creating a string from the byte array with // \"UTF-8\" encoding String string = new String(bytes, StandardCharsets.UTF_8); // Print and display the string System.out.println(string); }}",
"e": 3400,
"s": 2690,
"text": null
},
{
"code": null,
"e": 3414,
"s": 3400,
"text": "Geeksforgeeks"
},
{
"code": null,
"e": 3419,
"s": 3414,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Conversion of// Byte Array to String// Using String Class Constructor // Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Getting bytes of input byte array // using getBytes() method byte[] input = \"GeeksforGeeks\".getBytes(); // Creating a corresponding string String str = new String(input); // Printing the above string System.out.println(str); } // Catch block to handle exceptions catch (Exception e) { // Display exceptions along with line number // using printStackTrace() method e.printStackTrace(); } }}",
"e": 4217,
"s": 3419,
"text": null
},
{
"code": null,
"e": 4231,
"s": 4217,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 4355,
"s": 4231,
"text": "Conclusion: We should focus on the type of input data when working with conversion between byte[] array and String in Java."
},
{
"code": null,
"e": 4419,
"s": 4355,
"text": "Use String class when you input data is string or text content."
},
{
"code": null,
"e": 4473,
"s": 4419,
"text": "Use Base64 class when you input data in a byte array."
},
{
"code": null,
"e": 4486,
"s": 4473,
"text": "AshokJaiswal"
},
{
"code": null,
"e": 4500,
"s": 4486,
"text": "solankimayank"
},
{
"code": null,
"e": 4520,
"s": 4500,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 4527,
"s": 4520,
"text": "Picked"
},
{
"code": null,
"e": 4532,
"s": 4527,
"text": "Java"
},
{
"code": null,
"e": 4546,
"s": 4532,
"text": "Java Programs"
},
{
"code": null,
"e": 4551,
"s": 4546,
"text": "Java"
}
] |
Strategy Pattern | Set 2 (Implementation) | 14 Feb, 2018
We have discussed a fighter example and introduced Strategy Pattern in set 1.
Strategy Pattern | Set 1 (Introduction)
In this post, we apply Strategy Pattern to the Fighter Problem and discuss implementation.
The first step is to identify the behaviors that may vary across different classes in future and separate them from the rest. For our example let them be kick and jump behaviors. To separate these behaviors we will pull both methods out of Fighter class and create a new set of classes to represent each behavior.
The Fighter class will now delegate its kick and jump behavior instead of using kick and jump methods defined in the Fighter class or its subclass.
After reworking the final class diagram would be (Click on image for better view):
Comparing our design to the definition of strategy pattern encapsulated kick and jump behaviors are two families of algorithms. And these algorithms are interchangeable as evident in implementation.
Below is the Java implementation of the same.
// Java program to demonstrate implementation of// Strategy Pattern // Abstract as you must have a specific fighterabstract class Fighter{ KickBehavior kickBehavior; JumpBehavior jumpBehavior; public Fighter(KickBehavior kickBehavior, JumpBehavior jumpBehavior) { this.jumpBehavior = jumpBehavior; this.kickBehavior = kickBehavior; } public void punch() { System.out.println("Default Punch"); } public void kick() { // delegate to kick behavior kickBehavior.kick(); } public void jump() { // delegate to jump behavior jumpBehavior.jump(); } public void roll() { System.out.println("Default Roll"); } public void setKickBehavior(KickBehavior kickBehavior) { this.kickBehavior = kickBehavior; } public void setJumpBehavior(JumpBehavior jumpBehavior) { this.jumpBehavior = jumpBehavior; } public abstract void display();} // Encapsulated kick behaviorsinterface KickBehavior{ public void kick();}class LightningKick implements KickBehavior{ public void kick() { System.out.println("Lightning Kick"); }}class TornadoKick implements KickBehavior{ public void kick() { System.out.println("Tornado Kick"); }} // Encapsulated jump behaviorsinterface JumpBehavior{ public void jump();}class ShortJump implements JumpBehavior{ public void jump() { System.out.println("Short Jump"); }}class LongJump implements JumpBehavior{ public void jump() { System.out.println("Long Jump"); }} // Charactersclass Ryu extends Fighter{ public Ryu(KickBehavior kickBehavior, JumpBehavior jumpBehavior) { super(kickBehavior,jumpBehavior); } public void display() { System.out.println("Ryu"); }}class Ken extends Fighter{ public Ken(KickBehavior kickBehavior, JumpBehavior jumpBehavior) { super(kickBehavior,jumpBehavior); } public void display() { System.out.println("Ken"); }}class ChunLi extends Fighter{ public ChunLi(KickBehavior kickBehavior, JumpBehavior jumpBehavior) { super(kickBehavior,jumpBehavior); } public void display() { System.out.println("ChunLi"); }} // Driver classclass StreetFighter{ public static void main(String args[]) { // let us make some behaviors first JumpBehavior shortJump = new ShortJump(); JumpBehavior LongJump = new LongJump(); KickBehavior tornadoKick = new TornadoKick(); // Make a fighter with desired behaviors Fighter ken = new Ken(tornadoKick,shortJump); ken.display(); // Test behaviors ken.punch(); ken.kick(); ken.jump(); // Change behavior dynamically (algorithms are // interchangeable) ken.setJumpBehavior(LongJump); ken.jump(); }}
Output :
Ken
Default Punch
Tornado Kick
Short Jump
Long Jump
References:Head First Design Patterns
This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unified Modeling Language (UML) | An Introduction
Abstract Factory Pattern
Monolithic vs Microservices architecture
Observer Pattern | Set 1 (Introduction)
Composite Design Pattern
Singleton Design Pattern | Introduction
Unified Modeling Language (UML) | State Diagrams
Chain of Responsibility Design Pattern
Facade Design Pattern | Introduction
How to design a parking lot using object-oriented principles? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Feb, 2018"
},
{
"code": null,
"e": 130,
"s": 52,
"text": "We have discussed a fighter example and introduced Strategy Pattern in set 1."
},
{
"code": null,
"e": 170,
"s": 130,
"text": "Strategy Pattern | Set 1 (Introduction)"
},
{
"code": null,
"e": 261,
"s": 170,
"text": "In this post, we apply Strategy Pattern to the Fighter Problem and discuss implementation."
},
{
"code": null,
"e": 575,
"s": 261,
"text": "The first step is to identify the behaviors that may vary across different classes in future and separate them from the rest. For our example let them be kick and jump behaviors. To separate these behaviors we will pull both methods out of Fighter class and create a new set of classes to represent each behavior."
},
{
"code": null,
"e": 723,
"s": 575,
"text": "The Fighter class will now delegate its kick and jump behavior instead of using kick and jump methods defined in the Fighter class or its subclass."
},
{
"code": null,
"e": 806,
"s": 723,
"text": "After reworking the final class diagram would be (Click on image for better view):"
},
{
"code": null,
"e": 1007,
"s": 808,
"text": "Comparing our design to the definition of strategy pattern encapsulated kick and jump behaviors are two families of algorithms. And these algorithms are interchangeable as evident in implementation."
},
{
"code": null,
"e": 1053,
"s": 1007,
"text": "Below is the Java implementation of the same."
},
{
"code": "// Java program to demonstrate implementation of// Strategy Pattern // Abstract as you must have a specific fighterabstract class Fighter{ KickBehavior kickBehavior; JumpBehavior jumpBehavior; public Fighter(KickBehavior kickBehavior, JumpBehavior jumpBehavior) { this.jumpBehavior = jumpBehavior; this.kickBehavior = kickBehavior; } public void punch() { System.out.println(\"Default Punch\"); } public void kick() { // delegate to kick behavior kickBehavior.kick(); } public void jump() { // delegate to jump behavior jumpBehavior.jump(); } public void roll() { System.out.println(\"Default Roll\"); } public void setKickBehavior(KickBehavior kickBehavior) { this.kickBehavior = kickBehavior; } public void setJumpBehavior(JumpBehavior jumpBehavior) { this.jumpBehavior = jumpBehavior; } public abstract void display();} // Encapsulated kick behaviorsinterface KickBehavior{ public void kick();}class LightningKick implements KickBehavior{ public void kick() { System.out.println(\"Lightning Kick\"); }}class TornadoKick implements KickBehavior{ public void kick() { System.out.println(\"Tornado Kick\"); }} // Encapsulated jump behaviorsinterface JumpBehavior{ public void jump();}class ShortJump implements JumpBehavior{ public void jump() { System.out.println(\"Short Jump\"); }}class LongJump implements JumpBehavior{ public void jump() { System.out.println(\"Long Jump\"); }} // Charactersclass Ryu extends Fighter{ public Ryu(KickBehavior kickBehavior, JumpBehavior jumpBehavior) { super(kickBehavior,jumpBehavior); } public void display() { System.out.println(\"Ryu\"); }}class Ken extends Fighter{ public Ken(KickBehavior kickBehavior, JumpBehavior jumpBehavior) { super(kickBehavior,jumpBehavior); } public void display() { System.out.println(\"Ken\"); }}class ChunLi extends Fighter{ public ChunLi(KickBehavior kickBehavior, JumpBehavior jumpBehavior) { super(kickBehavior,jumpBehavior); } public void display() { System.out.println(\"ChunLi\"); }} // Driver classclass StreetFighter{ public static void main(String args[]) { // let us make some behaviors first JumpBehavior shortJump = new ShortJump(); JumpBehavior LongJump = new LongJump(); KickBehavior tornadoKick = new TornadoKick(); // Make a fighter with desired behaviors Fighter ken = new Ken(tornadoKick,shortJump); ken.display(); // Test behaviors ken.punch(); ken.kick(); ken.jump(); // Change behavior dynamically (algorithms are // interchangeable) ken.setJumpBehavior(LongJump); ken.jump(); }}",
"e": 4009,
"s": 1055,
"text": null
},
{
"code": null,
"e": 4018,
"s": 4009,
"text": "Output :"
},
{
"code": null,
"e": 4071,
"s": 4018,
"text": "Ken\nDefault Punch\nTornado Kick\nShort Jump\nLong Jump\n"
},
{
"code": null,
"e": 4109,
"s": 4071,
"text": "References:Head First Design Patterns"
},
{
"code": null,
"e": 4375,
"s": 4109,
"text": "This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4499,
"s": 4375,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 4514,
"s": 4499,
"text": "Design Pattern"
},
{
"code": null,
"e": 4612,
"s": 4514,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4662,
"s": 4612,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 4687,
"s": 4662,
"text": "Abstract Factory Pattern"
},
{
"code": null,
"e": 4728,
"s": 4687,
"text": "Monolithic vs Microservices architecture"
},
{
"code": null,
"e": 4768,
"s": 4728,
"text": "Observer Pattern | Set 1 (Introduction)"
},
{
"code": null,
"e": 4793,
"s": 4768,
"text": "Composite Design Pattern"
},
{
"code": null,
"e": 4833,
"s": 4793,
"text": "Singleton Design Pattern | Introduction"
},
{
"code": null,
"e": 4882,
"s": 4833,
"text": "Unified Modeling Language (UML) | State Diagrams"
},
{
"code": null,
"e": 4921,
"s": 4882,
"text": "Chain of Responsibility Design Pattern"
},
{
"code": null,
"e": 4958,
"s": 4921,
"text": "Facade Design Pattern | Introduction"
}
] |
Softmax Regression Using Keras | 16 Jan, 2022
Prerequisites: Logistic RegressionGetting Started With Keras: Deep learning is one of the major subfields of machine learning framework. It is supported by various libraries such as Theano, TensorFlow, Caffe, Mxnet etc., Keras is one of the most powerful and easy to use python library, which is built on top of popular deep learning libraries like TensorFlow, Theano, etc., for creating deep learning models. Keras offers a collection of datasets that can be used to train and test the model. The Fashion MNIST dataset is a part of the available datasets present in the tf.keras datasets API. This dataset contains 70 thousand images of fashion objects that spread across 10 categories such as shoe, bag, T-shirts etc. which are scaled to 28 by 28 Grayscale pixels.Approach: So, the approach would be to first load the MNIST Objects Dataset and then we will use the Matplotlib to see examples so as to get a better idea about the dataset. Then finally we will classify them using Keras API by building a Neural Network. Later we will test our trained model on the test set to check the accuracy of our model. Implementation: Code: Loading the Data
Python3
mnist = tf.keras.datasets.fashion_mnist(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
Calling load_data on this object will give us two sets of two lists, these will be the training and testing values for the graphics that contain the dataset items and their labels.Code: Understanding The Data
Python3
import numpy as npnp.set_printoptions(linewidth = 200)import matplotlib.pyplot as pltplt.imshow(training_images[42]) # printing training labels and training imagesprint(training_labels[42])print(training_images[42])
Output:
9
[[ 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 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 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 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 0 0 0 0 82 187 26 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 179 240 237 255 240 139 83 64 43 60 54 0 1]
[ 0 0 0 0 0 0 0 0 0 1 0 0 1 0 58 239 222 234 238 246 252 254 255 248 255 187 0 0]
[ 0 0 0 0 0 0 0 0 0 0 2 3 0 0 194 239 226 237 235 232 230 234 234 233 249 171 0 0]
[ 0 0 0 0 0 0 0 0 0 1 1 0 0 10 255 226 242 239 238 239 240 239 242 238 248 192 0 0]
[ 0 0 0 0 0 0 0 0 0 0 0 0 0 172 245 229 240 241 240 241 243 243 241 227 250 209 0 0]
[ 0 0 0 0 0 0 0 0 0 6 5 0 62 255 230 236 239 241 242 241 242 242 238 238 242 253 0 0]
[ 0 0 0 0 0 0 0 0 0 3 0 0 255 235 228 244 241 241 244 243 243 244 243 239 235 255 22 0]
[ 0 0 0 0 0 0 0 0 0 0 0 246 228 220 245 243 237 241 242 242 242 243 239 237 235 253 106 0]
[ 0 0 3 4 4 2 1 0 0 18 243 228 231 241 243 237 238 242 241 240 240 240 235 237 236 246 234 0]
[ 1 0 0 0 0 0 0 0 22 255 238 227 238 239 237 241 241 237 236 238 239 239 239 239 239 237 255 0]
[ 0 0 0 0 0 25 83 168 255 225 225 235 228 230 227 225 227 231 232 237 240 236 238 239 239 235 251 62]
[ 0 165 225 220 224 255 255 233 229 223 227 228 231 232 235 237 233 230 228 230 233 232 235 233 234 235 255 58]
[ 52 251 221 226 227 225 225 225 226 226 225 227 231 229 232 239 245 250 251 252 254 254 252 254 252 235 255 0]
[ 31 208 230 233 233 237 236 236 241 235 241 247 251 254 242 236 233 227 219 202 193 189 186 181 171 165 190 42]
[ 77 199 172 188 199 202 218 219 220 229 234 222 213 209 207 210 203 184 152 171 165 162 162 167 168 157 192 78]
[ 0 45 101 140 159 174 182 186 185 188 195 197 188 175 133 70 19 0 0 209 231 218 222 224 227 217 229 93]
[ 0 0 0 0 0 0 2 24 37 45 32 18 11 0 0 0 0 0 0 72 51 53 37 34 29 31 5 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 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 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 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]]
Normalisation: Notice that all of the values in the number are between 0 and 255. If we are training a neural network, for various reasons it’s easier if we treat all values as between 0 and 1, a process called ‘normalizing’...and fortunately in Python it’s easy to normalize a list like this without looping. We can do it like this:Code:
Python3
training_images = training_images / 255.0test_images = test_images / 255.0
Code: Implementing Keras Model
Python3
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation = tf.nn.relu), tf.keras.layers.Dense(10, activation = tf.nn.softmax)])
Sequential: That defines a SEQUENCE of layers in the neural network.
Flatten: It justs takes the image and convert it to a 1 Dimensional set.
Dense: Adds a layer of neurons.
Each layer of neurons need an activation function to tell them what to do. There’s lots of options, but just use these for now.
Relu: Effectively means “If X > 0 return X, else return 0′′ — so what it does it it only passes values 0 or greater to the next layer in the network.
Softmax: takes a set of values, and effectively picks the biggest one, so, for example, if the output of the last layer looks like [0.1, 0.1, 0.05, 0.1, 9.5, 0.1, 0.05, 0.05, 0.05], it saves you from fishing through it looking for the biggest value, and turns it into [0, 0, 0, 0, 1, 0, 0, 0, 0]. The goal is to save a lot of coding
Step 5: Compile The Model The next thing to do, now the model is defined, is to actually build it. You do this by compiling it with an optimizer and loss function as before and then you train it by calling model.fit asking it to fit your training data to your training labels i.e. have it figure out the relationship between the training data and its actual labels, so in future, if you have data that looks like the training data, then it can make a prediction for what that data would look like. Code:
Python3
model.compile(optimizer = tf.optimizers.Adam(), loss = 'sparse_categorical_crossentropy', metrics =['accuracy']) model.fit(training_images, training_labels, epochs = 5)
Output:
Instructions for updating:
Colocations handled automatically by placer.
Epoch 1/5
60000/60000 [==============================] - 8s 130us/sample - loss: 0.4714 - acc: 0.8322
Epoch 2/5
60000/60000 [==============================] - 8s 137us/sample - loss: 0.3598 - acc: 0.8683
Epoch 3/5
60000/60000 [==============================] - 9s 142us/sample - loss: 0.3201 - acc: 0.8824
Epoch 4/5
60000/60000 [==============================] - 8s 131us/sample - loss: 0.2949 - acc: 0.8917
Epoch 5/5
60000/60000 [==============================] - 8s 140us/sample - loss: 0.2767 - acc: 0.9098
Once it’s done training we should see an accuracy value at the end of the final epoch. It might look something like 0.9098. This tells us that your neural network is about 91% accurate in classifying the training data. i.e. it figured out a pattern match between the image and the labels that worked 91% of the time. Not great, but not bad considering it was only trained for 5 epochs and done quite quickly.Step 6: Model Evaluation But how would it work with unseen data? That’s why we have the test images. We can call model.evaluate, and pass in the two sets, and it will report back the loss for each.
Code:
Python3
model.evaluate(test_images, test_labels)
Output:
10000/10000 [==============================] - 1s 60us/sample - loss: 0.2908 - acc: 0.8956
Finally, we have trained our model and got an accuracy of 90% on the unseen dataset. That’s pretty good.Advantages of Using KERAS: We have seen that our calculations have just reduced to 7-8 lines rather than a hundred lines of code. That’s awesome. Overall, this helps us save our time and energy and also reduces the chances of error in our code.
adnanirshad158
Deep-Learning
Image-Processing
Regression
Tensorflow
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jan, 2022"
},
{
"code": null,
"e": 1204,
"s": 54,
"text": "Prerequisites: Logistic RegressionGetting Started With Keras: Deep learning is one of the major subfields of machine learning framework. It is supported by various libraries such as Theano, TensorFlow, Caffe, Mxnet etc., Keras is one of the most powerful and easy to use python library, which is built on top of popular deep learning libraries like TensorFlow, Theano, etc., for creating deep learning models. Keras offers a collection of datasets that can be used to train and test the model. The Fashion MNIST dataset is a part of the available datasets present in the tf.keras datasets API. This dataset contains 70 thousand images of fashion objects that spread across 10 categories such as shoe, bag, T-shirts etc. which are scaled to 28 by 28 Grayscale pixels.Approach: So, the approach would be to first load the MNIST Objects Dataset and then we will use the Matplotlib to see examples so as to get a better idea about the dataset. Then finally we will classify them using Keras API by building a Neural Network. Later we will test our trained model on the test set to check the accuracy of our model. Implementation: Code: Loading the Data "
},
{
"code": null,
"e": 1212,
"s": 1204,
"text": "Python3"
},
{
"code": "mnist = tf.keras.datasets.fashion_mnist(training_images, training_labels), (test_images, test_labels) = mnist.load_data()",
"e": 1334,
"s": 1212,
"text": null
},
{
"code": null,
"e": 1544,
"s": 1334,
"text": "Calling load_data on this object will give us two sets of two lists, these will be the training and testing values for the graphics that contain the dataset items and their labels.Code: Understanding The Data "
},
{
"code": null,
"e": 1552,
"s": 1544,
"text": "Python3"
},
{
"code": "import numpy as npnp.set_printoptions(linewidth = 200)import matplotlib.pyplot as pltplt.imshow(training_images[42]) # printing training labels and training imagesprint(training_labels[42])print(training_images[42])",
"e": 1768,
"s": 1552,
"text": null
},
{
"code": null,
"e": 1778,
"s": 1768,
"text": "Output: "
},
{
"code": null,
"e": 5001,
"s": 1778,
"text": "9\n[[ 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 [ 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 [ 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 [ 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 [ 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 [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 82 187 26 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 179 240 237 255 240 139 83 64 43 60 54 0 1]\n [ 0 0 0 0 0 0 0 0 0 1 0 0 1 0 58 239 222 234 238 246 252 254 255 248 255 187 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 2 3 0 0 194 239 226 237 235 232 230 234 234 233 249 171 0 0]\n [ 0 0 0 0 0 0 0 0 0 1 1 0 0 10 255 226 242 239 238 239 240 239 242 238 248 192 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 172 245 229 240 241 240 241 243 243 241 227 250 209 0 0]\n [ 0 0 0 0 0 0 0 0 0 6 5 0 62 255 230 236 239 241 242 241 242 242 238 238 242 253 0 0]\n [ 0 0 0 0 0 0 0 0 0 3 0 0 255 235 228 244 241 241 244 243 243 244 243 239 235 255 22 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 246 228 220 245 243 237 241 242 242 242 243 239 237 235 253 106 0]\n [ 0 0 3 4 4 2 1 0 0 18 243 228 231 241 243 237 238 242 241 240 240 240 235 237 236 246 234 0]\n [ 1 0 0 0 0 0 0 0 22 255 238 227 238 239 237 241 241 237 236 238 239 239 239 239 239 237 255 0]\n [ 0 0 0 0 0 25 83 168 255 225 225 235 228 230 227 225 227 231 232 237 240 236 238 239 239 235 251 62]\n [ 0 165 225 220 224 255 255 233 229 223 227 228 231 232 235 237 233 230 228 230 233 232 235 233 234 235 255 58]\n [ 52 251 221 226 227 225 225 225 226 226 225 227 231 229 232 239 245 250 251 252 254 254 252 254 252 235 255 0]\n [ 31 208 230 233 233 237 236 236 241 235 241 247 251 254 242 236 233 227 219 202 193 189 186 181 171 165 190 42]\n [ 77 199 172 188 199 202 218 219 220 229 234 222 213 209 207 210 203 184 152 171 165 162 162 167 168 157 192 78]\n [ 0 45 101 140 159 174 182 186 185 188 195 197 188 175 133 70 19 0 0 209 231 218 222 224 227 217 229 93]\n [ 0 0 0 0 0 0 2 24 37 45 32 18 11 0 0 0 0 0 0 72 51 53 37 34 29 31 5 0]\n [ 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 [ 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 [ 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 [ 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 [ 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]]"
},
{
"code": null,
"e": 5346,
"s": 5003,
"text": " Normalisation: Notice that all of the values in the number are between 0 and 255. If we are training a neural network, for various reasons it’s easier if we treat all values as between 0 and 1, a process called ‘normalizing’...and fortunately in Python it’s easy to normalize a list like this without looping. We can do it like this:Code: "
},
{
"code": null,
"e": 5354,
"s": 5346,
"text": "Python3"
},
{
"code": "training_images = training_images / 255.0test_images = test_images / 255.0",
"e": 5429,
"s": 5354,
"text": null
},
{
"code": null,
"e": 5461,
"s": 5429,
"text": "Code: Implementing Keras Model "
},
{
"code": null,
"e": 5469,
"s": 5461,
"text": "Python3"
},
{
"code": "model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation = tf.nn.relu), tf.keras.layers.Dense(10, activation = tf.nn.softmax)])",
"e": 5711,
"s": 5469,
"text": null
},
{
"code": null,
"e": 5780,
"s": 5711,
"text": "Sequential: That defines a SEQUENCE of layers in the neural network."
},
{
"code": null,
"e": 5853,
"s": 5780,
"text": "Flatten: It justs takes the image and convert it to a 1 Dimensional set."
},
{
"code": null,
"e": 5885,
"s": 5853,
"text": "Dense: Adds a layer of neurons."
},
{
"code": null,
"e": 6013,
"s": 5885,
"text": "Each layer of neurons need an activation function to tell them what to do. There’s lots of options, but just use these for now."
},
{
"code": null,
"e": 6163,
"s": 6013,
"text": "Relu: Effectively means “If X > 0 return X, else return 0′′ — so what it does it it only passes values 0 or greater to the next layer in the network."
},
{
"code": null,
"e": 6496,
"s": 6163,
"text": "Softmax: takes a set of values, and effectively picks the biggest one, so, for example, if the output of the last layer looks like [0.1, 0.1, 0.05, 0.1, 9.5, 0.1, 0.05, 0.05, 0.05], it saves you from fishing through it looking for the biggest value, and turns it into [0, 0, 0, 0, 1, 0, 0, 0, 0]. The goal is to save a lot of coding"
},
{
"code": null,
"e": 7002,
"s": 6496,
"text": "Step 5: Compile The Model The next thing to do, now the model is defined, is to actually build it. You do this by compiling it with an optimizer and loss function as before and then you train it by calling model.fit asking it to fit your training data to your training labels i.e. have it figure out the relationship between the training data and its actual labels, so in future, if you have data that looks like the training data, then it can make a prediction for what that data would look like. Code: "
},
{
"code": null,
"e": 7010,
"s": 7002,
"text": "Python3"
},
{
"code": "model.compile(optimizer = tf.optimizers.Adam(), loss = 'sparse_categorical_crossentropy', metrics =['accuracy']) model.fit(training_images, training_labels, epochs = 5)",
"e": 7205,
"s": 7010,
"text": null
},
{
"code": null,
"e": 7215,
"s": 7205,
"text": "Output: "
},
{
"code": null,
"e": 7797,
"s": 7215,
"text": "Instructions for updating:\nColocations handled automatically by placer.\nEpoch 1/5\n60000/60000 [==============================] - 8s 130us/sample - loss: 0.4714 - acc: 0.8322\nEpoch 2/5\n60000/60000 [==============================] - 8s 137us/sample - loss: 0.3598 - acc: 0.8683\nEpoch 3/5\n60000/60000 [==============================] - 9s 142us/sample - loss: 0.3201 - acc: 0.8824\nEpoch 4/5\n60000/60000 [==============================] - 8s 131us/sample - loss: 0.2949 - acc: 0.8917\nEpoch 5/5\n60000/60000 [==============================] - 8s 140us/sample - loss: 0.2767 - acc: 0.9098"
},
{
"code": null,
"e": 8404,
"s": 7797,
"text": "Once it’s done training we should see an accuracy value at the end of the final epoch. It might look something like 0.9098. This tells us that your neural network is about 91% accurate in classifying the training data. i.e. it figured out a pattern match between the image and the labels that worked 91% of the time. Not great, but not bad considering it was only trained for 5 epochs and done quite quickly.Step 6: Model Evaluation But how would it work with unseen data? That’s why we have the test images. We can call model.evaluate, and pass in the two sets, and it will report back the loss for each. "
},
{
"code": null,
"e": 8412,
"s": 8404,
"text": "Code: "
},
{
"code": null,
"e": 8420,
"s": 8412,
"text": "Python3"
},
{
"code": "model.evaluate(test_images, test_labels)",
"e": 8461,
"s": 8420,
"text": null
},
{
"code": null,
"e": 8471,
"s": 8461,
"text": "Output: "
},
{
"code": null,
"e": 8562,
"s": 8471,
"text": "10000/10000 [==============================] - 1s 60us/sample - loss: 0.2908 - acc: 0.8956"
},
{
"code": null,
"e": 8912,
"s": 8562,
"text": "Finally, we have trained our model and got an accuracy of 90% on the unseen dataset. That’s pretty good.Advantages of Using KERAS: We have seen that our calculations have just reduced to 7-8 lines rather than a hundred lines of code. That’s awesome. Overall, this helps us save our time and energy and also reduces the chances of error in our code. "
},
{
"code": null,
"e": 8927,
"s": 8912,
"text": "adnanirshad158"
},
{
"code": null,
"e": 8941,
"s": 8927,
"text": "Deep-Learning"
},
{
"code": null,
"e": 8958,
"s": 8941,
"text": "Image-Processing"
},
{
"code": null,
"e": 8969,
"s": 8958,
"text": "Regression"
},
{
"code": null,
"e": 8980,
"s": 8969,
"text": "Tensorflow"
},
{
"code": null,
"e": 8997,
"s": 8980,
"text": "Machine Learning"
},
{
"code": null,
"e": 9004,
"s": 8997,
"text": "Python"
},
{
"code": null,
"e": 9021,
"s": 9004,
"text": "Machine Learning"
}
] |
Redis - List Lindex Command | Redis LINDEX command is used to get the element at the index in the list stored at the key. The index is zero-based, so 0 means the first element, 1 the second element, and so on. Negative indices can be used to designate elements starting at the tail of the list. Here, -1 means the last element, -2 means the penultimate, and so forth.
String reply, the requested element, or nil when the index is out of range.
Following is the basic syntax of Redis LINDEX command.
redis 127.0.0.1:6379> LINDEX KEY_NAME INDEX_POSITION
redis 127.0.0.1:6379> LPUSH list1 "foo"
(integer) 1
redis 127.0.0.1:6379> LPUSH list1 "bar"
(integer) 2
redis 127.0.0.1:6379> LINDEX list1 0
"foo"
redis 127.0.0.1:6379> LINDEX list1 -1
"bar"
redis 127.0.0.1:6379> LINDEX list1 5
nil
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2383,
"s": 2045,
"text": "Redis LINDEX command is used to get the element at the index in the list stored at the key. The index is zero-based, so 0 means the first element, 1 the second element, and so on. Negative indices can be used to designate elements starting at the tail of the list. Here, -1 means the last element, -2 means the penultimate, and so forth."
},
{
"code": null,
"e": 2459,
"s": 2383,
"text": "String reply, the requested element, or nil when the index is out of range."
},
{
"code": null,
"e": 2514,
"s": 2459,
"text": "Following is the basic syntax of Redis LINDEX command."
},
{
"code": null,
"e": 2568,
"s": 2514,
"text": "redis 127.0.0.1:6379> LINDEX KEY_NAME INDEX_POSITION\n"
},
{
"code": null,
"e": 2811,
"s": 2568,
"text": "redis 127.0.0.1:6379> LPUSH list1 \"foo\" \n(integer) 1 \nredis 127.0.0.1:6379> LPUSH list1 \"bar\" \n(integer) 2 \nredis 127.0.0.1:6379> LINDEX list1 0 \n\"foo\" \nredis 127.0.0.1:6379> LINDEX list1 -1 \n\"bar\" \nredis 127.0.0.1:6379> LINDEX list1 5 \nnil \n"
},
{
"code": null,
"e": 2843,
"s": 2811,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2863,
"s": 2843,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2870,
"s": 2863,
"text": " Print"
},
{
"code": null,
"e": 2881,
"s": 2870,
"text": " Add Notes"
}
] |
Data Normalization with Python scikit-learn | by Angelica Lo Duca | Towards Data Science | Following the series of publications on data preprocessing, in this tutorial, I deal with Data Normalization in Python scikit-learn . As already said in my previous tutorial, Data Normalization involves adjusting values measured on different scales to a common scale.
Normalization applies only to columns containing numeric values. Five methods of normalization exist:
single feature scaling
min max
z-score
log scaling
clipping
In this tutorial, I use the scikit-learn library to perform normalization, while in my previous tutorial, I dealt with data normalization using the pandas library. I use the same dataset used in my previous tutorial, thus results can be compared. Indeed, we obtain the same results using the two methodologies.
Anyway, in this tutorial I don’t deal with log scaling and clipping, which will be the object of a future tutorial.
The scikit-learn library can be used also to deal with missing values, as explained in my previous post.
All the scikit-learn operations described in this tutorial follow the following steps:
select a preprocessing methodology
fit it through the fit() function
apply it to data through the transform() function.
The scikit-learn library works only with arrays, thus when performing every operation, a dataframe column must be converted to an array. This can be achieved through the numpy.array() function, which receives the dataframe column as input. The fit() function receives as input an array of arrays, each representing a sample of the dataset. Thus the reshape() function could be used to convert a standard array to an array of arrays.
All the code described in this tutorial can be downloaded from my Github repository.
As an example dataset, in this tutorial we consider the dataset provided by the Italian Protezione Civile, related to the number of COVID-19 cases registered since the beginning of the COVID-19 pandemic. The dataset is updated daily and can be downloaded from this link.
First of all, we need to import the Python pandas library and read the dataset through the read_csv() function. Then we can drop all the columns with NaN values. This is done through dropna() function.
import pandas as pddf = pd.read_csv('https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv')df.dropna(axis=1,inplace=True)df.head(10)
Single Feature Scaling converts every value of a column into a number between 0 and 1. The new value is calculated as the current value divided by the max value of the column. This can be done through the MaxAbsScaler class. We apply the scaler to the tamponi column, which must be converted to array and reshaped.
import numpy as npfrom sklearn.preprocessing import MaxAbsScalerX = np.array(df['tamponi']).reshape(-1,1)scaler = MaxAbsScaler()
Now we can fit the scaler and then apply the transformation. We convert it to the original shape by applying the inverse reshape() function and we store the result into a new column of the dataframe df.
scaler.fit(X)X_scaled = scaler.transform(X)df['single feature scaling'] = X_scaled.reshape(1,-1)[0]
The scikit-learn library also provides a function to restore the original values, given the transformation. This function also works for the transformations described later in this article.
scaler.inverse_transform(X_scaled)
which gives the following output:
array([[5.000000e+00], [0.000000e+00], [1.000000e+00], ..., [5.507300e+05], [6.654400e+04], [3.643743e+06]])
Similar to Single Feature Scaling, Min Max converts every value of a column into a number between 0 and 1. The new value is calculated as the difference between the current value and the min value, divided by the range of the column values. In scikit-learn we use the MinMaxScaler class. For example, we can apply the min max method to the column totale_casi.
from sklearn.preprocessing import MinMaxScalerX = np.array(df['totale_casi']).reshape(-1,1)scaler = MinMaxScaler()scaler.fit(X)X_scaled = scaler.transform(X)df['min max'] = X_scaled.reshape(1,-1)[0]
Z-Score converts every value of a column into a number around 0. Typical values obtained by a z-score transformation range from -3 and 3. The new value is calculated as the difference between the current value and the average value, divided by the standard deviation. In scikit-learn we can use the StandardScaler function. For example, we can calculate the z-score of the column deceduti.
from sklearn.preprocessing import StandardScalerX = np.array(df['deceduti']).reshape(-1,1)scaler = StandardScaler()scaler.fit(X)X_scaled = scaler.transform(X)df['z score'] = X_scaled.reshape(1,-1)[0]
In this tutorial, I have illustrated how to normalize a dataset using the preprocessing package of the scikit-learn library. We can achieve the same results by manually applying the formulas, as explained in my previous tutorial.
The main advantages of using scikit-learn are the following:
you don’t need to know the formula in advance, because you have prepackaged classes to perform operations
you can restore the original data through inverse_transform() function.
If you wanted to learn how to perform the other aspects of data preprocessing using the scikit-learn library, stay tuned...
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and Github. | [
{
"code": null,
"e": 440,
"s": 172,
"text": "Following the series of publications on data preprocessing, in this tutorial, I deal with Data Normalization in Python scikit-learn . As already said in my previous tutorial, Data Normalization involves adjusting values measured on different scales to a common scale."
},
{
"code": null,
"e": 542,
"s": 440,
"text": "Normalization applies only to columns containing numeric values. Five methods of normalization exist:"
},
{
"code": null,
"e": 565,
"s": 542,
"text": "single feature scaling"
},
{
"code": null,
"e": 573,
"s": 565,
"text": "min max"
},
{
"code": null,
"e": 581,
"s": 573,
"text": "z-score"
},
{
"code": null,
"e": 593,
"s": 581,
"text": "log scaling"
},
{
"code": null,
"e": 602,
"s": 593,
"text": "clipping"
},
{
"code": null,
"e": 913,
"s": 602,
"text": "In this tutorial, I use the scikit-learn library to perform normalization, while in my previous tutorial, I dealt with data normalization using the pandas library. I use the same dataset used in my previous tutorial, thus results can be compared. Indeed, we obtain the same results using the two methodologies."
},
{
"code": null,
"e": 1029,
"s": 913,
"text": "Anyway, in this tutorial I don’t deal with log scaling and clipping, which will be the object of a future tutorial."
},
{
"code": null,
"e": 1134,
"s": 1029,
"text": "The scikit-learn library can be used also to deal with missing values, as explained in my previous post."
},
{
"code": null,
"e": 1221,
"s": 1134,
"text": "All the scikit-learn operations described in this tutorial follow the following steps:"
},
{
"code": null,
"e": 1256,
"s": 1221,
"text": "select a preprocessing methodology"
},
{
"code": null,
"e": 1290,
"s": 1256,
"text": "fit it through the fit() function"
},
{
"code": null,
"e": 1341,
"s": 1290,
"text": "apply it to data through the transform() function."
},
{
"code": null,
"e": 1774,
"s": 1341,
"text": "The scikit-learn library works only with arrays, thus when performing every operation, a dataframe column must be converted to an array. This can be achieved through the numpy.array() function, which receives the dataframe column as input. The fit() function receives as input an array of arrays, each representing a sample of the dataset. Thus the reshape() function could be used to convert a standard array to an array of arrays."
},
{
"code": null,
"e": 1859,
"s": 1774,
"text": "All the code described in this tutorial can be downloaded from my Github repository."
},
{
"code": null,
"e": 2130,
"s": 1859,
"text": "As an example dataset, in this tutorial we consider the dataset provided by the Italian Protezione Civile, related to the number of COVID-19 cases registered since the beginning of the COVID-19 pandemic. The dataset is updated daily and can be downloaded from this link."
},
{
"code": null,
"e": 2332,
"s": 2130,
"text": "First of all, we need to import the Python pandas library and read the dataset through the read_csv() function. Then we can drop all the columns with NaN values. This is done through dropna() function."
},
{
"code": null,
"e": 2511,
"s": 2332,
"text": "import pandas as pddf = pd.read_csv('https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv')df.dropna(axis=1,inplace=True)df.head(10)"
},
{
"code": null,
"e": 2826,
"s": 2511,
"text": "Single Feature Scaling converts every value of a column into a number between 0 and 1. The new value is calculated as the current value divided by the max value of the column. This can be done through the MaxAbsScaler class. We apply the scaler to the tamponi column, which must be converted to array and reshaped."
},
{
"code": null,
"e": 2955,
"s": 2826,
"text": "import numpy as npfrom sklearn.preprocessing import MaxAbsScalerX = np.array(df['tamponi']).reshape(-1,1)scaler = MaxAbsScaler()"
},
{
"code": null,
"e": 3158,
"s": 2955,
"text": "Now we can fit the scaler and then apply the transformation. We convert it to the original shape by applying the inverse reshape() function and we store the result into a new column of the dataframe df."
},
{
"code": null,
"e": 3258,
"s": 3158,
"text": "scaler.fit(X)X_scaled = scaler.transform(X)df['single feature scaling'] = X_scaled.reshape(1,-1)[0]"
},
{
"code": null,
"e": 3448,
"s": 3258,
"text": "The scikit-learn library also provides a function to restore the original values, given the transformation. This function also works for the transformations described later in this article."
},
{
"code": null,
"e": 3483,
"s": 3448,
"text": "scaler.inverse_transform(X_scaled)"
},
{
"code": null,
"e": 3517,
"s": 3483,
"text": "which gives the following output:"
},
{
"code": null,
"e": 3662,
"s": 3517,
"text": "array([[5.000000e+00], [0.000000e+00], [1.000000e+00], ..., [5.507300e+05], [6.654400e+04], [3.643743e+06]])"
},
{
"code": null,
"e": 4022,
"s": 3662,
"text": "Similar to Single Feature Scaling, Min Max converts every value of a column into a number between 0 and 1. The new value is calculated as the difference between the current value and the min value, divided by the range of the column values. In scikit-learn we use the MinMaxScaler class. For example, we can apply the min max method to the column totale_casi."
},
{
"code": null,
"e": 4221,
"s": 4022,
"text": "from sklearn.preprocessing import MinMaxScalerX = np.array(df['totale_casi']).reshape(-1,1)scaler = MinMaxScaler()scaler.fit(X)X_scaled = scaler.transform(X)df['min max'] = X_scaled.reshape(1,-1)[0]"
},
{
"code": null,
"e": 4611,
"s": 4221,
"text": "Z-Score converts every value of a column into a number around 0. Typical values obtained by a z-score transformation range from -3 and 3. The new value is calculated as the difference between the current value and the average value, divided by the standard deviation. In scikit-learn we can use the StandardScaler function. For example, we can calculate the z-score of the column deceduti."
},
{
"code": null,
"e": 4811,
"s": 4611,
"text": "from sklearn.preprocessing import StandardScalerX = np.array(df['deceduti']).reshape(-1,1)scaler = StandardScaler()scaler.fit(X)X_scaled = scaler.transform(X)df['z score'] = X_scaled.reshape(1,-1)[0]"
},
{
"code": null,
"e": 5041,
"s": 4811,
"text": "In this tutorial, I have illustrated how to normalize a dataset using the preprocessing package of the scikit-learn library. We can achieve the same results by manually applying the formulas, as explained in my previous tutorial."
},
{
"code": null,
"e": 5102,
"s": 5041,
"text": "The main advantages of using scikit-learn are the following:"
},
{
"code": null,
"e": 5208,
"s": 5102,
"text": "you don’t need to know the formula in advance, because you have prepackaged classes to perform operations"
},
{
"code": null,
"e": 5280,
"s": 5208,
"text": "you can restore the original data through inverse_transform() function."
},
{
"code": null,
"e": 5404,
"s": 5280,
"text": "If you wanted to learn how to perform the other aspects of data preprocessing using the scikit-learn library, stay tuned..."
}
] |
What is narrowing in java? Explain. | Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) as listed below −
boolean − Stores 1-bit value representing true or, false.
byte − Stores twos compliment integer up to 8 bits.
char − Stores a Unicode character value up to 16 bits.
short − Stores an integer value upto 16 bits.
int − Stores an integer value upto 32 bits.
long − Stores an integer value upto 64 bits.
float − Stores a floating point value upto 32bits.
double − Stores a floating point value up to 64 bits.
Converting one primitive data type into another is known as type conversion. There are two types of type conversions −
Widening − Converting a lower datatype to a higher datatype is known as widening.
Narrowing − Converting a higher datatype to a lower datatype is known as narrowing.
Whenever you assign a lower datatype to higher the Java compiler converts it implicitly and assigns to the specified variable.
Live Demo
public class CastingExample {
public static void main(String args[]){
char ch = 'C';
int i = ch;
System.out.println("Integer value of the given character: "+i);
float f = 10021.224f;
double d = f;
System.out.println("double value: "+d);
}
}
Integer value of the given character: 67
double value: 10021.2236328125
But, when you try to assign a higher datatype to lower, at the time of compilation you will get an error saying “incompatible types: possible lossy conversion”
In the following example we are trying to assign an integer value to a character value −
public class CastingExample {
public static void main(String args[]){
int i = 67;
char ch = i;
System.out.println("Character value of the given integer: "+ch);
}
}
On compiling, the above program generates the following error.
CastingExample.java:4: error: incompatible types: possible lossy conversion from int to char
char ch = i;
^
1 error
In the following example we are trying to assign a double value to a float variable.
public class CastingExample {
public static void main(String args[]){
double d = 10021.224d;
float f = d;
System.out.println("double value: "+f);
}
}
On compiling, the above program generates the following error.
CastingExample.java:22: error: incompatible types: possible lossy conversion from double to float
float f = d;
^
1 error
Therefore, to assign a higher datatype to lower, you need to convert it using the cast operator explicitly as −
float f = (float)d;
Let us rewrite the Example2 and Exampe3 by converting explicitly.
In the following example we are trying to assign an integer value to a character value by converting it explicitly using the cast operator −
Live Demo
public class CastingExample {
public static void main(String args[]){
int i = 67;
char ch = (char)i;
System.out.println("Character value of the given integer: "+ch);
}
}
Character value of the given integer: C
In the following example we are trying to assign a double value to a float variable by converting it explicitly using the cast operator.
Live Demo
public class CastingExample {
public static void main(String args[]){
double d = 10021.224d;
float f = (float)d;
System.out.println("double value: "+f);
}
}
double value: 10021.224 | [
{
"code": null,
"e": 1199,
"s": 1062,
"text": "Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) as listed below −"
},
{
"code": null,
"e": 1257,
"s": 1199,
"text": "boolean − Stores 1-bit value representing true or, false."
},
{
"code": null,
"e": 1309,
"s": 1257,
"text": "byte − Stores twos compliment integer up to 8 bits."
},
{
"code": null,
"e": 1364,
"s": 1309,
"text": "char − Stores a Unicode character value up to 16 bits."
},
{
"code": null,
"e": 1410,
"s": 1364,
"text": "short − Stores an integer value upto 16 bits."
},
{
"code": null,
"e": 1454,
"s": 1410,
"text": "int − Stores an integer value upto 32 bits."
},
{
"code": null,
"e": 1499,
"s": 1454,
"text": "long − Stores an integer value upto 64 bits."
},
{
"code": null,
"e": 1550,
"s": 1499,
"text": "float − Stores a floating point value upto 32bits."
},
{
"code": null,
"e": 1604,
"s": 1550,
"text": "double − Stores a floating point value up to 64 bits."
},
{
"code": null,
"e": 1723,
"s": 1604,
"text": "Converting one primitive data type into another is known as type conversion. There are two types of type conversions −"
},
{
"code": null,
"e": 1805,
"s": 1723,
"text": "Widening − Converting a lower datatype to a higher datatype is known as widening."
},
{
"code": null,
"e": 1889,
"s": 1805,
"text": "Narrowing − Converting a higher datatype to a lower datatype is known as narrowing."
},
{
"code": null,
"e": 2016,
"s": 1889,
"text": "Whenever you assign a lower datatype to higher the Java compiler converts it implicitly and assigns to the specified variable."
},
{
"code": null,
"e": 2027,
"s": 2016,
"text": " Live Demo"
},
{
"code": null,
"e": 2310,
"s": 2027,
"text": "public class CastingExample {\n public static void main(String args[]){\n char ch = 'C';\n int i = ch;\n System.out.println(\"Integer value of the given character: \"+i);\n float f = 10021.224f;\n double d = f;\n System.out.println(\"double value: \"+d);\n }\n}"
},
{
"code": null,
"e": 2382,
"s": 2310,
"text": "Integer value of the given character: 67\ndouble value: 10021.2236328125"
},
{
"code": null,
"e": 2542,
"s": 2382,
"text": "But, when you try to assign a higher datatype to lower, at the time of compilation you will get an error saying “incompatible types: possible lossy conversion”"
},
{
"code": null,
"e": 2631,
"s": 2542,
"text": "In the following example we are trying to assign an integer value to a character value −"
},
{
"code": null,
"e": 2819,
"s": 2631,
"text": "public class CastingExample {\n public static void main(String args[]){\n int i = 67;\n char ch = i;\n System.out.println(\"Character value of the given integer: \"+ch);\n }\n}"
},
{
"code": null,
"e": 2882,
"s": 2819,
"text": "On compiling, the above program generates the following error."
},
{
"code": null,
"e": 2998,
"s": 2882,
"text": "CastingExample.java:4: error: incompatible types: possible lossy conversion from int to char\nchar ch = i;\n^\n1 error"
},
{
"code": null,
"e": 3083,
"s": 2998,
"text": "In the following example we are trying to assign a double value to a float variable."
},
{
"code": null,
"e": 3257,
"s": 3083,
"text": "public class CastingExample {\n public static void main(String args[]){\n double d = 10021.224d;\n float f = d;\n System.out.println(\"double value: \"+f);\n }\n}"
},
{
"code": null,
"e": 3320,
"s": 3257,
"text": "On compiling, the above program generates the following error."
},
{
"code": null,
"e": 3441,
"s": 3320,
"text": "CastingExample.java:22: error: incompatible types: possible lossy conversion from double to float\nfloat f = d;\n^\n1 error"
},
{
"code": null,
"e": 3553,
"s": 3441,
"text": "Therefore, to assign a higher datatype to lower, you need to convert it using the cast operator explicitly as −"
},
{
"code": null,
"e": 3573,
"s": 3553,
"text": "float f = (float)d;"
},
{
"code": null,
"e": 3639,
"s": 3573,
"text": "Let us rewrite the Example2 and Exampe3 by converting explicitly."
},
{
"code": null,
"e": 3780,
"s": 3639,
"text": "In the following example we are trying to assign an integer value to a character value by converting it explicitly using the cast operator −"
},
{
"code": null,
"e": 3791,
"s": 3780,
"text": " Live Demo"
},
{
"code": null,
"e": 3985,
"s": 3791,
"text": "public class CastingExample {\n public static void main(String args[]){\n int i = 67;\n char ch = (char)i;\n System.out.println(\"Character value of the given integer: \"+ch);\n }\n}"
},
{
"code": null,
"e": 4025,
"s": 3985,
"text": "Character value of the given integer: C"
},
{
"code": null,
"e": 4162,
"s": 4025,
"text": "In the following example we are trying to assign a double value to a float variable by converting it explicitly using the cast operator."
},
{
"code": null,
"e": 4173,
"s": 4162,
"text": " Live Demo"
},
{
"code": null,
"e": 4354,
"s": 4173,
"text": "public class CastingExample {\n public static void main(String args[]){\n double d = 10021.224d;\n float f = (float)d;\n System.out.println(\"double value: \"+f);\n }\n}"
},
{
"code": null,
"e": 4378,
"s": 4354,
"text": "double value: 10021.224"
}
] |
as_integer_ratio() in Python for reduced fraction of a given rational | In this tutorial, we are going to write a program that returns two numbers whose ratio is equal to the given float value. We have a method called as_integer_ratio() that helps to achieve our goal.
Let's see some examples.
Input:
1.5
Output:
3 / 2
Input:
5.3
Output:
5967269506265907 / 1125899906842624
Let's examine the code.
# initializing the float value
float_value = 1.5
# getting integers tuple using the as_integer_ratio() method
integers = float_value.as_integer_ratio()
# printing the integers
print(f'{integers[0]} / {integers[1]}')
If you run the above code, you will get the following results.
3 / 2
Let's see another example.
# initializing the float value
float_value = 5.3
# getting integers tuple using the as_integer_ratio() method
integers = float_value.as_integer_ratio()
# printing the integers
print(f'{integers[0]} / {integers[1]}')
If you run the above code, you will get the following results.
5967269506265907 / 1125899906842624
If you have any queries in the tutorial, ask them in the comment section. | [
{
"code": null,
"e": 1259,
"s": 1062,
"text": "In this tutorial, we are going to write a program that returns two numbers whose ratio is equal to the given float value. We have a method called as_integer_ratio() that helps to achieve our goal."
},
{
"code": null,
"e": 1284,
"s": 1259,
"text": "Let's see some examples."
},
{
"code": null,
"e": 1364,
"s": 1284,
"text": "Input:\n1.5\nOutput:\n3 / 2\nInput:\n5.3\nOutput:\n5967269506265907 / 1125899906842624"
},
{
"code": null,
"e": 1388,
"s": 1364,
"text": "Let's examine the code."
},
{
"code": null,
"e": 1604,
"s": 1388,
"text": "# initializing the float value\nfloat_value = 1.5\n# getting integers tuple using the as_integer_ratio() method\nintegers = float_value.as_integer_ratio()\n# printing the integers\nprint(f'{integers[0]} / {integers[1]}')"
},
{
"code": null,
"e": 1667,
"s": 1604,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 1674,
"s": 1667,
"text": "3 / 2\n"
},
{
"code": null,
"e": 1701,
"s": 1674,
"text": "Let's see another example."
},
{
"code": null,
"e": 1917,
"s": 1701,
"text": "# initializing the float value\nfloat_value = 5.3\n# getting integers tuple using the as_integer_ratio() method\nintegers = float_value.as_integer_ratio()\n# printing the integers\nprint(f'{integers[0]} / {integers[1]}')"
},
{
"code": null,
"e": 1980,
"s": 1917,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 2017,
"s": 1980,
"text": "5967269506265907 / 1125899906842624\n"
},
{
"code": null,
"e": 2091,
"s": 2017,
"text": "If you have any queries in the tutorial, ask them in the comment section."
}
] |
SQLAlchemy Core - Executing Expression | In the previous chapter, we have learnt SQL Expressions. In this chapter, we shall look into the execution of these expressions.
In order to execute the resulting SQL expressions, we have to obtain a connection object representing an actively checked out DBAPI connection resource and then feed the expression object as shown in the code below.
conn = engine.connect()
The following insert() object can be used for execute() method −
ins = students.insert().values(name = 'Ravi', lastname = 'Kapoor')
result = conn.execute(ins)
The console shows the result of execution of SQL expression as below −
INSERT INTO students (name, lastname) VALUES (?, ?)
('Ravi', 'Kapoor')
COMMIT
Following is the entire snippet that shows the execution of INSERT query using SQLAlchemy’s core technique −
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
engine = create_engine('sqlite:///college.db', echo = True)
meta = MetaData()
students = Table(
'students', meta,
Column('id', Integer, primary_key = True),
Column('name', String),
Column('lastname', String),
)
ins = students.insert()
ins = students.insert().values(name = 'Ravi', lastname = 'Kapoor')
conn = engine.connect()
result = conn.execute(ins)
The result can be verified by opening the database using SQLite Studio as shown in the below screenshot −
The result variable is known as a ResultProxy object. It is analogous to the DBAPI cursor object. We can acquire information about the primary key values which were generated from our statement using ResultProxy.inserted_primary_key as shown below −
result.inserted_primary_key
[1]
To issue many inserts using DBAPI’s execute many() method, we can send in a list of dictionaries each containing a distinct set of parameters to be inserted.
conn.execute(students.insert(), [
{'name':'Rajiv', 'lastname' : 'Khanna'},
{'name':'Komal','lastname' : 'Bhandari'},
{'name':'Abdul','lastname' : 'Sattar'},
{'name':'Priya','lastname' : 'Rajhans'},
])
This is reflected in the data view of the table as shown in the following figure −
21 Lectures
1.5 hours
Jack Chan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2469,
"s": 2340,
"text": "In the previous chapter, we have learnt SQL Expressions. In this chapter, we shall look into the execution of these expressions."
},
{
"code": null,
"e": 2685,
"s": 2469,
"text": "In order to execute the resulting SQL expressions, we have to obtain a connection object representing an actively checked out DBAPI connection resource and then feed the expression object as shown in the code below."
},
{
"code": null,
"e": 2709,
"s": 2685,
"text": "conn = engine.connect()"
},
{
"code": null,
"e": 2774,
"s": 2709,
"text": "The following insert() object can be used for execute() method −"
},
{
"code": null,
"e": 2868,
"s": 2774,
"text": "ins = students.insert().values(name = 'Ravi', lastname = 'Kapoor')\nresult = conn.execute(ins)"
},
{
"code": null,
"e": 2939,
"s": 2868,
"text": "The console shows the result of execution of SQL expression as below −"
},
{
"code": null,
"e": 3017,
"s": 2939,
"text": "INSERT INTO students (name, lastname) VALUES (?, ?)\n('Ravi', 'Kapoor')\nCOMMIT"
},
{
"code": null,
"e": 3126,
"s": 3017,
"text": "Following is the entire snippet that shows the execution of INSERT query using SQLAlchemy’s core technique −"
},
{
"code": null,
"e": 3576,
"s": 3126,
"text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\nins = students.insert()\nins = students.insert().values(name = 'Ravi', lastname = 'Kapoor')\nconn = engine.connect()\nresult = conn.execute(ins)"
},
{
"code": null,
"e": 3682,
"s": 3576,
"text": "The result can be verified by opening the database using SQLite Studio as shown in the below screenshot −"
},
{
"code": null,
"e": 3932,
"s": 3682,
"text": "The result variable is known as a ResultProxy object. It is analogous to the DBAPI cursor object. We can acquire information about the primary key values which were generated from our statement using ResultProxy.inserted_primary_key as shown below −"
},
{
"code": null,
"e": 3964,
"s": 3932,
"text": "result.inserted_primary_key\n[1]"
},
{
"code": null,
"e": 4122,
"s": 3964,
"text": "To issue many inserts using DBAPI’s execute many() method, we can send in a list of dictionaries each containing a distinct set of parameters to be inserted."
},
{
"code": null,
"e": 4336,
"s": 4122,
"text": "conn.execute(students.insert(), [\n {'name':'Rajiv', 'lastname' : 'Khanna'},\n {'name':'Komal','lastname' : 'Bhandari'},\n {'name':'Abdul','lastname' : 'Sattar'},\n {'name':'Priya','lastname' : 'Rajhans'},\n])\n"
},
{
"code": null,
"e": 4419,
"s": 4336,
"text": "This is reflected in the data view of the table as shown in the following figure −"
},
{
"code": null,
"e": 4454,
"s": 4419,
"text": "\n 21 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4465,
"s": 4454,
"text": " Jack Chan"
},
{
"code": null,
"e": 4472,
"s": 4465,
"text": " Print"
},
{
"code": null,
"e": 4483,
"s": 4472,
"text": " Add Notes"
}
] |
C library function - srand() | The C library function void srand(unsigned int seed) seeds the random number generator used by the function rand.
Following is the declaration for srand() function.
void srand(unsigned int seed)
seed − This is an integer value to be used as seed by the pseudo-random number generator algorithm.
seed − This is an integer value to be used as seed by the pseudo-random number generator algorithm.
This function does not return any value.
The following example shows the usage of srand() function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int i, n;
time_t t;
n = 5;
/* Intializes random number generator */
srand((unsigned) time(&t));
/* Print 5 random numbers from 0 to 50 */
for( i = 0 ; i < n ; i++ ) {
printf("%d\n", rand() % 50);
}
return(0);
}
Let us compile and run the above program that will produce the following result −
38
45
29
29
47
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2121,
"s": 2007,
"text": "The C library function void srand(unsigned int seed) seeds the random number generator used by the function rand."
},
{
"code": null,
"e": 2172,
"s": 2121,
"text": "Following is the declaration for srand() function."
},
{
"code": null,
"e": 2202,
"s": 2172,
"text": "void srand(unsigned int seed)"
},
{
"code": null,
"e": 2302,
"s": 2202,
"text": "seed − This is an integer value to be used as seed by the pseudo-random number generator algorithm."
},
{
"code": null,
"e": 2402,
"s": 2302,
"text": "seed − This is an integer value to be used as seed by the pseudo-random number generator algorithm."
},
{
"code": null,
"e": 2443,
"s": 2402,
"text": "This function does not return any value."
},
{
"code": null,
"e": 2502,
"s": 2443,
"text": "The following example shows the usage of srand() function."
},
{
"code": null,
"e": 2831,
"s": 2502,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main () {\n int i, n;\n time_t t;\n \n n = 5;\n \n /* Intializes random number generator */\n srand((unsigned) time(&t));\n\n /* Print 5 random numbers from 0 to 50 */\n for( i = 0 ; i < n ; i++ ) {\n printf(\"%d\\n\", rand() % 50);\n }\n \n return(0);\n}"
},
{
"code": null,
"e": 2913,
"s": 2831,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 2929,
"s": 2913,
"text": "38\n45\n29\n29\n47\n"
},
{
"code": null,
"e": 2962,
"s": 2929,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2977,
"s": 2962,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3012,
"s": 2977,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3027,
"s": 3012,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3062,
"s": 3027,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3076,
"s": 3062,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3109,
"s": 3076,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3127,
"s": 3109,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3162,
"s": 3127,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3181,
"s": 3162,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3214,
"s": 3181,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3226,
"s": 3214,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3233,
"s": 3226,
"text": " Print"
},
{
"code": null,
"e": 3244,
"s": 3233,
"text": " Add Notes"
}
] |
How to do UI testing with Selenium? | We can do UI testing with Selenium webdriver. To achieve this, we have to follow the steps listed below which can be applied to any script developed to test the UI of the application −
Step1 − Object of Webdriver should be created. For example,
WebDriver driver = new ChromeDriver();
The above piece of code is used to create a webdriver instance and initiate the script execution in the Chrome browser.
Step2 − Launch the URL on which we want to perform the UI testing. For example,
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
The above piece of code shall launch the URL passed as a parameter to the get method.
Step3 − Identify webelement with the help of any of the locators like id, class, name, tagname, link text, partial link text, css or xpath. The method - findElement is used to identify the element with these locators. For example,
WebElement elm = driver.findElement(By.tagName("h4"));
The above code is used to identify an element with the help of the locator tagname.
Step4 − After the element has been located, perform an action on it like inputting a text, clicking, and so on. For example,
elm.sendKeys("Selenium");
The above code is used to input a text on the element identified in Step3.
Step5 − Validate the impact on the webpage on performing the operation in Step4. For example,
Assert.assertEquals(s, "Selenium");
The above code is used to compare and verify if the actual value is equal to expected value - Selenium.
Step6 − Execute the test and record the result created with a test framework.
Step7 − Finish the test by quitting the webdriver session. For example,
driver.quit();
Code Implementation
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class NewTest {
@Test
public void f() {
System.setProperty("webdriver.chrome.driver", "chromedriver");
//webdriver instance
WebDriver driver = new ChromeDriver();
// implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//url launch
driver.get("https://www.tutorialspoint.com/index.htm");
//element identify
WebElement elm = driver.findElement(By.tagName("input"));
//perform action - input text
elm.sendKeys("Selenium");
String s = elm.getAttribute("value");
//validate result with Assertion
Assert.assertEquals(s, "Selenium");
//quit browser
driver.quit();
}
} | [
{
"code": null,
"e": 1247,
"s": 1062,
"text": "We can do UI testing with Selenium webdriver. To achieve this, we have to follow the steps listed below which can be applied to any script developed to test the UI of the application −"
},
{
"code": null,
"e": 1307,
"s": 1247,
"text": "Step1 − Object of Webdriver should be created. For example,"
},
{
"code": null,
"e": 1346,
"s": 1307,
"text": "WebDriver driver = new ChromeDriver();"
},
{
"code": null,
"e": 1466,
"s": 1346,
"text": "The above piece of code is used to create a webdriver instance and initiate the script execution in the Chrome browser."
},
{
"code": null,
"e": 1546,
"s": 1466,
"text": "Step2 − Launch the URL on which we want to perform the UI testing. For example,"
},
{
"code": null,
"e": 1616,
"s": 1546,
"text": "driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");"
},
{
"code": null,
"e": 1702,
"s": 1616,
"text": "The above piece of code shall launch the URL passed as a parameter to the get method."
},
{
"code": null,
"e": 1933,
"s": 1702,
"text": "Step3 − Identify webelement with the help of any of the locators like id, class, name, tagname, link text, partial link text, css or xpath. The method - findElement is used to identify the element with these locators. For example,"
},
{
"code": null,
"e": 1988,
"s": 1933,
"text": "WebElement elm = driver.findElement(By.tagName(\"h4\"));"
},
{
"code": null,
"e": 2072,
"s": 1988,
"text": "The above code is used to identify an element with the help of the locator tagname."
},
{
"code": null,
"e": 2197,
"s": 2072,
"text": "Step4 − After the element has been located, perform an action on it like inputting a text, clicking, and so on. For example,"
},
{
"code": null,
"e": 2223,
"s": 2197,
"text": "elm.sendKeys(\"Selenium\");"
},
{
"code": null,
"e": 2298,
"s": 2223,
"text": "The above code is used to input a text on the element identified in Step3."
},
{
"code": null,
"e": 2392,
"s": 2298,
"text": "Step5 − Validate the impact on the webpage on performing the operation in Step4. For example,"
},
{
"code": null,
"e": 2428,
"s": 2392,
"text": "Assert.assertEquals(s, \"Selenium\");"
},
{
"code": null,
"e": 2532,
"s": 2428,
"text": "The above code is used to compare and verify if the actual value is equal to expected value - Selenium."
},
{
"code": null,
"e": 2610,
"s": 2532,
"text": "Step6 − Execute the test and record the result created with a test framework."
},
{
"code": null,
"e": 2682,
"s": 2610,
"text": "Step7 − Finish the test by quitting the webdriver session. For example,"
},
{
"code": null,
"e": 2697,
"s": 2682,
"text": "driver.quit();"
},
{
"code": null,
"e": 2717,
"s": 2697,
"text": "Code Implementation"
},
{
"code": null,
"e": 3672,
"s": 2717,
"text": "import java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\npublic class NewTest {\n @Test\n public void f() {\n System.setProperty(\"webdriver.chrome.driver\", \"chromedriver\");\n //webdriver instance\n WebDriver driver = new ChromeDriver();\n // implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //url launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n //element identify\n WebElement elm = driver.findElement(By.tagName(\"input\"));\n //perform action - input text\n elm.sendKeys(\"Selenium\");\n String s = elm.getAttribute(\"value\");\n //validate result with Assertion\n Assert.assertEquals(s, \"Selenium\");\n //quit browser\n driver.quit();\n }\n}"
}
] |
How to represent all values of X-axis or Y-axis on the graph in R using ggplot2 package? | If we have many unique elements or repeated in a column of an R data frame and create a graph using that column, either on X-axis or Y-axis then R automatically choses the axes labels, this might not display all the unique values of the column in the plot. Therefore, we can use scale_x_continuous function or scale_y_continuous function with labels depending on our requirement to display the column values.
Consider the below data frame −
Live Demo
x<-1:10
y<-rpois(10,2)
df<-data.frame(x,y)
df
x y
1 1 1
2 2 1
3 3 5
4 4 3
5 5 3
6 6 0
7 7 2
8 8 5
9 9 2
10 10 4
Loading ggplot2 package and creating a point chart between x and y by displaying all values of x axis −
library(ggplot2) ggplot(df,aes(x,y))+geom_point()+scale_x_continuous(labels=as.character(x),breaks=x)
Creating a point chart between x and y by displaying all values of Y axis −
ggplot(df,aes(x,y))+geom_point()+scale_y_continuous(labels=as.character(y),breaks=y) | [
{
"code": null,
"e": 1471,
"s": 1062,
"text": "If we have many unique elements or repeated in a column of an R data frame and create a graph using that column, either on X-axis or Y-axis then R automatically choses the axes labels, this might not display all the unique values of the column in the plot. Therefore, we can use scale_x_continuous function or scale_y_continuous function with labels depending on our requirement to display the column values."
},
{
"code": null,
"e": 1503,
"s": 1471,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1514,
"s": 1503,
"text": " Live Demo"
},
{
"code": null,
"e": 1560,
"s": 1514,
"text": "x<-1:10\ny<-rpois(10,2)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 1626,
"s": 1560,
"text": "x y\n1 1 1\n2 2 1\n3 3 5\n4 4 3\n5 5 3\n6 6 0\n7 7 2\n8 8 5\n9 9 2\n10 10 4"
},
{
"code": null,
"e": 1730,
"s": 1626,
"text": "Loading ggplot2 package and creating a point chart between x and y by displaying all values of x axis −"
},
{
"code": null,
"e": 1832,
"s": 1730,
"text": "library(ggplot2) ggplot(df,aes(x,y))+geom_point()+scale_x_continuous(labels=as.character(x),breaks=x)"
},
{
"code": null,
"e": 1908,
"s": 1832,
"text": "Creating a point chart between x and y by displaying all values of Y axis −"
},
{
"code": null,
"e": 1993,
"s": 1908,
"text": "ggplot(df,aes(x,y))+geom_point()+scale_y_continuous(labels=as.character(y),breaks=y)"
}
] |
How to Fix: ‘numpy.float64’ object cannot be interpreted as an integer - GeeksforGeeks | 19 Dec, 2021
In this article, we are going to see how to fix: ‘numpy.float64’ object cannot be interpreted as an integer.
When a function or operation is applied to an object of the wrong type, a type error is raised. The ‘numpy.float64’ object cannot be interpreted as an integer is one example of this type of problem. Let’s see what we can do about that.
if we give a float number in a range() in python, it results in a ”numpy.float64’ object that cannot be interpreted as an integer ‘ error.
range() function: The range() function returns a number series that starts at 0 and increments by 1 before stopping at a specified value.
syntax: range(start,stop,step)
Python3
# codeimport numpy as np # an array of float valuesarr = np.array([1.5, 2.5, 3.5]) # we loop to print out range of values # at each indexfor i in range(len(arr)): print(range(arr[i]))
Output:
TypeError: ‘numpy.float64’ object cannot be interpreted as an integer
when we have a list of values, and we want to change their type to prevent errors.
We can use the .astype() function and give the argument “int”. astype() function: When we need to convert a certain array of data from one type to another, the method comes in helpful.
Parameters
dtype: refers to data type of list, or dict of column name
copy: boolean value,in default it’s set to True
errors: {‘raise’, ‘ignore’}, default is ‘raise’
Python3
# codeimport numpy as np # an array of float valuesarr = np.array([1.5, 2.5, 3.5]) arr = arr.astype(int) # we loop to print out range of values# at each indexfor i in range(len(arr)): print(range(arr[i]))
Output:
range(0, 1)
range(0, 2)
range(0, 3)
Here we will int() function to cast the array object before getting into range.
Python3
# codeimport numpy as np # an array of float valuesarr = np.array([1.5, 2.5, 3.5]) # we loop to print out range of values# at each indexfor i in range(len(arr)): print(range(int(arr[i])))
Output:
range(0, 1)
range(0, 2)
range(0, 3)
Picked
Python How-to-fix
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 24011,
"s": 23901,
"text": "In this article, we are going to see how to fix: ‘numpy.float64’ object cannot be interpreted as an integer."
},
{
"code": null,
"e": 24247,
"s": 24011,
"text": "When a function or operation is applied to an object of the wrong type, a type error is raised. The ‘numpy.float64’ object cannot be interpreted as an integer is one example of this type of problem. Let’s see what we can do about that."
},
{
"code": null,
"e": 24386,
"s": 24247,
"text": "if we give a float number in a range() in python, it results in a ”numpy.float64’ object that cannot be interpreted as an integer ‘ error."
},
{
"code": null,
"e": 24524,
"s": 24386,
"text": "range() function: The range() function returns a number series that starts at 0 and increments by 1 before stopping at a specified value."
},
{
"code": null,
"e": 24555,
"s": 24524,
"text": "syntax: range(start,stop,step)"
},
{
"code": null,
"e": 24563,
"s": 24555,
"text": "Python3"
},
{
"code": "# codeimport numpy as np # an array of float valuesarr = np.array([1.5, 2.5, 3.5]) # we loop to print out range of values # at each indexfor i in range(len(arr)): print(range(arr[i]))",
"e": 24754,
"s": 24563,
"text": null
},
{
"code": null,
"e": 24762,
"s": 24754,
"text": "Output:"
},
{
"code": null,
"e": 24832,
"s": 24762,
"text": "TypeError: ‘numpy.float64’ object cannot be interpreted as an integer"
},
{
"code": null,
"e": 24915,
"s": 24832,
"text": "when we have a list of values, and we want to change their type to prevent errors."
},
{
"code": null,
"e": 25102,
"s": 24915,
"text": " We can use the .astype() function and give the argument “int”. astype() function: When we need to convert a certain array of data from one type to another, the method comes in helpful."
},
{
"code": null,
"e": 25113,
"s": 25102,
"text": "Parameters"
},
{
"code": null,
"e": 25173,
"s": 25113,
"text": "dtype: refers to data type of list, or dict of column name"
},
{
"code": null,
"e": 25221,
"s": 25173,
"text": "copy: boolean value,in default it’s set to True"
},
{
"code": null,
"e": 25270,
"s": 25221,
"text": "errors: {‘raise’, ‘ignore’}, default is ‘raise’"
},
{
"code": null,
"e": 25278,
"s": 25270,
"text": "Python3"
},
{
"code": "# codeimport numpy as np # an array of float valuesarr = np.array([1.5, 2.5, 3.5]) arr = arr.astype(int) # we loop to print out range of values# at each indexfor i in range(len(arr)): print(range(arr[i]))",
"e": 25489,
"s": 25278,
"text": null
},
{
"code": null,
"e": 25497,
"s": 25489,
"text": "Output:"
},
{
"code": null,
"e": 25533,
"s": 25497,
"text": "range(0, 1)\nrange(0, 2)\nrange(0, 3)"
},
{
"code": null,
"e": 25613,
"s": 25533,
"text": "Here we will int() function to cast the array object before getting into range."
},
{
"code": null,
"e": 25621,
"s": 25613,
"text": "Python3"
},
{
"code": "# codeimport numpy as np # an array of float valuesarr = np.array([1.5, 2.5, 3.5]) # we loop to print out range of values# at each indexfor i in range(len(arr)): print(range(int(arr[i])))",
"e": 25816,
"s": 25621,
"text": null
},
{
"code": null,
"e": 25824,
"s": 25816,
"text": "Output:"
},
{
"code": null,
"e": 25860,
"s": 25824,
"text": "range(0, 1)\nrange(0, 2)\nrange(0, 3)"
},
{
"code": null,
"e": 25867,
"s": 25860,
"text": "Picked"
},
{
"code": null,
"e": 25885,
"s": 25867,
"text": "Python How-to-fix"
},
{
"code": null,
"e": 25898,
"s": 25885,
"text": "Python-numpy"
},
{
"code": null,
"e": 25905,
"s": 25898,
"text": "Python"
},
{
"code": null,
"e": 26003,
"s": 25905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26012,
"s": 26003,
"text": "Comments"
},
{
"code": null,
"e": 26025,
"s": 26012,
"text": "Old Comments"
},
{
"code": null,
"e": 26057,
"s": 26025,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26113,
"s": 26057,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26155,
"s": 26113,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26197,
"s": 26155,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26233,
"s": 26197,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26255,
"s": 26233,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26294,
"s": 26255,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26321,
"s": 26294,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26352,
"s": 26321,
"text": "Python | os.path.join() method"
}
] |
Reflection Array Class in Java - GeeksforGeeks | 10 Nov, 2021
The Array class in java.lang.reflect package is a part of the Java Reflection. This class provides static methods to create and access Java arrays dynamically. It is a final class, which means it can’t be instantiated or changed. Only the methods of this class can be used by the class name itself.
The java.util.Arrays class contains various methods for manipulating arrays (such as sorting and searching), whereas this java.lang.reflect.Array class provides static methods to create and access Java arrays dynamically. This Array class keeps the array to be type-safe.
java.lang.Object
↳ java.lang.reflect.Array
public final class Array extends Object
Array.<function name>;
Creating an array using reflect.Array Class is different from the usual way. The process to create such an array is as follows:
Get the size of the array to be created
To create an array (say of X class), use the newInstance() method of Array class to pass the X class as the type of the array, and the size of the array, as parameters.
Syntax:
X[] arrayOfXType = (X[]) Array.newInstance(X.class, size);
Where X is to be replaced by the type of the array like int, double, etc.
This method returns an Object array of the given size, then cast into the required X[] type.
Hence the required array of type X has been created.
Below is an example to create an integer array of size 5, using the Array class:
Example: To create an integer array of size 5:
Java
// Java code to create an integer array of size 5,// using the Array class: import java.lang.reflect.Array;import java.util.Arrays; public class GfG { public static void main(String[] args) { // Get the size of the array int sizeOfArray = 5; // Create an integer array // using reflect.Array class // This is done using the newInstance() method int[] intArray = (int[])Array.newInstance( int.class, sizeOfArray); // Printing the Array content System.out.println(Arrays.toString(intArray)); }}
[0, 0, 0, 0, 0]
Like creating an array, adding elements in the array using reflect.Array Class is also different from the usual way. The process to add elements in such an array is as follows:
Get the value of the element to be added.
Get the index at which the element is to be added.
To add an element in an array (say of X class), use the setX() method of Array class, where X is to be replaced by the type of the array such as setInt(), setDouble(), etc. This method takes the X[] as the first parameter, the index at which the element is added as the second parameter, and the element as the third parameter in the below syntax.
Syntax:
Array.setX(X[], indexOfInsertion, elementToBeInserted);
Where X is to be replaced by the type of the array like int, double, etc.
This method inserts the element at the specified index in this array.
Hence the required element has been inserted into the array.
Below is an example to add an element into an integer array, using the Array class:
Example: To add an element into an integer array:
Java
// Java code to add an element into an integer array,// using the Array class: import java.lang.reflect.Array;import java.util.Arrays; public class GfG { public static void main(String[] args) { // Get the size of the array int sizeOfArray = 3; // Create an integer array // using reflect.Array class // This is done using the newInstance() method int[] intArray = (int[])Array.newInstance( int.class, sizeOfArray); // Add elements into the array // This is done using the setInt() method Array.setInt(intArray, 0, 10); Array.setInt(intArray, 1, 20); Array.setInt(intArray, 2, 30); // Printing the Array content System.out.println(Arrays.toString(intArray)); }}
[10, 20, 30]
Like creating an array, retrieving elements in the array using reflect.Array Class is also different from the usual way. The process to retrieve elements in such an array is as follows:
Get the index at which the element is to be retrieved.
To retrieve an element in an array (say of X class), use the getX() method of Array class, where X is to be replaced by the type of the array such as getInt(), getDouble(), etc. This method takes the X[] as the first parameter and the index at which the element is retrieved as the second parameter in the syntax below.
Syntax:
Array.getX(X[], indexOfRetrieval);
Where X is to be replaced by the type of the array like int, double, etc.
This method retrieves the element at the specified index from this array.
Hence the required element has been retrieved from the array.
Below is an example to retrieve an element from an integer array using the Array class:
Example: To retrieve an element from an integer array:
Java
// Java code to retrieve an element from an integer array,// using the Array class: import java.lang.reflect.Array;import java.util.Arrays; public class GfG { public static void main(String[] args) { // Get the size of the array int sizeOfArray = 3; // Create an integer array // using reflect.Array class // This is done using the newInstance() method int[] intArray = (int[])Array.newInstance( int.class, sizeOfArray); // Add elements from the array // This is done using the getInt() method Array.setInt(intArray, 0, 10); Array.setInt(intArray, 1, 20); Array.setInt(intArray, 2, 30); // Printing the Array content System.out.println(Arrays.toString(intArray)); // Retrieve elements from the array // This is done using the getInt() method System.out.println("Element at index 0: " + Array.getInt(intArray, 0)); System.out.println("Element at index 1: " + Array.getInt(intArray, 1)); System.out.println("Element at index 2: " + Array.getInt(intArray, 2)); }}
[10, 20, 30]
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
nishkarshgandhi
Java-Class and Object
java-reflection-array
Java
Java-Class and Object
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java | [
{
"code": null,
"e": 24437,
"s": 24409,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 24736,
"s": 24437,
"text": "The Array class in java.lang.reflect package is a part of the Java Reflection. This class provides static methods to create and access Java arrays dynamically. It is a final class, which means it can’t be instantiated or changed. Only the methods of this class can be used by the class name itself."
},
{
"code": null,
"e": 25008,
"s": 24736,
"text": "The java.util.Arrays class contains various methods for manipulating arrays (such as sorting and searching), whereas this java.lang.reflect.Array class provides static methods to create and access Java arrays dynamically. This Array class keeps the array to be type-safe."
},
{
"code": null,
"e": 25052,
"s": 25008,
"text": "java.lang.Object\n ↳ java.lang.reflect.Array"
},
{
"code": null,
"e": 25092,
"s": 25052,
"text": "public final class Array extends Object"
},
{
"code": null,
"e": 25115,
"s": 25092,
"text": "Array.<function name>;"
},
{
"code": null,
"e": 25244,
"s": 25115,
"text": "Creating an array using reflect.Array Class is different from the usual way. The process to create such an array is as follows: "
},
{
"code": null,
"e": 25284,
"s": 25244,
"text": "Get the size of the array to be created"
},
{
"code": null,
"e": 25453,
"s": 25284,
"text": "To create an array (say of X class), use the newInstance() method of Array class to pass the X class as the type of the array, and the size of the array, as parameters."
},
{
"code": null,
"e": 25462,
"s": 25453,
"text": "Syntax: "
},
{
"code": null,
"e": 25521,
"s": 25462,
"text": "X[] arrayOfXType = (X[]) Array.newInstance(X.class, size);"
},
{
"code": null,
"e": 25595,
"s": 25521,
"text": "Where X is to be replaced by the type of the array like int, double, etc."
},
{
"code": null,
"e": 25688,
"s": 25595,
"text": "This method returns an Object array of the given size, then cast into the required X[] type."
},
{
"code": null,
"e": 25741,
"s": 25688,
"text": "Hence the required array of type X has been created."
},
{
"code": null,
"e": 25822,
"s": 25741,
"text": "Below is an example to create an integer array of size 5, using the Array class:"
},
{
"code": null,
"e": 25870,
"s": 25822,
"text": "Example: To create an integer array of size 5: "
},
{
"code": null,
"e": 25875,
"s": 25870,
"text": "Java"
},
{
"code": "// Java code to create an integer array of size 5,// using the Array class: import java.lang.reflect.Array;import java.util.Arrays; public class GfG { public static void main(String[] args) { // Get the size of the array int sizeOfArray = 5; // Create an integer array // using reflect.Array class // This is done using the newInstance() method int[] intArray = (int[])Array.newInstance( int.class, sizeOfArray); // Printing the Array content System.out.println(Arrays.toString(intArray)); }}",
"e": 26454,
"s": 25875,
"text": null
},
{
"code": null,
"e": 26470,
"s": 26454,
"text": "[0, 0, 0, 0, 0]"
},
{
"code": null,
"e": 26648,
"s": 26470,
"text": "Like creating an array, adding elements in the array using reflect.Array Class is also different from the usual way. The process to add elements in such an array is as follows: "
},
{
"code": null,
"e": 26690,
"s": 26648,
"text": "Get the value of the element to be added."
},
{
"code": null,
"e": 26741,
"s": 26690,
"text": "Get the index at which the element is to be added."
},
{
"code": null,
"e": 27089,
"s": 26741,
"text": "To add an element in an array (say of X class), use the setX() method of Array class, where X is to be replaced by the type of the array such as setInt(), setDouble(), etc. This method takes the X[] as the first parameter, the index at which the element is added as the second parameter, and the element as the third parameter in the below syntax."
},
{
"code": null,
"e": 27098,
"s": 27089,
"text": "Syntax: "
},
{
"code": null,
"e": 27154,
"s": 27098,
"text": "Array.setX(X[], indexOfInsertion, elementToBeInserted);"
},
{
"code": null,
"e": 27228,
"s": 27154,
"text": "Where X is to be replaced by the type of the array like int, double, etc."
},
{
"code": null,
"e": 27298,
"s": 27228,
"text": "This method inserts the element at the specified index in this array."
},
{
"code": null,
"e": 27359,
"s": 27298,
"text": "Hence the required element has been inserted into the array."
},
{
"code": null,
"e": 27443,
"s": 27359,
"text": "Below is an example to add an element into an integer array, using the Array class:"
},
{
"code": null,
"e": 27494,
"s": 27443,
"text": "Example: To add an element into an integer array: "
},
{
"code": null,
"e": 27499,
"s": 27494,
"text": "Java"
},
{
"code": "// Java code to add an element into an integer array,// using the Array class: import java.lang.reflect.Array;import java.util.Arrays; public class GfG { public static void main(String[] args) { // Get the size of the array int sizeOfArray = 3; // Create an integer array // using reflect.Array class // This is done using the newInstance() method int[] intArray = (int[])Array.newInstance( int.class, sizeOfArray); // Add elements into the array // This is done using the setInt() method Array.setInt(intArray, 0, 10); Array.setInt(intArray, 1, 20); Array.setInt(intArray, 2, 30); // Printing the Array content System.out.println(Arrays.toString(intArray)); }}",
"e": 28276,
"s": 27499,
"text": null
},
{
"code": null,
"e": 28289,
"s": 28276,
"text": "[10, 20, 30]"
},
{
"code": null,
"e": 28476,
"s": 28289,
"text": "Like creating an array, retrieving elements in the array using reflect.Array Class is also different from the usual way. The process to retrieve elements in such an array is as follows: "
},
{
"code": null,
"e": 28531,
"s": 28476,
"text": "Get the index at which the element is to be retrieved."
},
{
"code": null,
"e": 28851,
"s": 28531,
"text": "To retrieve an element in an array (say of X class), use the getX() method of Array class, where X is to be replaced by the type of the array such as getInt(), getDouble(), etc. This method takes the X[] as the first parameter and the index at which the element is retrieved as the second parameter in the syntax below."
},
{
"code": null,
"e": 28860,
"s": 28851,
"text": "Syntax: "
},
{
"code": null,
"e": 28895,
"s": 28860,
"text": "Array.getX(X[], indexOfRetrieval);"
},
{
"code": null,
"e": 28969,
"s": 28895,
"text": "Where X is to be replaced by the type of the array like int, double, etc."
},
{
"code": null,
"e": 29043,
"s": 28969,
"text": "This method retrieves the element at the specified index from this array."
},
{
"code": null,
"e": 29105,
"s": 29043,
"text": "Hence the required element has been retrieved from the array."
},
{
"code": null,
"e": 29193,
"s": 29105,
"text": "Below is an example to retrieve an element from an integer array using the Array class:"
},
{
"code": null,
"e": 29249,
"s": 29193,
"text": "Example: To retrieve an element from an integer array: "
},
{
"code": null,
"e": 29254,
"s": 29249,
"text": "Java"
},
{
"code": "// Java code to retrieve an element from an integer array,// using the Array class: import java.lang.reflect.Array;import java.util.Arrays; public class GfG { public static void main(String[] args) { // Get the size of the array int sizeOfArray = 3; // Create an integer array // using reflect.Array class // This is done using the newInstance() method int[] intArray = (int[])Array.newInstance( int.class, sizeOfArray); // Add elements from the array // This is done using the getInt() method Array.setInt(intArray, 0, 10); Array.setInt(intArray, 1, 20); Array.setInt(intArray, 2, 30); // Printing the Array content System.out.println(Arrays.toString(intArray)); // Retrieve elements from the array // This is done using the getInt() method System.out.println(\"Element at index 0: \" + Array.getInt(intArray, 0)); System.out.println(\"Element at index 1: \" + Array.getInt(intArray, 1)); System.out.println(\"Element at index 2: \" + Array.getInt(intArray, 2)); }}",
"e": 30444,
"s": 29254,
"text": null
},
{
"code": null,
"e": 30526,
"s": 30444,
"text": "[10, 20, 30]\nElement at index 0: 10\nElement at index 1: 20\nElement at index 2: 30"
},
{
"code": null,
"e": 30542,
"s": 30526,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 30564,
"s": 30542,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 30586,
"s": 30564,
"text": "java-reflection-array"
},
{
"code": null,
"e": 30591,
"s": 30586,
"text": "Java"
},
{
"code": null,
"e": 30613,
"s": 30591,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 30618,
"s": 30613,
"text": "Java"
},
{
"code": null,
"e": 30716,
"s": 30618,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30725,
"s": 30716,
"text": "Comments"
},
{
"code": null,
"e": 30738,
"s": 30725,
"text": "Old Comments"
},
{
"code": null,
"e": 30789,
"s": 30738,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30819,
"s": 30789,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30850,
"s": 30819,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30869,
"s": 30850,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30901,
"s": 30869,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30919,
"s": 30901,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30939,
"s": 30919,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30971,
"s": 30939,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30995,
"s": 30971,
"text": "Singleton Class in Java"
}
] |
Raft Algorithm Explained 2. Part 2 — Log Replication | by Zixuan Zhang | Towards Data Science | Raft is a consensus algorithm built to orchestrate replicas in a distributed fashion. Designed with understandability in mind, Raft has only a few moving parts and is easy to implement. In the last article, I talked about the basics of Raft and explained the leader-election mechanism. In this post, we are going to focus on another important issue — log replication.
Raft is essentially a bunch of replicated state machines. Whenever a request is received by the leader node, it is appended to the log for durability. The same log is replicated across multiple machines for redundancy.
For instance, in figure 1, the current leader has four entries in its log. Follower 1 is fully in sync, but follower 2 is missing the latest entry. If you don’t understand what Term is in fig 0, check out my previous article.
RPC for log replication
Designed for understandability, Raft only uses two RPC calls for all communications:
AppendEntry: This RPC is initiated by the leader and carries the latest commands received. It also serves as the heartbeat message. When a follower gets this message, the election timer is reset. The AppendEntry message is a struct like this (I’m using Golang here)
It’s okay if you don’t understand the meaning of each field. We are going to examine them one by one.
RequestVote: This RPC is used for leader election, which is covered by the last post. I’m going to skip it since we care only about log replication.
Let’s start with a vanilla log replication algorithm. Whenever a request is received by the leader, it forwards the log entry to all followers and waits for the majority to acknowledge it.
Problem 1: Log ordering
The vanilla algorithm sends out messages to the followers as soon as they arrive. To do so, it only needs two fields in the message — leaderID and Entry. One major issue is that the log order cannot be preserved because of potential message delays. Consider the scenario in figure 1.
Raft uses two additional fields to ensure the integrity of the log — PrevLogIndex and PrevLogTerm. When a new entry is sent out, the leader also sends out the index and term number of the entry before. The receiver makes sure its latest entry has the identical index and term before appending the new request to its local log.
With these two additional parameters, we can achieve something awesome:
Given an index of the log, if the entries from two logs (on two different machines) share the same term, they are identicalIf two entries in different logs have the same index and term, all preceding entries are identical
Given an index of the log, if the entries from two logs (on two different machines) share the same term, they are identical
If two entries in different logs have the same index and term, all preceding entries are identical
The first property is easy to prove. Assume the claim is wrong. If there exist two distinct entries with the same term, one of them must be received by the leader later than the other. Since the log is append-only, one of the entries will have a larger PrevLogIndex. However, if they show up in the same index in two different logs, they must have the same PrevLogIndex. (otherwise, the receiver rejects it) Contradiction!!
The second claim can be proved by induction:
Together, these two guarantees consist of the Log Matching Property of Raft.
Problem 2: Followers with conflicting entries
If the leader log is the only authority in the cluster, it will overwrite any conflict that a follower has. Is it possible to lose some log entries? Consider the following case:
Before diving into the problem, I want to convince you that the above scenarios can indeed happen. Logs are in sync before index 2. From there onward, the following could happen to create these logs:
1) node 2 becomes the leader (votes from itself, 1 and 0) with term 22) node 2 receives a request from the client but failed to sync with other nodes3) node 0 becomes the leader (vote from 1 and itself) with term 34) node 0 receives requests from the client. but failed to sync
Now, if node 0 regains contact with node 2, it will try to replicate its log, as depicted in figure 5
As you can see, the green entry indeed gets dropped. With the current design, this problem is unavoidable. However, a key observation here is that the green entry isn’t replicated on the majority (at least two nodes). If it is, it will never get dropped for the following reasons:
if an entry is replicated on the majority, at least N/2 + 1 nodes have itfor a node without the entry to win the election, it needs N/2 votes from other nodes (candidate always votes for itself)Since the candidate doesn’t have the entry, the N/2 + 1 nodes with the entry won’t vote for it (election restriction explained in part 1)It won’t get enough votes to win the election
if an entry is replicated on the majority, at least N/2 + 1 nodes have it
for a node without the entry to win the election, it needs N/2 votes from other nodes (candidate always votes for itself)
Since the candidate doesn’t have the entry, the N/2 + 1 nodes with the entry won’t vote for it (election restriction explained in part 1)
It won’t get enough votes to win the election
This is the second key feature of Raft — Log Completeness Property. If an entry is replicated on the majority, it will always show up in the future leader logs, regardless of which node it might be. If not replicated on the majority, an entry could be dropped if leadership changes.
With the Log Completeness Property, it is important not to acknowledge client requests before the majority has it.
Problem 3: When to commit?
Finally, we arrive at the last issue — when to commit an entry? First of all, what is commit and why commit? Raft is a low-level consensus algorithm used by upper-level applications like key-value stores (e.g. something like ZooKeeper). When an entry is safely replicated by Raft, we want to make sure the client can see it via the application. Hence, Raft needs to decide when to tell the upper-level application an entry is ready for use (a partially replicated entry, as the last entry in the leader’s log should not be visible!).
So far our vanilla algorithm does not carry any information regarding the commit index. Because the data flow is a one-way street, flowing from the leader to the followers, the nodes won’t know if an entry is replicated on the majority.
To address this issue, we can add yet another field to the AppendEntry message called LeaderCommit. The leader increases the commit index if an entry is received by the majority. Below is the actual code that keeps track of the commit index used by the leader node.
In this article, we started with a vanilla log replication algorithm(broadcasting entries without any additional bookkeeping) and evolved it to the full-fledged version by considering various corner cases. The most important RPC in log replication is the AppendEntry RPC, which uses a struct with four fields:
Term: very important for log replication and leader election
LeaderId: show the identity of the candidate.
Entries: a list of entries that the leader wishes to replicate.
PrevLogIndex: the index of the log entry right before Entries[0]. Used to ensure Log Completeness and Log Match Properties
PrevLogTerm: the term of the log entry right before Entries[0]. Used to ensure Log Completeness and Log Match Properties
LeaderCommit: important for upper-level applications. Only committed entries can be applied to the application and visible to the clients. | [
{
"code": null,
"e": 539,
"s": 171,
"text": "Raft is a consensus algorithm built to orchestrate replicas in a distributed fashion. Designed with understandability in mind, Raft has only a few moving parts and is easy to implement. In the last article, I talked about the basics of Raft and explained the leader-election mechanism. In this post, we are going to focus on another important issue — log replication."
},
{
"code": null,
"e": 758,
"s": 539,
"text": "Raft is essentially a bunch of replicated state machines. Whenever a request is received by the leader node, it is appended to the log for durability. The same log is replicated across multiple machines for redundancy."
},
{
"code": null,
"e": 984,
"s": 758,
"text": "For instance, in figure 1, the current leader has four entries in its log. Follower 1 is fully in sync, but follower 2 is missing the latest entry. If you don’t understand what Term is in fig 0, check out my previous article."
},
{
"code": null,
"e": 1008,
"s": 984,
"text": "RPC for log replication"
},
{
"code": null,
"e": 1093,
"s": 1008,
"text": "Designed for understandability, Raft only uses two RPC calls for all communications:"
},
{
"code": null,
"e": 1359,
"s": 1093,
"text": "AppendEntry: This RPC is initiated by the leader and carries the latest commands received. It also serves as the heartbeat message. When a follower gets this message, the election timer is reset. The AppendEntry message is a struct like this (I’m using Golang here)"
},
{
"code": null,
"e": 1461,
"s": 1359,
"text": "It’s okay if you don’t understand the meaning of each field. We are going to examine them one by one."
},
{
"code": null,
"e": 1610,
"s": 1461,
"text": "RequestVote: This RPC is used for leader election, which is covered by the last post. I’m going to skip it since we care only about log replication."
},
{
"code": null,
"e": 1799,
"s": 1610,
"text": "Let’s start with a vanilla log replication algorithm. Whenever a request is received by the leader, it forwards the log entry to all followers and waits for the majority to acknowledge it."
},
{
"code": null,
"e": 1823,
"s": 1799,
"text": "Problem 1: Log ordering"
},
{
"code": null,
"e": 2107,
"s": 1823,
"text": "The vanilla algorithm sends out messages to the followers as soon as they arrive. To do so, it only needs two fields in the message — leaderID and Entry. One major issue is that the log order cannot be preserved because of potential message delays. Consider the scenario in figure 1."
},
{
"code": null,
"e": 2434,
"s": 2107,
"text": "Raft uses two additional fields to ensure the integrity of the log — PrevLogIndex and PrevLogTerm. When a new entry is sent out, the leader also sends out the index and term number of the entry before. The receiver makes sure its latest entry has the identical index and term before appending the new request to its local log."
},
{
"code": null,
"e": 2506,
"s": 2434,
"text": "With these two additional parameters, we can achieve something awesome:"
},
{
"code": null,
"e": 2728,
"s": 2506,
"text": "Given an index of the log, if the entries from two logs (on two different machines) share the same term, they are identicalIf two entries in different logs have the same index and term, all preceding entries are identical"
},
{
"code": null,
"e": 2852,
"s": 2728,
"text": "Given an index of the log, if the entries from two logs (on two different machines) share the same term, they are identical"
},
{
"code": null,
"e": 2951,
"s": 2852,
"text": "If two entries in different logs have the same index and term, all preceding entries are identical"
},
{
"code": null,
"e": 3375,
"s": 2951,
"text": "The first property is easy to prove. Assume the claim is wrong. If there exist two distinct entries with the same term, one of them must be received by the leader later than the other. Since the log is append-only, one of the entries will have a larger PrevLogIndex. However, if they show up in the same index in two different logs, they must have the same PrevLogIndex. (otherwise, the receiver rejects it) Contradiction!!"
},
{
"code": null,
"e": 3420,
"s": 3375,
"text": "The second claim can be proved by induction:"
},
{
"code": null,
"e": 3497,
"s": 3420,
"text": "Together, these two guarantees consist of the Log Matching Property of Raft."
},
{
"code": null,
"e": 3543,
"s": 3497,
"text": "Problem 2: Followers with conflicting entries"
},
{
"code": null,
"e": 3721,
"s": 3543,
"text": "If the leader log is the only authority in the cluster, it will overwrite any conflict that a follower has. Is it possible to lose some log entries? Consider the following case:"
},
{
"code": null,
"e": 3921,
"s": 3721,
"text": "Before diving into the problem, I want to convince you that the above scenarios can indeed happen. Logs are in sync before index 2. From there onward, the following could happen to create these logs:"
},
{
"code": null,
"e": 4199,
"s": 3921,
"text": "1) node 2 becomes the leader (votes from itself, 1 and 0) with term 22) node 2 receives a request from the client but failed to sync with other nodes3) node 0 becomes the leader (vote from 1 and itself) with term 34) node 0 receives requests from the client. but failed to sync"
},
{
"code": null,
"e": 4301,
"s": 4199,
"text": "Now, if node 0 regains contact with node 2, it will try to replicate its log, as depicted in figure 5"
},
{
"code": null,
"e": 4582,
"s": 4301,
"text": "As you can see, the green entry indeed gets dropped. With the current design, this problem is unavoidable. However, a key observation here is that the green entry isn’t replicated on the majority (at least two nodes). If it is, it will never get dropped for the following reasons:"
},
{
"code": null,
"e": 4959,
"s": 4582,
"text": "if an entry is replicated on the majority, at least N/2 + 1 nodes have itfor a node without the entry to win the election, it needs N/2 votes from other nodes (candidate always votes for itself)Since the candidate doesn’t have the entry, the N/2 + 1 nodes with the entry won’t vote for it (election restriction explained in part 1)It won’t get enough votes to win the election"
},
{
"code": null,
"e": 5033,
"s": 4959,
"text": "if an entry is replicated on the majority, at least N/2 + 1 nodes have it"
},
{
"code": null,
"e": 5155,
"s": 5033,
"text": "for a node without the entry to win the election, it needs N/2 votes from other nodes (candidate always votes for itself)"
},
{
"code": null,
"e": 5293,
"s": 5155,
"text": "Since the candidate doesn’t have the entry, the N/2 + 1 nodes with the entry won’t vote for it (election restriction explained in part 1)"
},
{
"code": null,
"e": 5339,
"s": 5293,
"text": "It won’t get enough votes to win the election"
},
{
"code": null,
"e": 5622,
"s": 5339,
"text": "This is the second key feature of Raft — Log Completeness Property. If an entry is replicated on the majority, it will always show up in the future leader logs, regardless of which node it might be. If not replicated on the majority, an entry could be dropped if leadership changes."
},
{
"code": null,
"e": 5737,
"s": 5622,
"text": "With the Log Completeness Property, it is important not to acknowledge client requests before the majority has it."
},
{
"code": null,
"e": 5764,
"s": 5737,
"text": "Problem 3: When to commit?"
},
{
"code": null,
"e": 6298,
"s": 5764,
"text": "Finally, we arrive at the last issue — when to commit an entry? First of all, what is commit and why commit? Raft is a low-level consensus algorithm used by upper-level applications like key-value stores (e.g. something like ZooKeeper). When an entry is safely replicated by Raft, we want to make sure the client can see it via the application. Hence, Raft needs to decide when to tell the upper-level application an entry is ready for use (a partially replicated entry, as the last entry in the leader’s log should not be visible!)."
},
{
"code": null,
"e": 6535,
"s": 6298,
"text": "So far our vanilla algorithm does not carry any information regarding the commit index. Because the data flow is a one-way street, flowing from the leader to the followers, the nodes won’t know if an entry is replicated on the majority."
},
{
"code": null,
"e": 6801,
"s": 6535,
"text": "To address this issue, we can add yet another field to the AppendEntry message called LeaderCommit. The leader increases the commit index if an entry is received by the majority. Below is the actual code that keeps track of the commit index used by the leader node."
},
{
"code": null,
"e": 7111,
"s": 6801,
"text": "In this article, we started with a vanilla log replication algorithm(broadcasting entries without any additional bookkeeping) and evolved it to the full-fledged version by considering various corner cases. The most important RPC in log replication is the AppendEntry RPC, which uses a struct with four fields:"
},
{
"code": null,
"e": 7172,
"s": 7111,
"text": "Term: very important for log replication and leader election"
},
{
"code": null,
"e": 7218,
"s": 7172,
"text": "LeaderId: show the identity of the candidate."
},
{
"code": null,
"e": 7282,
"s": 7218,
"text": "Entries: a list of entries that the leader wishes to replicate."
},
{
"code": null,
"e": 7405,
"s": 7282,
"text": "PrevLogIndex: the index of the log entry right before Entries[0]. Used to ensure Log Completeness and Log Match Properties"
},
{
"code": null,
"e": 7526,
"s": 7405,
"text": "PrevLogTerm: the term of the log entry right before Entries[0]. Used to ensure Log Completeness and Log Match Properties"
}
] |
How to add colors to nodes in JavaFX? | You can apply colors to nodes in JavaFX using the setFill() and setStroke() methods. The setFill() method adds color to the surface area of the node whereas the setStroke() method applies color to the boundary of the node.
Both methods accept an object of the javafx.scene.paint.Paint class as a parameter. It is the base class for the color and gradients that are used to fill the shapes and backgrounds with color.
The javafx.scene.paint.Color class in JavaFX is a subclass of the Paint and it encapsulates all the colors in RGB color space (as its properties).
To apply color to a geometrical shape or background or the stroke of shape, you need to invoke the respective method by passing a Color object representing the desired color.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
public class ColorExample extends Application {
public void start(Stage stage) {
//Drawing a circle
Circle circle = new Circle(75.0f, 65.0f, 40.0f );
//Drawing a Rectangle
Rectangle rect = new Rectangle(150, 30, 100, 65);
//Drawing an ellipse
Ellipse ellipse = new Ellipse(330, 60, 60, 35);
//Drawing Polygon
Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );
//Color by name
circle.setFill(Color.CHOCOLATE);
circle.setStrokeWidth(5);
circle.setStroke(Color.DARKRED);
//Using RGB
rect.setFill(Color.rgb(150, 0, 255));
rect.setStrokeWidth(5);
rect.setStroke(Color.DARKRED);
//Using HSB
ellipse.setFill(Color.hsb(50, 1, 1));
ellipse.setStrokeWidth(5);
ellipse.setStroke(Color.DARKRED);
//Using web
poly.setFill(Color.web("#E9967A"));
poly.setStrokeWidth(5);
poly.setStroke(Color.DARKRED);
//Setting the stage
Group root = new Group(circle, ellipse, rect, poly);
Scene scene = new Scene(root, 600, 150);
stage.setTitle("Setting Colors");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
} | [
{
"code": null,
"e": 1285,
"s": 1062,
"text": "You can apply colors to nodes in JavaFX using the setFill() and setStroke() methods. The setFill() method adds color to the surface area of the node whereas the setStroke() method applies color to the boundary of the node."
},
{
"code": null,
"e": 1479,
"s": 1285,
"text": "Both methods accept an object of the javafx.scene.paint.Paint class as a parameter. It is the base class for the color and gradients that are used to fill the shapes and backgrounds with color."
},
{
"code": null,
"e": 1626,
"s": 1479,
"text": "The javafx.scene.paint.Color class in JavaFX is a subclass of the Paint and it encapsulates all the colors in RGB color space (as its properties)."
},
{
"code": null,
"e": 1801,
"s": 1626,
"text": "To apply color to a geometrical shape or background or the stroke of shape, you need to invoke the respective method by passing a Color object representing the desired color."
},
{
"code": null,
"e": 3359,
"s": 1801,
"text": "import javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\nimport javafx.scene.shape.Circle;\nimport javafx.scene.shape.Ellipse;\nimport javafx.scene.shape.Polygon;\nimport javafx.scene.shape.Rectangle;\npublic class ColorExample extends Application {\n public void start(Stage stage) {\n //Drawing a circle\n Circle circle = new Circle(75.0f, 65.0f, 40.0f );\n //Drawing a Rectangle\n Rectangle rect = new Rectangle(150, 30, 100, 65);\n //Drawing an ellipse\n Ellipse ellipse = new Ellipse(330, 60, 60, 35);\n //Drawing Polygon\n Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );\n //Color by name\n circle.setFill(Color.CHOCOLATE);\n circle.setStrokeWidth(5);\n circle.setStroke(Color.DARKRED);\n //Using RGB\n rect.setFill(Color.rgb(150, 0, 255));\n rect.setStrokeWidth(5);\n rect.setStroke(Color.DARKRED);\n //Using HSB\n ellipse.setFill(Color.hsb(50, 1, 1));\n ellipse.setStrokeWidth(5);\n ellipse.setStroke(Color.DARKRED);\n //Using web\n poly.setFill(Color.web(\"#E9967A\"));\n poly.setStrokeWidth(5);\n poly.setStroke(Color.DARKRED);\n //Setting the stage\n Group root = new Group(circle, ellipse, rect, poly);\n Scene scene = new Scene(root, 600, 150);\n stage.setTitle(\"Setting Colors\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
How to write Web apps using simple Python for Data Scientists? | by Rahul Agarwal | Towards Data Science | A Machine Learning project is never really complete if we don’t have a good way to showcase it.
While in the past, a well-made visualization or a small PPT used to be enough for showcasing a data science project, with the advent of dashboarding tools like RShiny and Dash, a good data scientist needs to have a fair bit of knowledge of web frameworks to get along.
And Web frameworks are hard to learn. I still get confused in all that HTML, CSS, and Javascript with all the hit and trials, for something seemingly simple to do.
Not to mention the many ways to do the same thing, making it confusing for us data science folks for whom web development is a secondary skill.
So, are we doomed to learn web frameworks? Or to call our developer friend for silly doubts in the middle of the night?
This is where StreamLit comes in and delivers on its promise to create web apps just using Python.
Zen of Python: Simple is better than complex and Streamlit makes it dead simple to create apps.
This post is about understanding how to create apps that support data science projects using Streamlit.
To understand more about the architecture and the thought process that led to streamlit, have a look at this excellent post by one of the original developers/founder Adrien Treuille.
If you want to deploy a streamlit app on Amazon ec2 check out my next post.
Installation is as simple as running the command:
pip install streamlit
To see if our installation is successful, we can just run:
streamlit hello
This should show you a screen that says:
You can go to the local URL: localhost:8501 in your browser to see a Streamlit app in action. The developers have provided some cool demos that you can play with. Do take your time and feel the power of the tool before coming back.
Streamlit aims to make app development easy using simple Python.
So let us write a simple app to see if it delivers on that promise.
Here I start with a simple app which we will call the Hello World of streamlit. Just paste the code given below in a file named helloworld.py
import streamlit as stx = st.slider('x')st.write(x, 'squared is', x * x)
And, on the terminal run:
streamlit run helloworld.py
And voila, you should be able to see a simple app in action in your browser at localhost:8501 that allows you to move a slider and gives the result.
It was pretty easy. In the above app, we used two features from Streamlit:
the st.slider widget that we can slide to change the output of the web app.
and the versatile st.write command. I am amazed at how it can write anything from charts, dataframes, and simple text. More on this later.
Important: Remember that every time we change the widget value, the whole app runs from top to bottom.
Widgets provide us a way to control our app. The best place to read about the widgets is the API reference documentation itself but I will describe some most prominent ones that you might end up using.
streamlit.slider(label, min_value=None, max_value=None, value=None, step=None, format=None)
We already saw st.slider in action above. It can be used with min_value,max_value, and step for getting inputs in a range.
The simplest way to get user input be it some URL input or some text input for sentiment analysis. It just needs a single label for naming the textbox.
import streamlit as sturl = st.text_input('Enter URL')st.write('The Entered URL is', url)
This is how the app looks:
Tip: You can just change the file helloworld.py and refresh the browser. The way I work is to open and changehelloworld.py in sublime text and see the changes in the browser side by side.
One use case for checkboxes is to hide or show/hide a specific section in an app. Another could be setting up a boolean value in the parameters for a function.st.checkbox() takes a single argument, which is the widget label. In this app, the checkbox is used to toggle a conditional statement.
import streamlit as stimport pandas as pdimport numpy as npdf = pd.read_csv("football_data.csv")if st.checkbox('Show dataframe'): st.write(df)
We can use st.selectbox to choose from a series or a list. Normally a use case is to use it as a simple dropdown to select values from a list.
import streamlit as stimport pandas as pdimport numpy as npdf = pd.read_csv("football_data.csv")option = st.selectbox( 'Which Club do you like best?', df['Club'].unique())'You selected: ', option
We can also use multiple values from a dropdown. Here we use st.multiselect to get multiple values as a list in the variable options
import streamlit as stimport pandas as pdimport numpy as npdf = pd.read_csv("football_data.csv")options = st.multiselect( 'What are your favorite clubs?', df['Club'].unique())st.write('You selected:', options)
So much for understanding the important widgets. Now, we are going to create a simple app using multiple widgets at once.
To start simple, we will try to visualize our football data using streamlit. It is pretty much simple to do this with the help of the above widgets.
import streamlit as stimport pandas as pdimport numpy as npdf = pd.read_csv("football_data.csv")clubs = st.multiselect('Show Player for clubs?', df['Club'].unique())nationalities = st.multiselect('Show Player from Nationalities?', df['Nationality'].unique())# Filter dataframenew_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))]# write dataframe to screenst.write(new_df)
Our simple app looks like:
That was easy. But it seems pretty basic right now. Can we add some charts?
Streamlit currently supports many libraries for plotting. Plotly, Bokeh, Matplotlib, Altair, and Vega charts being some of them. Plotly Express also works, although they didn’t specify it in the docs. It also has some inbuilt chart types that are “native” to Streamlit, like st.line_chart and st.area_chart.
We will work with plotly_express here. Here is the code for our simple app. We just used four calls to streamlit. Rest is all simple python.
import streamlit as stimport pandas as pdimport numpy as npimport plotly_express as pxdf = pd.read_csv("football_data.csv")clubs = st.multiselect('Show Player for clubs?', df['Club'].unique())nationalities = st.multiselect('Show Player from Nationalities?', df['Nationality'].unique())new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))]st.write(new_df)# create figure using plotly expressfig = px.scatter(new_df, x ='Overall',y='Age',color='Name')# Plot!st.plotly_chart(fig)
In the start we said that each time we change any widget, the whole app runs from start to end. This is not feasible when we create apps that will serve deep learning models or complicated machine learning models. Streamlit covers us in this aspect by introducing Caching.
In our simple app. We read the pandas dataframe again and again whenever a value changes. While it works for the small data we have, it will not work for big data or when we have to do a lot of processing on the data. Let us use caching using the st.cache decorator function in streamlit like below.
import streamlit as stimport pandas as pdimport numpy as npimport plotly_express as pxdf = st.cache(pd.read_csv)("football_data.csv")
Or for more complex and time taking functions that need to run only once(think loading big Deep Learning models), using:
@st.cachedef complex_func(a,b): DO SOMETHING COMPLEX# Won't run again and again.complex_func(a,b)
When we mark a function with Streamlit’s cache decorator, whenever the function is called streamlit checks the input parameters that you called the function with.
If this is the first time Streamlit has seen these params, it runs the function and stores the result in a local cache.
When the function is called the next time, if those params have not changed, Streamlit knows it can skip executing the function altogether. It just uses the results from the cache.
For a cleaner look based on your preference, you might want to move your widgets into a sidebar, something like Rshiny dashboards. This is pretty simple. Just add st.sidebar in your widget’s code.
import streamlit as stimport pandas as pdimport numpy as npimport plotly_express as pxdf = st.cache(pd.read_csv)("football_data.csv")clubs = st.sidebar.multiselect('Show Player for clubs?', df['Club'].unique())nationalities = st.sidebar.multiselect('Show Player from Nationalities?', df['Nationality'].unique())new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))]st.write(new_df)# Create distplot with custom bin_sizefig = px.scatter(new_df, x ='Overall',y='Age',color='Name')# Plot!st.plotly_chart(fig)
I love writing in Markdown. I find it less verbose than HTML and much more suited for data science work. So, can we use Markdown with the streamlit app?
Yes, we can. There are a couple of ways to do this. In my view, the best one is to use Magic commands. Magic commands allow you to write markdown as easily as comments. You could also have used the command st.markdown
import streamlit as stimport pandas as pdimport numpy as npimport plotly_express as px'''# Club and Nationality AppThis very simple webapp allows you to select and visualize players from certain clubs and certain nationalities.'''df = st.cache(pd.read_csv)("football_data.csv")clubs = st.sidebar.multiselect('Show Player for clubs?', df['Club'].unique())nationalities = st.sidebar.multiselect('Show Player from Nationalities?', df['Nationality'].unique())new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))]st.write(new_df)# Create distplot with custom bin_sizefig = px.scatter(new_df, x ='Overall',y='Age',color='Name')'''### Here is a simple chart between player age and overall'''st.plotly_chart(fig)
Streamlit has democratized the whole process to create apps, and I couldn’t recommend it more.
In this post, we created a simple web app. But the possibilities are endless. To give an example here is face GAN from the streamlit site. And it works by just using the same guiding ideas of widgets and caching.
I love the default colors and styles that the developers have used, and I found it much more comfortable than using Dash, which I was using until now for my demos. You can also include audio and video in your streamlit apps.
On top of that, Streamlit is a free and open-source rather than a proprietary web app that just works out of the box.
In the past, I had to reach out to my developer friends for any single change in a demo or presentation; now it is relatively trivial to do that.
I aim to use it more in my workflow from now on, and considering the capabilities it provides without all the hard work, I think you should too.
I don’t have an idea if it will perform well in a production environment yet, but its a boon for the small proof of concept projects and demos. I aim to use it more in my workflow from now on, and considering the capabilities it provides without all the hard work, I think you should too.
You can find the full code for the final app here. If you want to deploy this app on Amazon ec2 check out my next post.
If you want to learn about the best strategies for creating Visualizations, I would like to call out an excellent course about Data Visualization and applied plotting from the University of Michigan, which is a part of a pretty good Data Science Specialization with Python in itself. Do check it out.
Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz.
Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea. | [
{
"code": null,
"e": 268,
"s": 172,
"text": "A Machine Learning project is never really complete if we don’t have a good way to showcase it."
},
{
"code": null,
"e": 537,
"s": 268,
"text": "While in the past, a well-made visualization or a small PPT used to be enough for showcasing a data science project, with the advent of dashboarding tools like RShiny and Dash, a good data scientist needs to have a fair bit of knowledge of web frameworks to get along."
},
{
"code": null,
"e": 701,
"s": 537,
"text": "And Web frameworks are hard to learn. I still get confused in all that HTML, CSS, and Javascript with all the hit and trials, for something seemingly simple to do."
},
{
"code": null,
"e": 845,
"s": 701,
"text": "Not to mention the many ways to do the same thing, making it confusing for us data science folks for whom web development is a secondary skill."
},
{
"code": null,
"e": 965,
"s": 845,
"text": "So, are we doomed to learn web frameworks? Or to call our developer friend for silly doubts in the middle of the night?"
},
{
"code": null,
"e": 1064,
"s": 965,
"text": "This is where StreamLit comes in and delivers on its promise to create web apps just using Python."
},
{
"code": null,
"e": 1160,
"s": 1064,
"text": "Zen of Python: Simple is better than complex and Streamlit makes it dead simple to create apps."
},
{
"code": null,
"e": 1264,
"s": 1160,
"text": "This post is about understanding how to create apps that support data science projects using Streamlit."
},
{
"code": null,
"e": 1447,
"s": 1264,
"text": "To understand more about the architecture and the thought process that led to streamlit, have a look at this excellent post by one of the original developers/founder Adrien Treuille."
},
{
"code": null,
"e": 1523,
"s": 1447,
"text": "If you want to deploy a streamlit app on Amazon ec2 check out my next post."
},
{
"code": null,
"e": 1573,
"s": 1523,
"text": "Installation is as simple as running the command:"
},
{
"code": null,
"e": 1595,
"s": 1573,
"text": "pip install streamlit"
},
{
"code": null,
"e": 1654,
"s": 1595,
"text": "To see if our installation is successful, we can just run:"
},
{
"code": null,
"e": 1670,
"s": 1654,
"text": "streamlit hello"
},
{
"code": null,
"e": 1711,
"s": 1670,
"text": "This should show you a screen that says:"
},
{
"code": null,
"e": 1943,
"s": 1711,
"text": "You can go to the local URL: localhost:8501 in your browser to see a Streamlit app in action. The developers have provided some cool demos that you can play with. Do take your time and feel the power of the tool before coming back."
},
{
"code": null,
"e": 2008,
"s": 1943,
"text": "Streamlit aims to make app development easy using simple Python."
},
{
"code": null,
"e": 2076,
"s": 2008,
"text": "So let us write a simple app to see if it delivers on that promise."
},
{
"code": null,
"e": 2218,
"s": 2076,
"text": "Here I start with a simple app which we will call the Hello World of streamlit. Just paste the code given below in a file named helloworld.py"
},
{
"code": null,
"e": 2291,
"s": 2218,
"text": "import streamlit as stx = st.slider('x')st.write(x, 'squared is', x * x)"
},
{
"code": null,
"e": 2317,
"s": 2291,
"text": "And, on the terminal run:"
},
{
"code": null,
"e": 2345,
"s": 2317,
"text": "streamlit run helloworld.py"
},
{
"code": null,
"e": 2494,
"s": 2345,
"text": "And voila, you should be able to see a simple app in action in your browser at localhost:8501 that allows you to move a slider and gives the result."
},
{
"code": null,
"e": 2569,
"s": 2494,
"text": "It was pretty easy. In the above app, we used two features from Streamlit:"
},
{
"code": null,
"e": 2645,
"s": 2569,
"text": "the st.slider widget that we can slide to change the output of the web app."
},
{
"code": null,
"e": 2784,
"s": 2645,
"text": "and the versatile st.write command. I am amazed at how it can write anything from charts, dataframes, and simple text. More on this later."
},
{
"code": null,
"e": 2887,
"s": 2784,
"text": "Important: Remember that every time we change the widget value, the whole app runs from top to bottom."
},
{
"code": null,
"e": 3089,
"s": 2887,
"text": "Widgets provide us a way to control our app. The best place to read about the widgets is the API reference documentation itself but I will describe some most prominent ones that you might end up using."
},
{
"code": null,
"e": 3181,
"s": 3089,
"text": "streamlit.slider(label, min_value=None, max_value=None, value=None, step=None, format=None)"
},
{
"code": null,
"e": 3304,
"s": 3181,
"text": "We already saw st.slider in action above. It can be used with min_value,max_value, and step for getting inputs in a range."
},
{
"code": null,
"e": 3456,
"s": 3304,
"text": "The simplest way to get user input be it some URL input or some text input for sentiment analysis. It just needs a single label for naming the textbox."
},
{
"code": null,
"e": 3546,
"s": 3456,
"text": "import streamlit as sturl = st.text_input('Enter URL')st.write('The Entered URL is', url)"
},
{
"code": null,
"e": 3573,
"s": 3546,
"text": "This is how the app looks:"
},
{
"code": null,
"e": 3761,
"s": 3573,
"text": "Tip: You can just change the file helloworld.py and refresh the browser. The way I work is to open and changehelloworld.py in sublime text and see the changes in the browser side by side."
},
{
"code": null,
"e": 4055,
"s": 3761,
"text": "One use case for checkboxes is to hide or show/hide a specific section in an app. Another could be setting up a boolean value in the parameters for a function.st.checkbox() takes a single argument, which is the widget label. In this app, the checkbox is used to toggle a conditional statement."
},
{
"code": null,
"e": 4201,
"s": 4055,
"text": "import streamlit as stimport pandas as pdimport numpy as npdf = pd.read_csv(\"football_data.csv\")if st.checkbox('Show dataframe'): st.write(df)"
},
{
"code": null,
"e": 4344,
"s": 4201,
"text": "We can use st.selectbox to choose from a series or a list. Normally a use case is to use it as a simple dropdown to select values from a list."
},
{
"code": null,
"e": 4547,
"s": 4344,
"text": "import streamlit as stimport pandas as pdimport numpy as npdf = pd.read_csv(\"football_data.csv\")option = st.selectbox( 'Which Club do you like best?', df['Club'].unique())'You selected: ', option"
},
{
"code": null,
"e": 4680,
"s": 4547,
"text": "We can also use multiple values from a dropdown. Here we use st.multiselect to get multiple values as a list in the variable options"
},
{
"code": null,
"e": 4890,
"s": 4680,
"text": "import streamlit as stimport pandas as pdimport numpy as npdf = pd.read_csv(\"football_data.csv\")options = st.multiselect( 'What are your favorite clubs?', df['Club'].unique())st.write('You selected:', options)"
},
{
"code": null,
"e": 5012,
"s": 4890,
"text": "So much for understanding the important widgets. Now, we are going to create a simple app using multiple widgets at once."
},
{
"code": null,
"e": 5161,
"s": 5012,
"text": "To start simple, we will try to visualize our football data using streamlit. It is pretty much simple to do this with the help of the above widgets."
},
{
"code": null,
"e": 5560,
"s": 5161,
"text": "import streamlit as stimport pandas as pdimport numpy as npdf = pd.read_csv(\"football_data.csv\")clubs = st.multiselect('Show Player for clubs?', df['Club'].unique())nationalities = st.multiselect('Show Player from Nationalities?', df['Nationality'].unique())# Filter dataframenew_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))]# write dataframe to screenst.write(new_df)"
},
{
"code": null,
"e": 5587,
"s": 5560,
"text": "Our simple app looks like:"
},
{
"code": null,
"e": 5663,
"s": 5587,
"text": "That was easy. But it seems pretty basic right now. Can we add some charts?"
},
{
"code": null,
"e": 5971,
"s": 5663,
"text": "Streamlit currently supports many libraries for plotting. Plotly, Bokeh, Matplotlib, Altair, and Vega charts being some of them. Plotly Express also works, although they didn’t specify it in the docs. It also has some inbuilt chart types that are “native” to Streamlit, like st.line_chart and st.area_chart."
},
{
"code": null,
"e": 6112,
"s": 5971,
"text": "We will work with plotly_express here. Here is the code for our simple app. We just used four calls to streamlit. Rest is all simple python."
},
{
"code": null,
"e": 6615,
"s": 6112,
"text": "import streamlit as stimport pandas as pdimport numpy as npimport plotly_express as pxdf = pd.read_csv(\"football_data.csv\")clubs = st.multiselect('Show Player for clubs?', df['Club'].unique())nationalities = st.multiselect('Show Player from Nationalities?', df['Nationality'].unique())new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))]st.write(new_df)# create figure using plotly expressfig = px.scatter(new_df, x ='Overall',y='Age',color='Name')# Plot!st.plotly_chart(fig)"
},
{
"code": null,
"e": 6888,
"s": 6615,
"text": "In the start we said that each time we change any widget, the whole app runs from start to end. This is not feasible when we create apps that will serve deep learning models or complicated machine learning models. Streamlit covers us in this aspect by introducing Caching."
},
{
"code": null,
"e": 7188,
"s": 6888,
"text": "In our simple app. We read the pandas dataframe again and again whenever a value changes. While it works for the small data we have, it will not work for big data or when we have to do a lot of processing on the data. Let us use caching using the st.cache decorator function in streamlit like below."
},
{
"code": null,
"e": 7322,
"s": 7188,
"text": "import streamlit as stimport pandas as pdimport numpy as npimport plotly_express as pxdf = st.cache(pd.read_csv)(\"football_data.csv\")"
},
{
"code": null,
"e": 7443,
"s": 7322,
"text": "Or for more complex and time taking functions that need to run only once(think loading big Deep Learning models), using:"
},
{
"code": null,
"e": 7544,
"s": 7443,
"text": "@st.cachedef complex_func(a,b): DO SOMETHING COMPLEX# Won't run again and again.complex_func(a,b)"
},
{
"code": null,
"e": 7707,
"s": 7544,
"text": "When we mark a function with Streamlit’s cache decorator, whenever the function is called streamlit checks the input parameters that you called the function with."
},
{
"code": null,
"e": 7827,
"s": 7707,
"text": "If this is the first time Streamlit has seen these params, it runs the function and stores the result in a local cache."
},
{
"code": null,
"e": 8008,
"s": 7827,
"text": "When the function is called the next time, if those params have not changed, Streamlit knows it can skip executing the function altogether. It just uses the results from the cache."
},
{
"code": null,
"e": 8205,
"s": 8008,
"text": "For a cleaner look based on your preference, you might want to move your widgets into a sidebar, something like Rshiny dashboards. This is pretty simple. Just add st.sidebar in your widget’s code."
},
{
"code": null,
"e": 8736,
"s": 8205,
"text": "import streamlit as stimport pandas as pdimport numpy as npimport plotly_express as pxdf = st.cache(pd.read_csv)(\"football_data.csv\")clubs = st.sidebar.multiselect('Show Player for clubs?', df['Club'].unique())nationalities = st.sidebar.multiselect('Show Player from Nationalities?', df['Nationality'].unique())new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))]st.write(new_df)# Create distplot with custom bin_sizefig = px.scatter(new_df, x ='Overall',y='Age',color='Name')# Plot!st.plotly_chart(fig)"
},
{
"code": null,
"e": 8889,
"s": 8736,
"text": "I love writing in Markdown. I find it less verbose than HTML and much more suited for data science work. So, can we use Markdown with the streamlit app?"
},
{
"code": null,
"e": 9107,
"s": 8889,
"text": "Yes, we can. There are a couple of ways to do this. In my view, the best one is to use Magic commands. Magic commands allow you to write markdown as easily as comments. You could also have used the command st.markdown"
},
{
"code": null,
"e": 9838,
"s": 9107,
"text": "import streamlit as stimport pandas as pdimport numpy as npimport plotly_express as px'''# Club and Nationality AppThis very simple webapp allows you to select and visualize players from certain clubs and certain nationalities.'''df = st.cache(pd.read_csv)(\"football_data.csv\")clubs = st.sidebar.multiselect('Show Player for clubs?', df['Club'].unique())nationalities = st.sidebar.multiselect('Show Player from Nationalities?', df['Nationality'].unique())new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))]st.write(new_df)# Create distplot with custom bin_sizefig = px.scatter(new_df, x ='Overall',y='Age',color='Name')'''### Here is a simple chart between player age and overall'''st.plotly_chart(fig)"
},
{
"code": null,
"e": 9933,
"s": 9838,
"text": "Streamlit has democratized the whole process to create apps, and I couldn’t recommend it more."
},
{
"code": null,
"e": 10146,
"s": 9933,
"text": "In this post, we created a simple web app. But the possibilities are endless. To give an example here is face GAN from the streamlit site. And it works by just using the same guiding ideas of widgets and caching."
},
{
"code": null,
"e": 10371,
"s": 10146,
"text": "I love the default colors and styles that the developers have used, and I found it much more comfortable than using Dash, which I was using until now for my demos. You can also include audio and video in your streamlit apps."
},
{
"code": null,
"e": 10489,
"s": 10371,
"text": "On top of that, Streamlit is a free and open-source rather than a proprietary web app that just works out of the box."
},
{
"code": null,
"e": 10635,
"s": 10489,
"text": "In the past, I had to reach out to my developer friends for any single change in a demo or presentation; now it is relatively trivial to do that."
},
{
"code": null,
"e": 10780,
"s": 10635,
"text": "I aim to use it more in my workflow from now on, and considering the capabilities it provides without all the hard work, I think you should too."
},
{
"code": null,
"e": 11069,
"s": 10780,
"text": "I don’t have an idea if it will perform well in a production environment yet, but its a boon for the small proof of concept projects and demos. I aim to use it more in my workflow from now on, and considering the capabilities it provides without all the hard work, I think you should too."
},
{
"code": null,
"e": 11189,
"s": 11069,
"text": "You can find the full code for the final app here. If you want to deploy this app on Amazon ec2 check out my next post."
},
{
"code": null,
"e": 11490,
"s": 11189,
"text": "If you want to learn about the best strategies for creating Visualizations, I would like to call out an excellent course about Data Visualization and applied plotting from the University of Michigan, which is a part of a pretty good Data Science Specialization with Python in itself. Do check it out."
},
{
"code": null,
"e": 11754,
"s": 11490,
"text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz."
}
] |
Credit Card Fraud Detection using Autoencoders in H2O | by Maneesha Rajaratne | Towards Data Science | Frauds in the finance field are very rare to be identified. Because of that, it can do a severe damage to the financial field. It is estimated that fraud costs at least $80 billion a year across all lines of insurance. If there is a small possibility of detecting fraudulent activities, that can do a major impact on annual losses. That is why financial companies invest in machine learning as a preemptive approach to tackling fraud.
The benefits of using a machine learning approach are that,
It helps to find hidden and implicit correlations in data.
Faster data processing and less manual work
Automatic detection of possible fraud scenarios.
The best way to detect frauds is anomaly detection.
Anomaly detection is a technique to identify unusual patterns that do not conform to the expected behaviors, called outliers. It has many applications in business from fraud detection in credit card transactions to fault detection in operating environments. Machine learning approaches for Anomaly detection;
K-Nearest Neighbor
Autoencoders — Deep neural network
K-means
Support Vector Machine
Naive Bayes
Today we will be using Autoencoders to train the model.
Most of us are not familiar with this model. Autoencoders is an unsupervised Neural Network. It is a data compression algorithm which takes the input and going through a compressed representation and gives the reconstructed output.
As for the dataset we will be using Credit Card Transaction dataset provided by Kaggle: https://www.kaggle.com/mlg-ulb/creditcardfraud
The dataset includes 284,807 transactions. among them, 492 transactions are labeled as frauds. Because of this, the dataset is highly imbalanced. It contains only numerical variables. Feature ‘Time’ contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature ‘Amount’ is the transaction Amount, this feature can be used for example-dependent cost-sensitive learning. Feature ‘Class’ is the response variable and it takes value 1 in case of fraud and 0 otherwise.
You can find my Kaggle Kernel here: https://www.kaggle.com/maneesha96/credit-card-fraud-detection-using-autoencoders
Full code: https://github.com/Mash96/Credit-Card-Fraud-Detection
Then Let's get started!!!
We will be using H2O as the ML platform today. You can find more info here: https://www.h2o.ai
import h2oimport matplotlib.pyplot as pltfrom pylab import rcParamsimport numpy as np # linear algebraimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)import osfrom h2o.estimators.deeplearning import H2OAutoEncoderEstimator, H2ODeepLearningEstimator
Initialize H2O server
h2o.init(max_mem_size = 2) # initializing h2o serverh2o.remove_all()
Loading dataset using pandas data frame
creditData = pd.read_csv(r"File_Path\creditcard.csv") creditData.describe()# H2O method# creditData_df = h2o.import_file(r"File_Path\creditcard.csv")
creditData.shape> (284807, 31)
Checking for null values in the dataset
creditData.isnull().values.any() # pandas method# creditData_h2o.na_omit() # h2o method# creditData_h2o.nacnt() # no missing values found> False
In order to proceed we need to convert the pandas data frame to H2O data frame
# Turns python pandas frame into an H2OFramecreditData_h2o = h2o.H2OFrame(creditData)# Let’s plot the Transaction class against the Frequencylabels = [‘normal’,’fraud’]classes = pd.value_counts(creditData[‘Class’], sort = True)classes.plot(kind = ‘bar’, rot=0)plt.title(“Transaction class distribution”)plt.xticks(range(2), labels)plt.xlabel(“Class”)plt.ylabel(“Frequency”)
fraud = creditData[creditData.Class == 1]normal = creditData[creditData.Class == 0]# Amount vs Classf, (ax1, ax2) = plt.subplots(2,1,sharex=True)f.suptitle('Amount per transaction by class')ax1.hist(fraud.Amount, bins = 50)ax1.set_title('Fraud List')ax2.hist(normal.Amount, bins = 50)ax2.set_title('Normal')plt.xlabel('Amount')plt.ylabel('Number of Transactions')plt.xlim((0, 10000))plt.yscale('log')plt.show()
# time vs Amountf, (ax1, ax2) = plt.subplots(2, 1, sharex=True)f.suptitle('Time of transaction vs Amount by class')ax1.scatter(fraud.Time, fraud.Amount)ax1.set_title('Fraud List')ax2.scatter(normal.Time, normal.Amount)ax2.set_title('Normal')plt.xlabel('Time (in seconds)')plt.ylabel('Amount')plt.show()
#plotting the dataset considering the classcolor = {1:'red', 0:'yellow'}fraudlist = creditData[creditData.Class == 1]normal = creditData[creditData.Class == 0]fig,axes = plt.subplots(1,2)axes[0].scatter(list(range(1,fraudlist.shape[0] + 1)), fraudlist.Amount,color='red')axes[1].scatter(list(range(1, normal.shape[0] + 1)), normal.Amount,color='yellow')plt.show()
The Time variable is not giving an impact on the model prediction. This can figure out from data visualization. Before moving on to the training part, we need to figure out which variables are important and which are not. So we can drop the unwanted variables.
features= creditData_h2o.drop(['Time'], axis=1)
Split the data frame as training set and testing set keeping 80% for the training set and rest to the testing set.
train, test = features.split_frame([0.8])print(train.shape)print(test.shape)> (227722, 30)> (57085, 30)
Our dataset has a lot of non-fraud transactions. Because of this for the model training, we only send non-fraud transactions. So that the model will learn the pattern of normal transactions.
# converting to pandas dataframetrain_df = train.as_data_frame()test_df = test.as_data_frame()train_df = train_df[train_df['Class'] == 0]# drop the Class variabletrain_df = train_df.drop(['Class'], axis=1)Y_test_df = test_df['Class'] # true labels of the testing settest_df = test_df.drop(['Class'], axis=1)train_df.shape> (227335, 29)
train_h2o = h2o.H2OFrame(train_df) # converting to h2o frametest_h2o = h2o.H2OFrame(test_df)x = train_h2o.columns
When building the model, 4 fully connected hidden layers were chosen with, [14,7,7,14] number of nodes for each layer. First two for the encoder and last two for the decoder.
anomaly_model = H2ODeepLearningEstimator(activation = "Tanh", hidden = [14,7,7,14], epochs = 100, standardize = True, stopping_metric = 'MSE', loss = 'automatic', train_samples_per_iteration = 32, shuffle_training_data = True, autoencoder = True, l1 = 10e-5)anomaly_model.train(x=x, training_frame = train_h2o)
Variable Importance : In H2O there is a special way of analyzing which variables are giving higher impact on the model.
anomaly_model._model_json['output']['variable_importances'].as_data_frame()
Visualization
# plotting the variable importancercParams['figure.figsize'] = 14, 8#plt.rcdefaults()fig, ax = plt.subplots()variables = anomaly_model._model_json['output']['variable_importances']['variable']var = variables[0:15]y_pos = np.arange(len(var))scaled_importance = anomaly_model._model_json['output']['variable_importances']['scaled_importance']sc = scaled_importance[0:15]ax.barh(y_pos, sc, align='center', color='green', ecolor='black')ax.set_yticks(y_pos)ax.set_yticklabels(variables)ax.invert_yaxis()ax.set_xlabel('Scaled Importance')ax.set_title('Variable Importance')plt.show()
# plotting the lossscoring_history = anomaly_model.score_history()%matplotlib inlinercParams['figure.figsize'] = 14, 8plt.plot(scoring_history['training_mse'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')
The testing set has both normal and fraud transactions in it. The Autoencoder will learn to identify the pattern of the input data. If an anomalous test point does not match the learned pattern, the autoencoder will likely have a high error rate in reconstructing this data, indicating anomalous data. So that we can identify the anomalies of the data. To calculate the error, it uses Mean Squared Error(MSE)
test_rec_error = anomaly_model.anomaly(test_h2o) # anomaly is a H2O function which calculates the error for the dataset# converting to pandas dataframetest_rec_error_df = test_rec_error.as_data_frame()# plotting the testing dataset against the errortest_rec_error_df['id']=test_rec_error_df.indexrcParams['figure.figsize'] = 14, 8test_rec_error_df.plot(kind="scatter", x='id', y="Reconstruction.MSE")plt.show()
# predicting the class for the testing datasetpredictions = anomaly_model.predict(test_h2o)error_df = pd.DataFrame({'reconstruction_error': test_rec_error_df['Reconstruction.MSE'], 'true_class': Y_test_df})error_df.describe()
# reconstruction error for the normal transactions in the testing datasetfig = plt.figure()ax = fig.add_subplot(111)rcParams['figure.figsize'] = 14, 8normal_error_df = error_df[(error_df['true_class']== 0) & (error_df['reconstruction_error'] < 10)]_ = ax.hist(normal_error_df.reconstruction_error.values, bins=10)
# reconstruction error for the fraud transactions in the testing datasetfig = plt.figure()ax = fig.add_subplot(111)rcParams['figure.figsize'] = 14, 8fraud_error_df = error_df[error_df['true_class'] == 1]_ = ax.hist(fraud_error_df.reconstruction_error.values, bins=10)
from sklearn.metrics import (confusion_matrix, precision_recall_curve, auc, roc_curve, recall_score, classification_report, f1_score, precision_recall_fscore_support)fpr, tpr, thresholds = roc_curve(error_df.true_class, error_df.reconstruction_error)roc_auc = auc(fpr, tpr)plt.title('Receiver Operating Characteristic')plt.plot(fpr, tpr, label='AUC = %0.4f'% roc_auc)plt.legend(loc='lower right')plt.plot([0,1],[0,1],'r--')plt.xlim([-0.001, 1])plt.ylim([0, 1.001])plt.ylabel('True Positive Rate')plt.xlabel('False Positive Rate')plt.show();
The accuracy is 0.9718
Since the data is highly imbalanced, it cannot be measured only by using accuracy. Precision vs Recall was chosen as the matrix for the classification task.
Precision: Measuring the relevancy of obtained results.
[ True positives / (True positives + False positives)]
Recall: Measuring how many relevant results are returned.
[ True positives / (True positives + False negatives)]
True Positives — Number of actual frauds predicted as frauds
False Positives — Number of non-frauds predicted as frauds
False Negatives — Number of frauds predicted as non-frauds.
precision, recall, th = precision_recall_curve(error_df.true_class, error_df.reconstruction_error)plt.plot(recall, precision, 'b', label='Precision-Recall curve')plt.title('Recall vs Precision')plt.xlabel('Recall')plt.ylabel('Precision')plt.show()
We need to find a better threshold that can separate the anomalies from normal. This can be done by calculating the intersection of the Precision/Recall vs Threshold graph.
plt.plot(th, precision[1:], label="Precision",linewidth=5)plt.plot(th, recall[1:], label="Recall",linewidth=5)plt.title('Precision and recall for different threshold values')plt.xlabel('Threshold')plt.ylabel('Precision/Recall')plt.legend()plt.show()
# plot the testing set with the thresholdthreshold = 0.01groups = error_df.groupby('true_class')fig, ax = plt.subplots()for name, group in groups: ax.plot(group.index, group.reconstruction_error, marker='o', ms=3.5, linestyle='', label= "Fraud" if name == 1 else "Normal")ax.hlines(threshold, ax.get_xlim()[0], ax.get_xlim()[1], colors="r", zorder=100, label='Threshold')ax.legend()plt.title("Reconstruction error for different classes")plt.ylabel("Reconstruction error")plt.xlabel("Data point index")plt.show();
import seaborn as snsLABELS = ['Normal', 'Fraud']y_pred = [1 if e > threshold else 0 for e in error_df.reconstruction_error.values]conf_matrix = confusion_matrix(error_df.true_class, y_pred)plt.figure(figsize=(12, 12))sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt="d");plt.title("Confusion matrix")plt.ylabel('True class')plt.xlabel('Predicted class')plt.show()
csr = classification_report(error_df.true_class, y_pred)print(csr)
Our model is catching most of the fraudulent data. In Autoencoders, it gives a good accuracy. But if we look into Precision and Recall of the dataset, it is not performing enough. As I mentioned earlier, there are other anomaly detection methods that perform well in highly imbalanced datasets.
I have tried more methods on this dataset. So I will see you soon with those. :) | [
{
"code": null,
"e": 607,
"s": 172,
"text": "Frauds in the finance field are very rare to be identified. Because of that, it can do a severe damage to the financial field. It is estimated that fraud costs at least $80 billion a year across all lines of insurance. If there is a small possibility of detecting fraudulent activities, that can do a major impact on annual losses. That is why financial companies invest in machine learning as a preemptive approach to tackling fraud."
},
{
"code": null,
"e": 667,
"s": 607,
"text": "The benefits of using a machine learning approach are that,"
},
{
"code": null,
"e": 726,
"s": 667,
"text": "It helps to find hidden and implicit correlations in data."
},
{
"code": null,
"e": 770,
"s": 726,
"text": "Faster data processing and less manual work"
},
{
"code": null,
"e": 819,
"s": 770,
"text": "Automatic detection of possible fraud scenarios."
},
{
"code": null,
"e": 871,
"s": 819,
"text": "The best way to detect frauds is anomaly detection."
},
{
"code": null,
"e": 1180,
"s": 871,
"text": "Anomaly detection is a technique to identify unusual patterns that do not conform to the expected behaviors, called outliers. It has many applications in business from fraud detection in credit card transactions to fault detection in operating environments. Machine learning approaches for Anomaly detection;"
},
{
"code": null,
"e": 1199,
"s": 1180,
"text": "K-Nearest Neighbor"
},
{
"code": null,
"e": 1234,
"s": 1199,
"text": "Autoencoders — Deep neural network"
},
{
"code": null,
"e": 1242,
"s": 1234,
"text": "K-means"
},
{
"code": null,
"e": 1265,
"s": 1242,
"text": "Support Vector Machine"
},
{
"code": null,
"e": 1277,
"s": 1265,
"text": "Naive Bayes"
},
{
"code": null,
"e": 1333,
"s": 1277,
"text": "Today we will be using Autoencoders to train the model."
},
{
"code": null,
"e": 1565,
"s": 1333,
"text": "Most of us are not familiar with this model. Autoencoders is an unsupervised Neural Network. It is a data compression algorithm which takes the input and going through a compressed representation and gives the reconstructed output."
},
{
"code": null,
"e": 1700,
"s": 1565,
"text": "As for the dataset we will be using Credit Card Transaction dataset provided by Kaggle: https://www.kaggle.com/mlg-ulb/creditcardfraud"
},
{
"code": null,
"e": 2211,
"s": 1700,
"text": "The dataset includes 284,807 transactions. among them, 492 transactions are labeled as frauds. Because of this, the dataset is highly imbalanced. It contains only numerical variables. Feature ‘Time’ contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature ‘Amount’ is the transaction Amount, this feature can be used for example-dependent cost-sensitive learning. Feature ‘Class’ is the response variable and it takes value 1 in case of fraud and 0 otherwise."
},
{
"code": null,
"e": 2328,
"s": 2211,
"text": "You can find my Kaggle Kernel here: https://www.kaggle.com/maneesha96/credit-card-fraud-detection-using-autoencoders"
},
{
"code": null,
"e": 2393,
"s": 2328,
"text": "Full code: https://github.com/Mash96/Credit-Card-Fraud-Detection"
},
{
"code": null,
"e": 2419,
"s": 2393,
"text": "Then Let's get started!!!"
},
{
"code": null,
"e": 2514,
"s": 2419,
"text": "We will be using H2O as the ML platform today. You can find more info here: https://www.h2o.ai"
},
{
"code": null,
"e": 2785,
"s": 2514,
"text": "import h2oimport matplotlib.pyplot as pltfrom pylab import rcParamsimport numpy as np # linear algebraimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)import osfrom h2o.estimators.deeplearning import H2OAutoEncoderEstimator, H2ODeepLearningEstimator"
},
{
"code": null,
"e": 2807,
"s": 2785,
"text": "Initialize H2O server"
},
{
"code": null,
"e": 2876,
"s": 2807,
"text": "h2o.init(max_mem_size = 2) # initializing h2o serverh2o.remove_all()"
},
{
"code": null,
"e": 2916,
"s": 2876,
"text": "Loading dataset using pandas data frame"
},
{
"code": null,
"e": 3067,
"s": 2916,
"text": "creditData = pd.read_csv(r\"File_Path\\creditcard.csv\") creditData.describe()# H2O method# creditData_df = h2o.import_file(r\"File_Path\\creditcard.csv\") "
},
{
"code": null,
"e": 3098,
"s": 3067,
"text": "creditData.shape> (284807, 31)"
},
{
"code": null,
"e": 3138,
"s": 3098,
"text": "Checking for null values in the dataset"
},
{
"code": null,
"e": 3283,
"s": 3138,
"text": "creditData.isnull().values.any() # pandas method# creditData_h2o.na_omit() # h2o method# creditData_h2o.nacnt() # no missing values found> False"
},
{
"code": null,
"e": 3362,
"s": 3283,
"text": "In order to proceed we need to convert the pandas data frame to H2O data frame"
},
{
"code": null,
"e": 3737,
"s": 3362,
"text": "# Turns python pandas frame into an H2OFramecreditData_h2o = h2o.H2OFrame(creditData)# Let’s plot the Transaction class against the Frequencylabels = [‘normal’,’fraud’]classes = pd.value_counts(creditData[‘Class’], sort = True)classes.plot(kind = ‘bar’, rot=0)plt.title(“Transaction class distribution”)plt.xticks(range(2), labels)plt.xlabel(“Class”)plt.ylabel(“Frequency”)"
},
{
"code": null,
"e": 4148,
"s": 3737,
"text": "fraud = creditData[creditData.Class == 1]normal = creditData[creditData.Class == 0]# Amount vs Classf, (ax1, ax2) = plt.subplots(2,1,sharex=True)f.suptitle('Amount per transaction by class')ax1.hist(fraud.Amount, bins = 50)ax1.set_title('Fraud List')ax2.hist(normal.Amount, bins = 50)ax2.set_title('Normal')plt.xlabel('Amount')plt.ylabel('Number of Transactions')plt.xlim((0, 10000))plt.yscale('log')plt.show()"
},
{
"code": null,
"e": 4451,
"s": 4148,
"text": "# time vs Amountf, (ax1, ax2) = plt.subplots(2, 1, sharex=True)f.suptitle('Time of transaction vs Amount by class')ax1.scatter(fraud.Time, fraud.Amount)ax1.set_title('Fraud List')ax2.scatter(normal.Time, normal.Amount)ax2.set_title('Normal')plt.xlabel('Time (in seconds)')plt.ylabel('Amount')plt.show()"
},
{
"code": null,
"e": 4815,
"s": 4451,
"text": "#plotting the dataset considering the classcolor = {1:'red', 0:'yellow'}fraudlist = creditData[creditData.Class == 1]normal = creditData[creditData.Class == 0]fig,axes = plt.subplots(1,2)axes[0].scatter(list(range(1,fraudlist.shape[0] + 1)), fraudlist.Amount,color='red')axes[1].scatter(list(range(1, normal.shape[0] + 1)), normal.Amount,color='yellow')plt.show()"
},
{
"code": null,
"e": 5076,
"s": 4815,
"text": "The Time variable is not giving an impact on the model prediction. This can figure out from data visualization. Before moving on to the training part, we need to figure out which variables are important and which are not. So we can drop the unwanted variables."
},
{
"code": null,
"e": 5124,
"s": 5076,
"text": "features= creditData_h2o.drop(['Time'], axis=1)"
},
{
"code": null,
"e": 5239,
"s": 5124,
"text": "Split the data frame as training set and testing set keeping 80% for the training set and rest to the testing set."
},
{
"code": null,
"e": 5343,
"s": 5239,
"text": "train, test = features.split_frame([0.8])print(train.shape)print(test.shape)> (227722, 30)> (57085, 30)"
},
{
"code": null,
"e": 5534,
"s": 5343,
"text": "Our dataset has a lot of non-fraud transactions. Because of this for the model training, we only send non-fraud transactions. So that the model will learn the pattern of normal transactions."
},
{
"code": null,
"e": 5870,
"s": 5534,
"text": "# converting to pandas dataframetrain_df = train.as_data_frame()test_df = test.as_data_frame()train_df = train_df[train_df['Class'] == 0]# drop the Class variabletrain_df = train_df.drop(['Class'], axis=1)Y_test_df = test_df['Class'] # true labels of the testing settest_df = test_df.drop(['Class'], axis=1)train_df.shape> (227335, 29)"
},
{
"code": null,
"e": 5984,
"s": 5870,
"text": "train_h2o = h2o.H2OFrame(train_df) # converting to h2o frametest_h2o = h2o.H2OFrame(test_df)x = train_h2o.columns"
},
{
"code": null,
"e": 6159,
"s": 5984,
"text": "When building the model, 4 fully connected hidden layers were chosen with, [14,7,7,14] number of nodes for each layer. First two for the encoder and last two for the decoder."
},
{
"code": null,
"e": 6750,
"s": 6159,
"text": "anomaly_model = H2ODeepLearningEstimator(activation = \"Tanh\", hidden = [14,7,7,14], epochs = 100, standardize = True, stopping_metric = 'MSE', loss = 'automatic', train_samples_per_iteration = 32, shuffle_training_data = True, autoencoder = True, l1 = 10e-5)anomaly_model.train(x=x, training_frame = train_h2o)"
},
{
"code": null,
"e": 6870,
"s": 6750,
"text": "Variable Importance : In H2O there is a special way of analyzing which variables are giving higher impact on the model."
},
{
"code": null,
"e": 6946,
"s": 6870,
"text": "anomaly_model._model_json['output']['variable_importances'].as_data_frame()"
},
{
"code": null,
"e": 6960,
"s": 6946,
"text": "Visualization"
},
{
"code": null,
"e": 7539,
"s": 6960,
"text": "# plotting the variable importancercParams['figure.figsize'] = 14, 8#plt.rcdefaults()fig, ax = plt.subplots()variables = anomaly_model._model_json['output']['variable_importances']['variable']var = variables[0:15]y_pos = np.arange(len(var))scaled_importance = anomaly_model._model_json['output']['variable_importances']['scaled_importance']sc = scaled_importance[0:15]ax.barh(y_pos, sc, align='center', color='green', ecolor='black')ax.set_yticks(y_pos)ax.set_yticklabels(variables)ax.invert_yaxis()ax.set_xlabel('Scaled Importance')ax.set_title('Variable Importance')plt.show()"
},
{
"code": null,
"e": 7759,
"s": 7539,
"text": "# plotting the lossscoring_history = anomaly_model.score_history()%matplotlib inlinercParams['figure.figsize'] = 14, 8plt.plot(scoring_history['training_mse'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')"
},
{
"code": null,
"e": 8168,
"s": 7759,
"text": "The testing set has both normal and fraud transactions in it. The Autoencoder will learn to identify the pattern of the input data. If an anomalous test point does not match the learned pattern, the autoencoder will likely have a high error rate in reconstructing this data, indicating anomalous data. So that we can identify the anomalies of the data. To calculate the error, it uses Mean Squared Error(MSE)"
},
{
"code": null,
"e": 8579,
"s": 8168,
"text": "test_rec_error = anomaly_model.anomaly(test_h2o) # anomaly is a H2O function which calculates the error for the dataset# converting to pandas dataframetest_rec_error_df = test_rec_error.as_data_frame()# plotting the testing dataset against the errortest_rec_error_df['id']=test_rec_error_df.indexrcParams['figure.figsize'] = 14, 8test_rec_error_df.plot(kind=\"scatter\", x='id', y=\"Reconstruction.MSE\")plt.show()"
},
{
"code": null,
"e": 8828,
"s": 8579,
"text": "# predicting the class for the testing datasetpredictions = anomaly_model.predict(test_h2o)error_df = pd.DataFrame({'reconstruction_error': test_rec_error_df['Reconstruction.MSE'], 'true_class': Y_test_df})error_df.describe()"
},
{
"code": null,
"e": 9142,
"s": 8828,
"text": "# reconstruction error for the normal transactions in the testing datasetfig = plt.figure()ax = fig.add_subplot(111)rcParams['figure.figsize'] = 14, 8normal_error_df = error_df[(error_df['true_class']== 0) & (error_df['reconstruction_error'] < 10)]_ = ax.hist(normal_error_df.reconstruction_error.values, bins=10)"
},
{
"code": null,
"e": 9410,
"s": 9142,
"text": "# reconstruction error for the fraud transactions in the testing datasetfig = plt.figure()ax = fig.add_subplot(111)rcParams['figure.figsize'] = 14, 8fraud_error_df = error_df[error_df['true_class'] == 1]_ = ax.hist(fraud_error_df.reconstruction_error.values, bins=10)"
},
{
"code": null,
"e": 10007,
"s": 9410,
"text": "from sklearn.metrics import (confusion_matrix, precision_recall_curve, auc, roc_curve, recall_score, classification_report, f1_score, precision_recall_fscore_support)fpr, tpr, thresholds = roc_curve(error_df.true_class, error_df.reconstruction_error)roc_auc = auc(fpr, tpr)plt.title('Receiver Operating Characteristic')plt.plot(fpr, tpr, label='AUC = %0.4f'% roc_auc)plt.legend(loc='lower right')plt.plot([0,1],[0,1],'r--')plt.xlim([-0.001, 1])plt.ylim([0, 1.001])plt.ylabel('True Positive Rate')plt.xlabel('False Positive Rate')plt.show();"
},
{
"code": null,
"e": 10030,
"s": 10007,
"text": "The accuracy is 0.9718"
},
{
"code": null,
"e": 10187,
"s": 10030,
"text": "Since the data is highly imbalanced, it cannot be measured only by using accuracy. Precision vs Recall was chosen as the matrix for the classification task."
},
{
"code": null,
"e": 10243,
"s": 10187,
"text": "Precision: Measuring the relevancy of obtained results."
},
{
"code": null,
"e": 10298,
"s": 10243,
"text": "[ True positives / (True positives + False positives)]"
},
{
"code": null,
"e": 10356,
"s": 10298,
"text": "Recall: Measuring how many relevant results are returned."
},
{
"code": null,
"e": 10411,
"s": 10356,
"text": "[ True positives / (True positives + False negatives)]"
},
{
"code": null,
"e": 10472,
"s": 10411,
"text": "True Positives — Number of actual frauds predicted as frauds"
},
{
"code": null,
"e": 10531,
"s": 10472,
"text": "False Positives — Number of non-frauds predicted as frauds"
},
{
"code": null,
"e": 10591,
"s": 10531,
"text": "False Negatives — Number of frauds predicted as non-frauds."
},
{
"code": null,
"e": 10839,
"s": 10591,
"text": "precision, recall, th = precision_recall_curve(error_df.true_class, error_df.reconstruction_error)plt.plot(recall, precision, 'b', label='Precision-Recall curve')plt.title('Recall vs Precision')plt.xlabel('Recall')plt.ylabel('Precision')plt.show()"
},
{
"code": null,
"e": 11012,
"s": 10839,
"text": "We need to find a better threshold that can separate the anomalies from normal. This can be done by calculating the intersection of the Precision/Recall vs Threshold graph."
},
{
"code": null,
"e": 11262,
"s": 11012,
"text": "plt.plot(th, precision[1:], label=\"Precision\",linewidth=5)plt.plot(th, recall[1:], label=\"Recall\",linewidth=5)plt.title('Precision and recall for different threshold values')plt.xlabel('Threshold')plt.ylabel('Precision/Recall')plt.legend()plt.show()"
},
{
"code": null,
"e": 11789,
"s": 11262,
"text": "# plot the testing set with the thresholdthreshold = 0.01groups = error_df.groupby('true_class')fig, ax = plt.subplots()for name, group in groups: ax.plot(group.index, group.reconstruction_error, marker='o', ms=3.5, linestyle='', label= \"Fraud\" if name == 1 else \"Normal\")ax.hlines(threshold, ax.get_xlim()[0], ax.get_xlim()[1], colors=\"r\", zorder=100, label='Threshold')ax.legend()plt.title(\"Reconstruction error for different classes\")plt.ylabel(\"Reconstruction error\")plt.xlabel(\"Data point index\")plt.show();"
},
{
"code": null,
"e": 12186,
"s": 11789,
"text": "import seaborn as snsLABELS = ['Normal', 'Fraud']y_pred = [1 if e > threshold else 0 for e in error_df.reconstruction_error.values]conf_matrix = confusion_matrix(error_df.true_class, y_pred)plt.figure(figsize=(12, 12))sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt=\"d\");plt.title(\"Confusion matrix\")plt.ylabel('True class')plt.xlabel('Predicted class')plt.show()"
},
{
"code": null,
"e": 12253,
"s": 12186,
"text": "csr = classification_report(error_df.true_class, y_pred)print(csr)"
},
{
"code": null,
"e": 12548,
"s": 12253,
"text": "Our model is catching most of the fraudulent data. In Autoencoders, it gives a good accuracy. But if we look into Precision and Recall of the dataset, it is not performing enough. As I mentioned earlier, there are other anomaly detection methods that perform well in highly imbalanced datasets."
}
] |
MATLAB | Change the color of background pixels by OTSU Thresholding - GeeksforGeeks | 15 Sep, 2021
MATLAB also called Matrix Laboratory is a numerical computing environment and a platform for programming language. it was designed and developed by MathWorks. MATLAB is a framework that allows you to perform matrix manipulations, implementing algorithms, plotting functions and data, creating user-interfaces and interfacing with programs that are written in different programming languages i.e. C, C++, Python, Java etc..OTSU Thresholding : OTSU thresholding is a segmentation algorithm through which we can segment an image into two or more than two regions. This algorithm checks on every single threshold if it can separate the two kinds of pixels optimally.By OTSU thresholding we separate the foreground and background pixels.Approach:
Read the image using imread() function and convert it to gray image using rgb2gray() function.Graythresh the image using greythresh() function.Detect the foreground and background pixels of the image.Pick the background pixels and color them blue.
Read the image using imread() function and convert it to gray image using rgb2gray() function.
Graythresh the image using greythresh() function.
Detect the foreground and background pixels of the image.
Pick the background pixels and color them blue.
Below is the implementation of above approach –
MATLAB
% read the rgb image.I = imread('leena.png'); % convert it to gray image using rgb2gray() function. Ig = rgb2gray(I); % apply inbuilt otsu thresholding and% convert the image to binary image. T = graythresh(Ig); Tg = T*255; % detect foreground and background% pixels of the binary image. m = Ig > Tg figure, imshow(m) I1 = I(:, :, 1); I2 = I(:, :, 2);I3 = I(:, :, 3);I1(~m) = 0;I2(~m) = 0; % in background pixels, take the third% channel and color it blue.I3(~m) = 255; In=cat(3, I1, I2, I3);figure, imshow(In);
Input Image:
Output:
surindertarika1234
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Fuzzy Logic | Introduction
Basics of API Testing Using Postman
Principal Component Analysis with Python
Markov Decision Process
ML | What is Machine Learning ?
OpenCV - Overview
Q-Learning in Python
How to create a REST API using Java Spring Boot
Getting Started with System Design | [
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 25070,
"s": 24326,
"text": "MATLAB also called Matrix Laboratory is a numerical computing environment and a platform for programming language. it was designed and developed by MathWorks. MATLAB is a framework that allows you to perform matrix manipulations, implementing algorithms, plotting functions and data, creating user-interfaces and interfacing with programs that are written in different programming languages i.e. C, C++, Python, Java etc..OTSU Thresholding : OTSU thresholding is a segmentation algorithm through which we can segment an image into two or more than two regions. This algorithm checks on every single threshold if it can separate the two kinds of pixels optimally.By OTSU thresholding we separate the foreground and background pixels.Approach: "
},
{
"code": null,
"e": 25318,
"s": 25070,
"text": "Read the image using imread() function and convert it to gray image using rgb2gray() function.Graythresh the image using greythresh() function.Detect the foreground and background pixels of the image.Pick the background pixels and color them blue."
},
{
"code": null,
"e": 25413,
"s": 25318,
"text": "Read the image using imread() function and convert it to gray image using rgb2gray() function."
},
{
"code": null,
"e": 25463,
"s": 25413,
"text": "Graythresh the image using greythresh() function."
},
{
"code": null,
"e": 25521,
"s": 25463,
"text": "Detect the foreground and background pixels of the image."
},
{
"code": null,
"e": 25569,
"s": 25521,
"text": "Pick the background pixels and color them blue."
},
{
"code": null,
"e": 25619,
"s": 25569,
"text": "Below is the implementation of above approach – "
},
{
"code": null,
"e": 25626,
"s": 25619,
"text": "MATLAB"
},
{
"code": "% read the rgb image.I = imread('leena.png'); % convert it to gray image using rgb2gray() function. Ig = rgb2gray(I); % apply inbuilt otsu thresholding and% convert the image to binary image. T = graythresh(Ig); Tg = T*255; % detect foreground and background% pixels of the binary image. m = Ig > Tg figure, imshow(m) I1 = I(:, :, 1); I2 = I(:, :, 2);I3 = I(:, :, 3);I1(~m) = 0;I2(~m) = 0; % in background pixels, take the third% channel and color it blue.I3(~m) = 255; In=cat(3, I1, I2, I3);figure, imshow(In);",
"e": 26220,
"s": 25626,
"text": null
},
{
"code": null,
"e": 26235,
"s": 26220,
"text": "Input Image: "
},
{
"code": null,
"e": 26245,
"s": 26235,
"text": "Output: "
},
{
"code": null,
"e": 26266,
"s": 26247,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26283,
"s": 26266,
"text": "Image-Processing"
},
{
"code": null,
"e": 26290,
"s": 26283,
"text": "MATLAB"
},
{
"code": null,
"e": 26316,
"s": 26290,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 26414,
"s": 26316,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26458,
"s": 26414,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 26485,
"s": 26458,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 26521,
"s": 26485,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 26562,
"s": 26521,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 26586,
"s": 26562,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 26618,
"s": 26586,
"text": "ML | What is Machine Learning ?"
},
{
"code": null,
"e": 26636,
"s": 26618,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 26657,
"s": 26636,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 26705,
"s": 26657,
"text": "How to create a REST API using Java Spring Boot"
}
] |
Getting factorial of a number in Julia - factorial() Method - GeeksforGeeks | 21 Apr, 2020
The factorial() is an inbuilt function in julia which is used to return the factorial of the specified number n.
Syntax: factorial(n::Integer)
Parameters:
n: Specified number
Returns: It returns the factorial of the specified number n.
Example 1:
# Julia program to illustrate # the use of factorial() method # Getting the factorial of # the specified numberprintln(factorial(0))println(factorial(1))println(factorial(2))
Output:
1
1
2
Example 2:
# Julia program to illustrate # the use of factorial() method # Getting the factorial of # the specified numberprintln(factorial(5))println(factorial(7))println(factorial(big(20)))println(factorial(big(15)))
Output:
120
5040
2432902008176640000
1307674368000
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Get array dimensions and size of a dimension in Julia - size() Method
Getting the maximum value from a list in Julia - max() Method
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Working with Date and Time in Julia
Working with Excel Files in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Exception handling in Julia
Functions in Julia
Replacing elements of a collection in Julia - replace() and replace!() Methods | [
{
"code": null,
"e": 24464,
"s": 24436,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 24577,
"s": 24464,
"text": "The factorial() is an inbuilt function in julia which is used to return the factorial of the specified number n."
},
{
"code": null,
"e": 24607,
"s": 24577,
"text": "Syntax: factorial(n::Integer)"
},
{
"code": null,
"e": 24619,
"s": 24607,
"text": "Parameters:"
},
{
"code": null,
"e": 24639,
"s": 24619,
"text": "n: Specified number"
},
{
"code": null,
"e": 24700,
"s": 24639,
"text": "Returns: It returns the factorial of the specified number n."
},
{
"code": null,
"e": 24711,
"s": 24700,
"text": "Example 1:"
},
{
"code": "# Julia program to illustrate # the use of factorial() method # Getting the factorial of # the specified numberprintln(factorial(0))println(factorial(1))println(factorial(2))",
"e": 24887,
"s": 24711,
"text": null
},
{
"code": null,
"e": 24895,
"s": 24887,
"text": "Output:"
},
{
"code": null,
"e": 24902,
"s": 24895,
"text": "1\n1\n2\n"
},
{
"code": null,
"e": 24913,
"s": 24902,
"text": "Example 2:"
},
{
"code": "# Julia program to illustrate # the use of factorial() method # Getting the factorial of # the specified numberprintln(factorial(5))println(factorial(7))println(factorial(big(20)))println(factorial(big(15)))",
"e": 25122,
"s": 24913,
"text": null
},
{
"code": null,
"e": 25130,
"s": 25122,
"text": "Output:"
},
{
"code": null,
"e": 25174,
"s": 25130,
"text": "120\n5040\n2432902008176640000\n1307674368000\n"
},
{
"code": null,
"e": 25180,
"s": 25174,
"text": "Julia"
},
{
"code": null,
"e": 25278,
"s": 25180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25287,
"s": 25278,
"text": "Comments"
},
{
"code": null,
"e": 25300,
"s": 25287,
"text": "Old Comments"
},
{
"code": null,
"e": 25370,
"s": 25300,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 25432,
"s": 25370,
"text": "Getting the maximum value from a list in Julia - max() Method"
},
{
"code": null,
"e": 25480,
"s": 25432,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 25550,
"s": 25480,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 25586,
"s": 25550,
"text": "Working with Date and Time in Julia"
},
{
"code": null,
"e": 25620,
"s": 25586,
"text": "Working with Excel Files in Julia"
},
{
"code": null,
"e": 25693,
"s": 25620,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 25721,
"s": 25693,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 25740,
"s": 25721,
"text": "Functions in Julia"
}
] |
How to make legend key fill transparent in ggplot2 in R? - GeeksforGeeks | 30 Jun, 2021
In this article, we will see how to make legend key fill transparent in ggplot2 in R Programming Language.
Note: Here we will be using a line graph, the same can be applied to any other plot.
Let us first draw a regular plot, so that the difference is apparent.
Example:
R
# Load Packagelibrary("ggplot2") # Create DataFrameDF <- data.frame(X = rnorm(50), Y = rnorm(50), Users = c("User1", "User2", "User3", "User4", "User5")) # Generate LineGraph from DataFrame # using ggplot2ggplot(DF,aes(X, Y, color = Users))+ geom_line(size = 1)
Output:
LineGraph with Default Legend Keys
As you can see clearly in the above plot, Legend Keys have a grey background. So now we are going to convert it into transparent by using theme() function. theme() in itself is a very big function containing lots of theme elements that we can apply to the plot for making our plot look presentable. To change the background of Legend keys, we use legend.key, which specifies the background underneath legend keys.
Syntax : theme(legend.key)
Parameter :
legend.key : For specify background underneath legend keys. we assign element_rect function as the value of it.
Return : Theme Of the plot
Further, we specify the element_rect() function as a value of legend.key, which is often used for backgrounds and borders. It also has some parameters for customization such as fill, color, size, and linetype but here for make fill the Legend Keys with transparent background, we will use only fill parameter out of them.
Syntax : element_rect(fill)
Parameter :
fill : fill with color.
return : Modifications on backgrounds and borders.
Syntax:
theme(legend.key = element_rect(fill))
Example:
R
# Load ggplot2 Packagelibrary("ggplot2") # Create DataFrame for PlottingDF <- data.frame(X = rnorm(50), Y = rnorm(50), Users = c("User1", "User2", "User3", "User4", "User5")) # Generate LineGraph with transparent fill # of Legend Keys.ggplot(DF,aes(X, Y, color = Users))+ geom_line(size = 1)+ theme(legend.key = element_rect(fill = "transparent"))
Output:
LineGraph with transparent filled Legend Keys
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
Time Series Analysis in R | [
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26705,
"s": 26597,
"text": "In this article, we will see how to make legend key fill transparent in ggplot2 in R Programming Language. "
},
{
"code": null,
"e": 26790,
"s": 26705,
"text": "Note: Here we will be using a line graph, the same can be applied to any other plot."
},
{
"code": null,
"e": 26860,
"s": 26790,
"text": "Let us first draw a regular plot, so that the difference is apparent."
},
{
"code": null,
"e": 26869,
"s": 26860,
"text": "Example:"
},
{
"code": null,
"e": 26871,
"s": 26869,
"text": "R"
},
{
"code": "# Load Packagelibrary(\"ggplot2\") # Create DataFrameDF <- data.frame(X = rnorm(50), Y = rnorm(50), Users = c(\"User1\", \"User2\", \"User3\", \"User4\", \"User5\")) # Generate LineGraph from DataFrame # using ggplot2ggplot(DF,aes(X, Y, color = Users))+ geom_line(size = 1)",
"e": 27218,
"s": 26871,
"text": null
},
{
"code": null,
"e": 27226,
"s": 27218,
"text": "Output:"
},
{
"code": null,
"e": 27261,
"s": 27226,
"text": "LineGraph with Default Legend Keys"
},
{
"code": null,
"e": 27676,
"s": 27261,
"text": "As you can see clearly in the above plot, Legend Keys have a grey background. So now we are going to convert it into transparent by using theme() function. theme() in itself is a very big function containing lots of theme elements that we can apply to the plot for making our plot look presentable. To change the background of Legend keys, we use legend.key, which specifies the background underneath legend keys. "
},
{
"code": null,
"e": 27703,
"s": 27676,
"text": "Syntax : theme(legend.key)"
},
{
"code": null,
"e": 27715,
"s": 27703,
"text": "Parameter :"
},
{
"code": null,
"e": 27827,
"s": 27715,
"text": "legend.key : For specify background underneath legend keys. we assign element_rect function as the value of it."
},
{
"code": null,
"e": 27854,
"s": 27827,
"text": "Return : Theme Of the plot"
},
{
"code": null,
"e": 28176,
"s": 27854,
"text": "Further, we specify the element_rect() function as a value of legend.key, which is often used for backgrounds and borders. It also has some parameters for customization such as fill, color, size, and linetype but here for make fill the Legend Keys with transparent background, we will use only fill parameter out of them."
},
{
"code": null,
"e": 28204,
"s": 28176,
"text": "Syntax : element_rect(fill)"
},
{
"code": null,
"e": 28216,
"s": 28204,
"text": "Parameter :"
},
{
"code": null,
"e": 28240,
"s": 28216,
"text": "fill : fill with color."
},
{
"code": null,
"e": 28291,
"s": 28240,
"text": "return : Modifications on backgrounds and borders."
},
{
"code": null,
"e": 28299,
"s": 28291,
"text": "Syntax:"
},
{
"code": null,
"e": 28338,
"s": 28299,
"text": "theme(legend.key = element_rect(fill))"
},
{
"code": null,
"e": 28347,
"s": 28338,
"text": "Example:"
},
{
"code": null,
"e": 28349,
"s": 28347,
"text": "R"
},
{
"code": "# Load ggplot2 Packagelibrary(\"ggplot2\") # Create DataFrame for PlottingDF <- data.frame(X = rnorm(50), Y = rnorm(50), Users = c(\"User1\", \"User2\", \"User3\", \"User4\", \"User5\")) # Generate LineGraph with transparent fill # of Legend Keys.ggplot(DF,aes(X, Y, color = Users))+ geom_line(size = 1)+ theme(legend.key = element_rect(fill = \"transparent\"))",
"e": 28784,
"s": 28349,
"text": null
},
{
"code": null,
"e": 28792,
"s": 28784,
"text": "Output:"
},
{
"code": null,
"e": 28838,
"s": 28792,
"text": "LineGraph with transparent filled Legend Keys"
},
{
"code": null,
"e": 28845,
"s": 28838,
"text": "Picked"
},
{
"code": null,
"e": 28854,
"s": 28845,
"text": "R-ggplot"
},
{
"code": null,
"e": 28865,
"s": 28854,
"text": "R Language"
},
{
"code": null,
"e": 28963,
"s": 28865,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29015,
"s": 28963,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29050,
"s": 29015,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29108,
"s": 29050,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29146,
"s": 29108,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29189,
"s": 29146,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29238,
"s": 29189,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29255,
"s": 29238,
"text": "R - if statement"
},
{
"code": null,
"e": 29305,
"s": 29255,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29357,
"s": 29305,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
Minimum height of a triangle with given base and area - GeeksforGeeks | 28 Nov, 2021
Given two integers a and b, find the smallest possible height such that a triangle of atleast area “a” and base “b” can be formed.
Examples :
Input : a = 2, b = 2
Output : Minimum height of triangle is 2
Explanation:
Input : a = 8, b = 4
Output : Minimum height of triangle is 4
Minimum height of Triangle with base “b” and area “a” can be evaluated by having the knowledge of the relationship between the three.
The relation between area, base and height is: area = (1/2) * base * heightSo height can be calculated as : height = (2 * area)/ baseMinimum height is the ceil of the height obtained using above formula.
C++
Java
Python
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;// function to calculate minimum height of // triangleint minHeight(int base, int area){ return ceil((float)(2*area)/base);} int main() { int base = 4, area = 8; cout << "Minimum height is " << minHeight(base, area) << endl; return 0;}
// Java code Minimum height of a // triangle with given base and area class GFG { // function to calculate minimum height of // triangle static double minHeight(double base, double area) { double d = (2 * area) / base; return Math.ceil(d); } // Driver code public static void main (String[] args) { double base = 4, area = 8; System.out.println("Minimum height is "+ minHeight(base, area)); }}// This code is contributed by Anant Agarwal.
# Python Program to find minimum height of triangleimport math def minHeight(area,base): return math.ceil((2*area)/base) # Driver codearea = 8base = 4height = minHeight(area, base)print("Minimum height is %d" % (height))
// C# program to find minimum height of// a triangle with given base and areausing System; public class GFG { // function to calculate minimum // height of triangle static int minHeight(int b_ase, int area) { return (int)Math.Round((float)(2 * area) / b_ase); } // Driver function static public void Main() { int b_ase = 4, area = 8; Console.WriteLine("Minimum height is " + minHeight(b_ase, area)); }} // This code is contributed by vt_m.
<?php // function to calculate minimum // height of trianglefunction minHeight($base, $area){ return ceil((2 * $area) / $base);} // Driver Code$base = 4;$area = 8;echo "Minimum height is ", minHeight($base, $area); // This code is contributed by anuj_67.?>
<script> // function to calculate minimum height of // trianglefunction minHeight( base, area){ return Math.ceil((2*area)/base);} let base = 4, area = 8; document.write( "Minimum height is " +minHeight(base, area)); // This code contributed by aashish1995 </script>
Output :
Minimum height is 4
vt_m
aashish1995
triangle
Geometric
Technical Scripter
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convex Hull using Divide and Conquer Algorithm
Equation of circle when three points on the circle are given
Circle and Lattice Points
Orientation of 3 ordered points
Program to find slope of a line
Program to find line passing through 2 Points
Check if a line touches or intersects a circle
Minimum Cost Polygon Triangulation
Minimum distance to the corner of a grid from source
Line Clipping | Set 2 (Cyrus Beck Algorithm) | [
{
"code": null,
"e": 25301,
"s": 25273,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25433,
"s": 25301,
"text": "Given two integers a and b, find the smallest possible height such that a triangle of atleast area “a” and base “b” can be formed. "
},
{
"code": null,
"e": 25446,
"s": 25433,
"text": "Examples : "
},
{
"code": null,
"e": 25523,
"s": 25446,
"text": "Input : a = 2, b = 2\nOutput : Minimum height of triangle is 2\n\nExplanation: "
},
{
"code": null,
"e": 25585,
"s": 25523,
"text": "Input : a = 8, b = 4\nOutput : Minimum height of triangle is 4"
},
{
"code": null,
"e": 25720,
"s": 25585,
"text": "Minimum height of Triangle with base “b” and area “a” can be evaluated by having the knowledge of the relationship between the three. "
},
{
"code": null,
"e": 25924,
"s": 25720,
"text": "The relation between area, base and height is: area = (1/2) * base * heightSo height can be calculated as : height = (2 * area)/ baseMinimum height is the ceil of the height obtained using above formula."
},
{
"code": null,
"e": 25930,
"s": 25926,
"text": "C++"
},
{
"code": null,
"e": 25935,
"s": 25930,
"text": "Java"
},
{
"code": null,
"e": 25942,
"s": 25935,
"text": "Python"
},
{
"code": null,
"e": 25945,
"s": 25942,
"text": "C#"
},
{
"code": null,
"e": 25949,
"s": 25945,
"text": "PHP"
},
{
"code": null,
"e": 25960,
"s": 25949,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;// function to calculate minimum height of // triangleint minHeight(int base, int area){ return ceil((float)(2*area)/base);} int main() { int base = 4, area = 8; cout << \"Minimum height is \" << minHeight(base, area) << endl; return 0;}",
"e": 26268,
"s": 25960,
"text": null
},
{
"code": "// Java code Minimum height of a // triangle with given base and area class GFG { // function to calculate minimum height of // triangle static double minHeight(double base, double area) { double d = (2 * area) / base; return Math.ceil(d); } // Driver code public static void main (String[] args) { double base = 4, area = 8; System.out.println(\"Minimum height is \"+ minHeight(base, area)); }}// This code is contributed by Anant Agarwal.",
"e": 26804,
"s": 26268,
"text": null
},
{
"code": "# Python Program to find minimum height of triangleimport math def minHeight(area,base): return math.ceil((2*area)/base) # Driver codearea = 8base = 4height = minHeight(area, base)print(\"Minimum height is %d\" % (height))",
"e": 27034,
"s": 26804,
"text": null
},
{
"code": "// C# program to find minimum height of// a triangle with given base and areausing System; public class GFG { // function to calculate minimum // height of triangle static int minHeight(int b_ase, int area) { return (int)Math.Round((float)(2 * area) / b_ase); } // Driver function static public void Main() { int b_ase = 4, area = 8; Console.WriteLine(\"Minimum height is \" + minHeight(b_ase, area)); }} // This code is contributed by vt_m.",
"e": 27555,
"s": 27034,
"text": null
},
{
"code": "<?php // function to calculate minimum // height of trianglefunction minHeight($base, $area){ return ceil((2 * $area) / $base);} // Driver Code$base = 4;$area = 8;echo \"Minimum height is \", minHeight($base, $area); // This code is contributed by anuj_67.?>",
"e": 27831,
"s": 27555,
"text": null
},
{
"code": "<script> // function to calculate minimum height of // trianglefunction minHeight( base, area){ return Math.ceil((2*area)/base);} let base = 4, area = 8; document.write( \"Minimum height is \" +minHeight(base, area)); // This code contributed by aashish1995 </script>",
"e": 28135,
"s": 27831,
"text": null
},
{
"code": null,
"e": 28145,
"s": 28135,
"text": "Output : "
},
{
"code": null,
"e": 28165,
"s": 28145,
"text": "Minimum height is 4"
},
{
"code": null,
"e": 28172,
"s": 28167,
"text": "vt_m"
},
{
"code": null,
"e": 28184,
"s": 28172,
"text": "aashish1995"
},
{
"code": null,
"e": 28193,
"s": 28184,
"text": "triangle"
},
{
"code": null,
"e": 28203,
"s": 28193,
"text": "Geometric"
},
{
"code": null,
"e": 28222,
"s": 28203,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28232,
"s": 28222,
"text": "Geometric"
},
{
"code": null,
"e": 28330,
"s": 28232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28339,
"s": 28330,
"text": "Comments"
},
{
"code": null,
"e": 28352,
"s": 28339,
"text": "Old Comments"
},
{
"code": null,
"e": 28399,
"s": 28352,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 28460,
"s": 28399,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 28486,
"s": 28460,
"text": "Circle and Lattice Points"
},
{
"code": null,
"e": 28518,
"s": 28486,
"text": "Orientation of 3 ordered points"
},
{
"code": null,
"e": 28550,
"s": 28518,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 28596,
"s": 28550,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 28643,
"s": 28596,
"text": "Check if a line touches or intersects a circle"
},
{
"code": null,
"e": 28678,
"s": 28643,
"text": "Minimum Cost Polygon Triangulation"
},
{
"code": null,
"e": 28731,
"s": 28678,
"text": "Minimum distance to the corner of a grid from source"
}
] |
Print 2D matrix in different lines and without curly braces in C/C++? - GeeksforGeeks | 09 May, 2022
Following is a general way of printing 2D matrix such that every row is printed in separate lines.
C
for (int i = 0; i < m; i++){ for (int j = 0; j < n; j++) { cout << arr[i][j] << " "; } // Newline for new row cout << endl;}
How to print without using any curly braces in for loops? We strongly recommend you to minimize your browser and try this yourself first. We can simply removed inner curly bracket as there is single line inner for loop. How to remove outer curly braces? Below is solution.
C
// C++ program to print a matrix line by line without// using curly braces.#include<iostream>using namespace std; int main(){ int m = 2, n = 3; int mat[][3] = { {1, 2, 3}, {4, 5, 6}, }; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) // Prints ' ' if j != n-1 else prints '\n' cout << mat[i][j] << " \n"[j == n-1]; return 0;}
Output:
1 2 3
4 5 6
The actual trick is in following statement “\n”[j == n-1], explanation is as follows: ” \n” is a 2 character string where 1st character is space and 2nd character is newline, so we want space after each value except last for which we want a newline. In C, string literals are treated character arrays [See this for more details]. j == n-1 statement evaluates to 0 for internal elements (because for them j < n-1) and for last value(of each row) it becomes 1. So for internal elements, statement evaluate to ” \n”[0] i.e. ” ” and for last element of each row ” \n”[1] i.e. “\n” Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sweetyty
cpp-array
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 25587,
"s": 25559,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 25687,
"s": 25587,
"text": "Following is a general way of printing 2D matrix such that every row is printed in separate lines. "
},
{
"code": null,
"e": 25689,
"s": 25687,
"text": "C"
},
{
"code": "for (int i = 0; i < m; i++){ for (int j = 0; j < n; j++) { cout << arr[i][j] << \" \"; } // Newline for new row cout << endl;}",
"e": 25833,
"s": 25689,
"text": null
},
{
"code": null,
"e": 26111,
"s": 25833,
"text": "How to print without using any curly braces in for loops? We strongly recommend you to minimize your browser and try this yourself first. We can simply removed inner curly bracket as there is single line inner for loop. How to remove outer curly braces? Below is solution. "
},
{
"code": null,
"e": 26113,
"s": 26111,
"text": "C"
},
{
"code": "// C++ program to print a matrix line by line without// using curly braces.#include<iostream>using namespace std; int main(){ int m = 2, n = 3; int mat[][3] = { {1, 2, 3}, {4, 5, 6}, }; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) // Prints ' ' if j != n-1 else prints '\\n' cout << mat[i][j] << \" \\n\"[j == n-1]; return 0;}",
"e": 26530,
"s": 26113,
"text": null
},
{
"code": null,
"e": 26538,
"s": 26530,
"text": "Output:"
},
{
"code": null,
"e": 26550,
"s": 26538,
"text": "1 2 3\n4 5 6"
},
{
"code": null,
"e": 27252,
"s": 26550,
"text": "The actual trick is in following statement “\\n”[j == n-1], explanation is as follows: ” \\n” is a 2 character string where 1st character is space and 2nd character is newline, so we want space after each value except last for which we want a newline. In C, string literals are treated character arrays [See this for more details]. j == n-1 statement evaluates to 0 for internal elements (because for them j < n-1) and for last value(of each row) it becomes 1. So for internal elements, statement evaluate to ” \\n”[0] i.e. ” ” and for last element of each row ” \\n”[1] i.e. “\\n” Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27261,
"s": 27252,
"text": "sweetyty"
},
{
"code": null,
"e": 27271,
"s": 27261,
"text": "cpp-array"
},
{
"code": null,
"e": 27282,
"s": 27271,
"text": "C Language"
},
{
"code": null,
"e": 27286,
"s": 27282,
"text": "C++"
},
{
"code": null,
"e": 27290,
"s": 27286,
"text": "CPP"
},
{
"code": null,
"e": 27388,
"s": 27290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27426,
"s": 27388,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27452,
"s": 27426,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 27474,
"s": 27452,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 27494,
"s": 27474,
"text": "Multithreading in C"
},
{
"code": null,
"e": 27535,
"s": 27494,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27553,
"s": 27535,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27572,
"s": 27553,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27618,
"s": 27572,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27661,
"s": 27618,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
useradd command in Linux with Examples - GeeksforGeeks | 26 May, 2020
useradd is a command in Linux that is used to add user accounts to your system. It is just a symbolic link to adduser command in Linux and the difference between both of them is that useradd is a native binary compiled with system whereas adduser is a Perl script which uses useradd binary in the background. It make changes to the following files:
/etc/passwd
/etc/shadow
/etc/group
/etc/gshadow
creates a directory for new user in /home
Syntax:
useradd [options] name_of_the_user
1. To add a simple user
sudo useraddtest_user
This command will add the user named “test_user”.
2. To give a home directory path for new user
sudo useradd -d /home/test_user test_user
This will set the home directory of the us”/home/test_user”.
3. To create a user with specific user id
sudo useradd -u 1234 test_user
This will create a new user with the user-id “1234” and the name “test_user”.
4. To create a user with specific group id
sudo useradd -g 1000 test_user
This will create a new user with the group id “1000” and the name “test_user”.
5. To create a user without home directory
sudo useradd -M test_user
This will create the user with the name “test_user” and that too without a home directory.
6. To create a user with expiry date
sudo useradd -e 2020-05-30 test_user
This will create the user named “test_user” with the expiry date of 30th May 2020.
7. To create a user with a comment
sudo useradd -c "This is a test user" test_user
This will create a user with a short comment or description of the user.
8. To create a user with changed login shell
sudo useradd -s /bin/sh test_user
This will create a user named “test_user” with the default shell /bin/sh.
9 To set an unencrypted password for the user
sudo useradd -p test_password test_user
This will create a new user with the name “test_user” and an unencrypted password “test_password”.
10. To display help
sudo useradd --help
This command will display the help section of the useradd command.
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Conditional Statements | Shell Script
Tail command in Linux with examples
'crontab' in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
scp command in Linux with Examples
Compiling with g++ | [
{
"code": null,
"e": 26326,
"s": 26298,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 26675,
"s": 26326,
"text": "useradd is a command in Linux that is used to add user accounts to your system. It is just a symbolic link to adduser command in Linux and the difference between both of them is that useradd is a native binary compiled with system whereas adduser is a Perl script which uses useradd binary in the background. It make changes to the following files:"
},
{
"code": null,
"e": 26687,
"s": 26675,
"text": "/etc/passwd"
},
{
"code": null,
"e": 26699,
"s": 26687,
"text": "/etc/shadow"
},
{
"code": null,
"e": 26710,
"s": 26699,
"text": "/etc/group"
},
{
"code": null,
"e": 26723,
"s": 26710,
"text": "/etc/gshadow"
},
{
"code": null,
"e": 26765,
"s": 26723,
"text": "creates a directory for new user in /home"
},
{
"code": null,
"e": 26773,
"s": 26765,
"text": "Syntax:"
},
{
"code": null,
"e": 26808,
"s": 26773,
"text": "useradd [options] name_of_the_user"
},
{
"code": null,
"e": 26832,
"s": 26808,
"text": "1. To add a simple user"
},
{
"code": null,
"e": 26854,
"s": 26832,
"text": "sudo useraddtest_user"
},
{
"code": null,
"e": 26904,
"s": 26854,
"text": "This command will add the user named “test_user”."
},
{
"code": null,
"e": 26950,
"s": 26904,
"text": "2. To give a home directory path for new user"
},
{
"code": null,
"e": 26992,
"s": 26950,
"text": "sudo useradd -d /home/test_user test_user"
},
{
"code": null,
"e": 27053,
"s": 26992,
"text": "This will set the home directory of the us”/home/test_user”."
},
{
"code": null,
"e": 27095,
"s": 27053,
"text": "3. To create a user with specific user id"
},
{
"code": null,
"e": 27126,
"s": 27095,
"text": "sudo useradd -u 1234 test_user"
},
{
"code": null,
"e": 27204,
"s": 27126,
"text": "This will create a new user with the user-id “1234” and the name “test_user”."
},
{
"code": null,
"e": 27247,
"s": 27204,
"text": "4. To create a user with specific group id"
},
{
"code": null,
"e": 27278,
"s": 27247,
"text": "sudo useradd -g 1000 test_user"
},
{
"code": null,
"e": 27357,
"s": 27278,
"text": "This will create a new user with the group id “1000” and the name “test_user”."
},
{
"code": null,
"e": 27400,
"s": 27357,
"text": "5. To create a user without home directory"
},
{
"code": null,
"e": 27426,
"s": 27400,
"text": "sudo useradd -M test_user"
},
{
"code": null,
"e": 27517,
"s": 27426,
"text": "This will create the user with the name “test_user” and that too without a home directory."
},
{
"code": null,
"e": 27554,
"s": 27517,
"text": "6. To create a user with expiry date"
},
{
"code": null,
"e": 27591,
"s": 27554,
"text": "sudo useradd -e 2020-05-30 test_user"
},
{
"code": null,
"e": 27674,
"s": 27591,
"text": "This will create the user named “test_user” with the expiry date of 30th May 2020."
},
{
"code": null,
"e": 27709,
"s": 27674,
"text": "7. To create a user with a comment"
},
{
"code": null,
"e": 27757,
"s": 27709,
"text": "sudo useradd -c \"This is a test user\" test_user"
},
{
"code": null,
"e": 27830,
"s": 27757,
"text": "This will create a user with a short comment or description of the user."
},
{
"code": null,
"e": 27875,
"s": 27830,
"text": "8. To create a user with changed login shell"
},
{
"code": null,
"e": 27909,
"s": 27875,
"text": "sudo useradd -s /bin/sh test_user"
},
{
"code": null,
"e": 27983,
"s": 27909,
"text": "This will create a user named “test_user” with the default shell /bin/sh."
},
{
"code": null,
"e": 28029,
"s": 27983,
"text": "9 To set an unencrypted password for the user"
},
{
"code": null,
"e": 28069,
"s": 28029,
"text": "sudo useradd -p test_password test_user"
},
{
"code": null,
"e": 28168,
"s": 28069,
"text": "This will create a new user with the name “test_user” and an unencrypted password “test_password”."
},
{
"code": null,
"e": 28188,
"s": 28168,
"text": "10. To display help"
},
{
"code": null,
"e": 28208,
"s": 28188,
"text": "sudo useradd --help"
},
{
"code": null,
"e": 28275,
"s": 28208,
"text": "This command will display the help section of the useradd command."
},
{
"code": null,
"e": 28289,
"s": 28275,
"text": "linux-command"
},
{
"code": null,
"e": 28311,
"s": 28289,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 28322,
"s": 28311,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28420,
"s": 28322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28455,
"s": 28420,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 28493,
"s": 28455,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 28529,
"s": 28493,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 28562,
"s": 28529,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 28600,
"s": 28562,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28635,
"s": 28600,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 28672,
"s": 28635,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 28708,
"s": 28672,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 28743,
"s": 28708,
"text": "scp command in Linux with Examples"
}
] |
GATE | GATE CS 2020 | Question 45 - GeeksforGeeks | 26 May, 2021
Consider the following five disk five disk access requests of the form (request id, cylinder number) that are present in the disk scheduler queue at a given time.
(P, 155), (Q, 85), (R, 110), (S, 30), (T, 115)
Assume the head is positioned at cylinder 100. The scheduler follows Shortest Seek Time First scheduling to service the requests.
Which one of the following statements is FALSE ?(A) T is serviced before P(B) Q is serviced after S, but before T(C) The head reverses its direction of movement between servicing of Q and P(D) R is serviced before PAnswer: (B)Explanation: According to Shortest Seek Time First (SSTF) is a disk scheduling algorithm:
Therefore, option (B) is False.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65 | [
{
"code": null,
"e": 24075,
"s": 24047,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 24238,
"s": 24075,
"text": "Consider the following five disk five disk access requests of the form (request id, cylinder number) that are present in the disk scheduler queue at a given time."
},
{
"code": null,
"e": 24286,
"s": 24238,
"text": "(P, 155), (Q, 85), (R, 110), (S, 30), (T, 115) "
},
{
"code": null,
"e": 24416,
"s": 24286,
"text": "Assume the head is positioned at cylinder 100. The scheduler follows Shortest Seek Time First scheduling to service the requests."
},
{
"code": null,
"e": 24732,
"s": 24416,
"text": "Which one of the following statements is FALSE ?(A) T is serviced before P(B) Q is serviced after S, but before T(C) The head reverses its direction of movement between servicing of Q and P(D) R is serviced before PAnswer: (B)Explanation: According to Shortest Seek Time First (SSTF) is a disk scheduling algorithm:"
},
{
"code": null,
"e": 24785,
"s": 24732,
"text": "Therefore, option (B) is False.Quiz of this Question"
},
{
"code": null,
"e": 24790,
"s": 24785,
"text": "GATE"
},
{
"code": null,
"e": 24888,
"s": 24790,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24897,
"s": 24888,
"text": "Comments"
},
{
"code": null,
"e": 24910,
"s": 24897,
"text": "Old Comments"
},
{
"code": null,
"e": 24952,
"s": 24910,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 24994,
"s": 24952,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 25028,
"s": 24994,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 25061,
"s": 25028,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25103,
"s": 25061,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25157,
"s": 25103,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 25191,
"s": 25157,
"text": "GATE | GATE CS 2012 | Question 40"
},
{
"code": null,
"e": 25225,
"s": 25191,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 25267,
"s": 25225,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 42"
}
] |
Find if two rectangles overlap using C++. | We know that a rectangle can be represented using two coordinates, the top left corner, and the bottom right corner. Suppose there are two rectangles, we have to check whether these two overlap or not. There are four coordinate points (l1, r1) and (l2, r2).
l1 is the top-left corner of first rectangle
r1 is the bottom-right corner of the first rectangle
l2 is the top-left corner of second rectangle
r2 is the bottom-right corner of the second rectangle
We have assumed that the rectangles are parallel to the coordinate axes. To solve this, we have to check a few conditions.
One rectangle is above the top edge of another rectangle
One rectangle is on the left side of the left edge of another rectangle.
Live Demo
#include<iostream>
using namespace std;
class Point {
public:
int x, y;
};
bool isOverlapping(Point l1, Point r1, Point l2, Point r2) {
if (l1.x > r2.x || l2.x > r1.x)
return false;
if (l1.y < r2.y || l2.y < r1.y)
return false;
return true;
}
int main() {
Point l1 = {0, 10}, r1 = {10, 0};
Point l2 = {5, 5}, r2 = {15, 0};
if (isOverlapping(l1, r1, l2, r2))
cout << "Rectangles are Overlapping";
else
cout << "Rectangles are not Overlapping";
}
Rectangles are Overlapping | [
{
"code": null,
"e": 1320,
"s": 1062,
"text": "We know that a rectangle can be represented using two coordinates, the top left corner, and the bottom right corner. Suppose there are two rectangles, we have to check whether these two overlap or not. There are four coordinate points (l1, r1) and (l2, r2)."
},
{
"code": null,
"e": 1365,
"s": 1320,
"text": "l1 is the top-left corner of first rectangle"
},
{
"code": null,
"e": 1418,
"s": 1365,
"text": "r1 is the bottom-right corner of the first rectangle"
},
{
"code": null,
"e": 1464,
"s": 1418,
"text": "l2 is the top-left corner of second rectangle"
},
{
"code": null,
"e": 1518,
"s": 1464,
"text": "r2 is the bottom-right corner of the second rectangle"
},
{
"code": null,
"e": 1641,
"s": 1518,
"text": "We have assumed that the rectangles are parallel to the coordinate axes. To solve this, we have to check a few conditions."
},
{
"code": null,
"e": 1698,
"s": 1641,
"text": "One rectangle is above the top edge of another rectangle"
},
{
"code": null,
"e": 1771,
"s": 1698,
"text": "One rectangle is on the left side of the left edge of another rectangle."
},
{
"code": null,
"e": 1782,
"s": 1771,
"text": " Live Demo"
},
{
"code": null,
"e": 2278,
"s": 1782,
"text": "#include<iostream>\nusing namespace std;\nclass Point {\n public:\n int x, y;\n};\nbool isOverlapping(Point l1, Point r1, Point l2, Point r2) {\n if (l1.x > r2.x || l2.x > r1.x)\n return false;\n if (l1.y < r2.y || l2.y < r1.y)\n return false;\n return true;\n}\nint main() {\n Point l1 = {0, 10}, r1 = {10, 0};\n Point l2 = {5, 5}, r2 = {15, 0};\n if (isOverlapping(l1, r1, l2, r2))\n cout << \"Rectangles are Overlapping\";\n else\n cout << \"Rectangles are not Overlapping\";\n}"
},
{
"code": null,
"e": 2305,
"s": 2278,
"text": "Rectangles are Overlapping"
}
] |
VBScript StrComp Function | The StrComp Function returns an integer value after comparing the two given strings. It can return any of the three values -1, 0 or 1 based on the input strings to be compared.
If String 1 < String 2 then StrComp returns -1
If String 1 < String 2 then StrComp returns -1
If String 1 = String 2 then StrComp returns 0
If String 1 = String 2 then StrComp returns 0
If String 1 > String 2 then StrComp returns 1
If String 1 > String 2 then StrComp returns 1
StrComp(string1,string2[,compare])
String1, a Required Parameter. The first String expression.
String1, a Required Parameter. The first String expression.
String2, a Required Parameter. The second String expression.
String2, a Required Parameter. The second String expression.
Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below-mentioned values −
0 = vbBinaryCompare - Performs Binary Comparison(Default)
1 = vbTextCompare - Performs Text Comparison
Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below-mentioned values −
0 = vbBinaryCompare - Performs Binary Comparison(Default)
0 = vbBinaryCompare - Performs Binary Comparison(Default)
1 = vbTextCompare - Performs Text Comparison
1 = vbTextCompare - Performs Text Comparison
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
document.write("Line 1 :" & StrComp("Microsoft","Microsoft") & "<br />")
document.write("Line 2 :" &StrComp("Microsoft","MICROSOFT") & "<br />")
document.write("Line 3 :" &StrComp("Microsoft","MiCrOsOfT") & "<br />")
document.write("Line 4 :" &StrComp("Microsoft","MiCrOsOfT",1) & "<br />")
document.write("Line 5 :" &StrComp("Microsoft","MiCrOsOfT",0) & "<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 :0
Line 2 :1
Line 3 :1
Line 4 :0
Line 5 :1
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2257,
"s": 2080,
"text": "The StrComp Function returns an integer value after comparing the two given strings. It can return any of the three values -1, 0 or 1 based on the input strings to be compared."
},
{
"code": null,
"e": 2304,
"s": 2257,
"text": "If String 1 < String 2 then StrComp returns -1"
},
{
"code": null,
"e": 2351,
"s": 2304,
"text": "If String 1 < String 2 then StrComp returns -1"
},
{
"code": null,
"e": 2397,
"s": 2351,
"text": "If String 1 = String 2 then StrComp returns 0"
},
{
"code": null,
"e": 2443,
"s": 2397,
"text": "If String 1 = String 2 then StrComp returns 0"
},
{
"code": null,
"e": 2489,
"s": 2443,
"text": "If String 1 > String 2 then StrComp returns 1"
},
{
"code": null,
"e": 2535,
"s": 2489,
"text": "If String 1 > String 2 then StrComp returns 1"
},
{
"code": null,
"e": 2572,
"s": 2535,
"text": "StrComp(string1,string2[,compare]) \n"
},
{
"code": null,
"e": 2632,
"s": 2572,
"text": "String1, a Required Parameter. The first String expression."
},
{
"code": null,
"e": 2692,
"s": 2632,
"text": "String1, a Required Parameter. The first String expression."
},
{
"code": null,
"e": 2753,
"s": 2692,
"text": "String2, a Required Parameter. The second String expression."
},
{
"code": null,
"e": 2814,
"s": 2753,
"text": "String2, a Required Parameter. The second String expression."
},
{
"code": null,
"e": 3037,
"s": 2814,
"text": "Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below-mentioned values −\n\n0 = vbBinaryCompare - Performs Binary Comparison(Default)\n1 = vbTextCompare - Performs Text Comparison\n\n"
},
{
"code": null,
"e": 3154,
"s": 3037,
"text": "Compare, an Optional Parameter. Specifies the String Comparison to be used. It can take the below-mentioned values −"
},
{
"code": null,
"e": 3212,
"s": 3154,
"text": "0 = vbBinaryCompare - Performs Binary Comparison(Default)"
},
{
"code": null,
"e": 3270,
"s": 3212,
"text": "0 = vbBinaryCompare - Performs Binary Comparison(Default)"
},
{
"code": null,
"e": 3315,
"s": 3270,
"text": "1 = vbTextCompare - Performs Text Comparison"
},
{
"code": null,
"e": 3360,
"s": 3315,
"text": "1 = vbTextCompare - Performs Text Comparison"
},
{
"code": null,
"e": 3899,
"s": 3360,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n document.write(\"Line 1 :\" & StrComp(\"Microsoft\",\"Microsoft\") & \"<br />\")\n document.write(\"Line 2 :\" &StrComp(\"Microsoft\",\"MICROSOFT\") & \"<br />\")\n document.write(\"Line 3 :\" &StrComp(\"Microsoft\",\"MiCrOsOfT\") & \"<br />\")\n document.write(\"Line 4 :\" &StrComp(\"Microsoft\",\"MiCrOsOfT\",1) & \"<br />\")\n document.write(\"Line 5 :\" &StrComp(\"Microsoft\",\"MiCrOsOfT\",0) & \"<br />\")\n\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4020,
"s": 3899,
"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": 4072,
"s": 4020,
"text": "Line 1 :0\nLine 2 :1\nLine 3 :1\nLine 4 :0\nLine 5 :1 \n"
},
{
"code": null,
"e": 4105,
"s": 4072,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4122,
"s": 4105,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4129,
"s": 4122,
"text": " Print"
},
{
"code": null,
"e": 4140,
"s": 4129,
"text": " Add Notes"
}
] |
Python | Insert the string at the beginning of all items in a list - GeeksforGeeks | 20 Nov, 2019
Given a list, write a Python program to insert some string at the beginning of all items in that list.
Examples:
Input : list = [1, 2, 3, 4], str = 'Geek'
Output : list = ['Geek1', 'Geek2', 'Geek3', 'Geek4']
Input : list = ['A', 'B', 'C'], str = 'Team'
Output : list = ['TeamA', 'TeamB', 'TeamC']
There are multiple ways to insert the string at the beginning of all items in a list.
Approach #1 : Using list comprehensionList comprehension is an elegant way to define and create list. It can also be used to apply an expression to each element in a sequence. We can use format() function which allows multiple substitutions and value formatting.
# Python3 program to insert the string # at the beginning of all items in a listdef prepend(list, str): # Using format() str += '{0}' list = [str.format(i) for i in list] return(list) # Driver functionlist = [1, 2, 3, 4]str = 'Geek'print(prepend(list, str))
Output:
['Geek1', 'Geek2', 'Geek3', 'Geek4']
Another method in list comprehension is to use ‘%’ instead of format() function
# Using '% s'str += '% s'list = [str % i for i in list]
Approach #2 : Using in-built map() functionAnother approach is to use map() function. The function maps the beginning of all items in the list to the string.
# Python3 program to insert the string # at the beginning of all items in a listdef prepend(List, str): # Using format() str += '{0}' List = ((map(str.format, List))) return List # Driver functionlist = [1, 2, 3, 4]str = 'Geek'print(prepend(list, str))
Output:
['Geek1', 'Geek2', 'Geek3', 'Geek4']
ManasChhabra2
Python list-programs
python-list
python-string
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
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
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 24506,
"s": 24478,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 24609,
"s": 24506,
"text": "Given a list, write a Python program to insert some string at the beginning of all items in that list."
},
{
"code": null,
"e": 24619,
"s": 24609,
"text": "Examples:"
},
{
"code": null,
"e": 24805,
"s": 24619,
"text": "Input : list = [1, 2, 3, 4], str = 'Geek'\nOutput : list = ['Geek1', 'Geek2', 'Geek3', 'Geek4']\n\nInput : list = ['A', 'B', 'C'], str = 'Team'\nOutput : list = ['TeamA', 'TeamB', 'TeamC']\n"
},
{
"code": null,
"e": 24891,
"s": 24805,
"text": "There are multiple ways to insert the string at the beginning of all items in a list."
},
{
"code": null,
"e": 25154,
"s": 24891,
"text": "Approach #1 : Using list comprehensionList comprehension is an elegant way to define and create list. It can also be used to apply an expression to each element in a sequence. We can use format() function which allows multiple substitutions and value formatting."
},
{
"code": "# Python3 program to insert the string # at the beginning of all items in a listdef prepend(list, str): # Using format() str += '{0}' list = [str.format(i) for i in list] return(list) # Driver functionlist = [1, 2, 3, 4]str = 'Geek'print(prepend(list, str))",
"e": 25431,
"s": 25154,
"text": null
},
{
"code": null,
"e": 25439,
"s": 25431,
"text": "Output:"
},
{
"code": null,
"e": 25476,
"s": 25439,
"text": "['Geek1', 'Geek2', 'Geek3', 'Geek4']"
},
{
"code": null,
"e": 25556,
"s": 25476,
"text": "Another method in list comprehension is to use ‘%’ instead of format() function"
},
{
"code": "# Using '% s'str += '% s'list = [str % i for i in list]",
"e": 25613,
"s": 25556,
"text": null
},
{
"code": null,
"e": 25772,
"s": 25613,
"text": " Approach #2 : Using in-built map() functionAnother approach is to use map() function. The function maps the beginning of all items in the list to the string."
},
{
"code": "# Python3 program to insert the string # at the beginning of all items in a listdef prepend(List, str): # Using format() str += '{0}' List = ((map(str.format, List))) return List # Driver functionlist = [1, 2, 3, 4]str = 'Geek'print(prepend(list, str))",
"e": 26046,
"s": 25772,
"text": null
},
{
"code": null,
"e": 26054,
"s": 26046,
"text": "Output:"
},
{
"code": null,
"e": 26091,
"s": 26054,
"text": "['Geek1', 'Geek2', 'Geek3', 'Geek4']"
},
{
"code": null,
"e": 26105,
"s": 26091,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 26126,
"s": 26105,
"text": "Python list-programs"
},
{
"code": null,
"e": 26138,
"s": 26126,
"text": "python-list"
},
{
"code": null,
"e": 26152,
"s": 26138,
"text": "python-string"
},
{
"code": null,
"e": 26159,
"s": 26152,
"text": "Python"
},
{
"code": null,
"e": 26171,
"s": 26159,
"text": "python-list"
},
{
"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": 26309,
"s": 26291,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26344,
"s": 26309,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26376,
"s": 26344,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26418,
"s": 26376,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26444,
"s": 26418,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26487,
"s": 26444,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26524,
"s": 26487,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26568,
"s": 26524,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26597,
"s": 26568,
"text": "*args and **kwargs in Python"
}
] |
Add a custom border to certain cells in a Matplotlib / Seaborn plot | To add a custom border to certain cells in a Matplotlib/Seaborn plot.
Set the figure size and adjust the padding between and around the subplots.
Create a dataframe with some columns.
Plot a matrix dataset as a hierarchically-clustered heatmap.
Get heatmap axis as a subplot arrangement.
To add a custom border to certain cells in Matplotlib, we can intialize a variable, border_color.
Using custom bordder color, add a rectangle patch on the heatmap axes.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({"col1": [1, 4, 2, 3, 5], "col2": [3, 4, 1, 5, 2]})
g = sns.clustermap(df, figsize=(7.50, 3.50))
ax = g.ax_heatmap
border_color = "yellow"
ax.add_patch(plt.Rectangle((1, 2), 2, 1, fill=False,
edgecolor=border_color, lw=5))
plt.show() | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "To add a custom border to certain cells in a Matplotlib/Seaborn plot."
},
{
"code": null,
"e": 1208,
"s": 1132,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1246,
"s": 1208,
"text": "Create a dataframe with some columns."
},
{
"code": null,
"e": 1307,
"s": 1246,
"text": "Plot a matrix dataset as a hierarchically-clustered heatmap."
},
{
"code": null,
"e": 1350,
"s": 1307,
"text": "Get heatmap axis as a subplot arrangement."
},
{
"code": null,
"e": 1448,
"s": 1350,
"text": "To add a custom border to certain cells in Matplotlib, we can intialize a variable, border_color."
},
{
"code": null,
"e": 1519,
"s": 1448,
"text": "Using custom bordder color, add a rectangle patch on the heatmap axes."
},
{
"code": null,
"e": 1561,
"s": 1519,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1979,
"s": 1561,
"text": "import pandas as pd\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndf = pd.DataFrame({\"col1\": [1, 4, 2, 3, 5], \"col2\": [3, 4, 1, 5, 2]})\ng = sns.clustermap(df, figsize=(7.50, 3.50))\nax = g.ax_heatmap\nborder_color = \"yellow\"\nax.add_patch(plt.Rectangle((1, 2), 2, 1, fill=False,\nedgecolor=border_color, lw=5))\nplt.show()"
}
] |
How can we use SET statement to assign a SELECT result to a MySQL user variable? | For using the SET statement to assign a SELECT result to a user variable we need to write the SELECT statement as a subquery within parentheses. The condition is that the SELECT statement must have to return a single value. To make it understand we are using the data from ‘Tender’ table which is as follows −
mysql> select * from Tender;
+----+---------------+--------------+
| Sr | CompanyName | Tender_value |
+----+---------------+--------------+
| 1 | Abc Corp. | 250.369003 |
| 2 | Khaitan Corp. | 265.588989 |
| 3 | Singla group. | 220.255997 |
| 4 | Hero group. | 221.253006 |
| 5 | Honda group | 225.292266 |
+----+---------------+--------------+
5 rows in set (0.04 sec)
Now, in the following query, we are setting the maximum value, after rounding it up to 2 decimal point, of tender_value to the variable @Val_Max.
mysql> SET @Val_Max = (SELECT ROUND(MAX(tender_value),2) from tender);
Query OK, 0 rows affected (0.00 sec)
mysql> Select @Val_Max;
+----------+
| @Val_Max |
+----------+
| 265.59 |
+----------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1372,
"s": 1062,
"text": "For using the SET statement to assign a SELECT result to a user variable we need to write the SELECT statement as a subquery within parentheses. The condition is that the SELECT statement must have to return a single value. To make it understand we are using the data from ‘Tender’ table which is as follows −"
},
{
"code": null,
"e": 1768,
"s": 1372,
"text": "mysql> select * from Tender;\n+----+---------------+--------------+\n| Sr | CompanyName | Tender_value |\n+----+---------------+--------------+\n| 1 | Abc Corp. | 250.369003 |\n| 2 | Khaitan Corp. | 265.588989 |\n| 3 | Singla group. | 220.255997 |\n| 4 | Hero group. | 221.253006 |\n| 5 | Honda group | 225.292266 |\n+----+---------------+--------------+\n5 rows in set (0.04 sec)"
},
{
"code": null,
"e": 1914,
"s": 1768,
"text": "Now, in the following query, we are setting the maximum value, after rounding it up to 2 decimal point, of tender_value to the variable @Val_Max."
},
{
"code": null,
"e": 2136,
"s": 1914,
"text": "mysql> SET @Val_Max = (SELECT ROUND(MAX(tender_value),2) from tender);\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select @Val_Max;\n+----------+\n| @Val_Max |\n+----------+\n| 265.59 |\n+----------+\n1 row in set (0.00 sec)"
}
] |
Python String | rpartition() - GeeksforGeeks | 17 Jun, 2021
rpartition() function in Python split the given string into three parts. rpartition() start looking for separator from right side, till the separator is found and return a tuple which contains part of the string before separator, argument of the string and the part after the separator.
Syntax :
string.rpartition(separator)
Parameters :
separator - separates the string at the first occurrence of it.
Return Value :
It returns the part the string before the separator, separator parameter itself, and the part after the separator if the separator parameter is found in the string.It returns two empty strings, followed by the given string if the separator is not found in the string.
It returns the part the string before the separator, separator parameter itself, and the part after the separator if the separator parameter is found in the string.
It returns two empty strings, followed by the given string if the separator is not found in the string.
Exception :
If separator argument is not supplied, it will throw TypeError.
Code #1 :
Python3
# Python3 code explaining rpartition() # String need to splitstring1 = "Geeks@for@Geeks@is@for@geeks" string2 = "Ram is not eating but Mohan is eating" # Here '@' is a separatorprint(string1.rpartition('@')) # Here 'is' is separatorprint(string2.rpartition('is'))
Output :
('Geeks@for@Geeks@is@for', '@', 'geeks')
('Ram is not eating but Mohan ', 'is', ' eating')
Code #2 :
Python3
# Python3 code explaining rpartition() # String need to splitstring = "Sita is going to school" # Here 'not' is a separator which is not# present in the given stringprint(string.rpartition('not'))
Output :
('', '', 'Sita is going to school')
Code #3 : TypeError
Python3
# Python3 code explaining TypeError# in rpartition() str = "Bruce Waine is Batman" # Nothing is passed as separatorprint(str.rpartition())
Output :
Traceback (most recent call last):
File "/home/e207c003f42055cf9697001645999d69.py", line 7, in
print(str.rpartition())
TypeError: rpartition() takes exactly one argument (0 given)
Code #4 : ValueError
Python3
# Python3 code explaining ValueError# in rpartition() str = "Bruce Waine is Batman" # Nothing is passed as separatorprint(str.rpartition(""))
Output :
Traceback (most recent call last):
File "/home/c8d9719625793f2c8948542159719007.py", line 7, in
print(str.rpartition(""))
ValueError: empty separator
anikakapoor
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 25027,
"s": 24999,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 25314,
"s": 25027,
"text": "rpartition() function in Python split the given string into three parts. rpartition() start looking for separator from right side, till the separator is found and return a tuple which contains part of the string before separator, argument of the string and the part after the separator."
},
{
"code": null,
"e": 25324,
"s": 25314,
"text": "Syntax : "
},
{
"code": null,
"e": 25353,
"s": 25324,
"text": "string.rpartition(separator)"
},
{
"code": null,
"e": 25368,
"s": 25353,
"text": "Parameters : "
},
{
"code": null,
"e": 25433,
"s": 25368,
"text": "separator - separates the string at the first occurrence of it."
},
{
"code": null,
"e": 25450,
"s": 25433,
"text": "Return Value : "
},
{
"code": null,
"e": 25718,
"s": 25450,
"text": "It returns the part the string before the separator, separator parameter itself, and the part after the separator if the separator parameter is found in the string.It returns two empty strings, followed by the given string if the separator is not found in the string."
},
{
"code": null,
"e": 25883,
"s": 25718,
"text": "It returns the part the string before the separator, separator parameter itself, and the part after the separator if the separator parameter is found in the string."
},
{
"code": null,
"e": 25987,
"s": 25883,
"text": "It returns two empty strings, followed by the given string if the separator is not found in the string."
},
{
"code": null,
"e": 26001,
"s": 25987,
"text": "Exception : "
},
{
"code": null,
"e": 26065,
"s": 26001,
"text": "If separator argument is not supplied, it will throw TypeError."
},
{
"code": null,
"e": 26077,
"s": 26065,
"text": "Code #1 : "
},
{
"code": null,
"e": 26085,
"s": 26077,
"text": "Python3"
},
{
"code": "# Python3 code explaining rpartition() # String need to splitstring1 = \"Geeks@for@Geeks@is@for@geeks\" string2 = \"Ram is not eating but Mohan is eating\" # Here '@' is a separatorprint(string1.rpartition('@')) # Here 'is' is separatorprint(string2.rpartition('is'))",
"e": 26349,
"s": 26085,
"text": null
},
{
"code": null,
"e": 26359,
"s": 26349,
"text": "Output : "
},
{
"code": null,
"e": 26450,
"s": 26359,
"text": "('Geeks@for@Geeks@is@for', '@', 'geeks')\n('Ram is not eating but Mohan ', 'is', ' eating')"
},
{
"code": null,
"e": 26462,
"s": 26450,
"text": "Code #2 : "
},
{
"code": null,
"e": 26470,
"s": 26462,
"text": "Python3"
},
{
"code": "# Python3 code explaining rpartition() # String need to splitstring = \"Sita is going to school\" # Here 'not' is a separator which is not# present in the given stringprint(string.rpartition('not'))",
"e": 26667,
"s": 26470,
"text": null
},
{
"code": null,
"e": 26677,
"s": 26667,
"text": "Output : "
},
{
"code": null,
"e": 26713,
"s": 26677,
"text": "('', '', 'Sita is going to school')"
},
{
"code": null,
"e": 26735,
"s": 26713,
"text": "Code #3 : TypeError "
},
{
"code": null,
"e": 26743,
"s": 26735,
"text": "Python3"
},
{
"code": "# Python3 code explaining TypeError# in rpartition() str = \"Bruce Waine is Batman\" # Nothing is passed as separatorprint(str.rpartition())",
"e": 26882,
"s": 26743,
"text": null
},
{
"code": null,
"e": 26892,
"s": 26882,
"text": "Output : "
},
{
"code": null,
"e": 27080,
"s": 26892,
"text": "Traceback (most recent call last):\n File \"/home/e207c003f42055cf9697001645999d69.py\", line 7, in \n print(str.rpartition())\nTypeError: rpartition() takes exactly one argument (0 given)"
},
{
"code": null,
"e": 27103,
"s": 27080,
"text": "Code #4 : ValueError "
},
{
"code": null,
"e": 27111,
"s": 27103,
"text": "Python3"
},
{
"code": "# Python3 code explaining ValueError# in rpartition() str = \"Bruce Waine is Batman\" # Nothing is passed as separatorprint(str.rpartition(\"\"))",
"e": 27253,
"s": 27111,
"text": null
},
{
"code": null,
"e": 27263,
"s": 27253,
"text": "Output : "
},
{
"code": null,
"e": 27420,
"s": 27263,
"text": "Traceback (most recent call last):\n File \"/home/c8d9719625793f2c8948542159719007.py\", line 7, in \n print(str.rpartition(\"\"))\nValueError: empty separator"
},
{
"code": null,
"e": 27434,
"s": 27422,
"text": "anikakapoor"
},
{
"code": null,
"e": 27460,
"s": 27434,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 27474,
"s": 27460,
"text": "python-string"
},
{
"code": null,
"e": 27481,
"s": 27474,
"text": "Python"
},
{
"code": null,
"e": 27579,
"s": 27481,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27607,
"s": 27579,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27657,
"s": 27607,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27679,
"s": 27657,
"text": "Python map() function"
},
{
"code": null,
"e": 27723,
"s": 27679,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 27741,
"s": 27723,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27764,
"s": 27741,
"text": "Taking input in Python"
},
{
"code": null,
"e": 27799,
"s": 27764,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27831,
"s": 27799,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27853,
"s": 27831,
"text": "Enumerate() in Python"
}
] |
AngularJS | ng-init Directive - GeeksforGeeks | 28 Mar, 2019
The ng-init directive is used to initialize an AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables.The ng-init directive defines initial values and variables for an AngularJS application.
Syntax:
<element ng-init = "expression">
...
</element>
Example: In this example, we initialize an array of string.
<html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/ angular.min.js"></script> <head> <title>AngularJS ng-init Directive</title> </head> <body> <h1 style = "color:green">GeeksforGeeks <h2>ng-init directive</h2> <div ng-app="" ng-init="sort=['quick sort', 'merge sort', 'bubble sort']"> Sorting techniques: <ul> <li>{{ sort[0] }} </li> <li>{{ sort[1] }} </li> <li>{{ sort[2] }} </li> </ul> </div> </body></html>
Output:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25670,
"s": 25642,
"text": "\n28 Mar, 2019"
},
{
"code": null,
"e": 25928,
"s": 25670,
"text": "The ng-init directive is used to initialize an AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables.The ng-init directive defines initial values and variables for an AngularJS application."
},
{
"code": null,
"e": 25936,
"s": 25928,
"text": "Syntax:"
},
{
"code": null,
"e": 25988,
"s": 25936,
"text": "<element ng-init = \"expression\">\n ...\n</element>\n"
},
{
"code": null,
"e": 26048,
"s": 25988,
"text": "Example: In this example, we initialize an array of string."
},
{
"code": "<html> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/ angular.min.js\"></script> <head> <title>AngularJS ng-init Directive</title> </head> <body> <h1 style = \"color:green\">GeeksforGeeks <h2>ng-init directive</h2> <div ng-app=\"\" ng-init=\"sort=['quick sort', 'merge sort', 'bubble sort']\"> Sorting techniques: <ul> <li>{{ sort[0] }} </li> <li>{{ sort[1] }} </li> <li>{{ sort[2] }} </li> </ul> </div> </body></html>",
"e": 26626,
"s": 26048,
"text": null
},
{
"code": null,
"e": 26634,
"s": 26626,
"text": "Output:"
},
{
"code": null,
"e": 26655,
"s": 26634,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 26665,
"s": 26655,
"text": "AngularJS"
},
{
"code": null,
"e": 26682,
"s": 26665,
"text": "Web Technologies"
},
{
"code": null,
"e": 26780,
"s": 26682,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26815,
"s": 26780,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 26846,
"s": 26815,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 26881,
"s": 26846,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 26926,
"s": 26881,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 26968,
"s": 26926,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 27008,
"s": 26968,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27041,
"s": 27008,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27086,
"s": 27041,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27129,
"s": 27086,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Dates in Power BI. Working with Dates | by Peter Hui | Towards Data Science | In Power BI, the highly recommended approach from many experts is to create a date table when working with dates. I’ve worked without it and it’s definitely not a good idea. It gave me a headache and needless suffering.
The date table is important! Here are 3 reasons why.
Date Calculations — DAX needs a date table to make date calculations! Those SAMEPERIODLASTYEAR, LASTQUARTER or DATESBETWEEN type calculations wouldn’t work without it. Maybe it will, but it will just be very convoluted. Why hurt your head?
Weekends/Holidays — if you need to exclude holidays in your calculations, and you are doing it without a date table? It would be very difficult.
Different Granularity — Sometimes, you need to put together a comparison between a table that is based on month, while another is based on days. You need something to join them so you can report adequately.
In this article, I’ll show you how to create a calendar table in M (Power Query) and in DAX.
Let’s get started!
Let’s open Power Query (if you don’t know where to open it, take a look at the basics in this article.)
The table I want is a list of all the dates of a fiscal year, with days of the week named, month, and week number... also if possible, the holidays as well. We just want to flag those.
Something like the below would be good.
To do this in Power Query, we need to create a new query.
To create a new query — Right-click on the query pane> Select New Blank Query > Select Advance Editor (button on the top)
Once that is done — plug in this function into the advance editor.
Source = List.Dates(#date(2019,04,01),365,#duration(1,0,0,0))
Okay, what the heck does that mean?
It means I am using a List.Dates function, creating a date table from April 1, 2019, in the duration of 365 days.
Once you input this, Power Query will give us a list of all dates from 4/1/2020 to 365 days after.
Now it comes in a List format, so we have to convert it to a table in order to use our other functions. You can Select the column > Right-Click > To Table. It’ll convert it to a table for you.
Now let’s add in some other functions.
There are many other functions you can browse here. You can use these functions by taking the name of the function listed, and referring it to your date column.
For example, if I am interested in adding in the name of the day of the week, I can type in Date.DayOfWeekName([Date]). Also if I am interested in just the number, the actual day of the week, I can use Date.DayofWeek([Date]).
Many functions are listed in the link, it’s a lot to experiment, so I have used only the ones I use the most. I don’t know them all by heart.
At the end, you will end up with a table like below.
Now it is quite tedious to type all this for your PBI reports, so I have created a simple script for you. You may have to adjust the data types when you load it into PBI.
Here is the script for a basic date table — copy the below Right Click >Select New Blank Query > Select Advance Editor > Paste the below
Add in the 4 parameters according to your needs and you are good to go.
(Year as number, Month as number, Days as number, Duration as number) =>let Source = List.Dates(#date(Year,Month,Days),Duration,#duration(1,0,0,0)), #"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error), #"Added Custom" = Table.AddColumn(#"Converted to Table", "Custom", each Date.DayOfWeek([Column1])), #"Renamed Columns5" = Table.RenameColumns(#"Added Custom",{{"Column1", "Date"}}), #"Added Custom1" = Table.AddColumn(#"Renamed Columns5", "Custom.1", each Date.DayOfWeekName([Date])), #"Renamed Columns" = Table.RenameColumns(#"Added Custom1",{{"Custom", "Day of Week"}, {"Custom.1", "Day of Week Name"}}), #"Added Custom2" = Table.AddColumn(#"Renamed Columns", "Custom", each Date.DayOfYear([Date])), #"Renamed Columns1" = Table.RenameColumns(#"Added Custom2",{{"Custom", "Day of Year"}}), #"Added Custom3" = Table.AddColumn(#"Renamed Columns1", "Custom", each Date.Month([Date])), #"Renamed Columns2" = Table.RenameColumns(#"Added Custom3",{{"Custom", "Month"}}), #"Added Custom4" = Table.AddColumn(#"Renamed Columns2", "Custom", each Date.MonthName([Date])), #"Renamed Columns3" = Table.RenameColumns(#"Added Custom4",{{"Custom", "Month Name"}})in #"Renamed Columns3"
Once entered, Power Query will bring you a date table. Now you can just enter the perimeters according to your needs.
When loaded into the report, you just have to mark your table as a date table. Marking your table as a date table is explained below.
You will then have a date table.
The process to create a date table in DAX is very similar.
You have to select Table Tools > New Table in Power BI report view, once that is done, you can populate your table by this function.
Table = CALENDAR(DATE(2019,04,01),DATE(2020,03,31))
Once you use this function to create a new table , you will get the following.
Now, mark it as a date table by going to Table Tools > Mark as Date Table
Power BI will ask you to select the date column. Once selected it will verify the table as a date table.
With that being done, you can add in the other columns using the FORMAT function. Here I have added in FORMAT(Table[Date],”DD”) and others, I’ve selected a few common ones I have used, but you can add your own format style as well, check out the last column below.
There are of course other formats as well. You can get more info here
You now know how to create a simple date table using both DAX and M. Now what’s the point of all this? This is so you can connect your table (likely a fact table) with your date table.
Something like this will likely help you.
You can now create a many to 1 join between the fact table and the date table.
Since your dates are now reflected in a date table, you can now do calculations like the below.
My personal favorite.
Getting the Total Sales of between two dates.
Now these DAX date calculations only work if you have a date table and if it’s connected this way. Perhaps your fact table is small and you can get away with having a date column within your fact table, but it just won’t be pretty.
There are many many cool DAX date-time intelligence functions that are here.
I get this too. “It’s great that you’ve shown me how to build a date table in DAX and in M and a couple of measures using time intelligence but I can’t even get started because my date column in my fact table is screwed up to begin with!”
Here is what you can do — and it works almost all the time for me. Hopefully, your table is not screwed up to a point where the months and days are reversed row by row.. that may be another article in itself.
I suggest using the “column by example” in Power Query. The “AI” in Power Query over here. I wasn’t able to use the Date column here because it is in Text and even when converted to date, it throws an Error.
Start populating the date column yourself and the AI will pick up what you are doing and create the new date column for you.
Notice how it picks up what you are doing when you are adding the slash?
It gets what you are trying to do!
Now you can do your join to the Date table.
Hope you’ve enjoyed this article!
Stay encouraged, stay safe and good luck with your data journey! | [
{
"code": null,
"e": 391,
"s": 171,
"text": "In Power BI, the highly recommended approach from many experts is to create a date table when working with dates. I’ve worked without it and it’s definitely not a good idea. It gave me a headache and needless suffering."
},
{
"code": null,
"e": 444,
"s": 391,
"text": "The date table is important! Here are 3 reasons why."
},
{
"code": null,
"e": 684,
"s": 444,
"text": "Date Calculations — DAX needs a date table to make date calculations! Those SAMEPERIODLASTYEAR, LASTQUARTER or DATESBETWEEN type calculations wouldn’t work without it. Maybe it will, but it will just be very convoluted. Why hurt your head?"
},
{
"code": null,
"e": 829,
"s": 684,
"text": "Weekends/Holidays — if you need to exclude holidays in your calculations, and you are doing it without a date table? It would be very difficult."
},
{
"code": null,
"e": 1036,
"s": 829,
"text": "Different Granularity — Sometimes, you need to put together a comparison between a table that is based on month, while another is based on days. You need something to join them so you can report adequately."
},
{
"code": null,
"e": 1129,
"s": 1036,
"text": "In this article, I’ll show you how to create a calendar table in M (Power Query) and in DAX."
},
{
"code": null,
"e": 1148,
"s": 1129,
"text": "Let’s get started!"
},
{
"code": null,
"e": 1252,
"s": 1148,
"text": "Let’s open Power Query (if you don’t know where to open it, take a look at the basics in this article.)"
},
{
"code": null,
"e": 1437,
"s": 1252,
"text": "The table I want is a list of all the dates of a fiscal year, with days of the week named, month, and week number... also if possible, the holidays as well. We just want to flag those."
},
{
"code": null,
"e": 1477,
"s": 1437,
"text": "Something like the below would be good."
},
{
"code": null,
"e": 1535,
"s": 1477,
"text": "To do this in Power Query, we need to create a new query."
},
{
"code": null,
"e": 1657,
"s": 1535,
"text": "To create a new query — Right-click on the query pane> Select New Blank Query > Select Advance Editor (button on the top)"
},
{
"code": null,
"e": 1724,
"s": 1657,
"text": "Once that is done — plug in this function into the advance editor."
},
{
"code": null,
"e": 1786,
"s": 1724,
"text": "Source = List.Dates(#date(2019,04,01),365,#duration(1,0,0,0))"
},
{
"code": null,
"e": 1822,
"s": 1786,
"text": "Okay, what the heck does that mean?"
},
{
"code": null,
"e": 1936,
"s": 1822,
"text": "It means I am using a List.Dates function, creating a date table from April 1, 2019, in the duration of 365 days."
},
{
"code": null,
"e": 2035,
"s": 1936,
"text": "Once you input this, Power Query will give us a list of all dates from 4/1/2020 to 365 days after."
},
{
"code": null,
"e": 2228,
"s": 2035,
"text": "Now it comes in a List format, so we have to convert it to a table in order to use our other functions. You can Select the column > Right-Click > To Table. It’ll convert it to a table for you."
},
{
"code": null,
"e": 2267,
"s": 2228,
"text": "Now let’s add in some other functions."
},
{
"code": null,
"e": 2428,
"s": 2267,
"text": "There are many other functions you can browse here. You can use these functions by taking the name of the function listed, and referring it to your date column."
},
{
"code": null,
"e": 2654,
"s": 2428,
"text": "For example, if I am interested in adding in the name of the day of the week, I can type in Date.DayOfWeekName([Date]). Also if I am interested in just the number, the actual day of the week, I can use Date.DayofWeek([Date])."
},
{
"code": null,
"e": 2796,
"s": 2654,
"text": "Many functions are listed in the link, it’s a lot to experiment, so I have used only the ones I use the most. I don’t know them all by heart."
},
{
"code": null,
"e": 2849,
"s": 2796,
"text": "At the end, you will end up with a table like below."
},
{
"code": null,
"e": 3020,
"s": 2849,
"text": "Now it is quite tedious to type all this for your PBI reports, so I have created a simple script for you. You may have to adjust the data types when you load it into PBI."
},
{
"code": null,
"e": 3157,
"s": 3020,
"text": "Here is the script for a basic date table — copy the below Right Click >Select New Blank Query > Select Advance Editor > Paste the below"
},
{
"code": null,
"e": 3229,
"s": 3157,
"text": "Add in the 4 parameters according to your needs and you are good to go."
},
{
"code": null,
"e": 4493,
"s": 3229,
"text": "(Year as number, Month as number, Days as number, Duration as number) =>let Source = List.Dates(#date(Year,Month,Days),Duration,#duration(1,0,0,0)), #\"Converted to Table\" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error), #\"Added Custom\" = Table.AddColumn(#\"Converted to Table\", \"Custom\", each Date.DayOfWeek([Column1])), #\"Renamed Columns5\" = Table.RenameColumns(#\"Added Custom\",{{\"Column1\", \"Date\"}}), #\"Added Custom1\" = Table.AddColumn(#\"Renamed Columns5\", \"Custom.1\", each Date.DayOfWeekName([Date])), #\"Renamed Columns\" = Table.RenameColumns(#\"Added Custom1\",{{\"Custom\", \"Day of Week\"}, {\"Custom.1\", \"Day of Week Name\"}}), #\"Added Custom2\" = Table.AddColumn(#\"Renamed Columns\", \"Custom\", each Date.DayOfYear([Date])), #\"Renamed Columns1\" = Table.RenameColumns(#\"Added Custom2\",{{\"Custom\", \"Day of Year\"}}), #\"Added Custom3\" = Table.AddColumn(#\"Renamed Columns1\", \"Custom\", each Date.Month([Date])), #\"Renamed Columns2\" = Table.RenameColumns(#\"Added Custom3\",{{\"Custom\", \"Month\"}}), #\"Added Custom4\" = Table.AddColumn(#\"Renamed Columns2\", \"Custom\", each Date.MonthName([Date])), #\"Renamed Columns3\" = Table.RenameColumns(#\"Added Custom4\",{{\"Custom\", \"Month Name\"}})in #\"Renamed Columns3\""
},
{
"code": null,
"e": 4611,
"s": 4493,
"text": "Once entered, Power Query will bring you a date table. Now you can just enter the perimeters according to your needs."
},
{
"code": null,
"e": 4745,
"s": 4611,
"text": "When loaded into the report, you just have to mark your table as a date table. Marking your table as a date table is explained below."
},
{
"code": null,
"e": 4778,
"s": 4745,
"text": "You will then have a date table."
},
{
"code": null,
"e": 4837,
"s": 4778,
"text": "The process to create a date table in DAX is very similar."
},
{
"code": null,
"e": 4970,
"s": 4837,
"text": "You have to select Table Tools > New Table in Power BI report view, once that is done, you can populate your table by this function."
},
{
"code": null,
"e": 5022,
"s": 4970,
"text": "Table = CALENDAR(DATE(2019,04,01),DATE(2020,03,31))"
},
{
"code": null,
"e": 5101,
"s": 5022,
"text": "Once you use this function to create a new table , you will get the following."
},
{
"code": null,
"e": 5175,
"s": 5101,
"text": "Now, mark it as a date table by going to Table Tools > Mark as Date Table"
},
{
"code": null,
"e": 5280,
"s": 5175,
"text": "Power BI will ask you to select the date column. Once selected it will verify the table as a date table."
},
{
"code": null,
"e": 5545,
"s": 5280,
"text": "With that being done, you can add in the other columns using the FORMAT function. Here I have added in FORMAT(Table[Date],”DD”) and others, I’ve selected a few common ones I have used, but you can add your own format style as well, check out the last column below."
},
{
"code": null,
"e": 5615,
"s": 5545,
"text": "There are of course other formats as well. You can get more info here"
},
{
"code": null,
"e": 5800,
"s": 5615,
"text": "You now know how to create a simple date table using both DAX and M. Now what’s the point of all this? This is so you can connect your table (likely a fact table) with your date table."
},
{
"code": null,
"e": 5842,
"s": 5800,
"text": "Something like this will likely help you."
},
{
"code": null,
"e": 5921,
"s": 5842,
"text": "You can now create a many to 1 join between the fact table and the date table."
},
{
"code": null,
"e": 6017,
"s": 5921,
"text": "Since your dates are now reflected in a date table, you can now do calculations like the below."
},
{
"code": null,
"e": 6039,
"s": 6017,
"text": "My personal favorite."
},
{
"code": null,
"e": 6085,
"s": 6039,
"text": "Getting the Total Sales of between two dates."
},
{
"code": null,
"e": 6317,
"s": 6085,
"text": "Now these DAX date calculations only work if you have a date table and if it’s connected this way. Perhaps your fact table is small and you can get away with having a date column within your fact table, but it just won’t be pretty."
},
{
"code": null,
"e": 6394,
"s": 6317,
"text": "There are many many cool DAX date-time intelligence functions that are here."
},
{
"code": null,
"e": 6633,
"s": 6394,
"text": "I get this too. “It’s great that you’ve shown me how to build a date table in DAX and in M and a couple of measures using time intelligence but I can’t even get started because my date column in my fact table is screwed up to begin with!”"
},
{
"code": null,
"e": 6842,
"s": 6633,
"text": "Here is what you can do — and it works almost all the time for me. Hopefully, your table is not screwed up to a point where the months and days are reversed row by row.. that may be another article in itself."
},
{
"code": null,
"e": 7050,
"s": 6842,
"text": "I suggest using the “column by example” in Power Query. The “AI” in Power Query over here. I wasn’t able to use the Date column here because it is in Text and even when converted to date, it throws an Error."
},
{
"code": null,
"e": 7175,
"s": 7050,
"text": "Start populating the date column yourself and the AI will pick up what you are doing and create the new date column for you."
},
{
"code": null,
"e": 7248,
"s": 7175,
"text": "Notice how it picks up what you are doing when you are adding the slash?"
},
{
"code": null,
"e": 7283,
"s": 7248,
"text": "It gets what you are trying to do!"
},
{
"code": null,
"e": 7327,
"s": 7283,
"text": "Now you can do your join to the Date table."
},
{
"code": null,
"e": 7361,
"s": 7327,
"text": "Hope you’ve enjoyed this article!"
}
] |
Hypothesis testing, a simple illustration of the superiority of the Bayesian framework | by Alain Tanguy | Towards Data Science | Usually hypothesis testing is not the first topic that comes to mind when we talk about bayesianism. The current trend is indeed more about incorporating this approach to Machine Learning models, and less about reviewing old-fashion statistics.
Nevertheless, more and more studies1 reveal the extent of the failure of so many reasearch papers that can be attributed to the misunderstanding/mis-use of “elementary” statistic methods. Given the extent of this phenomenom, it is quite obvious that such a is not the result of scientists personal lack of serious in that regard, but more of a global systemic anomaly which has been going on for quite a long time now. In light of this, it seems that more intuitive and easy to interpret methods should be considered.
Misconceptions over what p-values really lie at the root of this situation, or at least embody this reality the most. Most data-scientists are nowadays well educated when it comes to Machine learning, to the detriment of even the most basic statistic concepts ; hypothesis testing is among those.
We are now going to explore one of the simplest test a statistician may have to run, and from there see how to build a bayesian approach, that allow both a simple and forthright conclusion.
We’ll consider one of the simplest experiments there is in order not to lose sight of the point we want to make with unnecessary convolutions: Coin-flipping. The problem is defined this way:
A coin can be flipped a limited amount of times.
Our objective is to find if this coin is fair or not. in other words, we want to know how likely is our hypothesis (H0) “the coin is fair” to be false.
Pretty simple right?
The design of the experiment should be made considering the statistical method that will be used to answer our question. A student t-test appears as an obvious choice for our hypothesis testing. We will compare the mean of our sample to the value 0.5.
Good practice wants us to calculate the statistical power when designing our study in order to estimate the appropriate sample size, or at to least tell us about the limitations of our study if sample size is already fixed (it is commonly required to have at least a power of 0.8)
The power of a binary hypothesis test is the probability that the test rejects the null hypothesis (H0) when a specific alternative hypothesis (H1) is true.
In other words, the power of the test is the probability of getting a p-value under a specified threshold when the coin is actually unfair.
For convenience, we will only consider an alternative hypothesis (H1) “the coin follows a Bernoulli law of parameter p = 0.4”, which will allow us to easily compute the power of our test.
A look at the ROC curve of this test will help us understand what is going on. For a given significance level α, we can derive both the True and False Positive Rates, analytically or from simulation; or in other words, the statistical Power of the test and the significance level itself.
Usually α= 0.05 is the limit accepted, and for this threshold a minimum amount of 192 flips is required to reach our objective (and since flipping coins is not the 1st thing that comes to mind when one thinks about entertaining activities, we will limit ourselves to flipping this coin 192 times!).
Here comes our problem now. Assume we found that the coin is unfair with a p-value = 0.01, what can we conclude now?
Is there a 1% chance that the Null hypothesis is True?
Are we 99% sure that our coin is unfair?
None of these as you probably have already concluded. Actually, at this point, there is no way to give a probability of our coin being unfair... Quite annoying, especially given our original question: How likely is our coin to be unfair? The only conclusion we can draw is, had the coin been fair, we would only have a probability of 0.01 to observe such extreme results.
In fact Bayes theorem gives us a way to compute this value, but we need more information: priors. With H0 = “coin is unfair”, H1= “coin is fair”, and S = “test succesful with p-value < 0.05”, we have:
P(H0 | S) = P(S | H0) * P(H0) / (P(S | H0) * P(H0) + P(S | H1) * P(H1))
Initially assuming our coin more likely to be fair, we set P(H1) = 0.9 and P(H0) = 0.1. Thus we have
P(H0 | S) = 0.8 * 0.1 / (0.8 * 0.1 + 0.05 * 0.9)
P(H0 | S) = 0.64
So only 64% chance for our coin to be unfair even if our test came positive. Quite far from the 95% we would have hoped for... Yet this probability carries much more insights than a simple p-value, and luckily we can go further. This was just a first step into the bayesian world, and as we are going to see now there is much more to unfold to improve our test!
For this part, we are going to use the PyMC3 library for python, allowing us to easily build Bayesian nonparametric models.
We model the sampling of an unfair coin (p = 0.4) and compute the resulting posterior distributions. Though a non-trivial Markov chain Monte Carlo (MCMC) algorithm is used, the very idea behind it is simply the application of Bayes theorem.
Now that we understood how to transpose our regular hypothesis testing in bayesian terms, we can adjust the prior distributions to reflect our true belief of the initial state of the system: A beta distribution centered in 0.5, would highlight the fact that we believe that if the coin is biased it must not be as extreme as 0 or 1.
import pymc3 as pmN = 192 #Sampling sizewith pm.Model() as model: p = pm.Uniform("p", 0, 1) observations = pm.Binomial("observations", N, 0.4) obs = pm.Binomial("obs", N, p, observed=observations) step = pm.Metropolis() start = pm.find_MAP() trace = pm.sample(100000, step=step, start=start) burned_trace=trace[1000:] p_samples = burned_trace["p"]
We can also provide non-informative priors, as some many bayesianists would recommend. For example, we could assume a uniform prior for p over [0; 1].
p = pm.distributions.continuous.Beta("p", 2, 2)
In each case, we can directly compute the probability that p < 0.5 from the posterior distributions.
print(np.mean(p_samples<0.5))
We get respectively 0.98 and 0.97 with the uniform prior and the beta(2,2) prior, informing us of the degree of confidence we have that the coin we observe is actually fair or not.
In his paper Bayesian estimation supersedes the t-test (BEST)2, John Kruschke suggests looking at what he calls Highest Density Intervals, consisting of the smallest intervals containing 95% of the posterior density in order to define our tests criteria.
For example in our case, we would want to know if these intervals overlap with the value we are testing against 0.5, and conclude that (H0) is rejected if 0.5 was not included in those.
Reasoning with densities enables us to exploit all of the information we have access to. Better, it allows us to capture all the nuances from the data and draw non-ambiguous conclusions.
One could argue that our analysis is biased given that we had to pick a prior. I will not discuss here the difference of paradigm between frequentism and bayesianism, but will simply recall that not choosing a prior is often equivalent to implicitly picking one.
The Bayesian framework provides an easy to perform and easy to read alternative to classic statistical tests.
Posterior densities provide us with mathematical concepts much more convenient to grasp and use in comparison with notions such as p-values which have proven to be misleading countless times.
Eventually, the concept of the Bayesian network allows us to conceive much more complex experiments and to test any hypothesis by simply considering posterior distributions, as we observe with the case of A/B testing.
T.V. Pereira and J.P.A. Ioannidis. “Statistically significant meta- analyses of clinical trials have modest credibility and inflated effects.” Journal of Clinical Epidemiology 64, no. 10 (2011): 1060– 1069. DOI: 10.1016/j.jclinepi.2010.12.012.Kruschke, John. (2012) Bayesian estimation supersedes the t-test. Journal of Experimental Psychology: General.
T.V. Pereira and J.P.A. Ioannidis. “Statistically significant meta- analyses of clinical trials have modest credibility and inflated effects.” Journal of Clinical Epidemiology 64, no. 10 (2011): 1060– 1069. DOI: 10.1016/j.jclinepi.2010.12.012.
Kruschke, John. (2012) Bayesian estimation supersedes the t-test. Journal of Experimental Psychology: General. | [
{
"code": null,
"e": 417,
"s": 172,
"text": "Usually hypothesis testing is not the first topic that comes to mind when we talk about bayesianism. The current trend is indeed more about incorporating this approach to Machine Learning models, and less about reviewing old-fashion statistics."
},
{
"code": null,
"e": 935,
"s": 417,
"text": "Nevertheless, more and more studies1 reveal the extent of the failure of so many reasearch papers that can be attributed to the misunderstanding/mis-use of “elementary” statistic methods. Given the extent of this phenomenom, it is quite obvious that such a is not the result of scientists personal lack of serious in that regard, but more of a global systemic anomaly which has been going on for quite a long time now. In light of this, it seems that more intuitive and easy to interpret methods should be considered."
},
{
"code": null,
"e": 1232,
"s": 935,
"text": "Misconceptions over what p-values really lie at the root of this situation, or at least embody this reality the most. Most data-scientists are nowadays well educated when it comes to Machine learning, to the detriment of even the most basic statistic concepts ; hypothesis testing is among those."
},
{
"code": null,
"e": 1422,
"s": 1232,
"text": "We are now going to explore one of the simplest test a statistician may have to run, and from there see how to build a bayesian approach, that allow both a simple and forthright conclusion."
},
{
"code": null,
"e": 1613,
"s": 1422,
"text": "We’ll consider one of the simplest experiments there is in order not to lose sight of the point we want to make with unnecessary convolutions: Coin-flipping. The problem is defined this way:"
},
{
"code": null,
"e": 1662,
"s": 1613,
"text": "A coin can be flipped a limited amount of times."
},
{
"code": null,
"e": 1814,
"s": 1662,
"text": "Our objective is to find if this coin is fair or not. in other words, we want to know how likely is our hypothesis (H0) “the coin is fair” to be false."
},
{
"code": null,
"e": 1835,
"s": 1814,
"text": "Pretty simple right?"
},
{
"code": null,
"e": 2087,
"s": 1835,
"text": "The design of the experiment should be made considering the statistical method that will be used to answer our question. A student t-test appears as an obvious choice for our hypothesis testing. We will compare the mean of our sample to the value 0.5."
},
{
"code": null,
"e": 2368,
"s": 2087,
"text": "Good practice wants us to calculate the statistical power when designing our study in order to estimate the appropriate sample size, or at to least tell us about the limitations of our study if sample size is already fixed (it is commonly required to have at least a power of 0.8)"
},
{
"code": null,
"e": 2525,
"s": 2368,
"text": "The power of a binary hypothesis test is the probability that the test rejects the null hypothesis (H0) when a specific alternative hypothesis (H1) is true."
},
{
"code": null,
"e": 2665,
"s": 2525,
"text": "In other words, the power of the test is the probability of getting a p-value under a specified threshold when the coin is actually unfair."
},
{
"code": null,
"e": 2853,
"s": 2665,
"text": "For convenience, we will only consider an alternative hypothesis (H1) “the coin follows a Bernoulli law of parameter p = 0.4”, which will allow us to easily compute the power of our test."
},
{
"code": null,
"e": 3141,
"s": 2853,
"text": "A look at the ROC curve of this test will help us understand what is going on. For a given significance level α, we can derive both the True and False Positive Rates, analytically or from simulation; or in other words, the statistical Power of the test and the significance level itself."
},
{
"code": null,
"e": 3440,
"s": 3141,
"text": "Usually α= 0.05 is the limit accepted, and for this threshold a minimum amount of 192 flips is required to reach our objective (and since flipping coins is not the 1st thing that comes to mind when one thinks about entertaining activities, we will limit ourselves to flipping this coin 192 times!)."
},
{
"code": null,
"e": 3557,
"s": 3440,
"text": "Here comes our problem now. Assume we found that the coin is unfair with a p-value = 0.01, what can we conclude now?"
},
{
"code": null,
"e": 3612,
"s": 3557,
"text": "Is there a 1% chance that the Null hypothesis is True?"
},
{
"code": null,
"e": 3653,
"s": 3612,
"text": "Are we 99% sure that our coin is unfair?"
},
{
"code": null,
"e": 4025,
"s": 3653,
"text": "None of these as you probably have already concluded. Actually, at this point, there is no way to give a probability of our coin being unfair... Quite annoying, especially given our original question: How likely is our coin to be unfair? The only conclusion we can draw is, had the coin been fair, we would only have a probability of 0.01 to observe such extreme results."
},
{
"code": null,
"e": 4226,
"s": 4025,
"text": "In fact Bayes theorem gives us a way to compute this value, but we need more information: priors. With H0 = “coin is unfair”, H1= “coin is fair”, and S = “test succesful with p-value < 0.05”, we have:"
},
{
"code": null,
"e": 4298,
"s": 4226,
"text": "P(H0 | S) = P(S | H0) * P(H0) / (P(S | H0) * P(H0) + P(S | H1) * P(H1))"
},
{
"code": null,
"e": 4399,
"s": 4298,
"text": "Initially assuming our coin more likely to be fair, we set P(H1) = 0.9 and P(H0) = 0.1. Thus we have"
},
{
"code": null,
"e": 4448,
"s": 4399,
"text": "P(H0 | S) = 0.8 * 0.1 / (0.8 * 0.1 + 0.05 * 0.9)"
},
{
"code": null,
"e": 4465,
"s": 4448,
"text": "P(H0 | S) = 0.64"
},
{
"code": null,
"e": 4827,
"s": 4465,
"text": "So only 64% chance for our coin to be unfair even if our test came positive. Quite far from the 95% we would have hoped for... Yet this probability carries much more insights than a simple p-value, and luckily we can go further. This was just a first step into the bayesian world, and as we are going to see now there is much more to unfold to improve our test!"
},
{
"code": null,
"e": 4951,
"s": 4827,
"text": "For this part, we are going to use the PyMC3 library for python, allowing us to easily build Bayesian nonparametric models."
},
{
"code": null,
"e": 5192,
"s": 4951,
"text": "We model the sampling of an unfair coin (p = 0.4) and compute the resulting posterior distributions. Though a non-trivial Markov chain Monte Carlo (MCMC) algorithm is used, the very idea behind it is simply the application of Bayes theorem."
},
{
"code": null,
"e": 5525,
"s": 5192,
"text": "Now that we understood how to transpose our regular hypothesis testing in bayesian terms, we can adjust the prior distributions to reflect our true belief of the initial state of the system: A beta distribution centered in 0.5, would highlight the fact that we believe that if the coin is biased it must not be as extreme as 0 or 1."
},
{
"code": null,
"e": 5897,
"s": 5525,
"text": "import pymc3 as pmN = 192 #Sampling sizewith pm.Model() as model: p = pm.Uniform(\"p\", 0, 1) observations = pm.Binomial(\"observations\", N, 0.4) obs = pm.Binomial(\"obs\", N, p, observed=observations) step = pm.Metropolis() start = pm.find_MAP() trace = pm.sample(100000, step=step, start=start) burned_trace=trace[1000:] p_samples = burned_trace[\"p\"]"
},
{
"code": null,
"e": 6048,
"s": 5897,
"text": "We can also provide non-informative priors, as some many bayesianists would recommend. For example, we could assume a uniform prior for p over [0; 1]."
},
{
"code": null,
"e": 6096,
"s": 6048,
"text": "p = pm.distributions.continuous.Beta(\"p\", 2, 2)"
},
{
"code": null,
"e": 6197,
"s": 6096,
"text": "In each case, we can directly compute the probability that p < 0.5 from the posterior distributions."
},
{
"code": null,
"e": 6227,
"s": 6197,
"text": "print(np.mean(p_samples<0.5))"
},
{
"code": null,
"e": 6408,
"s": 6227,
"text": "We get respectively 0.98 and 0.97 with the uniform prior and the beta(2,2) prior, informing us of the degree of confidence we have that the coin we observe is actually fair or not."
},
{
"code": null,
"e": 6663,
"s": 6408,
"text": "In his paper Bayesian estimation supersedes the t-test (BEST)2, John Kruschke suggests looking at what he calls Highest Density Intervals, consisting of the smallest intervals containing 95% of the posterior density in order to define our tests criteria."
},
{
"code": null,
"e": 6849,
"s": 6663,
"text": "For example in our case, we would want to know if these intervals overlap with the value we are testing against 0.5, and conclude that (H0) is rejected if 0.5 was not included in those."
},
{
"code": null,
"e": 7036,
"s": 6849,
"text": "Reasoning with densities enables us to exploit all of the information we have access to. Better, it allows us to capture all the nuances from the data and draw non-ambiguous conclusions."
},
{
"code": null,
"e": 7299,
"s": 7036,
"text": "One could argue that our analysis is biased given that we had to pick a prior. I will not discuss here the difference of paradigm between frequentism and bayesianism, but will simply recall that not choosing a prior is often equivalent to implicitly picking one."
},
{
"code": null,
"e": 7409,
"s": 7299,
"text": "The Bayesian framework provides an easy to perform and easy to read alternative to classic statistical tests."
},
{
"code": null,
"e": 7601,
"s": 7409,
"text": "Posterior densities provide us with mathematical concepts much more convenient to grasp and use in comparison with notions such as p-values which have proven to be misleading countless times."
},
{
"code": null,
"e": 7819,
"s": 7601,
"text": "Eventually, the concept of the Bayesian network allows us to conceive much more complex experiments and to test any hypothesis by simply considering posterior distributions, as we observe with the case of A/B testing."
},
{
"code": null,
"e": 8173,
"s": 7819,
"text": "T.V. Pereira and J.P.A. Ioannidis. “Statistically significant meta- analyses of clinical trials have modest credibility and inflated effects.” Journal of Clinical Epidemiology 64, no. 10 (2011): 1060– 1069. DOI: 10.1016/j.jclinepi.2010.12.012.Kruschke, John. (2012) Bayesian estimation supersedes the t-test. Journal of Experimental Psychology: General."
},
{
"code": null,
"e": 8417,
"s": 8173,
"text": "T.V. Pereira and J.P.A. Ioannidis. “Statistically significant meta- analyses of clinical trials have modest credibility and inflated effects.” Journal of Clinical Epidemiology 64, no. 10 (2011): 1060– 1069. DOI: 10.1016/j.jclinepi.2010.12.012."
}
] |
Building Knowledge Graphs from Structured Sources | by Giuseppe Futia | Towards Data Science | Knowledge Graphs (KGs) are labeled and directed multigraphs that encode information in the form of entities and relations relevant to a specific domain or organization. KGs are effective tools for capturing and organizing a large amount of structured and multi-relational data that can be explored employing query mechanisms. Considering these features, KGs are becoming the backbone of Web and legacy information systems in different research fields and industrial applications. Further details on KG features, including RDF, ontologies, and SPARQL, are available in the following article:
towardsdatascience.com
Publishing data into KGs is a complex process because it requires extracting and integrating information from heterogeneous sources. The goal of integrating these sources is harmonizing their data and leading to a coherent perspective on the overall information. Heterogeneous sources range from unstructured data, such as plain text, to structured data, including table formats such as CSVs and relational databases, and tree-structured formats, such as JSONs and XMLs. The contribution of this article is specifically related to the publishing of data into KGs from structured data sources through a mapping-based approach.
Structured data sources play a fundamental role in the data ecosystem because much of the valuable (and reusable) information within organizations and the Web is available as structured data.
Unlike other sources, such as plain texts, structured information can be mapped to KGs through a semantic integration process. The common strategy adopted by the Semantic Web (SW) community to apply this process is adopting reference ontologies as global schemas. Then, mappings are constructed to describe the relationships between the global schema and the local schema of the target data source. From a data integration perspective, this approach is classified as Global-As-View (GAV).
According to this perspective, data integration performance is based on the consistency and the expressiveness of the ontology adopted as a global schema. In order to clarify the mapping process in a real scenario, the following section introduces a running example in the public procurement domain.
Public procurement refers to the process by which public authorities and administrations purchase goods or services from companies. In this process, the public authority announces a call for tenders, companies participate in this call with a specific tender, and the public authority shall award one of these tenders.
Suppose we have a target data source ds, including a set of attributes ds{a1, a2, a3, ...}. In public procurement, the target data source is a JSON file representing a specific public contract. The JSON (JavaScript Object Notation) is a language-independent data interchange format. It employs human-readable text to store and transfer data objects characterized by attribute-value pairs and any serializable datatype, including arrays.
{ "contract_id":"Z4ADEA9DE4", "contract_object":"MANUTENZIONE ORDINARIA MEZZI DI TRASPORTO", "proposing_struct":{ "business_id":"80004990927", "business_name":"Ministero dell'Interno" }, "participants":[ { "business_id":"08106710158", "business_name":"CAR WASH CARALIS" } ]}
This JSON describes the following data:
contract_id includes the identifier of the required service (“Z4ADEA9DE4”).
contract_object includes the description of the service (“MANUTENZIONE ORDINARIA MEZZI DI TRASPORTO”).
business_id and business_name, nested in the proposing_struct field, include the identifier (“80004990927”) and the name (“Ministero dell’Interno”) of the public body, which proposes the tender.
business_id and business_name, nested in the participants field, include the identifier (“Z4ADEA9DE4”) and the name (“CAR WASH CARALIS”).
The mapping process requires a reference ontology O as a global schema. The Czech OpenData.cz initiative releases one of the most common ontologies adopted in public procurement, and it is available on GitHub: https://github.com/opendatacz/public-contracts-ontology.
The ontology axioms involved in the mapping process related to our running example can be represented in Turtle format as follows:
@prefix dcterms: <http://purl.org/dc/terms/> .@prefix gr: <http://purl.org/goodrelations/v1#> .@prefix owl: <http://www.w3.org/2002/07/owl#> .@prefix pc: <http://purl.org/procurement/public-contracts#> .@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .####### ####### Classes#######pc:Contract a owl:Class .gr:Offering a owl:Class .pc:Tender a owl:Class ; rdfs:subClassOf gr:Offering .####### ####### Relations (or Object Properties)#######pc:contractingAuthority a owl:FunctionalProperty, owl:ObjectProperty ; rdfs:domain pc:Contract ; rdfs:range gr:BusinessEntity .pc:tender a owl:ObjectProperty ; rdfs:domain pc:Contract ; rdfs:range pc:Tender .pc:awardedTender a owl:FunctionalProperty, owl:ObjectProperty ; rdfs:subPropertyOf pc:tender .pc:bidder a owl:ObjectProperty ; rdfs:domain pc:Tender ; rdfs:range gr:BusinessEntity .####### ####### Datatype properties#######dcterms:identifier a owl:DatatypeProperty ; rdfs:domain pc:Contract ; rdfs:domain gr:BusinessEntity ; rdfs:range rdfs:Literal .rdfs:label a owl:DatatypeProperty ; rdfs:domain pc:Contract ; rdfs:domain gr:BusinessEntity ; rdfs:range rdfs:Literal .rdfs:description a owl:DatatypeProperty ; rdfs:domain pc:Contract ; rdfs:range rdfs:Literal .
The whole mapping process includes two main steps. The first step is creating a map between the local schema of the target data source and the reference ontology. The second step is materializing the source’s data as KG statements or virtualizing the access to the source, defining a graph-based view over the legacy information. Materialized statements can be directly published into KGs, while a graph-based and virtualized access allows us to retrieve and explore data of the target data source like it is a KG.
The widest-adopted approaches for the mapping step are based on the so-called custom mappings. These approaches exploit customizable documents written with declarative languages to perform the map generation step. Declarative languages exploit the SW formalism to describe the relationships between the local and the global schemas.
The most prominent language adopted by the research community is R2RML, which expresses customized mappings written in RDF between relational databases to KGs. An extension of this language, known as RML, is a more generic mapping language, whose applicability is extended to other types of tables, such as CSV files and tree-structured schemes. Other types of languages, such as TARQL and JARQL, adopt the SPARQL syntax to create mappings for specific formats, such as CSV and JSON files, respectively. An example of JARQL describing the mapping between the ds and O is available below:
@prefix dcterms: <http://purl.org/dc/terms/> .@prefix pc: <http://purl.org/procurement/public-contracts#> .@prefix gr: <http://purl.org/goodrelations/v1#> .@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .CONSTRUCT { ?BusinessEntity0 dcterms:identifier ?proposing_struct__business_id ; rdf:type gr:BusinessEntity. ?BusinessEntity1 dcterms:identifier ?participants__business_id ; rdf:type gr:BusinessEntity . ?Tender0 pc:bidder ?BusinessEntity1 . ?Contract0 dcterms:identifier ?contract_id ; rdf:type pc:Contract ; pc:contractingAuthority ?BusinessEntity0 ; pc:tender ?Tender0 .}WHERE { ?root a jarql:Root. OPTIONAL { ?root jarql:contract_id ?contract_id . } OPTIONAL { ?root jarql:proposing_struct ?proposing_struct . } OPTIONAL { ?proposing_struct jarql:proposing_struct__business_id ?proposing_struct__business_id . } OPTIONAL { ?root jarql:participants ?participants . } OPTIONAL { ?participants jarql:participants__business_id ?participants__business_id . } BIND (URI(CONCAT('http://purl.org/procurement/public-contracts/contract/', ?contract_id)) as ?Contract0) BIND (URI(CONCAT('http://purl.org/goodrelations/v1/businessentity/', ?proposing_struct__business_id)) as ?BusinessEntity0) BIND (URI(CONCAT('http://purl.org/goodrelations/v1/businessentity/', ?participants__business_id)) as ?BusinessEntity1) BIND (URI(CONCAT('http://purl.org/procurement/public-contracts/tender/' ?contract_id + + '_' participants__business_id)) as ?Tender0)}
This JARQL file includes 3 main parts. The first one is included in the CONSTRUCT section, while the others are included in the WHERE section.
The CONSTRUCT section describes the graph patterns that encode the semantic types, such as
?BusinessEntity0 dcterms:identifier ?proposing_struct__business_id .
and the semantic relations, such as
?Contract0 pc:contractingAuthority ?BusinessEntity0 .
The first segment of the WHERE section, which includes the OPTIONAL operators, describes how to parse the JSON file for extracting the data required to create the KG statements. For instance: the pattern
?proposing_struct jarql:proposing_struct__business_id ?proposing_struct__business_id .
indicates that the variable ?proposing_struct__business_id has to be replaced with the proposing_struct__business_id attribute of the JSON.
The second segment of the WHERE section, which includes different BIND operators, declares how to generate the entity URIs for the data extracted from the JSON. The line
BIND (URI(CONCAT(‘http://purl.org/procurement/public-contracts/contract/', ?contract\_id)) as ?Contract0) .
indicates that the URIs of contracts are built combining the http://purl.org/procurement/public-contracts/contract/ URI and the value extracted from the values bound to the ?contract_id variable.
Language-driven engines aim to materialize or virtualize KG statements, following the instructions of the mapping documents written using declarative languages. These engines perform two different tasks: the first task is to link the target data source fields to a class or a property defined by the reference ontology. Once this link has been created, these engines materialize or virtualize the URIs and the KG statements, retrieving the legacy information included in the data source. The JARQL file describing the link between the set of attributes ds{a1, a2, a3, ...} and the global schema represented by O allows to materialize the following statements:
@prefix dcterms: <http://purl.org/dc/terms/> .@prefix pc: <http://purl.org/procurement/public-contracts#> .@prefix gr: <http://purl.org/goodrelations/v1#> .@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .@prefix contract: <http://purl.org/procurement/public-contracts/contract/> .@prefix be: <http://purl.org/goodrelations/v1/businessentity/> .@prefix tender: <http://purl.org/procurement/public-contracts/tender/> .# ?BusinessEntity0 dcterms:identifier ?proposing_struct__business_id ;# rdf:type gr:BusinessEntity .be:08106710158 dcterms:identifier 08106710158 ; rdf:type gr:BusinessEntity .# ?BusinessEntity1 dcterms:identifier ?participants__business_id ;# rdf:type gr:BusinessEntity .be:08106710158 dcterms:identifier 08106710158 ; rdf:type gr:BusinessEntity .# ?Tender0 pc:bidder ?BusinessEntity1 .tender:Z4ADEA9DE4-80004990927 pc:bidder be:08106710158 .# ?Contract0 dcterms:identifier ?contract_id ;# rdf:type pc:Contract ;# pc:contractingAuthority ?BusinessEntity0 ;# pc:tender ?Tender0 .contract:Z4ADEA9DE4 dcterms:identifier Z4ADEA9DE4 ; rdf:type pc:Contract ; pc:contractingAuthority 80004990927 ; pc:tender tender:Z4ADEA9DE4-80004990927 .
To clarify the transformation process enabled by the JARQL file, this example reports as comments the graph patterns included in its CONSTRUCT section. One of the main reasons for using JARQL as declarative language is its capacity to create URIs, combining data located at different levels of the JSON tree structure. In the running example, the Tender’s URI is built combining the id of the contract (“Z4ADEA9DE4”), located at the JSON’s root level, and the id of the business entity (“80004990927”), located in a nested structure of the JSON.
In the following article, I will show you a particular approach based on semantic models for capturing the semantics of data sources with graph-based structures.
towardsdatascience.com
If you like my articles, you can support me using this link https://medium.com/@giuseppefutia/membership and becoming a Medium member.
Some rights reserved | [
{
"code": null,
"e": 763,
"s": 172,
"text": "Knowledge Graphs (KGs) are labeled and directed multigraphs that encode information in the form of entities and relations relevant to a specific domain or organization. KGs are effective tools for capturing and organizing a large amount of structured and multi-relational data that can be explored employing query mechanisms. Considering these features, KGs are becoming the backbone of Web and legacy information systems in different research fields and industrial applications. Further details on KG features, including RDF, ontologies, and SPARQL, are available in the following article:"
},
{
"code": null,
"e": 786,
"s": 763,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1412,
"s": 786,
"text": "Publishing data into KGs is a complex process because it requires extracting and integrating information from heterogeneous sources. The goal of integrating these sources is harmonizing their data and leading to a coherent perspective on the overall information. Heterogeneous sources range from unstructured data, such as plain text, to structured data, including table formats such as CSVs and relational databases, and tree-structured formats, such as JSONs and XMLs. The contribution of this article is specifically related to the publishing of data into KGs from structured data sources through a mapping-based approach."
},
{
"code": null,
"e": 1604,
"s": 1412,
"text": "Structured data sources play a fundamental role in the data ecosystem because much of the valuable (and reusable) information within organizations and the Web is available as structured data."
},
{
"code": null,
"e": 2093,
"s": 1604,
"text": "Unlike other sources, such as plain texts, structured information can be mapped to KGs through a semantic integration process. The common strategy adopted by the Semantic Web (SW) community to apply this process is adopting reference ontologies as global schemas. Then, mappings are constructed to describe the relationships between the global schema and the local schema of the target data source. From a data integration perspective, this approach is classified as Global-As-View (GAV)."
},
{
"code": null,
"e": 2393,
"s": 2093,
"text": "According to this perspective, data integration performance is based on the consistency and the expressiveness of the ontology adopted as a global schema. In order to clarify the mapping process in a real scenario, the following section introduces a running example in the public procurement domain."
},
{
"code": null,
"e": 2711,
"s": 2393,
"text": "Public procurement refers to the process by which public authorities and administrations purchase goods or services from companies. In this process, the public authority announces a call for tenders, companies participate in this call with a specific tender, and the public authority shall award one of these tenders."
},
{
"code": null,
"e": 3148,
"s": 2711,
"text": "Suppose we have a target data source ds, including a set of attributes ds{a1, a2, a3, ...}. In public procurement, the target data source is a JSON file representing a specific public contract. The JSON (JavaScript Object Notation) is a language-independent data interchange format. It employs human-readable text to store and transfer data objects characterized by attribute-value pairs and any serializable datatype, including arrays."
},
{
"code": null,
"e": 3471,
"s": 3148,
"text": "{ \"contract_id\":\"Z4ADEA9DE4\", \"contract_object\":\"MANUTENZIONE ORDINARIA MEZZI DI TRASPORTO\", \"proposing_struct\":{ \"business_id\":\"80004990927\", \"business_name\":\"Ministero dell'Interno\" }, \"participants\":[ { \"business_id\":\"08106710158\", \"business_name\":\"CAR WASH CARALIS\" } ]}"
},
{
"code": null,
"e": 3511,
"s": 3471,
"text": "This JSON describes the following data:"
},
{
"code": null,
"e": 3587,
"s": 3511,
"text": "contract_id includes the identifier of the required service (“Z4ADEA9DE4”)."
},
{
"code": null,
"e": 3690,
"s": 3587,
"text": "contract_object includes the description of the service (“MANUTENZIONE ORDINARIA MEZZI DI TRASPORTO”)."
},
{
"code": null,
"e": 3885,
"s": 3690,
"text": "business_id and business_name, nested in the proposing_struct field, include the identifier (“80004990927”) and the name (“Ministero dell’Interno”) of the public body, which proposes the tender."
},
{
"code": null,
"e": 4023,
"s": 3885,
"text": "business_id and business_name, nested in the participants field, include the identifier (“Z4ADEA9DE4”) and the name (“CAR WASH CARALIS”)."
},
{
"code": null,
"e": 4290,
"s": 4023,
"text": "The mapping process requires a reference ontology O as a global schema. The Czech OpenData.cz initiative releases one of the most common ontologies adopted in public procurement, and it is available on GitHub: https://github.com/opendatacz/public-contracts-ontology."
},
{
"code": null,
"e": 4421,
"s": 4290,
"text": "The ontology axioms involved in the mapping process related to our running example can be represented in Turtle format as follows:"
},
{
"code": null,
"e": 5746,
"s": 4421,
"text": "@prefix dcterms: <http://purl.org/dc/terms/> .@prefix gr: <http://purl.org/goodrelations/v1#> .@prefix owl: <http://www.w3.org/2002/07/owl#> .@prefix pc: <http://purl.org/procurement/public-contracts#> .@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .####### ####### Classes#######pc:Contract a owl:Class .gr:Offering a owl:Class .pc:Tender a owl:Class ; rdfs:subClassOf gr:Offering .####### ####### Relations (or Object Properties)#######pc:contractingAuthority a owl:FunctionalProperty, owl:ObjectProperty ; rdfs:domain pc:Contract ; rdfs:range gr:BusinessEntity .pc:tender a owl:ObjectProperty ; rdfs:domain pc:Contract ; rdfs:range pc:Tender .pc:awardedTender a owl:FunctionalProperty, owl:ObjectProperty ; rdfs:subPropertyOf pc:tender .pc:bidder a owl:ObjectProperty ; rdfs:domain pc:Tender ; rdfs:range gr:BusinessEntity .####### ####### Datatype properties#######dcterms:identifier a owl:DatatypeProperty ; rdfs:domain pc:Contract ; rdfs:domain gr:BusinessEntity ; rdfs:range rdfs:Literal .rdfs:label a owl:DatatypeProperty ; rdfs:domain pc:Contract ; rdfs:domain gr:BusinessEntity ; rdfs:range rdfs:Literal .rdfs:description a owl:DatatypeProperty ; rdfs:domain pc:Contract ; rdfs:range rdfs:Literal ."
},
{
"code": null,
"e": 6261,
"s": 5746,
"text": "The whole mapping process includes two main steps. The first step is creating a map between the local schema of the target data source and the reference ontology. The second step is materializing the source’s data as KG statements or virtualizing the access to the source, defining a graph-based view over the legacy information. Materialized statements can be directly published into KGs, while a graph-based and virtualized access allows us to retrieve and explore data of the target data source like it is a KG."
},
{
"code": null,
"e": 6594,
"s": 6261,
"text": "The widest-adopted approaches for the mapping step are based on the so-called custom mappings. These approaches exploit customizable documents written with declarative languages to perform the map generation step. Declarative languages exploit the SW formalism to describe the relationships between the local and the global schemas."
},
{
"code": null,
"e": 7182,
"s": 6594,
"text": "The most prominent language adopted by the research community is R2RML, which expresses customized mappings written in RDF between relational databases to KGs. An extension of this language, known as RML, is a more generic mapping language, whose applicability is extended to other types of tables, such as CSV files and tree-structured schemes. Other types of languages, such as TARQL and JARQL, adopt the SPARQL syntax to create mappings for specific formats, such as CSV and JSON files, respectively. An example of JARQL describing the mapping between the ds and O is available below:"
},
{
"code": null,
"e": 8732,
"s": 7182,
"text": "@prefix dcterms: <http://purl.org/dc/terms/> .@prefix pc: <http://purl.org/procurement/public-contracts#> .@prefix gr: <http://purl.org/goodrelations/v1#> .@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .CONSTRUCT { ?BusinessEntity0 dcterms:identifier ?proposing_struct__business_id ; rdf:type gr:BusinessEntity. ?BusinessEntity1 dcterms:identifier ?participants__business_id ; rdf:type gr:BusinessEntity . ?Tender0 pc:bidder ?BusinessEntity1 . ?Contract0 dcterms:identifier ?contract_id ; rdf:type pc:Contract ; pc:contractingAuthority ?BusinessEntity0 ; pc:tender ?Tender0 .}WHERE { ?root a jarql:Root. OPTIONAL { ?root jarql:contract_id ?contract_id . } OPTIONAL { ?root jarql:proposing_struct ?proposing_struct . } OPTIONAL { ?proposing_struct jarql:proposing_struct__business_id ?proposing_struct__business_id . } OPTIONAL { ?root jarql:participants ?participants . } OPTIONAL { ?participants jarql:participants__business_id ?participants__business_id . } BIND (URI(CONCAT('http://purl.org/procurement/public-contracts/contract/', ?contract_id)) as ?Contract0) BIND (URI(CONCAT('http://purl.org/goodrelations/v1/businessentity/', ?proposing_struct__business_id)) as ?BusinessEntity0) BIND (URI(CONCAT('http://purl.org/goodrelations/v1/businessentity/', ?participants__business_id)) as ?BusinessEntity1) BIND (URI(CONCAT('http://purl.org/procurement/public-contracts/tender/' ?contract_id + + '_' participants__business_id)) as ?Tender0)}"
},
{
"code": null,
"e": 8875,
"s": 8732,
"text": "This JARQL file includes 3 main parts. The first one is included in the CONSTRUCT section, while the others are included in the WHERE section."
},
{
"code": null,
"e": 8966,
"s": 8875,
"text": "The CONSTRUCT section describes the graph patterns that encode the semantic types, such as"
},
{
"code": null,
"e": 9035,
"s": 8966,
"text": "?BusinessEntity0 dcterms:identifier ?proposing_struct__business_id ."
},
{
"code": null,
"e": 9071,
"s": 9035,
"text": "and the semantic relations, such as"
},
{
"code": null,
"e": 9125,
"s": 9071,
"text": "?Contract0 pc:contractingAuthority ?BusinessEntity0 ."
},
{
"code": null,
"e": 9329,
"s": 9125,
"text": "The first segment of the WHERE section, which includes the OPTIONAL operators, describes how to parse the JSON file for extracting the data required to create the KG statements. For instance: the pattern"
},
{
"code": null,
"e": 9416,
"s": 9329,
"text": "?proposing_struct jarql:proposing_struct__business_id ?proposing_struct__business_id ."
},
{
"code": null,
"e": 9556,
"s": 9416,
"text": "indicates that the variable ?proposing_struct__business_id has to be replaced with the proposing_struct__business_id attribute of the JSON."
},
{
"code": null,
"e": 9726,
"s": 9556,
"text": "The second segment of the WHERE section, which includes different BIND operators, declares how to generate the entity URIs for the data extracted from the JSON. The line"
},
{
"code": null,
"e": 9834,
"s": 9726,
"text": "BIND (URI(CONCAT(‘http://purl.org/procurement/public-contracts/contract/', ?contract\\_id)) as ?Contract0) ."
},
{
"code": null,
"e": 10030,
"s": 9834,
"text": "indicates that the URIs of contracts are built combining the http://purl.org/procurement/public-contracts/contract/ URI and the value extracted from the values bound to the ?contract_id variable."
},
{
"code": null,
"e": 10690,
"s": 10030,
"text": "Language-driven engines aim to materialize or virtualize KG statements, following the instructions of the mapping documents written using declarative languages. These engines perform two different tasks: the first task is to link the target data source fields to a class or a property defined by the reference ontology. Once this link has been created, these engines materialize or virtualize the URIs and the KG statements, retrieving the legacy information included in the data source. The JARQL file describing the link between the set of attributes ds{a1, a2, a3, ...} and the global schema represented by O allows to materialize the following statements:"
},
{
"code": null,
"e": 11891,
"s": 10690,
"text": "@prefix dcterms: <http://purl.org/dc/terms/> .@prefix pc: <http://purl.org/procurement/public-contracts#> .@prefix gr: <http://purl.org/goodrelations/v1#> .@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .@prefix contract: <http://purl.org/procurement/public-contracts/contract/> .@prefix be: <http://purl.org/goodrelations/v1/businessentity/> .@prefix tender: <http://purl.org/procurement/public-contracts/tender/> .# ?BusinessEntity0 dcterms:identifier ?proposing_struct__business_id ;# rdf:type gr:BusinessEntity .be:08106710158 dcterms:identifier 08106710158 ; rdf:type gr:BusinessEntity .# ?BusinessEntity1 dcterms:identifier ?participants__business_id ;# rdf:type gr:BusinessEntity .be:08106710158 dcterms:identifier 08106710158 ; rdf:type gr:BusinessEntity .# ?Tender0 pc:bidder ?BusinessEntity1 .tender:Z4ADEA9DE4-80004990927 pc:bidder be:08106710158 .# ?Contract0 dcterms:identifier ?contract_id ;# rdf:type pc:Contract ;# pc:contractingAuthority ?BusinessEntity0 ;# pc:tender ?Tender0 .contract:Z4ADEA9DE4 dcterms:identifier Z4ADEA9DE4 ; rdf:type pc:Contract ; pc:contractingAuthority 80004990927 ; pc:tender tender:Z4ADEA9DE4-80004990927 ."
},
{
"code": null,
"e": 12437,
"s": 11891,
"text": "To clarify the transformation process enabled by the JARQL file, this example reports as comments the graph patterns included in its CONSTRUCT section. One of the main reasons for using JARQL as declarative language is its capacity to create URIs, combining data located at different levels of the JSON tree structure. In the running example, the Tender’s URI is built combining the id of the contract (“Z4ADEA9DE4”), located at the JSON’s root level, and the id of the business entity (“80004990927”), located in a nested structure of the JSON."
},
{
"code": null,
"e": 12599,
"s": 12437,
"text": "In the following article, I will show you a particular approach based on semantic models for capturing the semantics of data sources with graph-based structures."
},
{
"code": null,
"e": 12622,
"s": 12599,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12757,
"s": 12622,
"text": "If you like my articles, you can support me using this link https://medium.com/@giuseppefutia/membership and becoming a Medium member."
}
] |
Bloom Filter in Java with Examples - GeeksforGeeks | 16 Apr, 2020
Bloom filters are for set membership which determines whether an element is present in a set or not. Bloom filter was invented by Burton H. Bloom in 1970 in a paper called Space/Time Trade-offs in Hash Coding with Allowable Errors (1970). Bloom filter is a probabilistic data structure that works on hash-coding methods (similar to HashTable).
When do we need a Bloom Filter?Consider any of the following situations:
Suppose we have a list of some elements and we want to check whether a given element is present or not?Consider you are working on email service and you are trying to implement sign up endpoint with a feature that a given username is already present or not?Suppose you have given a set of blacklisted IP’s and you want to filter out a given IP is a blacklisted one or not?
Suppose we have a list of some elements and we want to check whether a given element is present or not?
Consider you are working on email service and you are trying to implement sign up endpoint with a feature that a given username is already present or not?
Suppose you have given a set of blacklisted IP’s and you want to filter out a given IP is a blacklisted one or not?
Can these problem be solved without the help of Bloom Filter?
Let us try to solve these problem using a HashSet
import java.util.HashSet;import java.util.Set; public class SetDemo { public static void main(String[] args) { Set<String> blackListedIPs = new HashSet<>(); blackListedIPs.add("192.170.0.1"); blackListedIPs.add("75.245.10.1"); blackListedIPs.add("10.125.22.20"); // true System.out.println( blackListedIPs .contains( "75.245.10.1")); // false System.out.println( blackListedIPs .contains( "101.125.20.22")); }}
true
false
Why does data structure like HashSet or HashTable fail?HashSet or HashTable works well when we have limited data set, but might not fit as we move with a large data set. With a large data set, it takes a lot of time with a lot of memory.
Size of Data set vs insertion time for HashSet like data structure
----------------------------------------------
|Number of UUIDs Insertion Time(ms) |
----------------------------------------------
|10 <1 |
|100 3 |
|1, 000 58 |
|10, 000 122 |
|100, 000 836 |
|1, 000, 000 7395 |
----------------------------------------------
Size of Data set vs memory (JVM Heap) for HashSet like data structure
----------------------------------------------
|Number of UUIDs JVM heap used(MB) |
----------------------------------------------
|10 <2 |
|100 <2 |
|1, 000 3 |
|10, 000 9 |
|100, 000 37 |
|1, 000, 000 264 |
-----------------------------------------------
So it is clear that if we have a large set of data then a normal data structure like the Set or HashTable is not feasible, and here Bloom filters come into the picture. Refer this article for more details on comparison between the two: Difference between Bloom filters and Hashtable
How to solve these problems with the help of Bloom Filter?Let’s take a bit array of size N (Here 24) and initialize each bit with binary zero, Now take some hash functions (You can take as many you want, we are taking two hash function here for our illustration).
Now pass the first IP you have to both hash function, which generates some random number as given belowhashFunction_1(192.170.0.1) : 2
hashFunction_2(192.170.0.1) : 6
Now, Go to index 2 and 6 and mark the bit as binary 1.
hashFunction_1(192.170.0.1) : 2
hashFunction_2(192.170.0.1) : 6
Now, Go to index 2 and 6 and mark the bit as binary 1.
Now pass the second IP you have, and follow the same step.hashFunction_1(75.245.10.1) : 4
hashFunction_2(75.245.10.1) : 10
Now, Go to index 4 and 10 and mark the bit as binary 1.
hashFunction_1(75.245.10.1) : 4
hashFunction_2(75.245.10.1) : 10
Now, Go to index 4 and 10 and mark the bit as binary 1.
Similarly pass the third IP to the both hash function, and suppose you got the below output of hash functionhashFunction_1(10.125.22.20) : 10
hashFunction_2(10.125.22.20) : 19
‘Now, go to index 10 and 19 and mark as binary 1, Here index 10 is already marked by previous entry so just mark the index 19 as binary 1.Now, It is time to check whether an IP is present in the data set or not,
hashFunction_1(10.125.22.20) : 10
hashFunction_2(10.125.22.20) : 19
‘Now, go to index 10 and 19 and mark as binary 1, Here index 10 is already marked by previous entry so just mark the index 19 as binary 1.
Now, It is time to check whether an IP is present in the data set or not,
Test input #1Let’s say we want to check IP 75.245.10.1. Pass this IP with the same two hash functions which we have taken for adding the above inputs.hashFunction_1(75.245.10.1) : 4
hashFunction_2(75.245.10.1) : 10
Now, Go to the index and check the bit, if both the index 4 and 10 is marked with binary 1 then the IP 75.245.10.1 is present in the set, otherwise it is not with the data set.
hashFunction_1(75.245.10.1) : 4
hashFunction_2(75.245.10.1) : 10
Now, Go to the index and check the bit, if both the index 4 and 10 is marked with binary 1 then the IP 75.245.10.1 is present in the set, otherwise it is not with the data set.
Test input #2Let’s say we want to check IP 75.245.20.30 is present in the set or not? So the process will be same, Pass this IP with the same two hash functions which we have taken for adding the above inputs.hashFunction_1(75.245.20.30) : 19
hashFunction_2(75.245.20.30) : 23
Since at index 19 it is set to 1 but at index 23 it is 0, So we can say given IP 75.245.20.30 is not present in the set.
hashFunction_1(75.245.20.30) : 19
hashFunction_2(75.245.20.30) : 23
Since at index 19 it is set to 1 but at index 23 it is 0, So we can say given IP 75.245.20.30 is not present in the set.
Why is Bloom Filter a probabilistic data structure?Let’s understand this with one more test, This time consider an IP 101.125.20.22 and check whether it is present in the set or not. Pass this to both hash function. Consider our hash function results as follows.
hashFunction_1(101.125.20.22) : 19
hashFunction_2(101.125.20.22) : 2
Now, visit the index 19 and 2 which is set to 1 and it says that the given IP101.125.20.22 is present in the set.
But, this IP 101.125.20.22 has bot been processed above in the data set while adding the IP’s to bit array. This is known as False Positive:
Expected Output: No
Actual Output: Yes (False Positive)
In this case, index 2 and 19 were set to 1 by other input and not by this IP 101.125.20.22. This is called collision and that’s why it is probabilistic, where chances of happening are not 100%.
What to expect from a Bloom filter?
When a Bloom filter says an element is not present it is for sure not present. It guarantees 100% that the given element is not available in the set, because either of the bit of index given by hash functions will be set to 0.But when Bloom filter says the given element is present it is not 100% sure, because there may be a chance due to collision all the bit of index given by hash functions has been set to 1 by other inputs.
When a Bloom filter says an element is not present it is for sure not present. It guarantees 100% that the given element is not available in the set, because either of the bit of index given by hash functions will be set to 0.
But when Bloom filter says the given element is present it is not 100% sure, because there may be a chance due to collision all the bit of index given by hash functions has been set to 1 by other inputs.
How to get 100% accurate result from a Bloom filter?Well, this could be achieved only by taking more number of hash functions. The more number of the hash function we take, the more accurate result we get, because of lesser chances of a collision.
Time and Space complexity of a Bloom filterSuppose we have around 40 million data sets and we are using around H hash functions, then:
Time complexity: O(H), where H is the number of hash functions usedSpace complexity: 159 Mb (For 40 million data sets)Case of False positive: 1 mistake per 10 million (for H = 23)
Implementing Bloom filter in Java using Guava Library:We can implement the Bloom filter using Java library provided by Guava.
Include the below maven dependency:<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version></dependency>Write the following code to implement the Bloom Filter:// Java program to implement// Bloom Filter using Guava Library import java.nio.charset.Charset;import com.google.common.hash.BloomFilter;import com.google.common.hash.Funnels; public class BloomFilterDemo { public static void main(String[] args) { // Create a Bloom Filter instance BloomFilter<String> blackListedIps = BloomFilter.create( Funnels.stringFunnel( Charset.forName("UTF-8")), 10000); // Add the data sets blackListedIps.put("192.170.0.1"); blackListedIps.put("75.245.10.1"); blackListedIps.put("10.125.22.20"); // Test the bloom filter System.out.println( blackListedIps .mightContain( "75.245.10.1")); System.out.println( blackListedIps .mightContain( "101.125.20.22")); }}Output:Bloom Filter OutputNote: The above Java code may return a 3% false-positive probability by default.Reduce the false-positive probabilityIntroduce another parameter in Bloom filter object creation as follows:BloomFilter blackListedIps = BloomFilter.create(Funnels.stringFunnel(Charset.forName("UTF-8")), 10000, 0.005);Now false-positive probability has been reduced from 0.03 to 0.005. But tweaking this parameter has an effect on the side of the bloom filter.
Include the below maven dependency:<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version></dependency>
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version></dependency>
Write the following code to implement the Bloom Filter:// Java program to implement// Bloom Filter using Guava Library import java.nio.charset.Charset;import com.google.common.hash.BloomFilter;import com.google.common.hash.Funnels; public class BloomFilterDemo { public static void main(String[] args) { // Create a Bloom Filter instance BloomFilter<String> blackListedIps = BloomFilter.create( Funnels.stringFunnel( Charset.forName("UTF-8")), 10000); // Add the data sets blackListedIps.put("192.170.0.1"); blackListedIps.put("75.245.10.1"); blackListedIps.put("10.125.22.20"); // Test the bloom filter System.out.println( blackListedIps .mightContain( "75.245.10.1")); System.out.println( blackListedIps .mightContain( "101.125.20.22")); }}Output:Bloom Filter OutputNote: The above Java code may return a 3% false-positive probability by default.
// Java program to implement// Bloom Filter using Guava Library import java.nio.charset.Charset;import com.google.common.hash.BloomFilter;import com.google.common.hash.Funnels; public class BloomFilterDemo { public static void main(String[] args) { // Create a Bloom Filter instance BloomFilter<String> blackListedIps = BloomFilter.create( Funnels.stringFunnel( Charset.forName("UTF-8")), 10000); // Add the data sets blackListedIps.put("192.170.0.1"); blackListedIps.put("75.245.10.1"); blackListedIps.put("10.125.22.20"); // Test the bloom filter System.out.println( blackListedIps .mightContain( "75.245.10.1")); System.out.println( blackListedIps .mightContain( "101.125.20.22")); }}
Output:
Bloom Filter Output
Note: The above Java code may return a 3% false-positive probability by default.
Reduce the false-positive probabilityIntroduce another parameter in Bloom filter object creation as follows:BloomFilter blackListedIps = BloomFilter.create(Funnels.stringFunnel(Charset.forName("UTF-8")), 10000, 0.005);Now false-positive probability has been reduced from 0.03 to 0.005. But tweaking this parameter has an effect on the side of the bloom filter.
Now false-positive probability has been reduced from 0.03 to 0.005. But tweaking this parameter has an effect on the side of the bloom filter.
Effect of reducing the false positive probability:Let’s analyze this effect with respect to the hash function, array bit, time complexity and space complexity.
Let’s look on insertion time for different data set.-----------------------------------------------------------------------------
|Number of UUIDs | Set Insertion Time(ms) | Bloom Filter Insertion Time(ms) |
-----------------------------------------------------------------------------
|10 <1 71 |
|100 3 17 |
|1, 000 58 84 |
|10, 000 122 272 |
|100, 000 836 556 |
|1, 000, 000 7395 5173 |
------------------------------------------------------------------------------
-----------------------------------------------------------------------------
|Number of UUIDs | Set Insertion Time(ms) | Bloom Filter Insertion Time(ms) |
-----------------------------------------------------------------------------
|10 <1 71 |
|100 3 17 |
|1, 000 58 84 |
|10, 000 122 272 |
|100, 000 836 556 |
|1, 000, 000 7395 5173 |
------------------------------------------------------------------------------
Now, Let’s have a look on memory(JVM heap)--------------------------------------------------------------------------
|Number of UUIDs | Set JVM heap used(MB) | Bloom filter JVM heap used(MB) |
--------------------------------------------------------------------------
|10 <2 0.01 |
|100 <2 0.01 |
|1, 000 3 0.01 |
|10, 000 9 0.02 |
|100, 000 37 0.1 |
|1, 000, 000 264 0.9 |
---------------------------------------------------------------------------
--------------------------------------------------------------------------
|Number of UUIDs | Set JVM heap used(MB) | Bloom filter JVM heap used(MB) |
--------------------------------------------------------------------------
|10 <2 0.01 |
|100 <2 0.01 |
|1, 000 3 0.01 |
|10, 000 9 0.02 |
|100, 000 37 0.1 |
|1, 000, 000 264 0.9 |
---------------------------------------------------------------------------
Bit counts----------------------------------------------
|Suggested size of Bloom Filter | Bit count |
----------------------------------------------
|10 40 |
|100 378 |
|1, 000 3654 |
|10, 000 36231 |
|100, 000 361992 |
|1, 000, 000 3619846 |
-----------------------------------------------
----------------------------------------------
|Suggested size of Bloom Filter | Bit count |
----------------------------------------------
|10 40 |
|100 378 |
|1, 000 3654 |
|10, 000 36231 |
|100, 000 361992 |
|1, 000, 000 3619846 |
-----------------------------------------------
Number of Hash Functions used for various false positive probabilities:-----------------------------------------------
|Suggested FPP of Bloom Filter | Hash Functions|
-----------------------------------------------
|3% 5 |
|1% 7 |
|0.1% 10 |
|0.01% 13 |
|0.001% 17 |
|0.0001% 20 |
------------------------------------------------
-----------------------------------------------
|Suggested FPP of Bloom Filter | Hash Functions|
-----------------------------------------------
|3% 5 |
|1% 7 |
|0.1% 10 |
|0.01% 13 |
|0.001% 17 |
|0.0001% 20 |
------------------------------------------------
Conclusion:
Therefore it can be said that Bloom filter is a good choice in a situation where we have to process large data set with low memory consumption. Also, the more accurate result we want, the number of hash functions has to be increased.
java-advanced
Advanced Computer Subject
Algorithms
Data Structures
Java
Java Programs
Data Structures
Java
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
How to create a REST API using Java Spring Boot
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Difference between BFS and DFS
A* Search Algorithm | [
{
"code": null,
"e": 24306,
"s": 24278,
"text": "\n16 Apr, 2020"
},
{
"code": null,
"e": 24650,
"s": 24306,
"text": "Bloom filters are for set membership which determines whether an element is present in a set or not. Bloom filter was invented by Burton H. Bloom in 1970 in a paper called Space/Time Trade-offs in Hash Coding with Allowable Errors (1970). Bloom filter is a probabilistic data structure that works on hash-coding methods (similar to HashTable)."
},
{
"code": null,
"e": 24723,
"s": 24650,
"text": "When do we need a Bloom Filter?Consider any of the following situations:"
},
{
"code": null,
"e": 25096,
"s": 24723,
"text": "Suppose we have a list of some elements and we want to check whether a given element is present or not?Consider you are working on email service and you are trying to implement sign up endpoint with a feature that a given username is already present or not?Suppose you have given a set of blacklisted IP’s and you want to filter out a given IP is a blacklisted one or not?"
},
{
"code": null,
"e": 25200,
"s": 25096,
"text": "Suppose we have a list of some elements and we want to check whether a given element is present or not?"
},
{
"code": null,
"e": 25355,
"s": 25200,
"text": "Consider you are working on email service and you are trying to implement sign up endpoint with a feature that a given username is already present or not?"
},
{
"code": null,
"e": 25471,
"s": 25355,
"text": "Suppose you have given a set of blacklisted IP’s and you want to filter out a given IP is a blacklisted one or not?"
},
{
"code": null,
"e": 25533,
"s": 25471,
"text": "Can these problem be solved without the help of Bloom Filter?"
},
{
"code": null,
"e": 25583,
"s": 25533,
"text": "Let us try to solve these problem using a HashSet"
},
{
"code": "import java.util.HashSet;import java.util.Set; public class SetDemo { public static void main(String[] args) { Set<String> blackListedIPs = new HashSet<>(); blackListedIPs.add(\"192.170.0.1\"); blackListedIPs.add(\"75.245.10.1\"); blackListedIPs.add(\"10.125.22.20\"); // true System.out.println( blackListedIPs .contains( \"75.245.10.1\")); // false System.out.println( blackListedIPs .contains( \"101.125.20.22\")); }}",
"e": 26165,
"s": 25583,
"text": null
},
{
"code": null,
"e": 26177,
"s": 26165,
"text": "true\nfalse\n"
},
{
"code": null,
"e": 26415,
"s": 26177,
"text": "Why does data structure like HashSet or HashTable fail?HashSet or HashTable works well when we have limited data set, but might not fit as we move with a large data set. With a large data set, it takes a lot of time with a lot of memory."
},
{
"code": null,
"e": 26482,
"s": 26415,
"text": "Size of Data set vs insertion time for HashSet like data structure"
},
{
"code": null,
"e": 26953,
"s": 26482,
"text": "----------------------------------------------\n|Number of UUIDs Insertion Time(ms) |\n----------------------------------------------\n|10 <1 |\n|100 3 |\n|1, 000 58 |\n|10, 000 122 |\n|100, 000 836 |\n|1, 000, 000 7395 |\n----------------------------------------------\n"
},
{
"code": null,
"e": 27023,
"s": 26953,
"text": "Size of Data set vs memory (JVM Heap) for HashSet like data structure"
},
{
"code": null,
"e": 27505,
"s": 27023,
"text": "----------------------------------------------\n|Number of UUIDs JVM heap used(MB) |\n----------------------------------------------\n|10 <2 | \n|100 <2 |\n|1, 000 3 |\n|10, 000 9 |\n|100, 000 37 |\n|1, 000, 000 264 |\n-----------------------------------------------\n"
},
{
"code": null,
"e": 27788,
"s": 27505,
"text": "So it is clear that if we have a large set of data then a normal data structure like the Set or HashTable is not feasible, and here Bloom filters come into the picture. Refer this article for more details on comparison between the two: Difference between Bloom filters and Hashtable"
},
{
"code": null,
"e": 28052,
"s": 27788,
"text": "How to solve these problems with the help of Bloom Filter?Let’s take a bit array of size N (Here 24) and initialize each bit with binary zero, Now take some hash functions (You can take as many you want, we are taking two hash function here for our illustration)."
},
{
"code": null,
"e": 28275,
"s": 28052,
"text": "Now pass the first IP you have to both hash function, which generates some random number as given belowhashFunction_1(192.170.0.1) : 2 \nhashFunction_2(192.170.0.1) : 6\nNow, Go to index 2 and 6 and mark the bit as binary 1."
},
{
"code": null,
"e": 28341,
"s": 28275,
"text": "hashFunction_1(192.170.0.1) : 2 \nhashFunction_2(192.170.0.1) : 6\n"
},
{
"code": null,
"e": 28396,
"s": 28341,
"text": "Now, Go to index 2 and 6 and mark the bit as binary 1."
},
{
"code": null,
"e": 28576,
"s": 28396,
"text": "Now pass the second IP you have, and follow the same step.hashFunction_1(75.245.10.1) : 4 \nhashFunction_2(75.245.10.1) : 10\nNow, Go to index 4 and 10 and mark the bit as binary 1."
},
{
"code": null,
"e": 28643,
"s": 28576,
"text": "hashFunction_1(75.245.10.1) : 4 \nhashFunction_2(75.245.10.1) : 10\n"
},
{
"code": null,
"e": 28699,
"s": 28643,
"text": "Now, Go to index 4 and 10 and mark the bit as binary 1."
},
{
"code": null,
"e": 29088,
"s": 28699,
"text": "Similarly pass the third IP to the both hash function, and suppose you got the below output of hash functionhashFunction_1(10.125.22.20) : 10 \nhashFunction_2(10.125.22.20) : 19\n‘Now, go to index 10 and 19 and mark as binary 1, Here index 10 is already marked by previous entry so just mark the index 19 as binary 1.Now, It is time to check whether an IP is present in the data set or not,"
},
{
"code": null,
"e": 29158,
"s": 29088,
"text": "hashFunction_1(10.125.22.20) : 10 \nhashFunction_2(10.125.22.20) : 19\n"
},
{
"code": null,
"e": 29297,
"s": 29158,
"text": "‘Now, go to index 10 and 19 and mark as binary 1, Here index 10 is already marked by previous entry so just mark the index 19 as binary 1."
},
{
"code": null,
"e": 29371,
"s": 29297,
"text": "Now, It is time to check whether an IP is present in the data set or not,"
},
{
"code": null,
"e": 29764,
"s": 29371,
"text": "Test input #1Let’s say we want to check IP 75.245.10.1. Pass this IP with the same two hash functions which we have taken for adding the above inputs.hashFunction_1(75.245.10.1) : 4 \nhashFunction_2(75.245.10.1) : 10\nNow, Go to the index and check the bit, if both the index 4 and 10 is marked with binary 1 then the IP 75.245.10.1 is present in the set, otherwise it is not with the data set."
},
{
"code": null,
"e": 29831,
"s": 29764,
"text": "hashFunction_1(75.245.10.1) : 4 \nhashFunction_2(75.245.10.1) : 10\n"
},
{
"code": null,
"e": 30008,
"s": 29831,
"text": "Now, Go to the index and check the bit, if both the index 4 and 10 is marked with binary 1 then the IP 75.245.10.1 is present in the set, otherwise it is not with the data set."
},
{
"code": null,
"e": 30407,
"s": 30008,
"text": "Test input #2Let’s say we want to check IP 75.245.20.30 is present in the set or not? So the process will be same, Pass this IP with the same two hash functions which we have taken for adding the above inputs.hashFunction_1(75.245.20.30) : 19 \nhashFunction_2(75.245.20.30) : 23\nSince at index 19 it is set to 1 but at index 23 it is 0, So we can say given IP 75.245.20.30 is not present in the set."
},
{
"code": null,
"e": 30477,
"s": 30407,
"text": "hashFunction_1(75.245.20.30) : 19 \nhashFunction_2(75.245.20.30) : 23\n"
},
{
"code": null,
"e": 30598,
"s": 30477,
"text": "Since at index 19 it is set to 1 but at index 23 it is 0, So we can say given IP 75.245.20.30 is not present in the set."
},
{
"code": null,
"e": 30861,
"s": 30598,
"text": "Why is Bloom Filter a probabilistic data structure?Let’s understand this with one more test, This time consider an IP 101.125.20.22 and check whether it is present in the set or not. Pass this to both hash function. Consider our hash function results as follows."
},
{
"code": null,
"e": 30932,
"s": 30861,
"text": "hashFunction_1(101.125.20.22) : 19 \nhashFunction_2(101.125.20.22) : 2\n"
},
{
"code": null,
"e": 31046,
"s": 30932,
"text": "Now, visit the index 19 and 2 which is set to 1 and it says that the given IP101.125.20.22 is present in the set."
},
{
"code": null,
"e": 31187,
"s": 31046,
"text": "But, this IP 101.125.20.22 has bot been processed above in the data set while adding the IP’s to bit array. This is known as False Positive:"
},
{
"code": null,
"e": 31244,
"s": 31187,
"text": "Expected Output: No\nActual Output: Yes (False Positive)\n"
},
{
"code": null,
"e": 31438,
"s": 31244,
"text": "In this case, index 2 and 19 were set to 1 by other input and not by this IP 101.125.20.22. This is called collision and that’s why it is probabilistic, where chances of happening are not 100%."
},
{
"code": null,
"e": 31474,
"s": 31438,
"text": "What to expect from a Bloom filter?"
},
{
"code": null,
"e": 31904,
"s": 31474,
"text": "When a Bloom filter says an element is not present it is for sure not present. It guarantees 100% that the given element is not available in the set, because either of the bit of index given by hash functions will be set to 0.But when Bloom filter says the given element is present it is not 100% sure, because there may be a chance due to collision all the bit of index given by hash functions has been set to 1 by other inputs."
},
{
"code": null,
"e": 32131,
"s": 31904,
"text": "When a Bloom filter says an element is not present it is for sure not present. It guarantees 100% that the given element is not available in the set, because either of the bit of index given by hash functions will be set to 0."
},
{
"code": null,
"e": 32335,
"s": 32131,
"text": "But when Bloom filter says the given element is present it is not 100% sure, because there may be a chance due to collision all the bit of index given by hash functions has been set to 1 by other inputs."
},
{
"code": null,
"e": 32583,
"s": 32335,
"text": "How to get 100% accurate result from a Bloom filter?Well, this could be achieved only by taking more number of hash functions. The more number of the hash function we take, the more accurate result we get, because of lesser chances of a collision."
},
{
"code": null,
"e": 32718,
"s": 32583,
"text": "Time and Space complexity of a Bloom filterSuppose we have around 40 million data sets and we are using around H hash functions, then:"
},
{
"code": null,
"e": 32898,
"s": 32718,
"text": "Time complexity: O(H), where H is the number of hash functions usedSpace complexity: 159 Mb (For 40 million data sets)Case of False positive: 1 mistake per 10 million (for H = 23)"
},
{
"code": null,
"e": 33024,
"s": 32898,
"text": "Implementing Bloom filter in Java using Guava Library:We can implement the Bloom filter using Java library provided by Guava."
},
{
"code": null,
"e": 34623,
"s": 33024,
"text": "Include the below maven dependency:<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version></dependency>Write the following code to implement the Bloom Filter:// Java program to implement// Bloom Filter using Guava Library import java.nio.charset.Charset;import com.google.common.hash.BloomFilter;import com.google.common.hash.Funnels; public class BloomFilterDemo { public static void main(String[] args) { // Create a Bloom Filter instance BloomFilter<String> blackListedIps = BloomFilter.create( Funnels.stringFunnel( Charset.forName(\"UTF-8\")), 10000); // Add the data sets blackListedIps.put(\"192.170.0.1\"); blackListedIps.put(\"75.245.10.1\"); blackListedIps.put(\"10.125.22.20\"); // Test the bloom filter System.out.println( blackListedIps .mightContain( \"75.245.10.1\")); System.out.println( blackListedIps .mightContain( \"101.125.20.22\")); }}Output:Bloom Filter OutputNote: The above Java code may return a 3% false-positive probability by default.Reduce the false-positive probabilityIntroduce another parameter in Bloom filter object creation as follows:BloomFilter blackListedIps = BloomFilter.create(Funnels.stringFunnel(Charset.forName(\"UTF-8\")), 10000, 0.005);Now false-positive probability has been reduced from 0.03 to 0.005. But tweaking this parameter has an effect on the side of the bloom filter."
},
{
"code": null,
"e": 34784,
"s": 34623,
"text": "Include the below maven dependency:<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version></dependency>"
},
{
"code": "<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version></dependency>",
"e": 34910,
"s": 34784,
"text": null
},
{
"code": null,
"e": 35989,
"s": 34910,
"text": "Write the following code to implement the Bloom Filter:// Java program to implement// Bloom Filter using Guava Library import java.nio.charset.Charset;import com.google.common.hash.BloomFilter;import com.google.common.hash.Funnels; public class BloomFilterDemo { public static void main(String[] args) { // Create a Bloom Filter instance BloomFilter<String> blackListedIps = BloomFilter.create( Funnels.stringFunnel( Charset.forName(\"UTF-8\")), 10000); // Add the data sets blackListedIps.put(\"192.170.0.1\"); blackListedIps.put(\"75.245.10.1\"); blackListedIps.put(\"10.125.22.20\"); // Test the bloom filter System.out.println( blackListedIps .mightContain( \"75.245.10.1\")); System.out.println( blackListedIps .mightContain( \"101.125.20.22\")); }}Output:Bloom Filter OutputNote: The above Java code may return a 3% false-positive probability by default."
},
{
"code": "// Java program to implement// Bloom Filter using Guava Library import java.nio.charset.Charset;import com.google.common.hash.BloomFilter;import com.google.common.hash.Funnels; public class BloomFilterDemo { public static void main(String[] args) { // Create a Bloom Filter instance BloomFilter<String> blackListedIps = BloomFilter.create( Funnels.stringFunnel( Charset.forName(\"UTF-8\")), 10000); // Add the data sets blackListedIps.put(\"192.170.0.1\"); blackListedIps.put(\"75.245.10.1\"); blackListedIps.put(\"10.125.22.20\"); // Test the bloom filter System.out.println( blackListedIps .mightContain( \"75.245.10.1\")); System.out.println( blackListedIps .mightContain( \"101.125.20.22\")); }}",
"e": 36907,
"s": 35989,
"text": null
},
{
"code": null,
"e": 36915,
"s": 36907,
"text": "Output:"
},
{
"code": null,
"e": 36935,
"s": 36915,
"text": "Bloom Filter Output"
},
{
"code": null,
"e": 37016,
"s": 36935,
"text": "Note: The above Java code may return a 3% false-positive probability by default."
},
{
"code": null,
"e": 37377,
"s": 37016,
"text": "Reduce the false-positive probabilityIntroduce another parameter in Bloom filter object creation as follows:BloomFilter blackListedIps = BloomFilter.create(Funnels.stringFunnel(Charset.forName(\"UTF-8\")), 10000, 0.005);Now false-positive probability has been reduced from 0.03 to 0.005. But tweaking this parameter has an effect on the side of the bloom filter."
},
{
"code": null,
"e": 37520,
"s": 37377,
"text": "Now false-positive probability has been reduced from 0.03 to 0.005. But tweaking this parameter has an effect on the side of the bloom filter."
},
{
"code": null,
"e": 37680,
"s": 37520,
"text": "Effect of reducing the false positive probability:Let’s analyze this effect with respect to the hash function, array bit, time complexity and space complexity."
},
{
"code": null,
"e": 38524,
"s": 37680,
"text": "Let’s look on insertion time for different data set.-----------------------------------------------------------------------------\n|Number of UUIDs | Set Insertion Time(ms) | Bloom Filter Insertion Time(ms) |\n-----------------------------------------------------------------------------\n|10 <1 71 | \n|100 3 17 |\n|1, 000 58 84 |\n|10, 000 122 272 |\n|100, 000 836 556 |\n|1, 000, 000 7395 5173 |\n------------------------------------------------------------------------------\n"
},
{
"code": null,
"e": 39316,
"s": 38524,
"text": "-----------------------------------------------------------------------------\n|Number of UUIDs | Set Insertion Time(ms) | Bloom Filter Insertion Time(ms) |\n-----------------------------------------------------------------------------\n|10 <1 71 | \n|100 3 17 |\n|1, 000 58 84 |\n|10, 000 122 272 |\n|100, 000 836 556 |\n|1, 000, 000 7395 5173 |\n------------------------------------------------------------------------------\n"
},
{
"code": null,
"e": 40121,
"s": 39316,
"text": "Now, Let’s have a look on memory(JVM heap)--------------------------------------------------------------------------\n|Number of UUIDs | Set JVM heap used(MB) | Bloom filter JVM heap used(MB) | \n--------------------------------------------------------------------------\n|10 <2 0.01 | \n|100 <2 0.01 |\n|1, 000 3 0.01 |\n|10, 000 9 0.02 |\n|100, 000 37 0.1 |\n|1, 000, 000 264 0.9 |\n---------------------------------------------------------------------------\n"
},
{
"code": null,
"e": 40884,
"s": 40121,
"text": "--------------------------------------------------------------------------\n|Number of UUIDs | Set JVM heap used(MB) | Bloom filter JVM heap used(MB) | \n--------------------------------------------------------------------------\n|10 <2 0.01 | \n|100 <2 0.01 |\n|1, 000 3 0.01 |\n|10, 000 9 0.02 |\n|100, 000 37 0.1 |\n|1, 000, 000 264 0.9 |\n---------------------------------------------------------------------------\n"
},
{
"code": null,
"e": 41376,
"s": 40884,
"text": "Bit counts----------------------------------------------\n|Suggested size of Bloom Filter | Bit count |\n----------------------------------------------\n|10 40 | \n|100 378 |\n|1, 000 3654 |\n|10, 000 36231 |\n|100, 000 361992 |\n|1, 000, 000 3619846 |\n-----------------------------------------------\n"
},
{
"code": null,
"e": 41858,
"s": 41376,
"text": "----------------------------------------------\n|Suggested size of Bloom Filter | Bit count |\n----------------------------------------------\n|10 40 | \n|100 378 |\n|1, 000 3654 |\n|10, 000 36231 |\n|100, 000 361992 |\n|1, 000, 000 3619846 |\n-----------------------------------------------\n"
},
{
"code": null,
"e": 42421,
"s": 41858,
"text": "Number of Hash Functions used for various false positive probabilities:-----------------------------------------------\n|Suggested FPP of Bloom Filter | Hash Functions|\n-----------------------------------------------\n|3% 5 | \n|1% 7 |\n|0.1% 10 |\n|0.01% 13 |\n|0.001% 17 |\n|0.0001% 20 |\n------------------------------------------------\n"
},
{
"code": null,
"e": 42913,
"s": 42421,
"text": "-----------------------------------------------\n|Suggested FPP of Bloom Filter | Hash Functions|\n-----------------------------------------------\n|3% 5 | \n|1% 7 |\n|0.1% 10 |\n|0.01% 13 |\n|0.001% 17 |\n|0.0001% 20 |\n------------------------------------------------\n"
},
{
"code": null,
"e": 42925,
"s": 42913,
"text": "Conclusion:"
},
{
"code": null,
"e": 43159,
"s": 42925,
"text": "Therefore it can be said that Bloom filter is a good choice in a situation where we have to process large data set with low memory consumption. Also, the more accurate result we want, the number of hash functions has to be increased."
},
{
"code": null,
"e": 43173,
"s": 43159,
"text": "java-advanced"
},
{
"code": null,
"e": 43199,
"s": 43173,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 43210,
"s": 43199,
"text": "Algorithms"
},
{
"code": null,
"e": 43226,
"s": 43210,
"text": "Data Structures"
},
{
"code": null,
"e": 43231,
"s": 43226,
"text": "Java"
},
{
"code": null,
"e": 43245,
"s": 43231,
"text": "Java Programs"
},
{
"code": null,
"e": 43261,
"s": 43245,
"text": "Data Structures"
},
{
"code": null,
"e": 43266,
"s": 43261,
"text": "Java"
},
{
"code": null,
"e": 43277,
"s": 43266,
"text": "Algorithms"
},
{
"code": null,
"e": 43375,
"s": 43277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43419,
"s": 43375,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 43460,
"s": 43419,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 43487,
"s": 43460,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 43550,
"s": 43487,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 43598,
"s": 43550,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 43647,
"s": 43598,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 43691,
"s": 43647,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 43716,
"s": 43691,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 43747,
"s": 43716,
"text": "Difference between BFS and DFS"
}
] |
How to clear the memory completely of all Matplotlib plots? | Using the following methods, we can clear the memory occupied by Matplotlib plots.
plt.figure() - Create a new figure or activate an existing figure.
plt.figure() - Create a new figure or activate an existing figure.
plt.figure().close() - Close a figure window.close() by itself closes the current figureclose(h), where h is a Figure instance, closes that figureclose(num) closes the figure number, numclose(name), where name is a string, closes figure with that labelclose('all') closes all the figure windows
plt.figure().close() - Close a figure window.
close() by itself closes the current figure
close() by itself closes the current figure
close(h), where h is a Figure instance, closes that figure
close(h), where h is a Figure instance, closes that figure
close(num) closes the figure number, num
close(num) closes the figure number, num
close(name), where name is a string, closes figure with that label
close(name), where name is a string, closes figure with that label
close('all') closes all the figure windows
close('all') closes all the figure windows
plt.figure().clear() - It is the same as clf.
plt.figure().clear() - It is the same as clf.
plt.cla() - Clear the current axes.
plt.cla() - Clear the current axes.
plt.clf() - Clear the current figure.
plt.clf() - Clear the current figure.
from matplotlib import pyplot as plt
fig = plt.figure()
plt.figure().clear()
plt.close()
plt.cla()
plt.clf()
When we execute the code, it will clear all the plots from the memory. | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "Using the following methods, we can clear the memory occupied by Matplotlib plots."
},
{
"code": null,
"e": 1212,
"s": 1145,
"text": "plt.figure() - Create a new figure or activate an existing figure."
},
{
"code": null,
"e": 1279,
"s": 1212,
"text": "plt.figure() - Create a new figure or activate an existing figure."
},
{
"code": null,
"e": 1575,
"s": 1279,
"text": "plt.figure().close() - Close a figure window.close() by itself closes the current figureclose(h), where h is a Figure instance, closes that figureclose(num) closes the figure number, numclose(name), where name is a string, closes figure with that labelclose('all') closes all the figure windows"
},
{
"code": null,
"e": 1622,
"s": 1575,
"text": "plt.figure().close() - Close a figure window."
},
{
"code": null,
"e": 1666,
"s": 1622,
"text": "close() by itself closes the current figure"
},
{
"code": null,
"e": 1710,
"s": 1666,
"text": "close() by itself closes the current figure"
},
{
"code": null,
"e": 1769,
"s": 1710,
"text": "close(h), where h is a Figure instance, closes that figure"
},
{
"code": null,
"e": 1828,
"s": 1769,
"text": "close(h), where h is a Figure instance, closes that figure"
},
{
"code": null,
"e": 1869,
"s": 1828,
"text": "close(num) closes the figure number, num"
},
{
"code": null,
"e": 1910,
"s": 1869,
"text": "close(num) closes the figure number, num"
},
{
"code": null,
"e": 1977,
"s": 1910,
"text": "close(name), where name is a string, closes figure with that label"
},
{
"code": null,
"e": 2044,
"s": 1977,
"text": "close(name), where name is a string, closes figure with that label"
},
{
"code": null,
"e": 2087,
"s": 2044,
"text": "close('all') closes all the figure windows"
},
{
"code": null,
"e": 2130,
"s": 2087,
"text": "close('all') closes all the figure windows"
},
{
"code": null,
"e": 2176,
"s": 2130,
"text": "plt.figure().clear() - It is the same as clf."
},
{
"code": null,
"e": 2222,
"s": 2176,
"text": "plt.figure().clear() - It is the same as clf."
},
{
"code": null,
"e": 2258,
"s": 2222,
"text": "plt.cla() - Clear the current axes."
},
{
"code": null,
"e": 2294,
"s": 2258,
"text": "plt.cla() - Clear the current axes."
},
{
"code": null,
"e": 2332,
"s": 2294,
"text": "plt.clf() - Clear the current figure."
},
{
"code": null,
"e": 2370,
"s": 2332,
"text": "plt.clf() - Clear the current figure."
},
{
"code": null,
"e": 2479,
"s": 2370,
"text": "from matplotlib import pyplot as plt\nfig = plt.figure()\nplt.figure().clear()\nplt.close()\nplt.cla()\nplt.clf()"
},
{
"code": null,
"e": 2550,
"s": 2479,
"text": "When we execute the code, it will clear all the plots from the memory."
}
] |
LiDAR point cloud based 3D object detection implementation with colab{Part 2 of 2} | by Gopalakrishna Adusumilli | Towards Data Science | VoxelNet a point cloud based 3D object detection algorithm is implemented using google colab.
In my previous article, I have explained crucial concepts required to implement the VoxelNet an end-to-end learning model for the 3d object detection you can find here
In continuation with the previous article, we will work out to implement the VoxelNet algorithm for the 3d object detection using KITTI point cloud data
Step 1: Processing the KITTI dataset to train the model[Detailed steps]
The following steps are crucial to prepare the data to train the model. KITTI dataset needs to be downloaded, cropped, processed, and save in the drive.
login to google colab, Open a notebook, GPU is not required at the moment.
Note: in case if GPU is selected, note that each user is provided with ~30GB of virtual space and the entire dataset has a size of ~40+ GB and then to unzip dataset memory will run out. In the next steps we will download the KITTI datset, process, crop and create .zip and move to the drive to use the data for future
Required dataset
Velodyne point clouds (29 GB): input data to VoxelNet
Velodyne point clouds (29 GB): input data to VoxelNet
2. Training labels of the object data set (5 MB): input label to VoxelNet
3. Camera calibration matrices of the object data set (16 MB): for visualization of predictions
4. Left color images of the object data set (12 GB): for visualization of predictions
#clone the voxelnet git repo!git clone https://github.com/gkadusumilli/Voxelnet.git#change the cwd%cd /content/drive/My Drive/Voxelnet/crop_data
To download the datasets (.zip) directly to the colab virtual machine [~ 15–20 mins]
#Data label file!wget (enter the link)#Calib file!wget (enter the link )#Velodyne file!wget (enter the link)# Image file!wget (enter the link)
Unzip the datasets(.zip) to the folder (~20- 30 mins)
#Unzip the velodyne training folder!unzip /content/Voxelnet/crop_data/data_object_velodyne.zip 'training/*' -d /content/Voxelnet/crop_data#Unzip the image training folder!unzip /content/Voxelnet/crop_data/data_object_image_2.zip 'training/*' -d /content/Voxelnet/crop_data#unzip the object label!unzip /content/Voxelnet/crop_data/data_object_label_2.zip#unzip the data object calib!unzip /content/Voxelnet/crop_data/data_object_calib.zip 'training/*' -d /content/Voxelnet/crop_data
cropping point cloud data for training and validation. Point clouds outside the image coordinates are removed. cropped point cloud will overwrite the existing raw point cloud [40–45 mins]
#to run the 'crop.py' lower version of scipy is needed!pip install scipy==1.1.0#run crop.py!python crop.py
Create the validation data to evaluate the model[~10–15 mins]
#create a folder 'validation' and copy the content in training #folder!mkdir /content/Voxelnet/crop_data/validation%cp -av /content/Voxelnet/crop_data/training /content/Voxelnet/crop_data/validation/
we will split the training as per the protocols here [2–3 mins]
Final step...
create .zip the folder of the processed, cropped data [30–40mins]
!zip -r /content/VoxelNet/data/data_lidar.zip /content/VoxelNet/crop_data
Move the .zip folder to the drive [~5 mins]
#rename the folder as you need in the drive, I've stored in dtive with the folder named 'AI'!mv "/content/VoxelNet/data/data_lidar.zip" "/content/gdrive/My Drive/AI"
Here is the link to the colab jupyter notebook with all the above-mentioned steps.
log in to google colab , create a new notebook
To access the GPU: Click on runtime > Change runtime type > GPU
Note: The colab GPU runtime is approximate ~12 hours post that, the runtime will be disconnected, the data stored will be lost. Since in our case each epoch would take ~2 hours and need to train for more than 20 epochs to observe the preliminary results. So will use google drive as a path to store the code, checkpoints, prediction results, and so on
Change the current working directory(CWD) to drive
#voxelnet is the folder name, you can rename as you need%cd /content/drive/My Drive/Voxelnet
VoxelNet implementation needs several dependencies. So we will clone the entire repository.
!git clone https://github.com/gkadusumilli/Voxelnet.git
Building the files
%cd /content/drive/My Drive/Voxelnet!python setup.py build_ext --inplace
Unzip the processed dataset in the crop_data folder [35–40 mins]
%cd /content/drive/My Drive/Voxelnet/crop_data#Locate the zip folder in the drive and unzip using !unzip command!unzip "/content/drive/My Drive/AI/data_lidar.zip"
Training the model
%cd /content/drive/My Drive/Voxelnet/
Important argument parse
!python train.py \--strategy="all" \--n_epochs=16 \--batch_size=2 \--learning_rate=0.001 \--small_addon_for_BCE=1e-6 \--max_gradient_norm=5 \--alpha_bce=1.5 \--beta_bce=1 \--huber_delta=3 \#if dump_vis == yes, boolean to save visualization results--dump_vis="no" \--data_root_dir="/content/drive/My Drive/Voxelnet/crop_data" \--model_dir="model" \--model_name="model6" \--dump_test_interval=3 \--summary_interval=2 \--summary_val_interval=40 \--summary_flush_interval=20 \--ckpt_max_keep=10 \
%load_ext tensorboard#summary_logdir is the logdir name%tensorboard --logdir summary_logdir
The below snap is the logdir results @ epoch6
!python predict.py \--strategy="all" \--batch_size=2 \--dump_vis="yes" \--data_root_dir="../DATA_DIR/T_DATA/" \--dataset_to_test="validation" \--model_dir="model" \--model_name="model6" \--ckpt_name="" \
The code to download, crop, process the KITTI dataset can be found here
The code to implement from step 2 can be found here
Here are some of the results obtained after training the model for 30 epochs.
Special thanks to Tsinghua Robot Learning Lab, Qiangui Huang, David Stephane for their valuable contribution in the implementation of VoxelNet
Special thanks:
Dr.Uma K Mudenagudi, KLE Technological University for the project mentorship.
References:
KITTI raw dataset: @ARTICLE{Geiger2013IJRR,author = {Andreas Geiger and Philip Lenz and Christoph Stiller and Raquel Urtasun},title = {Vision meets Robotics: The KITTI Dataset},journal = {International Journal of Robotics Research (IJRR)},year = {2013}} | [
{
"code": null,
"e": 266,
"s": 172,
"text": "VoxelNet a point cloud based 3D object detection algorithm is implemented using google colab."
},
{
"code": null,
"e": 434,
"s": 266,
"text": "In my previous article, I have explained crucial concepts required to implement the VoxelNet an end-to-end learning model for the 3d object detection you can find here"
},
{
"code": null,
"e": 587,
"s": 434,
"text": "In continuation with the previous article, we will work out to implement the VoxelNet algorithm for the 3d object detection using KITTI point cloud data"
},
{
"code": null,
"e": 659,
"s": 587,
"text": "Step 1: Processing the KITTI dataset to train the model[Detailed steps]"
},
{
"code": null,
"e": 812,
"s": 659,
"text": "The following steps are crucial to prepare the data to train the model. KITTI dataset needs to be downloaded, cropped, processed, and save in the drive."
},
{
"code": null,
"e": 887,
"s": 812,
"text": "login to google colab, Open a notebook, GPU is not required at the moment."
},
{
"code": null,
"e": 1205,
"s": 887,
"text": "Note: in case if GPU is selected, note that each user is provided with ~30GB of virtual space and the entire dataset has a size of ~40+ GB and then to unzip dataset memory will run out. In the next steps we will download the KITTI datset, process, crop and create .zip and move to the drive to use the data for future"
},
{
"code": null,
"e": 1222,
"s": 1205,
"text": "Required dataset"
},
{
"code": null,
"e": 1276,
"s": 1222,
"text": "Velodyne point clouds (29 GB): input data to VoxelNet"
},
{
"code": null,
"e": 1330,
"s": 1276,
"text": "Velodyne point clouds (29 GB): input data to VoxelNet"
},
{
"code": null,
"e": 1404,
"s": 1330,
"text": "2. Training labels of the object data set (5 MB): input label to VoxelNet"
},
{
"code": null,
"e": 1500,
"s": 1404,
"text": "3. Camera calibration matrices of the object data set (16 MB): for visualization of predictions"
},
{
"code": null,
"e": 1586,
"s": 1500,
"text": "4. Left color images of the object data set (12 GB): for visualization of predictions"
},
{
"code": null,
"e": 1731,
"s": 1586,
"text": "#clone the voxelnet git repo!git clone https://github.com/gkadusumilli/Voxelnet.git#change the cwd%cd /content/drive/My Drive/Voxelnet/crop_data"
},
{
"code": null,
"e": 1816,
"s": 1731,
"text": "To download the datasets (.zip) directly to the colab virtual machine [~ 15–20 mins]"
},
{
"code": null,
"e": 1959,
"s": 1816,
"text": "#Data label file!wget (enter the link)#Calib file!wget (enter the link )#Velodyne file!wget (enter the link)# Image file!wget (enter the link)"
},
{
"code": null,
"e": 2013,
"s": 1959,
"text": "Unzip the datasets(.zip) to the folder (~20- 30 mins)"
},
{
"code": null,
"e": 2495,
"s": 2013,
"text": "#Unzip the velodyne training folder!unzip /content/Voxelnet/crop_data/data_object_velodyne.zip 'training/*' -d /content/Voxelnet/crop_data#Unzip the image training folder!unzip /content/Voxelnet/crop_data/data_object_image_2.zip 'training/*' -d /content/Voxelnet/crop_data#unzip the object label!unzip /content/Voxelnet/crop_data/data_object_label_2.zip#unzip the data object calib!unzip /content/Voxelnet/crop_data/data_object_calib.zip 'training/*' -d /content/Voxelnet/crop_data"
},
{
"code": null,
"e": 2683,
"s": 2495,
"text": "cropping point cloud data for training and validation. Point clouds outside the image coordinates are removed. cropped point cloud will overwrite the existing raw point cloud [40–45 mins]"
},
{
"code": null,
"e": 2790,
"s": 2683,
"text": "#to run the 'crop.py' lower version of scipy is needed!pip install scipy==1.1.0#run crop.py!python crop.py"
},
{
"code": null,
"e": 2852,
"s": 2790,
"text": "Create the validation data to evaluate the model[~10–15 mins]"
},
{
"code": null,
"e": 3052,
"s": 2852,
"text": "#create a folder 'validation' and copy the content in training #folder!mkdir /content/Voxelnet/crop_data/validation%cp -av /content/Voxelnet/crop_data/training /content/Voxelnet/crop_data/validation/"
},
{
"code": null,
"e": 3116,
"s": 3052,
"text": "we will split the training as per the protocols here [2–3 mins]"
},
{
"code": null,
"e": 3130,
"s": 3116,
"text": "Final step..."
},
{
"code": null,
"e": 3196,
"s": 3130,
"text": "create .zip the folder of the processed, cropped data [30–40mins]"
},
{
"code": null,
"e": 3270,
"s": 3196,
"text": "!zip -r /content/VoxelNet/data/data_lidar.zip /content/VoxelNet/crop_data"
},
{
"code": null,
"e": 3314,
"s": 3270,
"text": "Move the .zip folder to the drive [~5 mins]"
},
{
"code": null,
"e": 3480,
"s": 3314,
"text": "#rename the folder as you need in the drive, I've stored in dtive with the folder named 'AI'!mv \"/content/VoxelNet/data/data_lidar.zip\" \"/content/gdrive/My Drive/AI\""
},
{
"code": null,
"e": 3563,
"s": 3480,
"text": "Here is the link to the colab jupyter notebook with all the above-mentioned steps."
},
{
"code": null,
"e": 3610,
"s": 3563,
"text": "log in to google colab , create a new notebook"
},
{
"code": null,
"e": 3674,
"s": 3610,
"text": "To access the GPU: Click on runtime > Change runtime type > GPU"
},
{
"code": null,
"e": 4026,
"s": 3674,
"text": "Note: The colab GPU runtime is approximate ~12 hours post that, the runtime will be disconnected, the data stored will be lost. Since in our case each epoch would take ~2 hours and need to train for more than 20 epochs to observe the preliminary results. So will use google drive as a path to store the code, checkpoints, prediction results, and so on"
},
{
"code": null,
"e": 4077,
"s": 4026,
"text": "Change the current working directory(CWD) to drive"
},
{
"code": null,
"e": 4170,
"s": 4077,
"text": "#voxelnet is the folder name, you can rename as you need%cd /content/drive/My Drive/Voxelnet"
},
{
"code": null,
"e": 4262,
"s": 4170,
"text": "VoxelNet implementation needs several dependencies. So we will clone the entire repository."
},
{
"code": null,
"e": 4318,
"s": 4262,
"text": "!git clone https://github.com/gkadusumilli/Voxelnet.git"
},
{
"code": null,
"e": 4337,
"s": 4318,
"text": "Building the files"
},
{
"code": null,
"e": 4410,
"s": 4337,
"text": "%cd /content/drive/My Drive/Voxelnet!python setup.py build_ext --inplace"
},
{
"code": null,
"e": 4475,
"s": 4410,
"text": "Unzip the processed dataset in the crop_data folder [35–40 mins]"
},
{
"code": null,
"e": 4638,
"s": 4475,
"text": "%cd /content/drive/My Drive/Voxelnet/crop_data#Locate the zip folder in the drive and unzip using !unzip command!unzip \"/content/drive/My Drive/AI/data_lidar.zip\""
},
{
"code": null,
"e": 4657,
"s": 4638,
"text": "Training the model"
},
{
"code": null,
"e": 4695,
"s": 4657,
"text": "%cd /content/drive/My Drive/Voxelnet/"
},
{
"code": null,
"e": 4720,
"s": 4695,
"text": "Important argument parse"
},
{
"code": null,
"e": 5213,
"s": 4720,
"text": "!python train.py \\--strategy=\"all\" \\--n_epochs=16 \\--batch_size=2 \\--learning_rate=0.001 \\--small_addon_for_BCE=1e-6 \\--max_gradient_norm=5 \\--alpha_bce=1.5 \\--beta_bce=1 \\--huber_delta=3 \\#if dump_vis == yes, boolean to save visualization results--dump_vis=\"no\" \\--data_root_dir=\"/content/drive/My Drive/Voxelnet/crop_data\" \\--model_dir=\"model\" \\--model_name=\"model6\" \\--dump_test_interval=3 \\--summary_interval=2 \\--summary_val_interval=40 \\--summary_flush_interval=20 \\--ckpt_max_keep=10 \\"
},
{
"code": null,
"e": 5305,
"s": 5213,
"text": "%load_ext tensorboard#summary_logdir is the logdir name%tensorboard --logdir summary_logdir"
},
{
"code": null,
"e": 5351,
"s": 5305,
"text": "The below snap is the logdir results @ epoch6"
},
{
"code": null,
"e": 5555,
"s": 5351,
"text": "!python predict.py \\--strategy=\"all\" \\--batch_size=2 \\--dump_vis=\"yes\" \\--data_root_dir=\"../DATA_DIR/T_DATA/\" \\--dataset_to_test=\"validation\" \\--model_dir=\"model\" \\--model_name=\"model6\" \\--ckpt_name=\"\" \\"
},
{
"code": null,
"e": 5627,
"s": 5555,
"text": "The code to download, crop, process the KITTI dataset can be found here"
},
{
"code": null,
"e": 5679,
"s": 5627,
"text": "The code to implement from step 2 can be found here"
},
{
"code": null,
"e": 5757,
"s": 5679,
"text": "Here are some of the results obtained after training the model for 30 epochs."
},
{
"code": null,
"e": 5900,
"s": 5757,
"text": "Special thanks to Tsinghua Robot Learning Lab, Qiangui Huang, David Stephane for their valuable contribution in the implementation of VoxelNet"
},
{
"code": null,
"e": 5916,
"s": 5900,
"text": "Special thanks:"
},
{
"code": null,
"e": 5994,
"s": 5916,
"text": "Dr.Uma K Mudenagudi, KLE Technological University for the project mentorship."
},
{
"code": null,
"e": 6006,
"s": 5994,
"text": "References:"
}
] |
Apache Kafka - Basic Operations | First let us start implementing single node-single broker configuration and we will then migrate our setup to single node-multiple brokers configuration.
Hopefully you would have installed Java, ZooKeeper and Kafka on your machine by now. Before moving to the Kafka Cluster Setup, first you would need to start your ZooKeeper because Kafka Cluster uses ZooKeeper.
Open a new terminal and type the following command −
bin/zookeeper-server-start.sh config/zookeeper.properties
To start Kafka Broker, type the following command −
bin/kafka-server-start.sh config/server.properties
After starting Kafka Broker, type the command jps on ZooKeeper terminal and you would see the following response −
821 QuorumPeerMain
928 Kafka
931 Jps
Now you could see two daemons running on the terminal where QuorumPeerMain is ZooKeeper daemon and another one is Kafka daemon.
In this configuration you have a single ZooKeeper and broker id instance. Following are the steps to configure it −
Creating a Kafka Topic − Kafka provides a command line utility named kafka-topics.sh to create topics on the server. Open new terminal and type the below example.
Syntax
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1
--partitions 1 --topic topic-name
Example
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1
--partitions 1 --topic Hello-Kafka
We just created a topic named Hello-Kafka with a single partition and one replica factor. The above created output will be similar to the following output −
Output − Created topic Hello-Kafka
Once the topic has been created, you can get the notification in Kafka broker terminal window and the log for the created topic specified in “/tmp/kafka-logs/“ in the config/server.properties file.
To get a list of topics in Kafka server, you can use the following command −
Syntax
bin/kafka-topics.sh --list --zookeeper localhost:2181
Output
Hello-Kafka
Since we have created a topic, it will list out Hello-Kafka only. Suppose, if you create more than one topics, you will get the topic names in the output.
Syntax
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic topic-name
From the above syntax, two main parameters are required for the producer command line client −
Broker-list − The list of brokers that we want to send the messages to. In this case we only have one broker. The Config/server.properties file contains broker port id, since we know our broker is listening on port 9092, so you can specify it directly.
Topic name − Here is an example for the topic name.
Example
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Hello-Kafka
The producer will wait on input from stdin and publishes to the Kafka cluster. By default, every new line is published as a new message then the default producer properties are specified in config/producer.properties file. Now you can type a few lines of messages in the terminal as shown below.
Output
$ bin/kafka-console-producer.sh --broker-list localhost:9092
--topic Hello-Kafka[2016-01-16 13:50:45,931]
WARN property topic is not valid (kafka.utils.Verifia-bleProperties)
Hello
My first message
My second message
Similar to producer, the default consumer properties are specified in config/consumer.proper-ties file. Open a new terminal and type the below syntax for consuming messages.
Syntax
bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic topic-name
--from-beginning
Example
bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic Hello-Kafka
--from-beginning
Output
Hello
My first message
My second message
Finally, you are able to enter messages from the producer’s terminal and see them appearing in the consumer’s terminal. As of now, you have a very good understanding on the single node cluster with a single broker. Let us now move on to the multiple brokers configuration.
Before moving on to the multiple brokers cluster setup, first start your ZooKeeper server.
Create Multiple Kafka Brokers − We have one Kafka broker instance already in con-fig/server.properties. Now we need multiple broker instances, so copy the existing server.prop-erties file into two new config files and rename it as server-one.properties and server-two.prop-erties. Then edit both new files and assign the following changes −
# The id of the broker. This must be set to a unique integer for each broker.
broker.id=1
# The port the socket server listens on
port=9093
# A comma seperated list of directories under which to store log files
log.dirs=/tmp/kafka-logs-1
# The id of the broker. This must be set to a unique integer for each broker.
broker.id=2
# The port the socket server listens on
port=9094
# A comma seperated list of directories under which to store log files
log.dirs=/tmp/kafka-logs-2
Start Multiple Brokers− After all the changes have been made on three servers then open three new terminals to start each broker one by one.
Broker1
bin/kafka-server-start.sh config/server.properties
Broker2
bin/kafka-server-start.sh config/server-one.properties
Broker3
bin/kafka-server-start.sh config/server-two.properties
Now we have three different brokers running on the machine. Try it by yourself to check all the daemons by typing jps on the ZooKeeper terminal, then you would see the response.
Let us assign the replication factor value as three for this topic because we have three different brokers running. If you have two brokers, then the assigned replica value will be two.
Syntax
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3
-partitions 1 --topic topic-name
Example
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3
-partitions 1 --topic Multibrokerapplication
Output
created topic “Multibrokerapplication”
The Describe command is used to check which broker is listening on the current created topic as shown below −
bin/kafka-topics.sh --describe --zookeeper localhost:2181
--topic Multibrokerappli-cation
Output
bin/kafka-topics.sh --describe --zookeeper localhost:2181
--topic Multibrokerappli-cation
Topic:Multibrokerapplication PartitionCount:1
ReplicationFactor:3 Configs:
Topic:Multibrokerapplication Partition:0 Leader:0
Replicas:0,2,1 Isr:0,2,1
From the above output, we can conclude that first line gives a summary of all the partitions, showing topic name, partition count and the replication factor that we have chosen already. In the second line, each node will be the leader for a randomly selected portion of the partitions.
In our case, we see that our first broker (with broker.id 0) is the leader. Then Replicas:0,2,1 means that all the brokers replicate the topic finally Isr is the set of in-sync replicas. Well, this is the subset of replicas that are currently alive and caught up by the leader.
This procedure remains the same as in the single broker setup.
Example
bin/kafka-console-producer.sh --broker-list localhost:9092
--topic Multibrokerapplication
Output
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Multibrokerapplication
[2016-01-20 19:27:21,045] WARN Property topic is not valid (kafka.utils.Verifia-bleProperties)
This is single node-multi broker demo
This is the second message
This procedure remains the same as shown in the single broker setup.
Example
bin/kafka-console-consumer.sh --zookeeper localhost:2181
—topic Multibrokerapplica-tion --from-beginning
Output
bin/kafka-console-consumer.sh --zookeeper localhost:2181
—topic Multibrokerapplica-tion —from-beginning
This is single node-multi broker demo
This is the second message
In this chapter we will discuss the various basic topic operations.
As you have already understood how to create a topic in Kafka Cluster. Now let us modify a created topic using the following command
Syntax
bin/kafka-topics.sh —zookeeper localhost:2181 --alter --topic topic_name
--parti-tions count
Example
We have already created a topic “Hello-Kafka” with single partition count and one replica factor.
Now using “alter” command we have changed the partition count.
bin/kafka-topics.sh --zookeeper localhost:2181
--alter --topic Hello-kafka --parti-tions 2
Output
WARNING: If partitions are increased for a topic that has a key,
the partition logic or ordering of the messages will be affected
Adding partitions succeeded!
To delete a topic, you can use the following syntax.
Syntax
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic topic_name
Example
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic Hello-kafka
Output
> Topic Hello-kafka marked for deletion
Note −This will have no impact if delete.topic.enable is not set to true
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": 2121,
"s": 1967,
"text": "First let us start implementing single node-single broker configuration and we will then migrate our setup to single node-multiple brokers configuration."
},
{
"code": null,
"e": 2331,
"s": 2121,
"text": "Hopefully you would have installed Java, ZooKeeper and Kafka on your machine by now. Before moving to the Kafka Cluster Setup, first you would need to start your ZooKeeper because Kafka Cluster uses ZooKeeper."
},
{
"code": null,
"e": 2384,
"s": 2331,
"text": "Open a new terminal and type the following command −"
},
{
"code": null,
"e": 2443,
"s": 2384,
"text": "bin/zookeeper-server-start.sh config/zookeeper.properties\n"
},
{
"code": null,
"e": 2495,
"s": 2443,
"text": "To start Kafka Broker, type the following command −"
},
{
"code": null,
"e": 2547,
"s": 2495,
"text": "bin/kafka-server-start.sh config/server.properties\n"
},
{
"code": null,
"e": 2662,
"s": 2547,
"text": "After starting Kafka Broker, type the command jps on ZooKeeper terminal and you would see the following response −"
},
{
"code": null,
"e": 2700,
"s": 2662,
"text": "821 QuorumPeerMain\n928 Kafka\n931 Jps\n"
},
{
"code": null,
"e": 2828,
"s": 2700,
"text": "Now you could see two daemons running on the terminal where QuorumPeerMain is ZooKeeper daemon and another one is Kafka daemon."
},
{
"code": null,
"e": 2944,
"s": 2828,
"text": "In this configuration you have a single ZooKeeper and broker id instance. Following are the steps to configure it −"
},
{
"code": null,
"e": 3107,
"s": 2944,
"text": "Creating a Kafka Topic − Kafka provides a command line utility named kafka-topics.sh to create topics on the server. Open new terminal and type the below example."
},
{
"code": null,
"e": 3114,
"s": 3107,
"text": "Syntax"
},
{
"code": null,
"e": 3229,
"s": 3114,
"text": "bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 \n--partitions 1 --topic topic-name\n"
},
{
"code": null,
"e": 3237,
"s": 3229,
"text": "Example"
},
{
"code": null,
"e": 3354,
"s": 3237,
"text": "bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 \n--partitions 1 --topic Hello-Kafka"
},
{
"code": null,
"e": 3511,
"s": 3354,
"text": "We just created a topic named Hello-Kafka with a single partition and one replica factor. The above created output will be similar to the following output −"
},
{
"code": null,
"e": 3546,
"s": 3511,
"text": "Output − Created topic Hello-Kafka"
},
{
"code": null,
"e": 3744,
"s": 3546,
"text": "Once the topic has been created, you can get the notification in Kafka broker terminal window and the log for the created topic specified in “/tmp/kafka-logs/“ in the config/server.properties file."
},
{
"code": null,
"e": 3821,
"s": 3744,
"text": "To get a list of topics in Kafka server, you can use the following command −"
},
{
"code": null,
"e": 3828,
"s": 3821,
"text": "Syntax"
},
{
"code": null,
"e": 3883,
"s": 3828,
"text": "bin/kafka-topics.sh --list --zookeeper localhost:2181\n"
},
{
"code": null,
"e": 3890,
"s": 3883,
"text": "Output"
},
{
"code": null,
"e": 3903,
"s": 3890,
"text": "Hello-Kafka\n"
},
{
"code": null,
"e": 4058,
"s": 3903,
"text": "Since we have created a topic, it will list out Hello-Kafka only. Suppose, if you create more than one topics, you will get the topic names in the output."
},
{
"code": null,
"e": 4065,
"s": 4058,
"text": "Syntax"
},
{
"code": null,
"e": 4144,
"s": 4065,
"text": "bin/kafka-console-producer.sh --broker-list localhost:9092 --topic topic-name\n"
},
{
"code": null,
"e": 4239,
"s": 4144,
"text": "From the above syntax, two main parameters are required for the producer command line client −"
},
{
"code": null,
"e": 4492,
"s": 4239,
"text": "Broker-list − The list of brokers that we want to send the messages to. In this case we only have one broker. The Config/server.properties file contains broker port id, since we know our broker is listening on port 9092, so you can specify it directly."
},
{
"code": null,
"e": 4544,
"s": 4492,
"text": "Topic name − Here is an example for the topic name."
},
{
"code": null,
"e": 4552,
"s": 4544,
"text": "Example"
},
{
"code": null,
"e": 4631,
"s": 4552,
"text": "bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Hello-Kafka"
},
{
"code": null,
"e": 4927,
"s": 4631,
"text": "The producer will wait on input from stdin and publishes to the Kafka cluster. By default, every new line is published as a new message then the default producer properties are specified in config/producer.properties file. Now you can type a few lines of messages in the terminal as shown below."
},
{
"code": null,
"e": 4934,
"s": 4927,
"text": "Output"
},
{
"code": null,
"e": 5134,
"s": 4934,
"text": "$ bin/kafka-console-producer.sh --broker-list localhost:9092 \n--topic Hello-Kafka[2016-01-16 13:50:45,931] \nWARN property topic is not valid (kafka.utils.Verifia-bleProperties)\nHello\nMy first message"
},
{
"code": null,
"e": 5153,
"s": 5134,
"text": "My second message\n"
},
{
"code": null,
"e": 5327,
"s": 5153,
"text": "Similar to producer, the default consumer properties are specified in config/consumer.proper-ties file. Open a new terminal and type the below syntax for consuming messages."
},
{
"code": null,
"e": 5334,
"s": 5327,
"text": "Syntax"
},
{
"code": null,
"e": 5428,
"s": 5334,
"text": "bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic topic-name \n--from-beginning\n"
},
{
"code": null,
"e": 5436,
"s": 5428,
"text": "Example"
},
{
"code": null,
"e": 5530,
"s": 5436,
"text": "bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic Hello-Kafka \n--from-beginning"
},
{
"code": null,
"e": 5537,
"s": 5530,
"text": "Output"
},
{
"code": null,
"e": 5579,
"s": 5537,
"text": "Hello\nMy first message\nMy second message\n"
},
{
"code": null,
"e": 5852,
"s": 5579,
"text": "Finally, you are able to enter messages from the producer’s terminal and see them appearing in the consumer’s terminal. As of now, you have a very good understanding on the single node cluster with a single broker. Let us now move on to the multiple brokers configuration."
},
{
"code": null,
"e": 5943,
"s": 5852,
"text": "Before moving on to the multiple brokers cluster setup, first start your ZooKeeper server."
},
{
"code": null,
"e": 6284,
"s": 5943,
"text": "Create Multiple Kafka Brokers − We have one Kafka broker instance already in con-fig/server.properties. Now we need multiple broker instances, so copy the existing server.prop-erties file into two new config files and rename it as server-one.properties and server-two.prop-erties. Then edit both new files and assign the following changes −"
},
{
"code": null,
"e": 6523,
"s": 6284,
"text": "# The id of the broker. This must be set to a unique integer for each broker.\nbroker.id=1\n# The port the socket server listens on\nport=9093\n# A comma seperated list of directories under which to store log files\nlog.dirs=/tmp/kafka-logs-1\n"
},
{
"code": null,
"e": 6762,
"s": 6523,
"text": "# The id of the broker. This must be set to a unique integer for each broker.\nbroker.id=2\n# The port the socket server listens on\nport=9094\n# A comma seperated list of directories under which to store log files\nlog.dirs=/tmp/kafka-logs-2\n"
},
{
"code": null,
"e": 6903,
"s": 6762,
"text": "Start Multiple Brokers− After all the changes have been made on three servers then open three new terminals to start each broker one by one."
},
{
"code": null,
"e": 7089,
"s": 6903,
"text": "Broker1\nbin/kafka-server-start.sh config/server.properties\nBroker2\nbin/kafka-server-start.sh config/server-one.properties\nBroker3\nbin/kafka-server-start.sh config/server-two.properties\n"
},
{
"code": null,
"e": 7267,
"s": 7089,
"text": "Now we have three different brokers running on the machine. Try it by yourself to check all the daemons by typing jps on the ZooKeeper terminal, then you would see the response."
},
{
"code": null,
"e": 7453,
"s": 7267,
"text": "Let us assign the replication factor value as three for this topic because we have three different brokers running. If you have two brokers, then the assigned replica value will be two."
},
{
"code": null,
"e": 7460,
"s": 7453,
"text": "Syntax"
},
{
"code": null,
"e": 7574,
"s": 7460,
"text": "bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 \n-partitions 1 --topic topic-name\n"
},
{
"code": null,
"e": 7582,
"s": 7574,
"text": "Example"
},
{
"code": null,
"e": 7707,
"s": 7582,
"text": "bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 \n-partitions 1 --topic Multibrokerapplication"
},
{
"code": null,
"e": 7714,
"s": 7707,
"text": "Output"
},
{
"code": null,
"e": 7754,
"s": 7714,
"text": "created topic “Multibrokerapplication”\n"
},
{
"code": null,
"e": 7864,
"s": 7754,
"text": "The Describe command is used to check which broker is listening on the current created topic as shown below −"
},
{
"code": null,
"e": 7956,
"s": 7864,
"text": "bin/kafka-topics.sh --describe --zookeeper localhost:2181 \n--topic Multibrokerappli-cation\n"
},
{
"code": null,
"e": 7963,
"s": 7956,
"text": "Output"
},
{
"code": null,
"e": 8215,
"s": 7963,
"text": "bin/kafka-topics.sh --describe --zookeeper localhost:2181 \n--topic Multibrokerappli-cation\n\nTopic:Multibrokerapplication PartitionCount:1 \nReplicationFactor:3 Configs:\n \nTopic:Multibrokerapplication Partition:0 Leader:0 \nReplicas:0,2,1 Isr:0,2,1\n"
},
{
"code": null,
"e": 8501,
"s": 8215,
"text": "From the above output, we can conclude that first line gives a summary of all the partitions, showing topic name, partition count and the replication factor that we have chosen already. In the second line, each node will be the leader for a randomly selected portion of the partitions."
},
{
"code": null,
"e": 8779,
"s": 8501,
"text": "In our case, we see that our first broker (with broker.id 0) is the leader. Then Replicas:0,2,1 means that all the brokers replicate the topic finally Isr is the set of in-sync replicas. Well, this is the subset of replicas that are currently alive and caught up by the leader."
},
{
"code": null,
"e": 8842,
"s": 8779,
"text": "This procedure remains the same as in the single broker setup."
},
{
"code": null,
"e": 8850,
"s": 8842,
"text": "Example"
},
{
"code": null,
"e": 8941,
"s": 8850,
"text": "bin/kafka-console-producer.sh --broker-list localhost:9092 \n--topic Multibrokerapplication"
},
{
"code": null,
"e": 8948,
"s": 8941,
"text": "Output"
},
{
"code": null,
"e": 9199,
"s": 8948,
"text": "bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Multibrokerapplication\n[2016-01-20 19:27:21,045] WARN Property topic is not valid (kafka.utils.Verifia-bleProperties)\nThis is single node-multi broker demo\nThis is the second message\n"
},
{
"code": null,
"e": 9268,
"s": 9199,
"text": "This procedure remains the same as shown in the single broker setup."
},
{
"code": null,
"e": 9276,
"s": 9268,
"text": "Example"
},
{
"code": null,
"e": 9382,
"s": 9276,
"text": "bin/kafka-console-consumer.sh --zookeeper localhost:2181 \n—topic Multibrokerapplica-tion --from-beginning"
},
{
"code": null,
"e": 9389,
"s": 9382,
"text": "Output"
},
{
"code": null,
"e": 9560,
"s": 9389,
"text": "bin/kafka-console-consumer.sh --zookeeper localhost:2181 \n—topic Multibrokerapplica-tion —from-beginning\nThis is single node-multi broker demo\nThis is the second message\n"
},
{
"code": null,
"e": 9628,
"s": 9560,
"text": "In this chapter we will discuss the various basic topic operations."
},
{
"code": null,
"e": 9761,
"s": 9628,
"text": "As you have already understood how to create a topic in Kafka Cluster. Now let us modify a created topic using the following command"
},
{
"code": null,
"e": 9768,
"s": 9761,
"text": "Syntax"
},
{
"code": null,
"e": 9863,
"s": 9768,
"text": "bin/kafka-topics.sh —zookeeper localhost:2181 --alter --topic topic_name \n--parti-tions count\n"
},
{
"code": null,
"e": 9871,
"s": 9863,
"text": "Example"
},
{
"code": null,
"e": 10125,
"s": 9871,
"text": "We have already created a topic “Hello-Kafka” with single partition count and one replica factor. \nNow using “alter” command we have changed the partition count.\nbin/kafka-topics.sh --zookeeper localhost:2181 \n--alter --topic Hello-kafka --parti-tions 2"
},
{
"code": null,
"e": 10132,
"s": 10125,
"text": "Output"
},
{
"code": null,
"e": 10293,
"s": 10132,
"text": "WARNING: If partitions are increased for a topic that has a key, \nthe partition logic or ordering of the messages will be affected\nAdding partitions succeeded!\n"
},
{
"code": null,
"e": 10346,
"s": 10293,
"text": "To delete a topic, you can use the following syntax."
},
{
"code": null,
"e": 10353,
"s": 10346,
"text": "Syntax"
},
{
"code": null,
"e": 10429,
"s": 10353,
"text": "bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic topic_name\n"
},
{
"code": null,
"e": 10437,
"s": 10429,
"text": "Example"
},
{
"code": null,
"e": 10513,
"s": 10437,
"text": "bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic Hello-kafka"
},
{
"code": null,
"e": 10520,
"s": 10513,
"text": "Output"
},
{
"code": null,
"e": 10561,
"s": 10520,
"text": "> Topic Hello-kafka marked for deletion\n"
},
{
"code": null,
"e": 10634,
"s": 10561,
"text": "Note −This will have no impact if delete.topic.enable is not set to true"
},
{
"code": null,
"e": 10669,
"s": 10634,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10688,
"s": 10669,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10723,
"s": 10688,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10744,
"s": 10723,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 10777,
"s": 10744,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10790,
"s": 10777,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 10825,
"s": 10790,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10843,
"s": 10825,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 10876,
"s": 10843,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10894,
"s": 10876,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 10927,
"s": 10894,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10945,
"s": 10927,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 10952,
"s": 10945,
"text": " Print"
},
{
"code": null,
"e": 10963,
"s": 10952,
"text": " Add Notes"
}
] |
How to create a modal dialog in tkinter? | Dialog Boxes are a very essential component of any application. It is generally used to interact with the user and the application interface. We can create dialog boxes for any tkinter application using the Toplevel window and other widgets. The toplevel window pops up the stuff above all the other windows. Thus, we can add more stuff on the toplevel window for building dialog boxes.
In this example, we have created a modal dialog which has two parts,
Initialization of the Toplevel window.
Function Definition for Popup Dialog Event.
Adding widgets in the Toplevel window.
Function Definition for Dialog options.
# Import required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
# Set the window size
win.geometry("700x350")
style = ttk.Style()
style.theme_use('clam')
# Define a function to implement choice function
def choice(option):
pop.destroy()
if option == "yes":
label.config(text="Hello, How are You?")
else:
label.config(text="You have selected No")
win.destroy()
def click_fun():
global pop
pop = Toplevel(win)
pop.title("Confirmation")
pop.geometry("300x150")
pop.config(bg="white")
# Create a Label Text
label = Label(pop, text="Would You like to Proceed?",
font=('Aerial', 12))
label.pack(pady=20)
# Add a Frame
frame = Frame(pop, bg="gray71")
frame.pack(pady=10)
# Add Button for making selection
button1 = Button(frame, text="Yes", command=lambda: choice("yes"), bg="blue", fg="white")
button1.grid(row=0, column=1)
button2 = Button(frame, text="No", command=lambda: choice("no"), bg="blue", fg="white")
button2.grid(row=0, column=2)
# Create a Label widget
label = Label(win, text="", font=('Aerial', 14))
label.pack(pady=40)
# Create a Tkinter button
ttk.Button(win, text="Click Here", command=click_fun).pack()
win.mainloop()
When we run the above code, it will display a window with a Button to open the modal dialog box.
Clicking the Button will open the Modal Dialog Box. | [
{
"code": null,
"e": 1449,
"s": 1062,
"text": "Dialog Boxes are a very essential component of any application. It is generally used to interact with the user and the application interface. We can create dialog boxes for any tkinter application using the Toplevel window and other widgets. The toplevel window pops up the stuff above all the other windows. Thus, we can add more stuff on the toplevel window for building dialog boxes."
},
{
"code": null,
"e": 1518,
"s": 1449,
"text": "In this example, we have created a modal dialog which has two parts,"
},
{
"code": null,
"e": 1557,
"s": 1518,
"text": "Initialization of the Toplevel window."
},
{
"code": null,
"e": 1601,
"s": 1557,
"text": "Function Definition for Popup Dialog Event."
},
{
"code": null,
"e": 1640,
"s": 1601,
"text": "Adding widgets in the Toplevel window."
},
{
"code": null,
"e": 1680,
"s": 1640,
"text": "Function Definition for Dialog options."
},
{
"code": null,
"e": 2953,
"s": 1680,
"text": "# Import required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the window size\nwin.geometry(\"700x350\")\nstyle = ttk.Style()\nstyle.theme_use('clam')\n\n# Define a function to implement choice function\ndef choice(option):\n pop.destroy()\n if option == \"yes\":\n label.config(text=\"Hello, How are You?\")\n else:\n label.config(text=\"You have selected No\")\n win.destroy()\ndef click_fun():\n global pop\n pop = Toplevel(win)\n pop.title(\"Confirmation\")\n pop.geometry(\"300x150\")\n pop.config(bg=\"white\")\n # Create a Label Text\n label = Label(pop, text=\"Would You like to Proceed?\",\n font=('Aerial', 12))\n label.pack(pady=20)\n # Add a Frame\n frame = Frame(pop, bg=\"gray71\")\n frame.pack(pady=10)\n # Add Button for making selection\n button1 = Button(frame, text=\"Yes\", command=lambda: choice(\"yes\"), bg=\"blue\", fg=\"white\")\n button1.grid(row=0, column=1)\n button2 = Button(frame, text=\"No\", command=lambda: choice(\"no\"), bg=\"blue\", fg=\"white\")\n button2.grid(row=0, column=2)\n# Create a Label widget\nlabel = Label(win, text=\"\", font=('Aerial', 14))\nlabel.pack(pady=40)\n\n# Create a Tkinter button\nttk.Button(win, text=\"Click Here\", command=click_fun).pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 3050,
"s": 2953,
"text": "When we run the above code, it will display a window with a Button to open the modal dialog box."
},
{
"code": null,
"e": 3102,
"s": 3050,
"text": "Clicking the Button will open the Modal Dialog Box."
}
] |
Python | Matplotlib.pyplot ticks - GeeksforGeeks | 20 Aug, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2003.One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc.Ticks are the values used to show specific points on the coordinate axis. It can be a number or a string. Whenever we plot a graph, the axes adjust and take the default ticks. Matplotlib’s default ticks are generally sufficient in common situations but are in no way optimal for every plot. Here, we will see how to customize these ticks as per our need.Parameters :
Example #1: Default plot
Python3
# importing required modulesimport matplotlib.pyplot as plt # values of x and y axesx = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]y = [1, 4, 3, 2, 7, 6, 9, 8, 10, 5] plt.plot(x, y)plt.xlabel('x')plt.ylabel('y') plt.show()
Output :
Example #2: Playing with the ticksSuppose we don’t want to display the values of ticks or want our ticks to be tilted or want any other customization. We can do it this way.
Python
# importing librariesimport randomimport matplotlib.pyplot as plt fig = plt.figure() # function to get random values for graphdef get_graphs(): xs =[] ys =[] for i in range(10): xs.append(i) ys.append(random.randrange(10)) return xs, ys # defining subplotsax1 = fig.add_subplot(221)ax2 = fig.add_subplot(222)ax3 = fig.add_subplot(223)ax4 = fig.add_subplot(224) # hiding the marker on axisx, y = get_graphs()ax1.plot(x, y)ax1.tick_params(axis ='both', which ='both', length = 0) # One can also change marker length# by setting (length = any float value) # hiding the ticks and markersx, y = get_graphs()ax2.plot(x, y)ax2.axes.get_xaxis().set_visible(False)ax2.axes.get_yaxis().set_visible(False) # hiding the values and displaying the markerx, y = get_graphs()ax3.plot(x, y)ax3.yaxis.set_major_formatter(plt.NullFormatter())ax3.xaxis.set_major_formatter(plt.NullFormatter()) # tilting the ticks (usually needed when# the ticks are densely populated)x, y = get_graphs()ax4.plot(x, y)ax4.tick_params(axis ='x', rotation = 45)ax4.tick_params(axis ='y', rotation =-45) plt.show()
Output:
Example #3: Changing the values of ticks.In the first example, the x-axis and y-axis were divided by the value of 10 and 2 respectively. Let’s make it 5 and 1.
Python3
# importing librariesimport matplotlib.pyplot as pltimport numpy as np # values of x and y axesx = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]y = [1, 4, 3, 2, 7, 6, 9, 8, 10, 5] plt.plot(x, y, 'b')plt.xlabel('x')plt.ylabel('y') # 0 is the initial value, 51 is the final value# (last value is not taken) and 5 is the difference# of values between two consecutive ticksplt.xticks(np.arange(0, 51, 5))plt.yticks(np.arange(0, 11, 1))plt.show()
Output:
The main difference from the 1st example is : plt.xticks(np.arange(0, 51, 5)) plt.yticks(np.arange(0, 11, 1))Changing the values in np.arange will change the range of ticks. Reference: Matplotlib ticks.
yogesh_pandey
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24961,
"s": 24933,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 25802,
"s": 24961,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2003.One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc.Ticks are the values used to show specific points on the coordinate axis. It can be a number or a string. Whenever we plot a graph, the axes adjust and take the default ticks. Matplotlib’s default ticks are generally sufficient in common situations but are in no way optimal for every plot. Here, we will see how to customize these ticks as per our need.Parameters : "
},
{
"code": null,
"e": 25830,
"s": 25804,
"text": "Example #1: Default plot "
},
{
"code": null,
"e": 25838,
"s": 25830,
"text": "Python3"
},
{
"code": "# importing required modulesimport matplotlib.pyplot as plt # values of x and y axesx = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]y = [1, 4, 3, 2, 7, 6, 9, 8, 10, 5] plt.plot(x, y)plt.xlabel('x')plt.ylabel('y') plt.show()",
"e": 26057,
"s": 25838,
"text": null
},
{
"code": null,
"e": 26068,
"s": 26057,
"text": "Output : "
},
{
"code": null,
"e": 26245,
"s": 26068,
"text": " Example #2: Playing with the ticksSuppose we don’t want to display the values of ticks or want our ticks to be tilted or want any other customization. We can do it this way. "
},
{
"code": null,
"e": 26252,
"s": 26245,
"text": "Python"
},
{
"code": "# importing librariesimport randomimport matplotlib.pyplot as plt fig = plt.figure() # function to get random values for graphdef get_graphs(): xs =[] ys =[] for i in range(10): xs.append(i) ys.append(random.randrange(10)) return xs, ys # defining subplotsax1 = fig.add_subplot(221)ax2 = fig.add_subplot(222)ax3 = fig.add_subplot(223)ax4 = fig.add_subplot(224) # hiding the marker on axisx, y = get_graphs()ax1.plot(x, y)ax1.tick_params(axis ='both', which ='both', length = 0) # One can also change marker length# by setting (length = any float value) # hiding the ticks and markersx, y = get_graphs()ax2.plot(x, y)ax2.axes.get_xaxis().set_visible(False)ax2.axes.get_yaxis().set_visible(False) # hiding the values and displaying the markerx, y = get_graphs()ax3.plot(x, y)ax3.yaxis.set_major_formatter(plt.NullFormatter())ax3.xaxis.set_major_formatter(plt.NullFormatter()) # tilting the ticks (usually needed when# the ticks are densely populated)x, y = get_graphs()ax4.plot(x, y)ax4.tick_params(axis ='x', rotation = 45)ax4.tick_params(axis ='y', rotation =-45) plt.show()",
"e": 27357,
"s": 26252,
"text": null
},
{
"code": null,
"e": 27367,
"s": 27357,
"text": "Output: "
},
{
"code": null,
"e": 27529,
"s": 27367,
"text": "Example #3: Changing the values of ticks.In the first example, the x-axis and y-axis were divided by the value of 10 and 2 respectively. Let’s make it 5 and 1. "
},
{
"code": null,
"e": 27537,
"s": 27529,
"text": "Python3"
},
{
"code": "# importing librariesimport matplotlib.pyplot as pltimport numpy as np # values of x and y axesx = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]y = [1, 4, 3, 2, 7, 6, 9, 8, 10, 5] plt.plot(x, y, 'b')plt.xlabel('x')plt.ylabel('y') # 0 is the initial value, 51 is the final value# (last value is not taken) and 5 is the difference# of values between two consecutive ticksplt.xticks(np.arange(0, 51, 5))plt.yticks(np.arange(0, 11, 1))plt.show()",
"e": 27973,
"s": 27537,
"text": null
},
{
"code": null,
"e": 27983,
"s": 27973,
"text": "Output: "
},
{
"code": null,
"e": 28188,
"s": 27983,
"text": "The main difference from the 1st example is : plt.xticks(np.arange(0, 51, 5)) plt.yticks(np.arange(0, 11, 1))Changing the values in np.arange will change the range of ticks. Reference: Matplotlib ticks. "
},
{
"code": null,
"e": 28202,
"s": 28188,
"text": "yogesh_pandey"
},
{
"code": null,
"e": 28209,
"s": 28202,
"text": "Python"
},
{
"code": null,
"e": 28307,
"s": 28209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28316,
"s": 28307,
"text": "Comments"
},
{
"code": null,
"e": 28329,
"s": 28316,
"text": "Old Comments"
},
{
"code": null,
"e": 28347,
"s": 28329,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28382,
"s": 28347,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28414,
"s": 28382,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28436,
"s": 28414,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28466,
"s": 28436,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28508,
"s": 28466,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28534,
"s": 28508,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28577,
"s": 28534,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28614,
"s": 28577,
"text": "Create a Pandas DataFrame from Lists"
}
] |
C++ Array Library - get() Function | The C++ function std::array::get(std::array) Returns reference to the Ith element of the array container.
Following is the declaration for std::array::get(std::array) function form std::array header.
template <size_t I, class T, size_t N> T& get (array<T,N>& arr) noexcept;
template <size_t I, class T, size_t N> T&& get (array<T,N>&& arr) noexcept;
template <size_t I, class T, size_t N> const T& get (const array<T,N>& arr) noexcept;
I − position of an element in the array, with 0 as the position of the first element.
I − position of an element in the array, with 0 as the position of the first element.
T − type of elements contained in the array.
T − type of elements contained in the array.
arr − an array container.
arr − an array container.
A reference to the element at the specified position in the array.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::array::get(std::array) function.
#include <iostream>
#include <array>
using namespace std;
int main(void) {
array<int, 3> arr = {10, 20, 30};
cout << "arr[0] = " << get<0>(arr) << "\n";
cout << "arr[1] = " << get<1>(arr) << "\n";
cout << "arr[2] = " << get<2>(arr) << "\n";
return 0;
}
Let us compile and run the above program, this will produce the following result −
arr[0] = 10
arr[1] = 20
arr[2] = 30
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2709,
"s": 2603,
"text": "The C++ function std::array::get(std::array) Returns reference to the Ith element of the array container."
},
{
"code": null,
"e": 2803,
"s": 2709,
"text": "Following is the declaration for std::array::get(std::array) function form std::array header."
},
{
"code": null,
"e": 3039,
"s": 2803,
"text": "template <size_t I, class T, size_t N> T& get (array<T,N>& arr) noexcept;\ntemplate <size_t I, class T, size_t N> T&& get (array<T,N>&& arr) noexcept;\ntemplate <size_t I, class T, size_t N> const T& get (const array<T,N>& arr) noexcept;"
},
{
"code": null,
"e": 3125,
"s": 3039,
"text": "I − position of an element in the array, with 0 as the position of the first element."
},
{
"code": null,
"e": 3211,
"s": 3125,
"text": "I − position of an element in the array, with 0 as the position of the first element."
},
{
"code": null,
"e": 3256,
"s": 3211,
"text": "T − type of elements contained in the array."
},
{
"code": null,
"e": 3301,
"s": 3256,
"text": "T − type of elements contained in the array."
},
{
"code": null,
"e": 3327,
"s": 3301,
"text": "arr − an array container."
},
{
"code": null,
"e": 3353,
"s": 3327,
"text": "arr − an array container."
},
{
"code": null,
"e": 3420,
"s": 3353,
"text": "A reference to the element at the specified position in the array."
},
{
"code": null,
"e": 3465,
"s": 3420,
"text": "This member function never throws exception."
},
{
"code": null,
"e": 3484,
"s": 3465,
"text": "Constant i.e. O(1)"
},
{
"code": null,
"e": 3563,
"s": 3484,
"text": "The following example shows the usage of std::array::get(std::array) function."
},
{
"code": null,
"e": 3836,
"s": 3563,
"text": "#include <iostream>\n#include <array>\n\nusing namespace std;\n\nint main(void) {\n\n array<int, 3> arr = {10, 20, 30};\n\n cout << \"arr[0] = \" << get<0>(arr) << \"\\n\";\n cout << \"arr[1] = \" << get<1>(arr) << \"\\n\";\n cout << \"arr[2] = \" << get<2>(arr) << \"\\n\";\n\n return 0;\n}"
},
{
"code": null,
"e": 3919,
"s": 3836,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3956,
"s": 3919,
"text": "arr[0] = 10\narr[1] = 20\narr[2] = 30\n"
},
{
"code": null,
"e": 3963,
"s": 3956,
"text": " Print"
},
{
"code": null,
"e": 3974,
"s": 3963,
"text": " Add Notes"
}
] |
Python - Sorting Algorithms | Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are in numerical or lexicographical order.
The importance of sorting lies in the fact that data searching can be optimized to a very high level, if data is stored in a sorted manner. Sorting is also used to represent data in more readable formats. Below we see five such implementations of sorting in python.
Bubble Sort
Bubble Sort
Merge Sort
Merge Sort
Insertion Sort
Insertion Sort
Shell Sort
Shell Sort
Selection Sort
Selection Sort
It is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.
def bubblesort(list):
# Swap the elements to arrange in order
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
list = [19,2,31,45,6,11,121,27]
bubblesort(list)
print(list)
When the above code is executed, it produces the following result −
[2, 6, 11, 19, 27, 31, 45, 121]
Merge sort first divides the array into equal halves and then combines them in a sorted manner.
def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
# Find the middle point and devide it
middle = len(unsorted_list) // 2
left_list = unsorted_list[:middle]
right_list = unsorted_list[middle:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return list(merge(left_list, right_list))
# Merge the sorted halves
def merge(left_half,right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res
unsorted_list = [64, 34, 25, 12, 22, 11, 90]
print(merge_sort(unsorted_list))
When the above code is executed, it produces the following result −
[11, 12, 22, 25, 34, 64, 90]
Insertion sort involves finding the right place for a given element in a sorted list. So in beginning we compare the first two elements and sort them by comparing them. Then we pick the third element and find its proper position among the previous two sorted elements. This way we gradually go on adding more elements to the already sorted list by putting them in their proper position.
def insertion_sort(InputList):
for i in range(1, len(InputList)):
j = i-1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j+1] = InputList[j]
j=j-1
InputList[j+1] = nxt_element
list = [19,2,31,45,30,11,121,27]
insertion_sort(list)
print(list)
When the above code is executed, it produces the following result −
[2, 11, 19, 27, 30, 31, 45, 121]
Shell Sort involves sorting elements which are away from each other. We sort a large sublist of a given list and go on reducing the size of the list until all elements are sorted. The below program finds the gap by equating it to half of the length of the list size and then starts sorting all elements in it. Then we keep resetting the gap until the entire list is sorted.
def shellSort(input_list):
gap = len(input_list) // 2
while gap > 0:
for i in range(gap, len(input_list)):
temp = input_list[i]
j = i
# Sort the sub list for this gap
while j >= gap and input_list[j - gap] > temp:
input_list[j] = input_list[j - gap]
j = j-gap
input_list[j] = temp
# Reduce the gap for the next element
gap = gap//2
list = [19,2,31,45,30,11,121,27]
shellSort(list)
print(list)
When the above code is executed, it produces the following result −
[2, 11, 19, 27, 30, 31, 45, 121]
In selection sort we start by finding the minimum value in a given list and move it to a sorted list. Then we repeat the process for each of the remaining elements in the unsorted list. The next element entering the sorted list is compared with the existing elements and placed at its correct position.So, at the end all the elements from the unsorted list are sorted.
def selection_sort(input_list):
for idx in range(len(input_list)):
min_idx = idx
for j in range( idx +1, len(input_list)):
if input_list[min_idx] > input_list[j]:
min_idx = j
# Swap the minimum value with the compared value
input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]
l = [19,2,31,45,30,11,121,27]
selection_sort(l)
print(l)
When the above code is executed, it produces the following result −
[2, 11, 19, 27, 30, 31, 45, 121]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2521,
"s": 2327,
"text": "Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are in numerical or lexicographical order."
},
{
"code": null,
"e": 2787,
"s": 2521,
"text": "The importance of sorting lies in the fact that data searching can be optimized to a very high level, if data is stored in a sorted manner. Sorting is also used to represent data in more readable formats. Below we see five such implementations of sorting in python."
},
{
"code": null,
"e": 2799,
"s": 2787,
"text": "Bubble Sort"
},
{
"code": null,
"e": 2811,
"s": 2799,
"text": "Bubble Sort"
},
{
"code": null,
"e": 2822,
"s": 2811,
"text": "Merge Sort"
},
{
"code": null,
"e": 2833,
"s": 2822,
"text": "Merge Sort"
},
{
"code": null,
"e": 2848,
"s": 2833,
"text": "Insertion Sort"
},
{
"code": null,
"e": 2863,
"s": 2848,
"text": "Insertion Sort"
},
{
"code": null,
"e": 2874,
"s": 2863,
"text": "Shell Sort"
},
{
"code": null,
"e": 2885,
"s": 2874,
"text": "Shell Sort"
},
{
"code": null,
"e": 2900,
"s": 2885,
"text": "Selection Sort"
},
{
"code": null,
"e": 2915,
"s": 2900,
"text": "Selection Sort"
},
{
"code": null,
"e": 3057,
"s": 2915,
"text": "It is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order."
},
{
"code": null,
"e": 3390,
"s": 3057,
"text": "def bubblesort(list):\n\n# Swap the elements to arrange in order\n for iter_num in range(len(list)-1,0,-1):\n for idx in range(iter_num):\n if list[idx]>list[idx+1]:\n temp = list[idx]\n list[idx] = list[idx+1]\n list[idx+1] = temp\nlist = [19,2,31,45,6,11,121,27]\nbubblesort(list)\nprint(list)"
},
{
"code": null,
"e": 3458,
"s": 3390,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3491,
"s": 3458,
"text": "[2, 6, 11, 19, 27, 31, 45, 121]\n"
},
{
"code": null,
"e": 3587,
"s": 3491,
"text": "Merge sort first divides the array into equal halves and then combines them in a sorted manner."
},
{
"code": null,
"e": 4463,
"s": 3587,
"text": "def merge_sort(unsorted_list):\n if len(unsorted_list) <= 1:\n return unsorted_list\n# Find the middle point and devide it\n middle = len(unsorted_list) // 2\n left_list = unsorted_list[:middle]\n right_list = unsorted_list[middle:]\n\n left_list = merge_sort(left_list)\n right_list = merge_sort(right_list)\n return list(merge(left_list, right_list))\n\n# Merge the sorted halves\ndef merge(left_half,right_half):\n res = []\n while len(left_half) != 0 and len(right_half) != 0:\n if left_half[0] < right_half[0]:\n res.append(left_half[0])\n left_half.remove(left_half[0])\n else:\n res.append(right_half[0])\n right_half.remove(right_half[0])\n if len(left_half) == 0:\n res = res + right_half\n else:\n res = res + left_half\n return res\nunsorted_list = [64, 34, 25, 12, 22, 11, 90]\nprint(merge_sort(unsorted_list))"
},
{
"code": null,
"e": 4531,
"s": 4463,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4561,
"s": 4531,
"text": "[11, 12, 22, 25, 34, 64, 90]\n"
},
{
"code": null,
"e": 4948,
"s": 4561,
"text": "Insertion sort involves finding the right place for a given element in a sorted list. So in beginning we compare the first two elements and sort them by comparing them. Then we pick the third element and find its proper position among the previous two sorted elements. This way we gradually go on adding more elements to the already sorted list by putting them in their proper position."
},
{
"code": null,
"e": 5306,
"s": 4948,
"text": "def insertion_sort(InputList):\n for i in range(1, len(InputList)):\n j = i-1\n nxt_element = InputList[i]\n# Compare the current element with next one\n while (InputList[j] > nxt_element) and (j >= 0):\n InputList[j+1] = InputList[j]\n j=j-1\n InputList[j+1] = nxt_element\nlist = [19,2,31,45,30,11,121,27]\ninsertion_sort(list)\nprint(list)"
},
{
"code": null,
"e": 5374,
"s": 5306,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 5408,
"s": 5374,
"text": "[2, 11, 19, 27, 30, 31, 45, 121]\n"
},
{
"code": null,
"e": 5782,
"s": 5408,
"text": "Shell Sort involves sorting elements which are away from each other. We sort a large sublist of a given list and go on reducing the size of the list until all elements are sorted. The below program finds the gap by equating it to half of the length of the list size and then starts sorting all elements in it. Then we keep resetting the gap until the entire list is sorted."
},
{
"code": null,
"e": 6229,
"s": 5782,
"text": "def shellSort(input_list):\n gap = len(input_list) // 2\n while gap > 0:\n for i in range(gap, len(input_list)):\n temp = input_list[i]\n j = i\n# Sort the sub list for this gap\n while j >= gap and input_list[j - gap] > temp:\n input_list[j] = input_list[j - gap]\n j = j-gap\n input_list[j] = temp\n# Reduce the gap for the next element\n gap = gap//2\nlist = [19,2,31,45,30,11,121,27]\nshellSort(list)\nprint(list)"
},
{
"code": null,
"e": 6297,
"s": 6229,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 6331,
"s": 6297,
"text": "[2, 11, 19, 27, 30, 31, 45, 121]\n"
},
{
"code": null,
"e": 6700,
"s": 6331,
"text": "In selection sort we start by finding the minimum value in a given list and move it to a sorted list. Then we repeat the process for each of the remaining elements in the unsorted list. The next element entering the sorted list is compared with the existing elements and placed at its correct position.So, at the end all the elements from the unsorted list are sorted."
},
{
"code": null,
"e": 7093,
"s": 6700,
"text": "def selection_sort(input_list):\n for idx in range(len(input_list)):\n min_idx = idx\n for j in range( idx +1, len(input_list)):\n if input_list[min_idx] > input_list[j]:\n min_idx = j\n# Swap the minimum value with the compared value\n input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]\nl = [19,2,31,45,30,11,121,27]\nselection_sort(l)\nprint(l)"
},
{
"code": null,
"e": 7161,
"s": 7093,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 7195,
"s": 7161,
"text": "[2, 11, 19, 27, 30, 31, 45, 121]\n"
},
{
"code": null,
"e": 7232,
"s": 7195,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7248,
"s": 7232,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7281,
"s": 7248,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7300,
"s": 7281,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7335,
"s": 7300,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 7357,
"s": 7335,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 7391,
"s": 7357,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 7419,
"s": 7391,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7454,
"s": 7419,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7468,
"s": 7454,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7501,
"s": 7468,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7518,
"s": 7501,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7525,
"s": 7518,
"text": " Print"
},
{
"code": null,
"e": 7536,
"s": 7525,
"text": " Add Notes"
}
] |
Java Program to Convert GIF Images to JPEG - GeeksforGeeks | 25 Nov, 2021
JPEG and GIF both are a type of image format to store images. JPEG uses lossy compression algorithm and the image may lose some of its data whereas GIF uses a lossless compression algorithm and no image data loss is present in GIF format. GIF images support animation and transparency. Sometimes it is required to attach the Image where we required an image file with the specified extension. And we have the image with the different extension which needs to be converted with a specified extension like in this we will convert the image having Extension of .jpeg to .gif and vice-versa.
In Java, write() method is used to convert an image from gif type of format to jpg, use the static method write() provided by the class ImageIO under javax.imageio package.
Syntax:
boolean write(RenderedImage image, String formatName, OutputStream output)
Parameters: write() method accepts 3 parameters namely image, formatName and output.
Image: The input image as a subclass of the RenderedImage interface, such as BufferedImage.To obtain a BufferedImage object from the input image file, we can use the read(InputStream) which is also provided by the ImageIO class.formatName: specifies format type of the output image.output specifies an OutputStream to which the output image will be written.
Image: The input image as a subclass of the RenderedImage interface, such as BufferedImage.To obtain a BufferedImage object from the input image file, we can use the read(InputStream) which is also provided by the ImageIO class.
formatName: specifies format type of the output image.
output specifies an OutputStream to which the output image will be written.
Return Type: Boolean value where returning true if it can find an ImageWriter and perform conversion successfully else it will return false.
Exceptions: It will throw IOException if an error occurs during execution. It is shown later on in the implementation part.
Following utility class implements a static method, convertImg() which takes input and output image path as parameters.
Procedure:
To convert .jpeg to .gif, in the below code do the following necessary changes
Change ‘formatType’ to GIF.
In ‘outputImage’ change the name of the image with the correct file extension.
Similarly, change name of ‘inputImage’ with the correct file extension.
Implementation:
Note: For input and output images path, Input and input images been passed are present on the desktop of the machine
Input image with name “demoImage.gif”
Output Image with name “demoImage.jpeg”
Code is present at the directory mentioned below
/Users/mayanksolanki/Desktop/Job/Coding/GFG/Folder/
Example
Java
// Java Program to Convert GIF Image to JPEG Image // Importing BufferdImage class from java.awt package// to describe an image with accessible buffer of imageimport java.awt.image.BufferedImage;// Importing all input output classesimport java.io.*;// Importing an interface// to determine the setting of IIOParam objectimport javax.imageio.ImageIO; // Class 1// Helper classclass Helper { // Method to convert image to JPEG public static boolean convertImg(String inputImgPath, String outputImgPath, String formatType) throws IOException { // Creating an object of FileInputStream to read FileInputStream inputStream = new FileInputStream(inputImgPath); // Creating an object of FileOutputStream to write FileOutputStream outputStream = new FileOutputStream(outputImgPath); // Reading the input image from file BufferedImage inputImage = ImageIO.read(inputStream); // Writing to the output image in specified format boolean result = ImageIO.write( inputImage, formatType, outputStream); // Closing the streams in order to avoid read write // operations outputStream.close(); inputStream.close(); return result; }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IllegalStateException { // Here, the local directories from machine // is passed as in strings // Creating a string to store the path of image // to be converted String inputImage = "/Users/mayanksolanki/Desktop/demoImage.gif"; // Creating a string to // store path of converted image String outputImage = "/Users/mayanksolanki/Desktop/demoImage.jpeg"; // Creating another string that will be // store format of converted image // Simply creating creating just to hold the format // type String formatType = "JPEG"; // Try block to check for exceptions try { // result will store boolean value whether image // is converted successfully or not boolean result = Helper.convertImg( inputImage, outputImage, formatType); if (result) { // Display message when image is converted // successfully System.out.println( "Image converted to jpeg successfully."); } else { // Display message when image is not // converted successfully System.out.println( "Could not convert image."); } } // Catch block to handle the exceptions catch (IOException ex) { // Display message when exception is thrown System.out.println( "Error during converting image."); // Print the line number // where the exception occurred ex.printStackTrace(); } }}
Output:
Case 1: When an error is thrown
Case 2: Successful compilation but exception thrown at runtime(failed to run properly)
Case 3: Successful compilation and successfully run
Image converted to jpeg successfully.
When executed it will show Image converted to jpeg successfully, we can find that on console and a new jpeg image created in the file
simmytarika5
ruhelaa48
Image-Processing
Java
Java Programs
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
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 24145,
"s": 23557,
"text": "JPEG and GIF both are a type of image format to store images. JPEG uses lossy compression algorithm and the image may lose some of its data whereas GIF uses a lossless compression algorithm and no image data loss is present in GIF format. GIF images support animation and transparency. Sometimes it is required to attach the Image where we required an image file with the specified extension. And we have the image with the different extension which needs to be converted with a specified extension like in this we will convert the image having Extension of .jpeg to .gif and vice-versa."
},
{
"code": null,
"e": 24320,
"s": 24145,
"text": "In Java, write() method is used to convert an image from gif type of format to jpg, use the static method write() provided by the class ImageIO under javax.imageio package. "
},
{
"code": null,
"e": 24328,
"s": 24320,
"text": "Syntax:"
},
{
"code": null,
"e": 24403,
"s": 24328,
"text": "boolean write(RenderedImage image, String formatName, OutputStream output)"
},
{
"code": null,
"e": 24488,
"s": 24403,
"text": "Parameters: write() method accepts 3 parameters namely image, formatName and output."
},
{
"code": null,
"e": 24846,
"s": 24488,
"text": "Image: The input image as a subclass of the RenderedImage interface, such as BufferedImage.To obtain a BufferedImage object from the input image file, we can use the read(InputStream) which is also provided by the ImageIO class.formatName: specifies format type of the output image.output specifies an OutputStream to which the output image will be written."
},
{
"code": null,
"e": 25075,
"s": 24846,
"text": "Image: The input image as a subclass of the RenderedImage interface, such as BufferedImage.To obtain a BufferedImage object from the input image file, we can use the read(InputStream) which is also provided by the ImageIO class."
},
{
"code": null,
"e": 25130,
"s": 25075,
"text": "formatName: specifies format type of the output image."
},
{
"code": null,
"e": 25206,
"s": 25130,
"text": "output specifies an OutputStream to which the output image will be written."
},
{
"code": null,
"e": 25347,
"s": 25206,
"text": "Return Type: Boolean value where returning true if it can find an ImageWriter and perform conversion successfully else it will return false."
},
{
"code": null,
"e": 25471,
"s": 25347,
"text": "Exceptions: It will throw IOException if an error occurs during execution. It is shown later on in the implementation part."
},
{
"code": null,
"e": 25591,
"s": 25471,
"text": "Following utility class implements a static method, convertImg() which takes input and output image path as parameters."
},
{
"code": null,
"e": 25602,
"s": 25591,
"text": "Procedure:"
},
{
"code": null,
"e": 25681,
"s": 25602,
"text": "To convert .jpeg to .gif, in the below code do the following necessary changes"
},
{
"code": null,
"e": 25709,
"s": 25681,
"text": "Change ‘formatType’ to GIF."
},
{
"code": null,
"e": 25788,
"s": 25709,
"text": "In ‘outputImage’ change the name of the image with the correct file extension."
},
{
"code": null,
"e": 25860,
"s": 25788,
"text": "Similarly, change name of ‘inputImage’ with the correct file extension."
},
{
"code": null,
"e": 25876,
"s": 25860,
"text": "Implementation:"
},
{
"code": null,
"e": 25993,
"s": 25876,
"text": "Note: For input and output images path, Input and input images been passed are present on the desktop of the machine"
},
{
"code": null,
"e": 26031,
"s": 25993,
"text": "Input image with name “demoImage.gif”"
},
{
"code": null,
"e": 26071,
"s": 26031,
"text": "Output Image with name “demoImage.jpeg”"
},
{
"code": null,
"e": 26120,
"s": 26071,
"text": "Code is present at the directory mentioned below"
},
{
"code": null,
"e": 26172,
"s": 26120,
"text": "/Users/mayanksolanki/Desktop/Job/Coding/GFG/Folder/"
},
{
"code": null,
"e": 26180,
"s": 26172,
"text": "Example"
},
{
"code": null,
"e": 26185,
"s": 26180,
"text": "Java"
},
{
"code": "// Java Program to Convert GIF Image to JPEG Image // Importing BufferdImage class from java.awt package// to describe an image with accessible buffer of imageimport java.awt.image.BufferedImage;// Importing all input output classesimport java.io.*;// Importing an interface// to determine the setting of IIOParam objectimport javax.imageio.ImageIO; // Class 1// Helper classclass Helper { // Method to convert image to JPEG public static boolean convertImg(String inputImgPath, String outputImgPath, String formatType) throws IOException { // Creating an object of FileInputStream to read FileInputStream inputStream = new FileInputStream(inputImgPath); // Creating an object of FileOutputStream to write FileOutputStream outputStream = new FileOutputStream(outputImgPath); // Reading the input image from file BufferedImage inputImage = ImageIO.read(inputStream); // Writing to the output image in specified format boolean result = ImageIO.write( inputImage, formatType, outputStream); // Closing the streams in order to avoid read write // operations outputStream.close(); inputStream.close(); return result; }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IllegalStateException { // Here, the local directories from machine // is passed as in strings // Creating a string to store the path of image // to be converted String inputImage = \"/Users/mayanksolanki/Desktop/demoImage.gif\"; // Creating a string to // store path of converted image String outputImage = \"/Users/mayanksolanki/Desktop/demoImage.jpeg\"; // Creating another string that will be // store format of converted image // Simply creating creating just to hold the format // type String formatType = \"JPEG\"; // Try block to check for exceptions try { // result will store boolean value whether image // is converted successfully or not boolean result = Helper.convertImg( inputImage, outputImage, formatType); if (result) { // Display message when image is converted // successfully System.out.println( \"Image converted to jpeg successfully.\"); } else { // Display message when image is not // converted successfully System.out.println( \"Could not convert image.\"); } } // Catch block to handle the exceptions catch (IOException ex) { // Display message when exception is thrown System.out.println( \"Error during converting image.\"); // Print the line number // where the exception occurred ex.printStackTrace(); } }}",
"e": 29325,
"s": 26185,
"text": null
},
{
"code": null,
"e": 29333,
"s": 29325,
"text": "Output:"
},
{
"code": null,
"e": 29365,
"s": 29333,
"text": "Case 1: When an error is thrown"
},
{
"code": null,
"e": 29454,
"s": 29365,
"text": " Case 2: Successful compilation but exception thrown at runtime(failed to run properly) "
},
{
"code": null,
"e": 29507,
"s": 29454,
"text": "Case 3: Successful compilation and successfully run "
},
{
"code": null,
"e": 29546,
"s": 29507,
"text": "Image converted to jpeg successfully. "
},
{
"code": null,
"e": 29681,
"s": 29546,
"text": " When executed it will show Image converted to jpeg successfully, we can find that on console and a new jpeg image created in the file"
},
{
"code": null,
"e": 29694,
"s": 29681,
"text": "simmytarika5"
},
{
"code": null,
"e": 29704,
"s": 29694,
"text": "ruhelaa48"
},
{
"code": null,
"e": 29721,
"s": 29704,
"text": "Image-Processing"
},
{
"code": null,
"e": 29726,
"s": 29721,
"text": "Java"
},
{
"code": null,
"e": 29740,
"s": 29726,
"text": "Java Programs"
},
{
"code": null,
"e": 29745,
"s": 29740,
"text": "Java"
},
{
"code": null,
"e": 29843,
"s": 29745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29852,
"s": 29843,
"text": "Comments"
},
{
"code": null,
"e": 29865,
"s": 29852,
"text": "Old Comments"
},
{
"code": null,
"e": 29895,
"s": 29865,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29910,
"s": 29895,
"text": "Stream In Java"
},
{
"code": null,
"e": 29931,
"s": 29910,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29977,
"s": 29931,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29996,
"s": 29977,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30040,
"s": 29996,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 30066,
"s": 30040,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30100,
"s": 30066,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 30147,
"s": 30100,
"text": "Implementing a Linked List in Java using Class"
}
] |
Removing whitespaces using C# Regex | Let’s say we want to remove whitespace from the following string str1.
string str1 = "Brad Pitt";
Now, use Regex Replace to replace whitespace with empty. Here, we have used System.Text.RegularExpressions.
string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");
Let us see the complete example.
Live Demo
using System;
using System.Text.RegularExpressions;
namespace Demo {
class Program {
static void Main(string[] args) {
string str1 = "Brad Pitt";
Console.WriteLine(str1);
string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");
Console.WriteLine(str2);
}
}
}
Brad Pitt
BradPitt | [
{
"code": null,
"e": 1133,
"s": 1062,
"text": "Let’s say we want to remove whitespace from the following string str1."
},
{
"code": null,
"e": 1160,
"s": 1133,
"text": "string str1 = \"Brad Pitt\";"
},
{
"code": null,
"e": 1268,
"s": 1160,
"text": "Now, use Regex Replace to replace whitespace with empty. Here, we have used System.Text.RegularExpressions."
},
{
"code": null,
"e": 1346,
"s": 1268,
"text": "string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @\"\\s+\", \"\");"
},
{
"code": null,
"e": 1379,
"s": 1346,
"text": "Let us see the complete example."
},
{
"code": null,
"e": 1390,
"s": 1379,
"text": " Live Demo"
},
{
"code": null,
"e": 1724,
"s": 1390,
"text": "using System;\nusing System.Text.RegularExpressions;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n string str1 = \"Brad Pitt\";\n Console.WriteLine(str1);\n string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @\"\\s+\", \"\");\n Console.WriteLine(str2);\n }\n }\n}"
},
{
"code": null,
"e": 1743,
"s": 1724,
"text": "Brad Pitt\nBradPitt"
}
] |
How to get row index based on a value of an R data frame column? | A row of an R data frame can have multiple ways in columns and these values can be numerical, logical, string etc. It is easy to find the values based on row numbers but finding the row numbers based on a value is different. If we want to find the row number for a particular value in a specific column then we can extract the whole row which seems to be a better way and it can be done by using single square brackets to take the subset of the row.
Consider the below data frame −
Live Demo
x1<-rnorm(20,0.5)
x2<-rpois(20,2)
x3<-rpois(20,5)
x4<-rpois(20,10)
x5<-rnorm(20,2)
df<-data.frame(x1,x2,x3,x4,x5)
df
x1 x2 x3 x4 x5
1 1.33780769 1 5 1 3.3322153
2 2.22651263 3 5 14 3.4969403
3 0.53231950 4 9 8 3.7816594
4 0.99704756 1 6 13 2.7308284
5 0.37735760 2 5 7 2.3210021
6 0.96967898 3 7 8 1.9086576
7 0.06543569 2 4 9 1.4005479
8 1.59064892 1 8 14 1.1250329
9 0.48771130 1 4 11 2.2479028
10 0.64134261 0 9 5 2.4194513
11 0.43355439 3 2 18 -0.7633724
12 1.31803573 3 4 10 2.6201427
13 0.25367683 3 6 9 1.5728880
14 1.07884550 5 4 9 0.8045540
15 0.78574641 6 6 8 1.3538888
16 -0.27873444 2 6 12 3.5431787
17 0.28112519 2 3 8 4.1865617
18 1.24416762 4 4 11 2.3626763
19 -0.04745463 2 5 13 3.4203297
20 1.33358241 1 9 14 2.8205837
Finding the rows that will also return row indexes for a value −
df[df$x4==14,]
x1 x2 x3 x4 x5
2 2.226513 3 5 14 3.496940
8 1.590649 1 8 14 1.125033
20 1.333582 1 9 14 2.820584
df[df$x4==12,]
x1 x2 x3 x4 x5
16 -0.2787344 2 6 12 3.543179
df[df$x4==7,]
x1 x2 x3 x4 x5
5 0.3773576 2 5 7 2.321002
df[df$x4==9,]
x1 x2 x3 x4 x5
7 0.06543569 2 4 9 1.400548
13 0.25367683 3 6 9 1.572888
14 1.07884550 5 4 9 0.804554
df[df$x2==2,]
x1 x2 x3 x4 x5
5 0.37735760 2 5 7 2.321002
7 0.06543569 2 4 9 1.400548
16 -0.27873444 2 6 12 3.543179
17 0.28112519 2 3 8 4.186562
19 -0.04745463 2 5 13 3.420330
df[df$x2==5,]
x1 x2 x3 x4 x5
14 1.078845 5 4 9 0.804554
df[df$x2==4,]
x1 x2 x3 x4 x5
3 0.5323195 4 9 8 3.781659
18 1.2441676 4 4 11 2.362676
df[df$x3==4,]
x1 x2 x3 x4 x5
7 0.06543569 2 4 9 1.400548
9 0.48771130 1 4 11 2.247903
12 1.31803573 3 4 10 2.620143
14 1.07884550 5 4 9 0.804554
18 1.24416762 4 4 11 2.362676
df[df$x3==6,]
x1 x2 x3 x4 x5
4 0.9970476 1 6 13 2.730828
13 0.2536768 3 6 9 1.572888
15 0.7857464 6 6 8 1.353889
16 -0.2787344 2 6 12 3.543179
df[df$x3==5,]
x1 x2 x3 x4 x5
1 1.33780769 1 5 1 3.332215
2 2.22651263 3 5 14 3.496940
5 0.37735760 2 5 7 2.321002
19 -0.04745463 2 5 13 3.420330
df[df$x3==8,]
x1 x2 x3 x4 x5
8 1.590649 1 8 14 1.125033
df[df$x2==1,]
x1 x2 x3 x4 x5
1 1.3378077 1 5 1 3.332215
4 0.9970476 1 6 13 2.730828
8 1.5906489 1 8 14 1.125033
9 0.4877113 1 4 11 2.247903
20 1.3335824 1 9 14 2.820584 | [
{
"code": null,
"e": 1512,
"s": 1062,
"text": "A row of an R data frame can have multiple ways in columns and these values can be numerical, logical, string etc. It is easy to find the values based on row numbers but finding the row numbers based on a value is different. If we want to find the row number for a particular value in a specific column then we can extract the whole row which seems to be a better way and it can be done by using single square brackets to take the subset of the row."
},
{
"code": null,
"e": 1544,
"s": 1512,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1555,
"s": 1544,
"text": " Live Demo"
},
{
"code": null,
"e": 1672,
"s": 1555,
"text": "x1<-rnorm(20,0.5)\nx2<-rpois(20,2)\nx3<-rpois(20,5)\nx4<-rpois(20,10)\nx5<-rnorm(20,2)\ndf<-data.frame(x1,x2,x3,x4,x5)\ndf"
},
{
"code": null,
"e": 2477,
"s": 1672,
"text": " x1 x2 x3 x4 x5\n1 1.33780769 1 5 1 3.3322153\n2 2.22651263 3 5 14 3.4969403\n3 0.53231950 4 9 8 3.7816594\n4 0.99704756 1 6 13 2.7308284\n5 0.37735760 2 5 7 2.3210021\n6 0.96967898 3 7 8 1.9086576\n7 0.06543569 2 4 9 1.4005479\n8 1.59064892 1 8 14 1.1250329\n9 0.48771130 1 4 11 2.2479028\n10 0.64134261 0 9 5 2.4194513\n11 0.43355439 3 2 18 -0.7633724\n12 1.31803573 3 4 10 2.6201427\n13 0.25367683 3 6 9 1.5728880\n14 1.07884550 5 4 9 0.8045540\n15 0.78574641 6 6 8 1.3538888\n16 -0.27873444 2 6 12 3.5431787\n17 0.28112519 2 3 8 4.1865617\n18 1.24416762 4 4 11 2.3626763\n19 -0.04745463 2 5 13 3.4203297\n20 1.33358241 1 9 14 2.8205837"
},
{
"code": null,
"e": 2542,
"s": 2477,
"text": "Finding the rows that will also return row indexes for a value −"
},
{
"code": null,
"e": 2557,
"s": 2542,
"text": "df[df$x4==14,]"
},
{
"code": null,
"e": 2667,
"s": 2557,
"text": " x1 x2 x3 x4 x5\n2 2.226513 3 5 14 3.496940\n8 1.590649 1 8 14 1.125033\n20 1.333582 1 9 14 2.820584"
},
{
"code": null,
"e": 2682,
"s": 2667,
"text": "df[df$x4==12,]"
},
{
"code": null,
"e": 2744,
"s": 2682,
"text": " x1 x2 x3 x4 x5\n16 -0.2787344 2 6 12 3.543179"
},
{
"code": null,
"e": 2758,
"s": 2744,
"text": "df[df$x4==7,]"
},
{
"code": null,
"e": 2817,
"s": 2758,
"text": " x1 x2 x3 x4 x5\n5 0.3773576 2 5 7 2.321002"
},
{
"code": null,
"e": 2831,
"s": 2817,
"text": "df[df$x4==9,]"
},
{
"code": null,
"e": 2969,
"s": 2831,
"text": " x1 x2 x3 x4 x5\n7 0.06543569 2 4 9 1.400548\n13 0.25367683 3 6 9 1.572888\n14 1.07884550 5 4 9 0.804554"
},
{
"code": null,
"e": 2983,
"s": 2969,
"text": "df[df$x2==2,]"
},
{
"code": null,
"e": 3194,
"s": 2983,
"text": " x1 x2 x3 x4 x5\n5 0.37735760 2 5 7 2.321002\n7 0.06543569 2 4 9 1.400548\n16 -0.27873444 2 6 12 3.543179\n17 0.28112519 2 3 8 4.186562\n19 -0.04745463 2 5 13 3.420330"
},
{
"code": null,
"e": 3208,
"s": 3194,
"text": "df[df$x2==5,]"
},
{
"code": null,
"e": 3265,
"s": 3208,
"text": " x1 x2 x3 x4 x5\n14 1.078845 5 4 9 0.804554"
},
{
"code": null,
"e": 3279,
"s": 3265,
"text": "df[df$x2==4,]"
},
{
"code": null,
"e": 3365,
"s": 3279,
"text": " x1 x2 x3 x4 x5\n3 0.5323195 4 9 8 3.781659\n18 1.2441676 4 4 11 2.362676"
},
{
"code": null,
"e": 3379,
"s": 3365,
"text": "df[df$x3==4,]"
},
{
"code": null,
"e": 3569,
"s": 3379,
"text": " x1 x2 x3 x4 x5\n7 0.06543569 2 4 9 1.400548\n9 0.48771130 1 4 11 2.247903\n12 1.31803573 3 4 10 2.620143\n14 1.07884550 5 4 9 0.804554\n18 1.24416762 4 4 11 2.362676"
},
{
"code": null,
"e": 3583,
"s": 3569,
"text": "df[df$x3==6,]"
},
{
"code": null,
"e": 3734,
"s": 3583,
"text": " x1 x2 x3 x4 x5\n4 0.9970476 1 6 13 2.730828\n13 0.2536768 3 6 9 1.572888\n15 0.7857464 6 6 8 1.353889\n16 -0.2787344 2 6 12 3.543179"
},
{
"code": null,
"e": 3748,
"s": 3734,
"text": "df[df$x3==5,]"
},
{
"code": null,
"e": 3890,
"s": 3748,
"text": " x1 x2 x3 x4 x5\n1 1.33780769 1 5 1 3.332215\n2 2.22651263 3 5 14 3.496940\n5 0.37735760 2 5 7 2.321002\n19 -0.04745463 2 5 13 3.420330"
},
{
"code": null,
"e": 3904,
"s": 3890,
"text": "df[df$x3==8,]"
},
{
"code": null,
"e": 3955,
"s": 3904,
"text": " x1 x2 x3 x4 x5\n8 1.590649 1 8 14 1.125033"
},
{
"code": null,
"e": 3969,
"s": 3955,
"text": "df[df$x2==1,]"
},
{
"code": null,
"e": 4155,
"s": 3969,
"text": " x1 x2 x3 x4 x5\n1 1.3378077 1 5 1 3.332215\n4 0.9970476 1 6 13 2.730828\n8 1.5906489 1 8 14 1.125033\n9 0.4877113 1 4 11 2.247903\n20 1.3335824 1 9 14 2.820584"
}
] |
AWK - String Concatenation Operator | Space is a string concatenation operator that merges two strings. The following example demonstrates this −
[jerry]$ awk 'BEGIN { str1 = "Hello, "; str2 = "World"; str3 = str1 str2; print str3 }'
On executing this code, you get the following result −
Hello, World
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1965,
"s": 1857,
"text": "Space is a string concatenation operator that merges two strings. The following example demonstrates this −"
},
{
"code": null,
"e": 2053,
"s": 1965,
"text": "[jerry]$ awk 'BEGIN { str1 = \"Hello, \"; str2 = \"World\"; str3 = str1 str2; print str3 }'"
},
{
"code": null,
"e": 2108,
"s": 2053,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 2122,
"s": 2108,
"text": "Hello, World\n"
},
{
"code": null,
"e": 2129,
"s": 2122,
"text": " Print"
},
{
"code": null,
"e": 2140,
"s": 2129,
"text": " Add Notes"
}
] |
How can I dynamically set the position of view in android? | This example demonstrates how do I in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2− Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relativeLayout"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="bold|italic"
android:text="Sample TextView"
android:padding="10dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Put text below this button"
android:layout_centerInParent="true" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
Button button;
TextView textView;
RelativeLayout relativeLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = findViewById(R.id.relativeLayout);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
layoutParams.addRule(RelativeLayout.BELOW, button.getId());
layoutParams.addRule(RelativeLayout.ALIGN_LEFT, button.getId());
textView.setLayoutParams(layoutParams);
}
});
}
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – | [
{
"code": null,
"e": 1109,
"s": 1062,
"text": "This example demonstrates how do I in android."
},
{
"code": null,
"e": 1238,
"s": 1109,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1302,
"s": 1238,
"text": "Step 2− Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2122,
"s": 1302,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/relativeLayout\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"12sp\"\n android:textStyle=\"bold|italic\"\n android:text=\"Sample TextView\"\n android:padding=\"10dp\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Put text below this button\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2179,
"s": 2122,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3268,
"s": 2179,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RelativeLayout;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity{\n Button button;\n TextView textView;\n RelativeLayout relativeLayout;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n relativeLayout = findViewById(R.id.relativeLayout);\n textView = findViewById(R.id.textView);\n button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();\n layoutParams.addRule(RelativeLayout.BELOW, button.getId());\n layoutParams.addRule(RelativeLayout.ALIGN_LEFT, button.getId());\n textView.setLayoutParams(layoutParams);\n }\n });\n }\n}"
},
{
"code": null,
"e": 3323,
"s": 3268,
"text": "Step 4 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3993,
"s": 3323,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4340,
"s": 3993,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
] |
Same Tree in C++ | Suppose we have two binary trees; we have to define a function to check whether they are the same or not. We know that the binary trees are considered the same when they are structurally identical and the nodes have the same value.
So, if the input is like [1,2,3],[1,2,3], then the output will be True
To solve this, we will follow these steps −
Define a function called isSameTree, this will take two tree nodes p and q
Define a function called isSameTree, this will take two tree nodes p and q
if p is the same as NULL and q is same as NULL, then −return true
if p is the same as NULL and q is same as NULL, then −
return true
return true
if p is the same as NULL or q is same as NULL, then −return false
if p is the same as NULL or q is same as NULL, then −
return false
return false
if val of p is the same as val of p and isSameTree(left of p, left of q) is true and
isSameTree(right of p, right of q) is true, thenreturn true
if val of p is the same as val of p and isSameTree(left of p, left of q) is true and
isSameTree(right of p, right of q) is true, then
return true
return true
return false
return false
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
}
else{
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
}
else{
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode* q){
if (p == NULL && q == NULL)
return true;
if (p == NULL || q == NULL)
return false;
if (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right))
return true;
return false;
}
};
main(){
Solution ob;
vector<int> v = {1,2,3}, v1 = {1,2,3};
TreeNode *root1 = make_tree(v);
TreeNode *root2 = make_tree(v1);
cout << (ob.isSameTree(root1, root2));
}
{1,2,3}, {1,2,3}
1 | [
{
"code": null,
"e": 1294,
"s": 1062,
"text": "Suppose we have two binary trees; we have to define a function to check whether they are the same or not. We know that the binary trees are considered the same when they are structurally identical and the nodes have the same value."
},
{
"code": null,
"e": 1365,
"s": 1294,
"text": "So, if the input is like [1,2,3],[1,2,3], then the output will be True"
},
{
"code": null,
"e": 1409,
"s": 1365,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1484,
"s": 1409,
"text": "Define a function called isSameTree, this will take two tree nodes p and q"
},
{
"code": null,
"e": 1559,
"s": 1484,
"text": "Define a function called isSameTree, this will take two tree nodes p and q"
},
{
"code": null,
"e": 1625,
"s": 1559,
"text": "if p is the same as NULL and q is same as NULL, then −return true"
},
{
"code": null,
"e": 1680,
"s": 1625,
"text": "if p is the same as NULL and q is same as NULL, then −"
},
{
"code": null,
"e": 1692,
"s": 1680,
"text": "return true"
},
{
"code": null,
"e": 1704,
"s": 1692,
"text": "return true"
},
{
"code": null,
"e": 1770,
"s": 1704,
"text": "if p is the same as NULL or q is same as NULL, then −return false"
},
{
"code": null,
"e": 1824,
"s": 1770,
"text": "if p is the same as NULL or q is same as NULL, then −"
},
{
"code": null,
"e": 1837,
"s": 1824,
"text": "return false"
},
{
"code": null,
"e": 1850,
"s": 1837,
"text": "return false"
},
{
"code": null,
"e": 1995,
"s": 1850,
"text": "if val of p is the same as val of p and isSameTree(left of p, left of q) is true and\nisSameTree(right of p, right of q) is true, thenreturn true"
},
{
"code": null,
"e": 2129,
"s": 1995,
"text": "if val of p is the same as val of p and isSameTree(left of p, left of q) is true and\nisSameTree(right of p, right of q) is true, then"
},
{
"code": null,
"e": 2141,
"s": 2129,
"text": "return true"
},
{
"code": null,
"e": 2153,
"s": 2141,
"text": "return true"
},
{
"code": null,
"e": 2166,
"s": 2153,
"text": "return false"
},
{
"code": null,
"e": 2179,
"s": 2166,
"text": "return false"
},
{
"code": null,
"e": 2249,
"s": 2179,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2260,
"s": 2249,
"text": " Live Demo"
},
{
"code": null,
"e": 3756,
"s": 2260,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass TreeNode{\n public:\n int val;\n TreeNode *left, *right;\n TreeNode(int data){\n val = data;\n left = NULL;\n right = NULL;\n }\n};\nvoid insert(TreeNode **root, int val){\n queue<TreeNode*> q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector<int> v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n insert(&root, v[i]);\n }\n return root;\n}\nclass Solution {\npublic:\n bool isSameTree(TreeNode *p, TreeNode* q){\n if (p == NULL && q == NULL)\n return true;\n if (p == NULL || q == NULL)\n return false;\n if (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right))\n return true;\n return false;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,2,3}, v1 = {1,2,3};\n TreeNode *root1 = make_tree(v);\n TreeNode *root2 = make_tree(v1);\n cout << (ob.isSameTree(root1, root2));\n}"
},
{
"code": null,
"e": 3773,
"s": 3756,
"text": "{1,2,3}, {1,2,3}"
},
{
"code": null,
"e": 3775,
"s": 3773,
"text": "1"
}
] |
How can we change the data type of the column in MySQL table? | It can be done with the help of ALTER TABLE command of MySQL. Consider the table ‘Student’ in which the data type of ‘RollNo’ column is declared as Integer, can be seen from the following query −
mysql> DESCRIBE Student;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Name | varchar(20) | YES | | NULL | |
| RollNo | int(11) | YES | | NULL | |
| Grade | varchar(50) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.06 sec)
Now suppose we want to change the data type of RollNo from Int(11) to Varchar(10) the following query will do it −
mysql> Alter Table student Modify column RollNo Varchar(10);
Query OK, 3 rows affected (0.25 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> Desc Student;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Name | varchar(20) | YES | | NULL | |
| RollNo | varchar(10) | YES | | NULL | |
| Grade | varchar(10) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.06 sec)
From the query above it can be observed that the data type of RollNo has been changed from integer to varchar. | [
{
"code": null,
"e": 1258,
"s": 1062,
"text": "It can be done with the help of ALTER TABLE command of MySQL. Consider the table ‘Student’ in which the data type of ‘RollNo’ column is declared as Integer, can be seen from the following query −"
},
{
"code": null,
"e": 1700,
"s": 1258,
"text": "mysql> DESCRIBE Student;\n+--------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------+-------------+------+-----+---------+-------+\n| Name | varchar(20) | YES | | NULL | |\n| RollNo | int(11) | YES | | NULL | |\n| Grade | varchar(50) | YES | | NULL | |\n+--------+-------------+------+-----+---------+-------+\n3 rows in set (0.06 sec)"
},
{
"code": null,
"e": 1815,
"s": 1700,
"text": "Now suppose we want to change the data type of RollNo from Int(11) to Varchar(10) the following query will do it −"
},
{
"code": null,
"e": 2389,
"s": 1815,
"text": "mysql> Alter Table student Modify column RollNo Varchar(10);\nQuery OK, 3 rows affected (0.25 sec)\nRecords: 3 Duplicates: 0 Warnings: 0\n\nmysql> Desc Student;\n+--------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------+-------------+------+-----+---------+-------+\n| Name | varchar(20) | YES | | NULL | |\n| RollNo | varchar(10) | YES | | NULL | |\n| Grade | varchar(10) | YES | | NULL | |\n+--------+-------------+------+-----+---------+-------+\n3 rows in set (0.06 sec)"
},
{
"code": null,
"e": 2500,
"s": 2389,
"text": "From the query above it can be observed that the data type of RollNo has been changed from integer to varchar."
}
] |
Feature Selection and Regression On the Airbnb Berlin Dataset | by Somesh Kumar Bhattacharya | Towards Data Science | The multidisciplinary field of data science can extract deep insights and knowledge from structured and unstructured data. It unifies the concepts of statistics, data analytics and machine learning and other related concepts to understand and analyze the actual phenomena with data. Machine learning (ML) equips computers to learn and interpret without being explicitly programmed. ML methods are used widely in finance, healthcare, materials science, transportation, oil and gas etc.
In this study we undertake the analysis of Airbnb dataset from the Berlin area [1] and predict the prices of Airbnb using the regression analysis. We have used the random forest regression [2] model available in the “scikit-learn” [3] library of the python-based open source data analytics platform and the plots were created using the Matplotlib.
The shape of the Airbnb dataset is (22552, 96). Many of the 96 features are non-numeric features and many features have missing values. Some of the non-numeric features were converted to numeric ones using the Label Encoder. The missing values were filled using the forward filling method and the certain features were cleaned from the ‘$’, ‘,’ etc. using the strip method. Additionally, we created a new feature ‘distance’ of the Airbnb from the center of Berlin using the longitude and latitude of the Airbnb. This new feature was then appended to the original dataset. Once the data processing is done, we used ‘feature selection’ available in the scikit-learn to select the important features. We calculate χ2 between each feature and the target and select the desired number of features with best χ2 scores. The best 25 features and the χ2 score are tabulated below in Table 1.
Table 1. Best 25 features of the dataset and their corresponding χ2 scores. Features χ2 scoresmaximum_nights 2.152729e+10minimum_nights 8.856912e+05security_deposit 7.716334e+05number_of_reviews 8.341015e+04square_feet 2.982368e+04property_type 2.222414e+04calculated_host_listings_count 1.072021e+04neighbourhood_cleansed 1.071895e+04accommodates 7.771539e+03room_type 4.234147e+03neighbourhood 3.254091e+03guests_included 3.061216e+03bedrooms 2.380380e+03cancellation_policy 1.444670e+03distance 9.580979e+02host_is_superhost 6.349556e+02neighbourhood_group_cleansed 5.957898e+02instant_bookable 3.502228e+02bathrooms 3.290317e+02review_scores_rating 2.151681e+02is_location_exact 9.053878e+01review_scores_cleanliness 5.194306e+01review_scores_accuracy 2.410470e+01bed_type 7.055763e+00longitude 1.016177e-01
Next, only the top five features were selected. This subset was split into training and test data. The ‘price’ was set as the target feature. The training data subset was used for fitting the random forest while the test subset was used for the prediction. This was repeated by using different subsets where top ten, top fifteen, top twenty and top twenty-five features were included. For each case we calculated the value which is defined as
adjusted R^2 = 1-R^2(N-1)/(N-M-1)
where N is the number of points in the dataset and M is the number of independent feature(s) while is the measure of the goodness of fit. increases with the number of features to the model. As always increases and never decreases, it can appear to be a better fit with the more terms that is added to the model. In regression analysis, it can be tempting to add more variables to the data which can be misleading. Some of those variables may be significant, but one can’t be sure that significance is just by chance. The compensate for this by that penalizing for those extra variables. The corresponding plot is shown in Figure 1.
Figure 1. Plot of the number of features and the corresponding adjusted R2
Exploratory data analysis (EDA) via graphs is definitely useful and important. However, for large datasets it becomes extremely difficult to adopt EDA as there are a large number of plots to analyze. Thus, features selection via the SelectKBest method of scikit learn provides a well defined way for feature selection as demonstrated here. | [
{
"code": null,
"e": 657,
"s": 172,
"text": "The multidisciplinary field of data science can extract deep insights and knowledge from structured and unstructured data. It unifies the concepts of statistics, data analytics and machine learning and other related concepts to understand and analyze the actual phenomena with data. Machine learning (ML) equips computers to learn and interpret without being explicitly programmed. ML methods are used widely in finance, healthcare, materials science, transportation, oil and gas etc."
},
{
"code": null,
"e": 1005,
"s": 657,
"text": "In this study we undertake the analysis of Airbnb dataset from the Berlin area [1] and predict the prices of Airbnb using the regression analysis. We have used the random forest regression [2] model available in the “scikit-learn” [3] library of the python-based open source data analytics platform and the plots were created using the Matplotlib."
},
{
"code": null,
"e": 1888,
"s": 1005,
"text": "The shape of the Airbnb dataset is (22552, 96). Many of the 96 features are non-numeric features and many features have missing values. Some of the non-numeric features were converted to numeric ones using the Label Encoder. The missing values were filled using the forward filling method and the certain features were cleaned from the ‘$’, ‘,’ etc. using the strip method. Additionally, we created a new feature ‘distance’ of the Airbnb from the center of Berlin using the longitude and latitude of the Airbnb. This new feature was then appended to the original dataset. Once the data processing is done, we used ‘feature selection’ available in the scikit-learn to select the important features. We calculate χ2 between each feature and the target and select the desired number of features with best χ2 scores. The best 25 features and the χ2 score are tabulated below in Table 1."
},
{
"code": null,
"e": 3080,
"s": 1888,
"text": "Table 1. Best 25 features of the dataset and their corresponding χ2 scores. Features χ2 scoresmaximum_nights 2.152729e+10minimum_nights 8.856912e+05security_deposit 7.716334e+05number_of_reviews 8.341015e+04square_feet 2.982368e+04property_type 2.222414e+04calculated_host_listings_count 1.072021e+04neighbourhood_cleansed 1.071895e+04accommodates 7.771539e+03room_type 4.234147e+03neighbourhood 3.254091e+03guests_included 3.061216e+03bedrooms 2.380380e+03cancellation_policy 1.444670e+03distance 9.580979e+02host_is_superhost 6.349556e+02neighbourhood_group_cleansed 5.957898e+02instant_bookable 3.502228e+02bathrooms 3.290317e+02review_scores_rating 2.151681e+02is_location_exact 9.053878e+01review_scores_cleanliness 5.194306e+01review_scores_accuracy 2.410470e+01bed_type 7.055763e+00longitude 1.016177e-01"
},
{
"code": null,
"e": 3523,
"s": 3080,
"text": "Next, only the top five features were selected. This subset was split into training and test data. The ‘price’ was set as the target feature. The training data subset was used for fitting the random forest while the test subset was used for the prediction. This was repeated by using different subsets where top ten, top fifteen, top twenty and top twenty-five features were included. For each case we calculated the value which is defined as"
},
{
"code": null,
"e": 3557,
"s": 3523,
"text": "adjusted R^2 = 1-R^2(N-1)/(N-M-1)"
},
{
"code": null,
"e": 4189,
"s": 3557,
"text": "where N is the number of points in the dataset and M is the number of independent feature(s) while is the measure of the goodness of fit. increases with the number of features to the model. As always increases and never decreases, it can appear to be a better fit with the more terms that is added to the model. In regression analysis, it can be tempting to add more variables to the data which can be misleading. Some of those variables may be significant, but one can’t be sure that significance is just by chance. The compensate for this by that penalizing for those extra variables. The corresponding plot is shown in Figure 1."
},
{
"code": null,
"e": 4264,
"s": 4189,
"text": "Figure 1. Plot of the number of features and the corresponding adjusted R2"
}
] |
How to get current Wi-Fi link speed in android? | This example demonstrates How to get current Wi-Fi link speed in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken a text view to show WIFI link speed.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
textView.setText("" + wifiInfo.getLinkSpeed());
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<action android:name = "android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code | [
{
"code": null,
"e": 1136,
"s": 1062,
"text": "This example demonstrates How to get current Wi-Fi link speed in android."
},
{
"code": null,
"e": 1265,
"s": 1136,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1330,
"s": 1265,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1890,
"s": 1330,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1960,
"s": 1890,
"text": "In the above code, we have taken a text view to show WIFI link speed."
},
{
"code": null,
"e": 2017,
"s": 1960,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3016,
"s": 2017,
"text": "package com.example.myapplication;\nimport android.net.wifi.WifiInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.format.Formatter;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);\n WifiInfo wifiInfo = wifiMgr.getConnectionInfo();\n textView.setText(\"\" + wifiInfo.getLinkSpeed());\n }\n @Override\n protected void onStop() {\n super.onStop();\n }\n @Override\n protected void onResume() {\n super.onResume();\n }\n}"
},
{
"code": null,
"e": 3071,
"s": 3016,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3935,
"s": 3071,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_WIFI_STATE\" />\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <action android:name = \"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4286,
"s": 3935,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4326,
"s": 4286,
"text": "Click here to download the project code"
}
] |
Ant - Environment Setup | Apache Ant is distributed under the Apache Software License which is a fully-fledged open source license certified by the open source initiative.
The latest Apache Ant version, including its full-source code, class files, and documentation can be found at https://ant.apache.org.
It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions available at file:///C:/java/java_environment_setup.htm
Ensure that the JAVA_HOME environment variable is set to the folder, where your JDK is installed.
Ensure that the JAVA_HOME environment variable is set to the folder, where your JDK is installed.
Download the binaries from https://ant.apache.org
Download the binaries from https://ant.apache.org
Unzip the zip file to a convenient location c:\folder by using Winzip, winRAR, 7-zip or similar tools.
Unzip the zip file to a convenient location c:\folder by using Winzip, winRAR, 7-zip or similar tools.
Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case, it is c:\apache-ant-1.10.12-bin folder.
Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case, it is c:\apache-ant-1.10.12-bin folder.
Append the path to the Apache Ant batch file to the PATH environment variable. In our case, this would be the c:\apache-ant-1.10.12-bin\bin folder.
Append the path to the Apache Ant batch file to the PATH environment variable. In our case, this would be the c:\apache-ant-1.10.12-bin\bin folder.
To verify the successful installation of Apache Ant on your computer, type ant on your command prompt.
You should see an output as given below −
C:\>ant -version
Apache Ant(TM) version 1.10.12 compiled on October 13 2021
If you do not see the above output, then please verify that you have followed the installation steps properly.
This tutorial also covers integration of Ant with Eclipse integrated development environment (IDE). Hence, if you have not installed Eclipse, please download and install Eclipse.
Download the latest Eclipse binaries from www.eclipse.org
Download the latest Eclipse binaries from www.eclipse.org
Unzip the Eclipse binaries to a convenient location, say c:\folder.
Unzip the Eclipse binaries to a convenient location, say c:\folder.
Run Eclipse from c:\eclipse\eclipse.exe.
Run Eclipse from c:\eclipse\eclipse.exe.
20 Lectures
2 hours
Deepti Trivedi
19 Lectures
2.5 hours
Deepti Trivedi
139 Lectures
14 hours
Er. Himanshu Vasishta
30 Lectures
1.5 hours
Pushpendu Mondal
65 Lectures
6.5 hours
Ridhi Arora
10 Lectures
2 hours
Manish Gupta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2243,
"s": 2097,
"text": "Apache Ant is distributed under the Apache Software License which is a fully-fledged open source license certified by the open source initiative."
},
{
"code": null,
"e": 2377,
"s": 2243,
"text": "The latest Apache Ant version, including its full-source code, class files, and documentation can be found at https://ant.apache.org."
},
{
"code": null,
"e": 2578,
"s": 2377,
"text": "It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions available at file:///C:/java/java_environment_setup.htm"
},
{
"code": null,
"e": 2676,
"s": 2578,
"text": "Ensure that the JAVA_HOME environment variable is set to the folder, where your JDK is installed."
},
{
"code": null,
"e": 2774,
"s": 2676,
"text": "Ensure that the JAVA_HOME environment variable is set to the folder, where your JDK is installed."
},
{
"code": null,
"e": 2824,
"s": 2774,
"text": "Download the binaries from https://ant.apache.org"
},
{
"code": null,
"e": 2874,
"s": 2824,
"text": "Download the binaries from https://ant.apache.org"
},
{
"code": null,
"e": 2977,
"s": 2874,
"text": "Unzip the zip file to a convenient location c:\\folder by using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 3080,
"s": 2977,
"text": "Unzip the zip file to a convenient location c:\\folder by using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 3228,
"s": 3080,
"text": "Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case, it is c:\\apache-ant-1.10.12-bin folder."
},
{
"code": null,
"e": 3376,
"s": 3228,
"text": "Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case, it is c:\\apache-ant-1.10.12-bin folder."
},
{
"code": null,
"e": 3524,
"s": 3376,
"text": "Append the path to the Apache Ant batch file to the PATH environment variable. In our case, this would be the c:\\apache-ant-1.10.12-bin\\bin folder."
},
{
"code": null,
"e": 3672,
"s": 3524,
"text": "Append the path to the Apache Ant batch file to the PATH environment variable. In our case, this would be the c:\\apache-ant-1.10.12-bin\\bin folder."
},
{
"code": null,
"e": 3775,
"s": 3672,
"text": "To verify the successful installation of Apache Ant on your computer, type ant on your command prompt."
},
{
"code": null,
"e": 3817,
"s": 3775,
"text": "You should see an output as given below −"
},
{
"code": null,
"e": 3894,
"s": 3817,
"text": "C:\\>ant -version\nApache Ant(TM) version 1.10.12 compiled on October 13 2021\n"
},
{
"code": null,
"e": 4005,
"s": 3894,
"text": "If you do not see the above output, then please verify that you have followed the installation steps properly."
},
{
"code": null,
"e": 4184,
"s": 4005,
"text": "This tutorial also covers integration of Ant with Eclipse integrated development environment (IDE). Hence, if you have not installed Eclipse, please download and install Eclipse."
},
{
"code": null,
"e": 4242,
"s": 4184,
"text": "Download the latest Eclipse binaries from www.eclipse.org"
},
{
"code": null,
"e": 4300,
"s": 4242,
"text": "Download the latest Eclipse binaries from www.eclipse.org"
},
{
"code": null,
"e": 4368,
"s": 4300,
"text": "Unzip the Eclipse binaries to a convenient location, say c:\\folder."
},
{
"code": null,
"e": 4436,
"s": 4368,
"text": "Unzip the Eclipse binaries to a convenient location, say c:\\folder."
},
{
"code": null,
"e": 4477,
"s": 4436,
"text": "Run Eclipse from c:\\eclipse\\eclipse.exe."
},
{
"code": null,
"e": 4518,
"s": 4477,
"text": "Run Eclipse from c:\\eclipse\\eclipse.exe."
},
{
"code": null,
"e": 4551,
"s": 4518,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4567,
"s": 4551,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 4602,
"s": 4567,
"text": "\n 19 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4618,
"s": 4602,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 4653,
"s": 4618,
"text": "\n 139 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 4676,
"s": 4653,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 4711,
"s": 4676,
"text": "\n 30 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4729,
"s": 4711,
"text": " Pushpendu Mondal"
},
{
"code": null,
"e": 4764,
"s": 4729,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4777,
"s": 4764,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 4810,
"s": 4777,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4824,
"s": 4810,
"text": " Manish Gupta"
},
{
"code": null,
"e": 4831,
"s": 4824,
"text": " Print"
},
{
"code": null,
"e": 4842,
"s": 4831,
"text": " Add Notes"
}
] |
C# Program to get the smallest and largest element from a list | Set a list.
List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };
To get the smallest element, use the Min() method.
list.AsQueryable().Min();
To get the largest element, use the Max() method.
list.AsQueryable().Max();
Let us see the complete code −
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };
foreach(long ele in list){
Console.WriteLine(ele);
}
// getting largest element
long max_num = list.AsQueryable().Max();
// getting smallest element
long min_num = list.AsQueryable().Min();
Console.WriteLine("Smallest number = {0}", min_num);
Console.WriteLine("Largest number = {0}", max_num);
}
}
150
300
400
350
450
550
600
Smallest number = 150
Largest number = 600 | [
{
"code": null,
"e": 1074,
"s": 1062,
"text": "Set a list."
},
{
"code": null,
"e": 1146,
"s": 1074,
"text": "List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };"
},
{
"code": null,
"e": 1197,
"s": 1146,
"text": "To get the smallest element, use the Min() method."
},
{
"code": null,
"e": 1223,
"s": 1197,
"text": "list.AsQueryable().Min();"
},
{
"code": null,
"e": 1273,
"s": 1223,
"text": "To get the largest element, use the Max() method."
},
{
"code": null,
"e": 1299,
"s": 1273,
"text": "list.AsQueryable().Max();"
},
{
"code": null,
"e": 1330,
"s": 1299,
"text": "Let us see the complete code −"
},
{
"code": null,
"e": 1341,
"s": 1330,
"text": " Live Demo"
},
{
"code": null,
"e": 1885,
"s": 1341,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nclass Demo {\n static void Main() {\n List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };\n foreach(long ele in list){\n Console.WriteLine(ele);\n }\n\n // getting largest element\n long max_num = list.AsQueryable().Max();\n\n // getting smallest element\n long min_num = list.AsQueryable().Min();\n\n Console.WriteLine(\"Smallest number = {0}\", min_num);\n Console.WriteLine(\"Largest number = {0}\", max_num);\n }\n}"
},
{
"code": null,
"e": 1956,
"s": 1885,
"text": "150\n300\n400\n350\n450\n550\n600\nSmallest number = 150\nLargest number = 600"
}
] |
Retrieving array values from a find query in MongoDB? | To retrieve array values, use dot(.) notation. Let us first create a collection with documents −
> db.retrievingArrayDemo.insertOne(
{ "UserDetails" : [
{ "UserName" : "John", "UserAge" : 23 } ],
"UserCountryName" : "AUS",
"UserLoginDate" : new ISODate(),
"UserMessage" : "Hello"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce9718478f00858fb12e920")
}
> db.retrievingArrayDemo.insertOne(
{ "UserDetails" : [
{ "UserName" : "Sam", "UserAge" : 24 } ],
"UserCountryName" : "UK",
"UserLoginDate" : new ISODate(),
"UserMessage" : "Bye"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce9718478f00858fb12e921")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.retrievingArrayDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ce9718478f00858fb12e920"),
"UserDetails" : [
{
"UserName" : "John",
"UserAge" : 23
}
],
"UserCountryName" : "AUS",
"UserLoginDate" : ISODate("2019-05-25T16:47:00.211Z"),
"UserMessage" : "Hello"
}
{
"_id" : ObjectId("5ce9718478f00858fb12e921"),
"UserDetails" : [
{
"UserName" : "Sam",
"UserAge" : 24
}
],
"UserCountryName" : "UK",
"UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"),
"UserMessage" : "Bye"
}
Following is the query to retrieve array values from a find query −
> db.retrievingArrayDemo.find({"UserCountryName" : "UK", "UserDetails.UserName":"Sam"}).pretty();
This will produce the following output −
{
"_id" : ObjectId("5ce9718478f00858fb12e921"),
"UserDetails" : [
{
"UserName" : "Sam",
"UserAge" : 24
}
],
"UserCountryName" : "UK",
"UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"),
"UserMessage" : "Bye"
} | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To retrieve array values, use dot(.) notation. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1761,
"s": 1159,
"text": "> db.retrievingArrayDemo.insertOne(\n { \"UserDetails\" : [\n { \"UserName\" : \"John\", \"UserAge\" : 23 } ],\n \"UserCountryName\" : \"AUS\",\n \"UserLoginDate\" : new ISODate(),\n \"UserMessage\" : \"Hello\"\n }\n);\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce9718478f00858fb12e920\")\n}\n> db.retrievingArrayDemo.insertOne(\n { \"UserDetails\" : [\n { \"UserName\" : \"Sam\", \"UserAge\" : 24 } ],\n \"UserCountryName\" : \"UK\",\n \"UserLoginDate\" : new ISODate(),\n \"UserMessage\" : \"Bye\"\n }\n);\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce9718478f00858fb12e921\")\n}"
},
{
"code": null,
"e": 1860,
"s": 1761,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1902,
"s": 1860,
"text": "> db.retrievingArrayDemo.find().pretty();"
},
{
"code": null,
"e": 1943,
"s": 1902,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2469,
"s": 1943,
"text": "{\n \"_id\" : ObjectId(\"5ce9718478f00858fb12e920\"),\n \"UserDetails\" : [\n {\n \"UserName\" : \"John\",\n \"UserAge\" : 23\n }\n ],\n \"UserCountryName\" : \"AUS\",\n \"UserLoginDate\" : ISODate(\"2019-05-25T16:47:00.211Z\"),\n \"UserMessage\" : \"Hello\"\n}\n{\n \"_id\" : ObjectId(\"5ce9718478f00858fb12e921\"),\n \"UserDetails\" : [\n {\n \"UserName\" : \"Sam\",\n \"UserAge\" : 24\n }\n ],\n \"UserCountryName\" : \"UK\",\n \"UserLoginDate\" : ISODate(\"2019-05-25T16:47:00.670Z\"),\n \"UserMessage\" : \"Bye\"\n}"
},
{
"code": null,
"e": 2537,
"s": 2469,
"text": "Following is the query to retrieve array values from a find query −"
},
{
"code": null,
"e": 2635,
"s": 2537,
"text": "> db.retrievingArrayDemo.find({\"UserCountryName\" : \"UK\", \"UserDetails.UserName\":\"Sam\"}).pretty();"
},
{
"code": null,
"e": 2676,
"s": 2635,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2937,
"s": 2676,
"text": "{\n \"_id\" : ObjectId(\"5ce9718478f00858fb12e921\"),\n \"UserDetails\" : [\n {\n \"UserName\" : \"Sam\",\n \"UserAge\" : 24\n }\n ],\n \"UserCountryName\" : \"UK\",\n \"UserLoginDate\" : ISODate(\"2019-05-25T16:47:00.670Z\"),\n \"UserMessage\" : \"Bye\"\n}"
}
] |
Introduction to URLSearchParams API in Node.js | Node is an open source project that is used to create dynamic web applications. The URLSearchParams API is an interface. It defines different utility that is required to work with the query string of the URL.
In this article, we will discuss the four different constructors of URLSearchParams that can be used as per the requirement.
This is a no argument constructor and therefore only used to initialize a new Empty URLSearchParams() object.
var params = new URLSearchParams();
This constructor can accept a string as an input parameter along with instantiating a new URLSearchParams object.
const params = new URLSearchParams('firstName=pqr & lastName=xyz');
console.log(params.get('firstName'));
console.log(params.get('lastName'));
pqr
xyz
This contructor accepts an object as an input parameter with a collection of key-value pairs to initialize a new URL. The key-value pair are always converted to string type. Duplicate keys are not allowed.
const params = new URLSearchParams({
user: 'John',
subjects: ['Physics', 'Chemistry', 'Maths']
});
console.log(params.toString());
user=John&subjects=Physics%2CChemistry%2CMaths
This contructor accepts an iterable object that contains a collection of key-value pairs to initialize a new URLSearchParams object. Since URLSearchParams is itself an iterable an object, therefore we can have another iterable URLSearchParams inside new URLSearchParams(). Duplicate keys are allowed inside this.
const map = new Map();
map.set('Taj Mahal', 'Agra');
map.set('Qutub Minar', 'Delhi');
map.set('Gateway of India', 'Mumbai');
params = new URLSearchParams(map);
console.log(params.toString());
Taj+Mahal=Agra&Qutub+Minar=Delhi&Gateway+of+India=Mumbai | [
{
"code": null,
"e": 1271,
"s": 1062,
"text": "Node is an open source project that is used to create dynamic web applications. The URLSearchParams API is an interface. It defines different utility that is required to work with the query string of the URL."
},
{
"code": null,
"e": 1396,
"s": 1271,
"text": "In this article, we will discuss the four different constructors of URLSearchParams that can be used as per the requirement."
},
{
"code": null,
"e": 1506,
"s": 1396,
"text": "This is a no argument constructor and therefore only used to initialize a new Empty URLSearchParams() object."
},
{
"code": null,
"e": 1542,
"s": 1506,
"text": "var params = new URLSearchParams();"
},
{
"code": null,
"e": 1656,
"s": 1542,
"text": "This constructor can accept a string as an input parameter along with instantiating a new URLSearchParams object."
},
{
"code": null,
"e": 1805,
"s": 1656,
"text": "const params = new URLSearchParams('firstName=pqr & lastName=xyz');\n console.log(params.get('firstName'));\n console.log(params.get('lastName'));"
},
{
"code": null,
"e": 1813,
"s": 1805,
"text": "pqr\nxyz"
},
{
"code": null,
"e": 2019,
"s": 1813,
"text": "This contructor accepts an object as an input parameter with a collection of key-value pairs to initialize a new URL. The key-value pair are always converted to string type. Duplicate keys are not allowed."
},
{
"code": null,
"e": 2156,
"s": 2019,
"text": "const params = new URLSearchParams({\n user: 'John',\n subjects: ['Physics', 'Chemistry', 'Maths']\n});\nconsole.log(params.toString());"
},
{
"code": null,
"e": 2203,
"s": 2156,
"text": "user=John&subjects=Physics%2CChemistry%2CMaths"
},
{
"code": null,
"e": 2516,
"s": 2203,
"text": "This contructor accepts an iterable object that contains a collection of key-value pairs to initialize a new URLSearchParams object. Since URLSearchParams is itself an iterable an object, therefore we can have another iterable URLSearchParams inside new URLSearchParams(). Duplicate keys are allowed inside this."
},
{
"code": null,
"e": 2723,
"s": 2516,
"text": "const map = new Map();\n map.set('Taj Mahal', 'Agra');\n map.set('Qutub Minar', 'Delhi');\n map.set('Gateway of India', 'Mumbai');\n params = new URLSearchParams(map);\n console.log(params.toString());"
},
{
"code": null,
"e": 2780,
"s": 2723,
"text": "Taj+Mahal=Agra&Qutub+Minar=Delhi&Gateway+of+India=Mumbai"
}
] |
What does 'show processlist' command do in MySQL? | The ‘SHOW processlist’ command can be used to display the running thread related to only your MySQL account. We can see almost all running threads if we have process privileges. It shows which threads are running.
The following is the query.
mysql> SHOW processlist;
Here is the output.
+----+-----------------+-----------------+------+---------+------+------------------------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+-----------------+-----------------+------+---------+------+------------------------+------------------+
| 4 | event_scheduler | localhost | NULL | Daemon | 968 | Waiting on empty queue | NULL |
| 9 | root | localhost:50255 | NULL | Query | 0 | starting | show processlist |
+----+-----------------+-----------------+------+---------+------+------------------------+------------------+
2 rows in set (0.00 sec)
If we change the database, then the output will be different, but there will always be the following two users: ‘event_scheduler’ and ‘root’.
Let us try the query again.
mysql> SHOW processlist;
The following is the output.
+----+-----------------+-----------------+----------+---------+------+------------------------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+-----------------+-----------------+----------+---------+------+------------------------+------------------+
| 4 | event_scheduler | localhost | NULL | Daemon | 1148 | Waiting on empty queue | NULL |
| 9 | root | localhost:50255 | business | Query | 0 | starting | show processlist |
+----+-----------------+-----------------+----------+---------+------+------------------------+------------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1276,
"s": 1062,
"text": "The ‘SHOW processlist’ command can be used to display the running thread related to only your MySQL account. We can see almost all running threads if we have process privileges. It shows which threads are running."
},
{
"code": null,
"e": 1304,
"s": 1276,
"text": "The following is the query."
},
{
"code": null,
"e": 1329,
"s": 1304,
"text": "mysql> SHOW processlist;"
},
{
"code": null,
"e": 1349,
"s": 1329,
"text": "Here is the output."
},
{
"code": null,
"e": 2041,
"s": 1349,
"text": "+----+-----------------+-----------------+------+---------+------+------------------------+------------------+\n| Id | User | Host | db | Command | Time | State | Info |\n+----+-----------------+-----------------+------+---------+------+------------------------+------------------+\n| 4 | event_scheduler | localhost | NULL | Daemon | 968 | Waiting on empty queue | NULL |\n| 9 | root | localhost:50255 | NULL | Query | 0 | starting | show processlist |\n+----+-----------------+-----------------+------+---------+------+------------------------+------------------+\n2 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 2183,
"s": 2041,
"text": "If we change the database, then the output will be different, but there will always be the following two users: ‘event_scheduler’ and ‘root’."
},
{
"code": null,
"e": 2211,
"s": 2183,
"text": "Let us try the query again."
},
{
"code": null,
"e": 2236,
"s": 2211,
"text": "mysql> SHOW processlist;"
},
{
"code": null,
"e": 2265,
"s": 2236,
"text": "The following is the output."
},
{
"code": null,
"e": 2981,
"s": 2265,
"text": "+----+-----------------+-----------------+----------+---------+------+------------------------+------------------+\n| Id | User | Host | db | Command | Time | State | Info |\n+----+-----------------+-----------------+----------+---------+------+------------------------+------------------+\n| 4 | event_scheduler | localhost | NULL | Daemon | 1148 | Waiting on empty queue | NULL |\n| 9 | root | localhost:50255 | business | Query | 0 | starting | show processlist |\n+----+-----------------+-----------------+----------+---------+------+------------------------+------------------+\n2 rows in set (0.00 sec)\n"
}
] |
How to add a list elements within an unordered list element using jQuery ? - GeeksforGeeks | 14 Apr, 2021
Here in this article, we will see that how we can add a list to the Unordered List using jQuery. So the function which we had used to append the items in the list are –
<script>
$(document).ready(function() {
$('.btn').click(function(){
var content = $('#addList').val();
var fixingContent='<li>'+content+'</li>';
$('.List').append(fixingContent);
})
})
</script>
Approach: First, we create a button that provides the functionality to add the items to the list.
When the button is clicked then through the button ID we will be first store the input from the textBox to the variable content having it’s value then simply put the content in the var fixingContent='<li><span>’+content+'</span></li>’
After that, we just append the content to the list having a class named list.
Code Implementation:
HTML
<!DOCTYPE html><html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <style> .btn { width: 66px; height: 21px; margin: 5px; padding: 0px; border-color: #b6b6bb; } #addList { border-color: rgb(183, 252, 252); } </style> <script> $(document).ready(function() { $('.btn').click(function() { var content = $('#addList').val(); var fixingContent = '<li>' + content + '</li>'; $('.List').append(fixingContent); }) }) </script></head> <body> <h3 class="head"> Type List to Add</h3> <input type="text" id="addList"> <input type="button" name="add" class="btn" value="Add"> </button> <div class="addTask"> <ul class="List"> </ul> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML-Questions
HTML-Tags
jQuery-Methods
jQuery-Questions
Picked
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
How to auto-resize an image to fit a div container using CSS?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to Dynamically Add/Remove Table Rows using jQuery ?
How to change the background color after clicking the button in JavaScript ? | [
{
"code": null,
"e": 24877,
"s": 24849,
"text": "\n14 Apr, 2021"
},
{
"code": null,
"e": 25046,
"s": 24877,
"text": "Here in this article, we will see that how we can add a list to the Unordered List using jQuery. So the function which we had used to append the items in the list are –"
},
{
"code": null,
"e": 25302,
"s": 25046,
"text": "<script>\n $(document).ready(function() {\n $('.btn').click(function(){\n var content = $('#addList').val();\n var fixingContent='<li>'+content+'</li>';\n $('.List').append(fixingContent);\n })\n }) \n</script>"
},
{
"code": null,
"e": 25400,
"s": 25302,
"text": "Approach: First, we create a button that provides the functionality to add the items to the list."
},
{
"code": null,
"e": 25636,
"s": 25400,
"text": "When the button is clicked then through the button ID we will be first store the input from the textBox to the variable content having it’s value then simply put the content in the var fixingContent='<li><span>’+content+'</span></li>’ "
},
{
"code": null,
"e": 25714,
"s": 25636,
"text": "After that, we just append the content to the list having a class named list."
},
{
"code": null,
"e": 25735,
"s": 25714,
"text": "Code Implementation:"
},
{
"code": null,
"e": 25740,
"s": 25735,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"> </script> <style> .btn { width: 66px; height: 21px; margin: 5px; padding: 0px; border-color: #b6b6bb; } #addList { border-color: rgb(183, 252, 252); } </style> <script> $(document).ready(function() { $('.btn').click(function() { var content = $('#addList').val(); var fixingContent = '<li>' + content + '</li>'; $('.List').append(fixingContent); }) }) </script></head> <body> <h3 class=\"head\"> Type List to Add</h3> <input type=\"text\" id=\"addList\"> <input type=\"button\" name=\"add\" class=\"btn\" value=\"Add\"> </button> <div class=\"addTask\"> <ul class=\"List\"> </ul> </div></body> </html>",
"e": 26745,
"s": 25740,
"text": null
},
{
"code": null,
"e": 26753,
"s": 26745,
"text": "Output:"
},
{
"code": null,
"e": 26890,
"s": 26753,
"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": 26906,
"s": 26890,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26921,
"s": 26906,
"text": "HTML-Questions"
},
{
"code": null,
"e": 26931,
"s": 26921,
"text": "HTML-Tags"
},
{
"code": null,
"e": 26946,
"s": 26931,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 26963,
"s": 26946,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 26970,
"s": 26963,
"text": "Picked"
},
{
"code": null,
"e": 26975,
"s": 26970,
"text": "HTML"
},
{
"code": null,
"e": 26982,
"s": 26975,
"text": "JQuery"
},
{
"code": null,
"e": 26999,
"s": 26982,
"text": "Web Technologies"
},
{
"code": null,
"e": 27004,
"s": 26999,
"text": "HTML"
},
{
"code": null,
"e": 27102,
"s": 27004,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27111,
"s": 27102,
"text": "Comments"
},
{
"code": null,
"e": 27124,
"s": 27111,
"text": "Old Comments"
},
{
"code": null,
"e": 27148,
"s": 27124,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27185,
"s": 27148,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27205,
"s": 27185,
"text": "Angular File Upload"
},
{
"code": null,
"e": 27234,
"s": 27205,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27296,
"s": 27234,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 27342,
"s": 27296,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 27371,
"s": 27342,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27434,
"s": 27371,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 27490,
"s": 27434,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
}
] |
Web scraping with Python — A to Z | by Shai Ardazi | Towards Data Science | Written by Shai Ardazi & Eitan Kassuto — February 2019
The act of going through web pages and extracting selected text or images.
An excellent tool for getting new data or enriching your current data.
Usually the first step of a data science project which requires a lot of data.
An alternative to API calls for data retrieval. Meaning, if you don’t have an API or if it’s limited in some way.
For example:
Tracking and predicting the stock market’s prices by enriching the up to date stock prices with the latest news stories. These news stories may not be available from an API and therefore would need to be scraped from a news website. This is done by going through a web page and extracting text (or images) of interest.
Our web scraping project was part of the Data Science fellows program at ITC (Israel Tech Challenge) which was designed to expose us to the real world problems a data scientist faces as well as to improve our coding skills.
In this post, we show our main steps and challenges along the way. We have included code snippets and recommendations on how to create an end to end pipeline for web scraping. The code snippets we show here are not OOP (Object Oriented Programming) for the sake of simplicity, but we highly recommend to write OOP code in your web scraper implementation.
Main tools we used:
Python (3.5)
BeautifulSoup library for handling the text extraction from the web page’s source code (HTML and CSS)
requests library for handling the interaction with the web page (Using HTTP requests)
MySQL database — for storing our data (mysql.connector is the MySQL API for Python)
API calls — for enriching our data
Proxy header rotations — generating random headers and getting free proxy IPs in order to avoid IP blocks
Workflow
In this project we were free to choose any website. The websites chosen by the rest of the cohort ranged from e-commerce to news websites showing the different applications of web scraping.
We chose a website for scientific articles because we thought it would be interesting to see what kind of data we could obtain and furthermore what insights we could gather as a result of this data.
We have chosen to keep the website anonymous. In any case the goal of this post is to outline how to build a pipeline for any website of interest.
First, one must inspect the website in order to determine which data one would like to scrape. It involves a basic understanding of the websites structure so that your code can scrape the data you want.
In order to inspect the structure of the website, open the inspector of the web page, right click on the page → hit “Inspect element”.
Then, locate the data you want to scrape and click on it. The highlighted part in the inspector pane shows the underlying HTML text of the webpage section of interest. The CSS class of the element is what Beautifulsoup will use to extract the data from the html.
In the following screenshot one can see that the “keywords” section is what needs to be scraped. Using the inspector, one can locate the HTML element of the “keywords” section and its CSS class.
The structure is as follows:
div (class=”keywords-section”) → div (class=“keyword”).
Using beautiful soup, the code to get all keywords is as follows:
From here, it’s pretty much the same. Locate the desired section, inspect the HTML element and get the data. Full documentation and much more examples of beautifulsoup can be found here (very friendly).
The scraping process involves many HTTP GET requests in a short amount of time because in many cases one may need to navigate automatically between multiple pages in order to get the data. Moreover, having an awesome scraper is not just about getting the data one wants, it’s also about getting new data or updating existing data frequently — This might lead to being blocked by the website. This leads us to the next section:
In general, websites don’t like bot scrapers but they probably don’t prevent it completely because of the search engine bots that scrape websites in order to categorize them. There’s a robots exclusion standard that defines the website’s terms and conditions with bot crawlers, which is usually found in the robots.txt file of the website. For example, the robots.txt file of Wikipedia can be found here: https://en.wikipedia.org/robots.txt.
The first few lines of Wikipedia’s robots.txt:
# robots.txt for http://www.wikipedia.org/ and friends## Please note: There are a lot of pages on this site, and there are# some misbehaved spiders out there that go _way_ too fast. If you're# irresponsible, your access to the site may be blocked.
As you can see, Wikipedia’s restrictions are not too strict. However, some websites are very strict and do not allow crawling part of the website or all of it. Their robots.txt would include this:
User-agent: *Disallow: /
One way of doing this is by rotating through different proxies and user agents (headers) when making requests to the website. Also, it is important to be considerate in how often you make requests to the website to avoid being a ‘spammer’.
Note — This is only for learning purposes. We do not encourage you to breach terms of any website.
See below on how to implement this method in just a few simple steps.
Proxies pool
Implementing a proxy server can be done easily in Python. A list of free proxies can be found here (Note that free proxies are usually less stable and slower than paid ones. If you don’t find the free ones good enough for your needs, you may consider getting a paid service).
Looking at the free proxies list, one can use BeautifulSoup in order to get the IP addresses and ports. The structure of the above-mentioned website can seen below.
The following function retrieves all the proxies’ IPs and ports and returns a list of them:
Headers pool
There are many HTTP headers that can be passed as part of a request when using the requests package in Python. We passed two header elements (which were sufficient for us), namely the Accept header (user permissions) and user agent (Pseudo-Browser).
The pool of pseudo random headers was created as follows (see code below):
Create a dictionary object of “accepts” where each accept header is related to a specific browser (depending on the user agent). A list of accept headers can be found here. This list contains default values for each user-agent and can be changed.
Get a random user-agent using fake-useragent package in Python. This is super easy to use as seen in the code below. We suggest creating a list of user-agents beforehand just in case the fake-useragent is unavailable. An example of a user-agent:‘Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20130326 Firefox/21.0’
Create a dictionary object with accept and user-agent as keys and the corresponding values
The partial code (full function in the appendix below):
Using the headers and proxies pools
The following code shows an example of how to use the function we wrote before. We did not include the OOP code for the sake of simplicity. See Appendix for the full function random_header().
Up until here we gave a brief introduction of web scraping and spoke about more advanced techniques on how to avoid being blocked by a website.
In the following section we show 2 examples of how to use API calls for data enrichment: Genderize.io and Aylien Text Analysis.
Genderize uses the first name of an individual to predict their gender (limited to male and female).
The output of this API is structured as JSON as seen in the example below:
{“name”:”peter”,”gender”:”male”,”probability”:”0.99",”count”:796}
This makes it very convenient to enrich the author data with each one’s gender. Since the probability of the predicted gender is included, one can set a threshold to ensure better quality predictions (we set our threshold at 60% — see below for code snippets). The value this API brings is the ability to determine the gender distribution of authors for a specified topic.
We did not have to worry about the API limit (1000 calls/day) since we were only able to scrape around 120 articles/day which on average resulted in less than 500 authors per day. If one is able to exceed this daily limit, the API limit would have to be taken into account. One way of avoiding this daily limit would be to check if the first name being evaluated has already been enriched in our database. This would allow us to determine the gender based on the existing data without wasting an API call.
Some code snippets for the tech hungry:
Connecting genderize:
Author gender enrichment:
We were interested in seeing the growth of keywords over time for a specified topic (think Google Trends) and therefore decided that we should enrich our data with more keywords. To do this, we used an API called Aylien Text Analysis, specifically the concept extraction API. This API allows one to input text which after processing outputs a list of keywords extracted from the text using NLP. Two of the various fields we scraped for each article were the Title and Abstract, these fields were concatenated and used as the input for the API. An example of the output JSON can be seen below:
{ “text”:”Apple was founded by Steve Jobs, Steve Wozniak and Ronald Wayne.”, “language”:”en”, “concepts”:{ “http://dbpedia.org/resource/Apple_Inc.":{ “surfaceForms”:[ { “string”:”Apple”, “score”:0.9994597361117074, “offset”:0 } ], “types”:[ “http://www.wikidata.org/entity/Q43229”, “http://schema.org/Organization", “http://dbpedia.org/ontology/Organisation", “http://dbpedia.org/ontology/Company" ], “support”:10626 } }}
In order to avoid duplicate keywords we checked that the keyword did not already exist in the keyword table of our database. In order to avoid adding too many keywords per article, two methods were instituted. The first was a simple keyword limit as seen in the code snippet below. The other made use of the score (probability of relevance) available in the output file for each keyword — This allows one to set a threshold (we used 80%) to ensure the most relevant keywords were added for each article.
An example of how the API works is seen in the figure below:
Below is a snippet of the code we used to connect to the Aylien Text API service:
Connect to aylien:
Enrich keywords using Aylien API:
Let’s move to the final part. So far we gave an introduction to web scraping and how to avoid being blocked, as well as using API calls in order to enrich one’s data. In the final part of this post we will go through how to set up a database in order to store the data and how to access this data for visualization. Visualizations are a powerful tool one can use to extract insights from the data.
When setting up the database for a web scraping project (or others in general) the following should be taken into account:
Tables creation
New data insertion
Data update (every hour/day...)
This stage of the pipeline should be done with caution and one should validate that the chosen structure (in terms of columns types, lengths, keys etc.) is suitable for the data and can handle extreme cases (missing data, non-English characters etc.). Avoid relying on an ID that is used by the website as the primary/unique key unless you have a really good reason (in our case doi_link of an article is a unique string that is acceptable everywhere, so we use it as a unique identifier of an article).
An example of tables creation using mysql.connector package:
The SQL command:
The function for building the database:
Note — in lines 12, 17, 23 and 25 we use the logger object. This is for logging to an external logs file and it’s super important. Creating a Logger class is recommended, you can see more below in this post, or click here.
Insertion of new data differs a bit from updating existing data. When new data is inserted to DB, one should make sure there are not duplicates. Also, in case of an error, one should catch it, log it and save the portion of data that caused that error for future inspection.
As seen below, we used again the cursor of mysql.connector in order to execute the SQL insert command.
Dynamic data requires frequent updates. One should define the time deltas (differences) between two updates which depends on the data type and source. In our project, we had to take into account that the number of citations for all articles would have to be updated periodically. The following piece of code illustrates the update process:
In order to help make sense of the collected data , one can use visualizations to provide an easy-to-understand overview of the data.
The visualizations we created enabled us to gain insights into the following use cases:
High-level trends
Identify leading Institutions/countries in the specified topic
Identify top researchers in the specified topic
The above use cases allow for a data-driven approach for: R&D Investment, consultation, general partnerships
In order to explore the above use cases we created visualizations of our data. We did this by using a simple but powerful open-source tool called Redash that was connected to our AWS machine(other kinds of instances are also available).
In order to set up Redash, do the following:
Click on the following link: https://redash.io/help/open-source/setup#aws
Choose the relevant AWS instance in order to create the Redash image on your machine.
Before moving on, here is an overview of the data we collected for the topic “Neural Networks”.
As you can see, not a lot of data was retrieved — this was because of the limited time we had available on the AWS (Amazon Web Services) machines. Due to the lack of sufficient data, the reader should evaluate the results with a pinch of salt — this is at this stage a proof of concept and is by no means a finished product.
For the high level trends we simply plotted the number of research papers published per month for the past 5 years.
SELECT publication_date, count(id) AS num FROM articles GROUP BY publication_date ORDER BY publication_date;
Gender Distribution
This visualization makes use of enriched author data from genderize to view the gender distribution of authors within the specified topic. As seen in the figure below there are a large proportion of authors whose gender are unknown due to limitations of the genderize API.
SELECT gender, count(ID) FROM authors GROUP BY gender;
Identifying leading countries in the field
When scraping affiliations for each author we were able to extract the country of each one, allowing us to create the visualization below. China publishes the majority of research papers for the topic “Neural Networks” as is expected due to their keen interest in AI. This information could be interesting for policy makers since one can track the advancements in AI in leading countries. Firstly, it can be helpful to monitor these leading countries to find opportunities for partnership in order to advance AI in both countries. Secondly, policy makers can use these insights in order to emulate leading countries in advancing AI within their own country.
SELECT country, count(affiliation_id) AS counterFROM affiliations GROUP BY country ORDER BY counter DESC;
Identifying top lead authors in the field
As a first approach to identifying the top researchers we decided to to compare the lead authors with the most citations associated to their name.
SELECT CONCAT(authors.first_name,” “, authors.last_name) AS name, SUM(articles.citations) AS num_citations FROM authors JOIN authors_article_junction JOIN articlesWHERE authors_article_junction.author_ID = authors.ID AND articles.ID = authors_article_junction.article_ID AND authors_article_junction.importance = 1 GROUP BY authors.ID ORDER BY num_citations DESC LIMIT 10;
Keywords map
The larger the word, the more frequent it is in the database
SELECT keywords.keyword_name, COUNT(keywords_ID) AS num FROM keyword_article_junction JOIN keywords WHERE keyword_article_junction.keywords_ID = keywords.ID GROUP BY keywords.keyword_name ORDER BY num DESC LIMIT 20;
Snapshot of our dashboard in Redash
We have reached the end of our Web Scraping with Python A — Z series. In the first part we gave a brief introduction of web scraping and spoke about more advanced techniques on how to avoid being blocked by a website. Also, we showed how one can use API calls in order to enrich the data to extract further insights. And lastly, we showed how to create a database for storing the data obtained from web scraping and how to visualize this data using an open source tool — Redash.
Consider using grequests for parallelizing the get requests. This can be done by doing the following:
This may not be as effective as it should be due to the limited speed of the free proxies but it is still worth trying.
Using Selenium for handling Javascript elements.
The full function to create random headers is as follows:
Note — In line 22 we saved a message into a logs file. It’s super important to have logs in your code! We suggest using logging package which is pretty simple to use.
The logger class that we built and used everywhere in our code: | [
{
"code": null,
"e": 226,
"s": 171,
"text": "Written by Shai Ardazi & Eitan Kassuto — February 2019"
},
{
"code": null,
"e": 301,
"s": 226,
"text": "The act of going through web pages and extracting selected text or images."
},
{
"code": null,
"e": 372,
"s": 301,
"text": "An excellent tool for getting new data or enriching your current data."
},
{
"code": null,
"e": 451,
"s": 372,
"text": "Usually the first step of a data science project which requires a lot of data."
},
{
"code": null,
"e": 565,
"s": 451,
"text": "An alternative to API calls for data retrieval. Meaning, if you don’t have an API or if it’s limited in some way."
},
{
"code": null,
"e": 578,
"s": 565,
"text": "For example:"
},
{
"code": null,
"e": 897,
"s": 578,
"text": "Tracking and predicting the stock market’s prices by enriching the up to date stock prices with the latest news stories. These news stories may not be available from an API and therefore would need to be scraped from a news website. This is done by going through a web page and extracting text (or images) of interest."
},
{
"code": null,
"e": 1121,
"s": 897,
"text": "Our web scraping project was part of the Data Science fellows program at ITC (Israel Tech Challenge) which was designed to expose us to the real world problems a data scientist faces as well as to improve our coding skills."
},
{
"code": null,
"e": 1476,
"s": 1121,
"text": "In this post, we show our main steps and challenges along the way. We have included code snippets and recommendations on how to create an end to end pipeline for web scraping. The code snippets we show here are not OOP (Object Oriented Programming) for the sake of simplicity, but we highly recommend to write OOP code in your web scraper implementation."
},
{
"code": null,
"e": 1496,
"s": 1476,
"text": "Main tools we used:"
},
{
"code": null,
"e": 1509,
"s": 1496,
"text": "Python (3.5)"
},
{
"code": null,
"e": 1611,
"s": 1509,
"text": "BeautifulSoup library for handling the text extraction from the web page’s source code (HTML and CSS)"
},
{
"code": null,
"e": 1697,
"s": 1611,
"text": "requests library for handling the interaction with the web page (Using HTTP requests)"
},
{
"code": null,
"e": 1781,
"s": 1697,
"text": "MySQL database — for storing our data (mysql.connector is the MySQL API for Python)"
},
{
"code": null,
"e": 1816,
"s": 1781,
"text": "API calls — for enriching our data"
},
{
"code": null,
"e": 1922,
"s": 1816,
"text": "Proxy header rotations — generating random headers and getting free proxy IPs in order to avoid IP blocks"
},
{
"code": null,
"e": 1931,
"s": 1922,
"text": "Workflow"
},
{
"code": null,
"e": 2121,
"s": 1931,
"text": "In this project we were free to choose any website. The websites chosen by the rest of the cohort ranged from e-commerce to news websites showing the different applications of web scraping."
},
{
"code": null,
"e": 2320,
"s": 2121,
"text": "We chose a website for scientific articles because we thought it would be interesting to see what kind of data we could obtain and furthermore what insights we could gather as a result of this data."
},
{
"code": null,
"e": 2467,
"s": 2320,
"text": "We have chosen to keep the website anonymous. In any case the goal of this post is to outline how to build a pipeline for any website of interest."
},
{
"code": null,
"e": 2670,
"s": 2467,
"text": "First, one must inspect the website in order to determine which data one would like to scrape. It involves a basic understanding of the websites structure so that your code can scrape the data you want."
},
{
"code": null,
"e": 2805,
"s": 2670,
"text": "In order to inspect the structure of the website, open the inspector of the web page, right click on the page → hit “Inspect element”."
},
{
"code": null,
"e": 3068,
"s": 2805,
"text": "Then, locate the data you want to scrape and click on it. The highlighted part in the inspector pane shows the underlying HTML text of the webpage section of interest. The CSS class of the element is what Beautifulsoup will use to extract the data from the html."
},
{
"code": null,
"e": 3263,
"s": 3068,
"text": "In the following screenshot one can see that the “keywords” section is what needs to be scraped. Using the inspector, one can locate the HTML element of the “keywords” section and its CSS class."
},
{
"code": null,
"e": 3292,
"s": 3263,
"text": "The structure is as follows:"
},
{
"code": null,
"e": 3348,
"s": 3292,
"text": "div (class=”keywords-section”) → div (class=“keyword”)."
},
{
"code": null,
"e": 3414,
"s": 3348,
"text": "Using beautiful soup, the code to get all keywords is as follows:"
},
{
"code": null,
"e": 3617,
"s": 3414,
"text": "From here, it’s pretty much the same. Locate the desired section, inspect the HTML element and get the data. Full documentation and much more examples of beautifulsoup can be found here (very friendly)."
},
{
"code": null,
"e": 4044,
"s": 3617,
"text": "The scraping process involves many HTTP GET requests in a short amount of time because in many cases one may need to navigate automatically between multiple pages in order to get the data. Moreover, having an awesome scraper is not just about getting the data one wants, it’s also about getting new data or updating existing data frequently — This might lead to being blocked by the website. This leads us to the next section:"
},
{
"code": null,
"e": 4486,
"s": 4044,
"text": "In general, websites don’t like bot scrapers but they probably don’t prevent it completely because of the search engine bots that scrape websites in order to categorize them. There’s a robots exclusion standard that defines the website’s terms and conditions with bot crawlers, which is usually found in the robots.txt file of the website. For example, the robots.txt file of Wikipedia can be found here: https://en.wikipedia.org/robots.txt."
},
{
"code": null,
"e": 4533,
"s": 4486,
"text": "The first few lines of Wikipedia’s robots.txt:"
},
{
"code": null,
"e": 4781,
"s": 4533,
"text": "# robots.txt for http://www.wikipedia.org/ and friends## Please note: There are a lot of pages on this site, and there are# some misbehaved spiders out there that go _way_ too fast. If you're# irresponsible, your access to the site may be blocked."
},
{
"code": null,
"e": 4978,
"s": 4781,
"text": "As you can see, Wikipedia’s restrictions are not too strict. However, some websites are very strict and do not allow crawling part of the website or all of it. Their robots.txt would include this:"
},
{
"code": null,
"e": 5003,
"s": 4978,
"text": "User-agent: *Disallow: /"
},
{
"code": null,
"e": 5243,
"s": 5003,
"text": "One way of doing this is by rotating through different proxies and user agents (headers) when making requests to the website. Also, it is important to be considerate in how often you make requests to the website to avoid being a ‘spammer’."
},
{
"code": null,
"e": 5342,
"s": 5243,
"text": "Note — This is only for learning purposes. We do not encourage you to breach terms of any website."
},
{
"code": null,
"e": 5412,
"s": 5342,
"text": "See below on how to implement this method in just a few simple steps."
},
{
"code": null,
"e": 5425,
"s": 5412,
"text": "Proxies pool"
},
{
"code": null,
"e": 5701,
"s": 5425,
"text": "Implementing a proxy server can be done easily in Python. A list of free proxies can be found here (Note that free proxies are usually less stable and slower than paid ones. If you don’t find the free ones good enough for your needs, you may consider getting a paid service)."
},
{
"code": null,
"e": 5866,
"s": 5701,
"text": "Looking at the free proxies list, one can use BeautifulSoup in order to get the IP addresses and ports. The structure of the above-mentioned website can seen below."
},
{
"code": null,
"e": 5958,
"s": 5866,
"text": "The following function retrieves all the proxies’ IPs and ports and returns a list of them:"
},
{
"code": null,
"e": 5971,
"s": 5958,
"text": "Headers pool"
},
{
"code": null,
"e": 6221,
"s": 5971,
"text": "There are many HTTP headers that can be passed as part of a request when using the requests package in Python. We passed two header elements (which were sufficient for us), namely the Accept header (user permissions) and user agent (Pseudo-Browser)."
},
{
"code": null,
"e": 6296,
"s": 6221,
"text": "The pool of pseudo random headers was created as follows (see code below):"
},
{
"code": null,
"e": 6543,
"s": 6296,
"text": "Create a dictionary object of “accepts” where each accept header is related to a specific browser (depending on the user agent). A list of accept headers can be found here. This list contains default values for each user-agent and can be changed."
},
{
"code": null,
"e": 6856,
"s": 6543,
"text": "Get a random user-agent using fake-useragent package in Python. This is super easy to use as seen in the code below. We suggest creating a list of user-agents beforehand just in case the fake-useragent is unavailable. An example of a user-agent:‘Mozilla/5.0 (Windows NT 6.2; rv:21.0) Gecko/20130326 Firefox/21.0’"
},
{
"code": null,
"e": 6947,
"s": 6856,
"text": "Create a dictionary object with accept and user-agent as keys and the corresponding values"
},
{
"code": null,
"e": 7003,
"s": 6947,
"text": "The partial code (full function in the appendix below):"
},
{
"code": null,
"e": 7039,
"s": 7003,
"text": "Using the headers and proxies pools"
},
{
"code": null,
"e": 7231,
"s": 7039,
"text": "The following code shows an example of how to use the function we wrote before. We did not include the OOP code for the sake of simplicity. See Appendix for the full function random_header()."
},
{
"code": null,
"e": 7375,
"s": 7231,
"text": "Up until here we gave a brief introduction of web scraping and spoke about more advanced techniques on how to avoid being blocked by a website."
},
{
"code": null,
"e": 7503,
"s": 7375,
"text": "In the following section we show 2 examples of how to use API calls for data enrichment: Genderize.io and Aylien Text Analysis."
},
{
"code": null,
"e": 7604,
"s": 7503,
"text": "Genderize uses the first name of an individual to predict their gender (limited to male and female)."
},
{
"code": null,
"e": 7679,
"s": 7604,
"text": "The output of this API is structured as JSON as seen in the example below:"
},
{
"code": null,
"e": 7745,
"s": 7679,
"text": "{“name”:”peter”,”gender”:”male”,”probability”:”0.99\",”count”:796}"
},
{
"code": null,
"e": 8118,
"s": 7745,
"text": "This makes it very convenient to enrich the author data with each one’s gender. Since the probability of the predicted gender is included, one can set a threshold to ensure better quality predictions (we set our threshold at 60% — see below for code snippets). The value this API brings is the ability to determine the gender distribution of authors for a specified topic."
},
{
"code": null,
"e": 8624,
"s": 8118,
"text": "We did not have to worry about the API limit (1000 calls/day) since we were only able to scrape around 120 articles/day which on average resulted in less than 500 authors per day. If one is able to exceed this daily limit, the API limit would have to be taken into account. One way of avoiding this daily limit would be to check if the first name being evaluated has already been enriched in our database. This would allow us to determine the gender based on the existing data without wasting an API call."
},
{
"code": null,
"e": 8664,
"s": 8624,
"text": "Some code snippets for the tech hungry:"
},
{
"code": null,
"e": 8686,
"s": 8664,
"text": "Connecting genderize:"
},
{
"code": null,
"e": 8712,
"s": 8686,
"text": "Author gender enrichment:"
},
{
"code": null,
"e": 9305,
"s": 8712,
"text": "We were interested in seeing the growth of keywords over time for a specified topic (think Google Trends) and therefore decided that we should enrich our data with more keywords. To do this, we used an API called Aylien Text Analysis, specifically the concept extraction API. This API allows one to input text which after processing outputs a list of keywords extracted from the text using NLP. Two of the various fields we scraped for each article were the Title and Abstract, these fields were concatenated and used as the input for the API. An example of the output JSON can be seen below:"
},
{
"code": null,
"e": 9727,
"s": 9305,
"text": "{ “text”:”Apple was founded by Steve Jobs, Steve Wozniak and Ronald Wayne.”, “language”:”en”, “concepts”:{ “http://dbpedia.org/resource/Apple_Inc.\":{ “surfaceForms”:[ { “string”:”Apple”, “score”:0.9994597361117074, “offset”:0 } ], “types”:[ “http://www.wikidata.org/entity/Q43229”, “http://schema.org/Organization\", “http://dbpedia.org/ontology/Organisation\", “http://dbpedia.org/ontology/Company\" ], “support”:10626 } }}"
},
{
"code": null,
"e": 10231,
"s": 9727,
"text": "In order to avoid duplicate keywords we checked that the keyword did not already exist in the keyword table of our database. In order to avoid adding too many keywords per article, two methods were instituted. The first was a simple keyword limit as seen in the code snippet below. The other made use of the score (probability of relevance) available in the output file for each keyword — This allows one to set a threshold (we used 80%) to ensure the most relevant keywords were added for each article."
},
{
"code": null,
"e": 10292,
"s": 10231,
"text": "An example of how the API works is seen in the figure below:"
},
{
"code": null,
"e": 10374,
"s": 10292,
"text": "Below is a snippet of the code we used to connect to the Aylien Text API service:"
},
{
"code": null,
"e": 10393,
"s": 10374,
"text": "Connect to aylien:"
},
{
"code": null,
"e": 10427,
"s": 10393,
"text": "Enrich keywords using Aylien API:"
},
{
"code": null,
"e": 10825,
"s": 10427,
"text": "Let’s move to the final part. So far we gave an introduction to web scraping and how to avoid being blocked, as well as using API calls in order to enrich one’s data. In the final part of this post we will go through how to set up a database in order to store the data and how to access this data for visualization. Visualizations are a powerful tool one can use to extract insights from the data."
},
{
"code": null,
"e": 10948,
"s": 10825,
"text": "When setting up the database for a web scraping project (or others in general) the following should be taken into account:"
},
{
"code": null,
"e": 10964,
"s": 10948,
"text": "Tables creation"
},
{
"code": null,
"e": 10983,
"s": 10964,
"text": "New data insertion"
},
{
"code": null,
"e": 11015,
"s": 10983,
"text": "Data update (every hour/day...)"
},
{
"code": null,
"e": 11519,
"s": 11015,
"text": "This stage of the pipeline should be done with caution and one should validate that the chosen structure (in terms of columns types, lengths, keys etc.) is suitable for the data and can handle extreme cases (missing data, non-English characters etc.). Avoid relying on an ID that is used by the website as the primary/unique key unless you have a really good reason (in our case doi_link of an article is a unique string that is acceptable everywhere, so we use it as a unique identifier of an article)."
},
{
"code": null,
"e": 11580,
"s": 11519,
"text": "An example of tables creation using mysql.connector package:"
},
{
"code": null,
"e": 11597,
"s": 11580,
"text": "The SQL command:"
},
{
"code": null,
"e": 11637,
"s": 11597,
"text": "The function for building the database:"
},
{
"code": null,
"e": 11860,
"s": 11637,
"text": "Note — in lines 12, 17, 23 and 25 we use the logger object. This is for logging to an external logs file and it’s super important. Creating a Logger class is recommended, you can see more below in this post, or click here."
},
{
"code": null,
"e": 12135,
"s": 11860,
"text": "Insertion of new data differs a bit from updating existing data. When new data is inserted to DB, one should make sure there are not duplicates. Also, in case of an error, one should catch it, log it and save the portion of data that caused that error for future inspection."
},
{
"code": null,
"e": 12238,
"s": 12135,
"text": "As seen below, we used again the cursor of mysql.connector in order to execute the SQL insert command."
},
{
"code": null,
"e": 12578,
"s": 12238,
"text": "Dynamic data requires frequent updates. One should define the time deltas (differences) between two updates which depends on the data type and source. In our project, we had to take into account that the number of citations for all articles would have to be updated periodically. The following piece of code illustrates the update process:"
},
{
"code": null,
"e": 12712,
"s": 12578,
"text": "In order to help make sense of the collected data , one can use visualizations to provide an easy-to-understand overview of the data."
},
{
"code": null,
"e": 12800,
"s": 12712,
"text": "The visualizations we created enabled us to gain insights into the following use cases:"
},
{
"code": null,
"e": 12818,
"s": 12800,
"text": "High-level trends"
},
{
"code": null,
"e": 12881,
"s": 12818,
"text": "Identify leading Institutions/countries in the specified topic"
},
{
"code": null,
"e": 12929,
"s": 12881,
"text": "Identify top researchers in the specified topic"
},
{
"code": null,
"e": 13038,
"s": 12929,
"text": "The above use cases allow for a data-driven approach for: R&D Investment, consultation, general partnerships"
},
{
"code": null,
"e": 13275,
"s": 13038,
"text": "In order to explore the above use cases we created visualizations of our data. We did this by using a simple but powerful open-source tool called Redash that was connected to our AWS machine(other kinds of instances are also available)."
},
{
"code": null,
"e": 13320,
"s": 13275,
"text": "In order to set up Redash, do the following:"
},
{
"code": null,
"e": 13394,
"s": 13320,
"text": "Click on the following link: https://redash.io/help/open-source/setup#aws"
},
{
"code": null,
"e": 13480,
"s": 13394,
"text": "Choose the relevant AWS instance in order to create the Redash image on your machine."
},
{
"code": null,
"e": 13576,
"s": 13480,
"text": "Before moving on, here is an overview of the data we collected for the topic “Neural Networks”."
},
{
"code": null,
"e": 13901,
"s": 13576,
"text": "As you can see, not a lot of data was retrieved — this was because of the limited time we had available on the AWS (Amazon Web Services) machines. Due to the lack of sufficient data, the reader should evaluate the results with a pinch of salt — this is at this stage a proof of concept and is by no means a finished product."
},
{
"code": null,
"e": 14017,
"s": 13901,
"text": "For the high level trends we simply plotted the number of research papers published per month for the past 5 years."
},
{
"code": null,
"e": 14126,
"s": 14017,
"text": "SELECT publication_date, count(id) AS num FROM articles GROUP BY publication_date ORDER BY publication_date;"
},
{
"code": null,
"e": 14146,
"s": 14126,
"text": "Gender Distribution"
},
{
"code": null,
"e": 14419,
"s": 14146,
"text": "This visualization makes use of enriched author data from genderize to view the gender distribution of authors within the specified topic. As seen in the figure below there are a large proportion of authors whose gender are unknown due to limitations of the genderize API."
},
{
"code": null,
"e": 14474,
"s": 14419,
"text": "SELECT gender, count(ID) FROM authors GROUP BY gender;"
},
{
"code": null,
"e": 14517,
"s": 14474,
"text": "Identifying leading countries in the field"
},
{
"code": null,
"e": 15175,
"s": 14517,
"text": "When scraping affiliations for each author we were able to extract the country of each one, allowing us to create the visualization below. China publishes the majority of research papers for the topic “Neural Networks” as is expected due to their keen interest in AI. This information could be interesting for policy makers since one can track the advancements in AI in leading countries. Firstly, it can be helpful to monitor these leading countries to find opportunities for partnership in order to advance AI in both countries. Secondly, policy makers can use these insights in order to emulate leading countries in advancing AI within their own country."
},
{
"code": null,
"e": 15281,
"s": 15175,
"text": "SELECT country, count(affiliation_id) AS counterFROM affiliations GROUP BY country ORDER BY counter DESC;"
},
{
"code": null,
"e": 15323,
"s": 15281,
"text": "Identifying top lead authors in the field"
},
{
"code": null,
"e": 15470,
"s": 15323,
"text": "As a first approach to identifying the top researchers we decided to to compare the lead authors with the most citations associated to their name."
},
{
"code": null,
"e": 15844,
"s": 15470,
"text": "SELECT CONCAT(authors.first_name,” “, authors.last_name) AS name, SUM(articles.citations) AS num_citations FROM authors JOIN authors_article_junction JOIN articlesWHERE authors_article_junction.author_ID = authors.ID AND articles.ID = authors_article_junction.article_ID AND authors_article_junction.importance = 1 GROUP BY authors.ID ORDER BY num_citations DESC LIMIT 10;"
},
{
"code": null,
"e": 15857,
"s": 15844,
"text": "Keywords map"
},
{
"code": null,
"e": 15918,
"s": 15857,
"text": "The larger the word, the more frequent it is in the database"
},
{
"code": null,
"e": 16134,
"s": 15918,
"text": "SELECT keywords.keyword_name, COUNT(keywords_ID) AS num FROM keyword_article_junction JOIN keywords WHERE keyword_article_junction.keywords_ID = keywords.ID GROUP BY keywords.keyword_name ORDER BY num DESC LIMIT 20;"
},
{
"code": null,
"e": 16170,
"s": 16134,
"text": "Snapshot of our dashboard in Redash"
},
{
"code": null,
"e": 16649,
"s": 16170,
"text": "We have reached the end of our Web Scraping with Python A — Z series. In the first part we gave a brief introduction of web scraping and spoke about more advanced techniques on how to avoid being blocked by a website. Also, we showed how one can use API calls in order to enrich the data to extract further insights. And lastly, we showed how to create a database for storing the data obtained from web scraping and how to visualize this data using an open source tool — Redash."
},
{
"code": null,
"e": 16751,
"s": 16649,
"text": "Consider using grequests for parallelizing the get requests. This can be done by doing the following:"
},
{
"code": null,
"e": 16871,
"s": 16751,
"text": "This may not be as effective as it should be due to the limited speed of the free proxies but it is still worth trying."
},
{
"code": null,
"e": 16920,
"s": 16871,
"text": "Using Selenium for handling Javascript elements."
},
{
"code": null,
"e": 16978,
"s": 16920,
"text": "The full function to create random headers is as follows:"
},
{
"code": null,
"e": 17145,
"s": 16978,
"text": "Note — In line 22 we saved a message into a logs file. It’s super important to have logs in your code! We suggest using logging package which is pretty simple to use."
}
] |
DB2 Quick Guide | This chapter describes history of DB2, its versions, editions and their respective features.
DB2 is a database product from IBM. It is a Relational Database Management System (RDBMS). DB2 is designed to store, analyze and retrieve the data efficiently. DB2 product is extended with the support of Object-Oriented features and non-relational structures with XML.
Initially, IBM had developed DB2 product for their specific platform. Since year 1990, it decided to develop a Universal Database (UDB) DB2 Server, which can run on any authoritative operating systems such as Linux, UNIX, and Windows.
For IBM DB2, the UDB current version is 10.5 with the features of BLU Acceleration and its code name as 'Kepler'. All the versions of DB2 till today are listed below:
Depending upon the requirement of needful features of DB2, the organizations select appropriate DB2 version. The following table shows DB2 server editions and their features:
This chapter describes installation steps of DB2 server.
You can download the DB2 Server trial version or purchase the product license from www.ibm.com. There are two separate DB2 servers available for downloading, depending upon the size of operating system, on which it is intended to execute. For example, if you want to download a DB2 server for 32bit Linux or UNIX operating system, then you need to download a 32 bit DB2 server. The same applies for 64bit DB2 server.
Processor : Minimum Core 2Duo
Ram : 1GB minimum
Hard disk : 30GB minimum
Before installing the DB2 server, your system needs to get ready with the required software on it. For Linux, you need to install “libstdc++6.0”.
Before installing DB2 Server, you need to verify if your system is compatible with the DB2 server. For confirming the compatibility, you need to call 'db2prereqcheck' command on command console.
Open the Terminal and set the db2 installation image folder path on console using “CD <DB2 installation folder>” command. Then type “./db2prereqcheck” command, which confirms the compatibility of your system with DB2 server.
./db2prereqcheck
Figure-1 shows the compatibility requirements of Linux operating system and hardware system.
Follow the given steps for installing DB2 on your Linux system:
Open the terminal.
Login as root user.
Open DB2 Installation folder.
Type “./db2setup” and press Enter.
This process will start execution of DB2 server setup.
Type “./db2setup” and press Enter on root terminal to start setup process of DB2 Server.
On doing so, the “Set up Launch Pad” screen appears. [Figure-2]
On Setup Launch pad page, select “Install a Product” option from left side menu. Select option “DB2 Advanced Enterprise Server Edition”. Select “Install New” Button.
A new frame appears with name “DB2 setup wizard”. Click “Next”. [Figure-3]
The next screen appears with DB2 license agreement. Select “I accept the terms...” Click “Next”. [Figure-4]
Next screen comes up with offer of Installation type, which is set to “Typical” by default.
Keep the same selection. Click “Next”. [Figure-5]
The next screen appears with installation action.
Select “Install DB2 Advanced Enterprise Server Edition...”
Click “Next”. [Figure-6]
On the next screen, the setup program asks for selection of installation directory.
Keep the default and click “Next”.
The next screen comes up with the user authentication. Enter your password for “dasusr1” user.
(Your password can be identical to username so that it is convenient to remember.)
On the following screen, the setup asks you for creation of DB2 Server Instance.
Here, it is creating a DB2 instance with name “db2inst1”.
The next screen asks you the number of partitions you require for your default instance.
You have a choice of “single or Multiple” partitions.
Select “single partition instance”. Click “next”.
On the next screen, the setup asks you for authentication for DB2 instance being created.
Here, by default username is created as “db2inst1”. You can enter password same as username.
Click “Next”.
On the next screen, the setup asks to enter authentication information for “db2fenc” user.
Here, you can enter password same as username.
Click “Next”.
On the next screen, you can select “Do not setup your db2 server to send notifications at this time” option.
Click ”Next”.
The next screen shows you the information about db2 setup.
Click “Finish”.
The DB2 Installation procedure is complete at this stage.
You need to verify the installation of DB2 server for its usefulness. On completing the DB2 Server installation, logout from current user mode and login to “db2inst1” user. In “db2inst1” user environment, you can open terminal and execute the following commands to verify if your db2 product is installed properly or not.
This command shows the current version and service level of the installed DB2 product for current instance.
Syntax:
db2level
Example:
db2level
Output:
DB21085I Instance "db2inst2" uses "64" bits
And DB2 code release "SQL10010" with level
identifier "0201010E". Informational tokens
are "DB2 v10.1.0.0", "s120403",
"LINUXAMD64101", and Fix Pack "0".
Product is installed at "/home/db2inst2/sqllib".
This command shows all the license related information of our DB2 Product.
Syntax:
db2licm <parameter>
Example:
db2licm -l
Output:
Product name: "DB2 Advanced Enterprise Server Edition"
License type: "Trial"
Expiry date: "10/02/2014"
Product identifier: "db2aese"
Version information: "10.1"
Product name: "DB2 Connect Server"
License type: "Trial"
Expiry date: "10/02/2014"
Product identifier: "db2consv"
Version information: "10.1"
The CLP can be started in one of the three modes:
Command mode: In this mode, each command and SQL statement must be prefixed by “db2”. For example, query “db2 activate database sample”.
Command mode: In this mode, each command and SQL statement must be prefixed by “db2”. For example, query “db2 activate database sample”.
Interactive input mode: you can launch this mode by using the “db2” command. Here, you can pass SQL statements without prefix. For example, “activate database sample”.
Interactive input mode: you can launch this mode by using the “db2” command. Here, you can pass SQL statements without prefix. For example, “activate database sample”.
Batch mode: Here, you need to create a script file, which contains all SQL queries of requirements and save the file with “.db2” extension. You can call this in command line using syntax “db2 –tf <filename.db2>”.
Batch mode: Here, you need to create a script file, which contains all SQL queries of requirements and save the file with “.db2” extension. You can call this in command line using syntax “db2 –tf <filename.db2>”.
An Instance is a logical environment for DB2 Database Manager. Using instance, you can manage databases. Depending on our requirements, you can create multiple instances on one physical machine. The contents of Instance directory are:
Database Manager Configuration file
System Database Directory
Node Directory
Node Configuration File [db2nodes.cfg]
Debugging files, dump files
For DB2 Database Server, the default instance is “DB2”. It is not possible to change the location of Instance directory after its creation. An instance can manage multiple databases. In an instance, each database has a unique name, its own set of catalog tables, configurations files, authorities and privileges.
You can create multiple instances in one DB2Server on Linux, UNIX and Windows. It is possible to install multiple DB2Servers on a physical machine.
You can create multiple instances on Linux and UNIX if DB2 Server is installed as root user. An instance can run simultaneously on Linux and UNIX independently. You can work within a single instance of the database manager at a time.
An Instance folder contains database configuration files and folders. The Instance directory is stored at different locations on Windows depending on the operating system versions.
The following command is used to list instances:
This command lists all the instances that are available on a system.
Syntax:
db2ilist
Example:[To see how many instances are created in DB2 copy]
db2ilist
Output:
db2inst1
db2inst2
db2inst3
These commands are useful to work with arrangement of instance in the DB2 CLI.
This command shows details of the currently running instance.
Syntax:
db2 get instance
Example:[To see the current instance which activated the current user]
db2 get instance
Output:
The current database manager instance is : db2inst1
To start or stop the database manager of an instance on DB2 UDB, the following command is executed for the current instance.
Syntax:
set db2instance=<instance_name>
Example:[ To arrange the “db2inst1” environment to current user]
set db2instance=db2inst1
Using this command, you can start an instance. Before this, you need to run “set instance”.
Syntax:
db2start
Example:[To start an instance]
db2start
Output:
SQL1063N DB2START processing was successful
Using this command you can stop a running instance.
Syntax:
db2stop
Output:
SQL1064N DB2STOP processing was successful.
Let us see how to create a new instance.
If you want to create a new instance, you need to log in with root. Instance id is not a root id or a root name.
Here are the steps to create a new instance:
Step1: Create an operating system user for instance.
Syntax:
useradd -u <ID> -g <group name> -m -d <user location> <user name>
-p <password>
Example: [To create a user for instance with name ‘db2inst2’ in group ‘db2iadm1’ and password ‘db2inst2’]
useradd -u 1000 -g db2iadm1 -m -d /home/db2inst2 db2inst2 -p db2inst2
Step2: Go to the DB2 instance directory in root user for create new instance.
Location:
cd /opt/ibm/db2/v10.1/instance
Step3: Create instance using the syntax below:
Syntax:
./db2icrt -s ese -u <inst id> <instance name>
Example: [To create a new instance ‘db2inst2’ in user ‘db2inst2’ with the features of ‘ESE’ (Enterprise Server Edition)]
./db2icrt -s ese -u db2inst2 db2inst2
Output:
DBI1446I The db2icrt command is running, please wait.
....
.....
DBI1070I Program db2icrt completed successfully.
Edit the /etc/services file and add the port number. In the syntax given below, ‘inst_name’ indicates the Instance name and ‘inst_port’ indicates port number of instance.
Syntax:
db2c_<inst name> <inst_port>/tcp
Example: [Adding ‘50001/tcp’ port number for instance ‘db2inst2’ with variable ‘db2c_db2inst2’ in ‘services’ file]
db2c_db2inst2 50001/tcp
Syntax 1: [Update Database Manager Configuration with service name. The following syntax ‘svcename’ indicates the instance service name and ‘inst_name’ indicates the instance name]
db2 update database manager configuration using svcename db2c_&<inst_name>
Example 1: [Updating DBM Configuration with variable svcename with value ‘db2c_db2inst2’ for instance ‘db2inst2’
db2 update database manager configuration using svcename db2c_db2inst2
Output
DB20000I The UPDATE DATABASE MANAGER CONFIGURATION command completed successfully.
Syntax 2: set the “tcpip” communication protocol for the current instance
db2set DB2COMM=tcpip
Syntax 3: [Stopping and starting current instance to get updated values from database manager configuration]
db2stop
db2start
You can update an instance using following command:
This command is used to update the instance within the same version release. Before executing this command, you need to stop the instance database manager using “db2stop” command. The syntax below “inst_name” indicates the previous released or installed db2 server instance name, which you want to update to newer release or installed db2 server version.
Syntax 1: To update an instance in normal mode
db2iupdt <inst_name>
Example1:
./db2iupdt db2inst2
Syntax 2: To update an instance in debugging mode
db2iupdt -D <inst_name>
Example
db2iupdt -D db2inst2
You can upgrade an instance from previous version of DB2 copy to current newly installed version of DB2 copy.
On Linux or UNIX system, this command is located in DB2DIR/instance directory. In the following syntaxes, “inst_name” indicates the previous version DB2 instance and “inst_username” indicates the current installed version DB2 copy instance user.
Syntax 2:
db2iupgrade -d -k -u <inst_username> <inst_name>
Example:
db2iupgrade -d -k -u db2inst2 db2inst2
Command Parameters:
-d : Turns debugging mode on.
-k : Keeps the pre-upgrade instance type if it is supported in the DB2 copy, from where you are running this command.
If you are using the Super User (su) on Linux for db2iupgrade command, you must issue the “su” command with the “-” option.
You can drop or delete the instance, which was created by “db2icrt” command.
On Linux and UNIX operating system, this command is located in the DB2_installation_folder/instance directory.
Syntax: [in the following syntax, ‘inst_username’ indicates username of instance and ‘inst_name’ indicates instance name]
db2idrop -u <inst_username> <inst_name>
Example: [To drop db2inst2]
./db2idrop -u db2inst2 db2inst2
Command to find out which DB2 instance we are working on now.
Syntax 1: [to check the current instance activated by database manager]
db2 get instance
Output:
The current database manager instance is: db2inst1
Syntax 2: [To see the current instance with operating bits and release version]
db2pd -inst | head -2
Example:
db2pd -inst | head -2
Output:
Instance db2inst1 uses 64 bits and DB2 code release SQL10010
Syntax 3: [To check the name of currently working instance]
db2 select inst_name from sysibmadm.env_inst_info
Example:
db2 select inst_name from sysibmadm.env_inst_info
Output:
INST_NAME --------------------------------------
db2inst1
1 record(s) selected.
Syntax: [To set a new instance as default]
db2set db2instdef=<inst_name> -g
Example: [To array newly created instance as a default instance]
db2set db2instdef=db2inst2 -g
This chapter describes creating, activating and deactivating the databases with the associated syntax.
A database is a collection of Tables, Schemas, Bufferpools, Logs, Storage groups and Tablespaces working together to handle database operations efficiently.
Database directory is an organized repository of databases. When you create a database, all the details about database are stored in a database directory, such as details of default storage devices, configuration files, and temporary tables list etc.
Partition global directory is created in the instance folder. This directory contains all global information related to the database. This partition global directory is named as NODExxxx/SQLyyy, where xxxx is the data partition number and yyy is the database token.
In the partition-global directory, a member-specific directory is created. This directory contains local database information. The member-specific directory is named as MEMBERxxxx where xxxx is a member number. DB2 Enterprise Server Edition environment runs on a single member and has only one member specific directory. This member specific directory is uniquely named as MEMBER0000.
Directory Location : <instance>/NODExxx/SQLxxx
The partition-global directory contains database related files as listed below.
Global deadlock write-to-file event monitoring files
Table space information files [SQLSPCS.1, SQLSPCS.2]
Storage group control files [SQLSGF.1, SQLSGF.2]
Temporary table space container files. [/storage path//T0000011/C000000.TMP/SQL00002.MEMBER0001.TDA]
Global Configuration file [SQLDBCONF]
History files [DB2RHIST.ASC, DB2RHIST.BAK, DB2TSCHG.HIS, DB2TSCHG.HIS]
Logging-related files [SQLOGCTL.GLFH.1, SQLOGCTL.GLFH.2]
Locking files [SQLINSLK, SQLTMPLK]
Automatic Storage containers
Directory location : /NODExxxx/SQLxxxx/MEMBER0000
This directory contains:
Objects associated with databases
Buffer pool information files [SQLBP.1, SQLBP.2]
Local event monitoring files
Logging-related files [SQLOGCTL.LFH.1, SQLOGCTL.LFH.2, SQLOGMIR.LFH].
Local configuration files
Deadlocks event monitor file. The detailed deadlock events monitor files are stored in the database directory of the catalog node in case of ESE and partitioned database environment.
You can create a database in instance using the “CREATE DATABASE” command. All databases are created with the default storage group “IBMSTOGROUP”, which is created at the time of creating an instance. In DB2, all the database tables are stored in “tablespace”, which use their respective storage groups.
The privileges for database are automatically set as PUBLIC [CREATETAB, BINDADD, CONNECT, IMPLICIT_SCHEMA, and SELECT], however, if the RESTRICTIVE option is present, the privileges are not granted as PUBLIC.
This command is used to create a non-restrictive database.
Syntax: [To create a new Database. ‘database_name’ indicates a new database name, which you want to create.]
db2 create database <database name>
Example: [To create a new non-restrictive database with name ‘one’]
db2 create database one
Output:
DB20000I The CREATE DATABASE command completed successfully.
Restrictive database is created on invoking this command.
Syntax: [In the syntax below, “db_name” indicates the database name.]
db2 create database <db_name> restrictive
Example: [To create a new restrictive database with the name ‘two’]
db2 create database two restrictive
Create a database with default storage group “IBMSTOGROUP” on different path. Earlier, you invoked the command “create database” without any user-defined location to store or create database at a particular location. To create the database using user- defined database location, the following procedure is followed:
Syntax: [In the syntax below, ‘db_name’ indicates the ‘database name’ and ‘data_location’ indicates where have to store data in folders and ‘db_path_location’ indicates driver location of ‘data_location’.]
db2 create database '<db_name>' on '<data location>' dbpath on '<db_path_location>'
Example: [To create database named ‘four’, where data is stored in ‘data1’ and this folder is stored in ‘dbpath1’]
db2 create database four on '/data1' dbpath on '/dbpath1'
You execute this command to see the list of directories available in the current instance.
Syntax:
db2 list database directory
Example:
db2 list database directory
Output:
System Database Directory
Number of entries in the directory = 6
Database 1 entry:
Database alias = FOUR
Database name = FOUR
Local database directory =
/home/db2inst4/Desktop/dbpath
Database release level = f.00
Comment =
Directory entry type = Indirect
Catalog database partition number = 0
Alternate server hostname =
Alternate server port number =
Database 2 entry:
Database alias = SIX
Database name = SIX
Local database directory = /home/db2inst4
Database release level = f.00
Comment =
Directory entry type = Indirect
Catalog database partition number = 0
Alternate server hostname =
Alternate server port number =
This command starts up all necessary services for a particular database so that the database is available for application.
Syntax:[‘db_name’ indicates database name]
db2 activate db <db_name>
Example: [Activating the database ‘one’]
db2 activate db one
Using this command, you can stop the database services.
Syntax:
db2 deactivate db <db_name>
Example: [To Deactivate database ‘one’]
db2 deactivate db one
After creating a database, to put it into use, you need to connect or start database.
Syntax:
db2 connect to <database name>
Example: [To Connect Database one to current CLI]
db2 connect to one
Output:
Database Connection Information
Database server = DB2/LINUXX8664 10.1.0
SQL authorization ID = DB2INST4
Local database alias = ONE
To check if this database is restrictive or not, here is the syntax:
Syntax: [In the following syntax, ‘db’ indicates Database, ‘cfg’ indicates configuration, ‘db_name’ indicates database name]
db2 get db cfg for <db_name> | grep -i restrict
Example: [To check if ‘one’ database is restricted or not]
db2 get db cfg for one | grep -i restrict
Output:
Restrict access = NO
Instance configuration (Database manager configuration) is stored in a file named 'db2system' and the database related configuration is stored in a file named 'SQLDBCON'. These files cannot be edited directly. You can edit these files using tools which call API. Using the command line processor, you can use these commands.
Syntax: [To get the information of Instance Database manager]
db2 get database manager configuration
db2 get dbm cfg
Syntax: [To update instance database manager]
db2 update database manager configuration
db2 update dbm cfg
Syntax: [To reset previous configurations]
db2 reset database manager configuration
db2 reset dbm cfg
Syntax: [To get the information of Database]
db2 get database configuration
db2 get db cfg
Syntax: [To update the database configuration]
db2 update database configuration
db2 update db cfg
Syntax: [To reset the previously configured values in database configuration
db2 reset database configuration
db2 reset db cfg
Syntax: [To check the size of Current Active Database]
db2 "call get_dbsize_info(?,?,?,-1)"
Example: [To verify the size of Currently Activate Database]
db2 "call get_dbsize_info(?,?,?,-1)"
Output:
Value of output parameters
--------------------------
Parameter Name : SNAPSHOTTIMESTAMP
Parameter Value : 2014-07-02-10.27.15.556775
Parameter Name : DATABASESIZE
Parameter Value : 105795584
Parameter Name : DATABASECAPACITY
Parameter Value : 396784705536
Return Status = 0
To estimate the size of a database, the contribution of the following factors must be considered:
System Catalog Tables
User Table Data
Long Field Data
Large Object (LOB) Data
Index Space
Temporary Work Space
XML data
Log file space
Local database directory
System files
You can use the following syntax to check which database authorities are granted to PUBLIC on the non-restrictive database.
Step 1: connect to database with authentication user-id and password of instance.
Syntax: [To connect to database with username and password]
db2 connect to <db_name> user <userid> using <password>
Example: [To Connect “one” Database with the user id ‘db2inst4’ and password ‘db2inst4’]
db2 connect to one user db2inst4 using db2inst4
Output:
Database Connection Information
Database server = DB2/LINUXX8664 10.1.0
SQL authorization ID = DB2INST4
Local database alias = ONE
Step2: To verify the authorities of database.
Syntax: [The syntax below shows the result of authority services for current database]
db2 "select substr(authority,1,25) as authority, d_user, d_group,
d_public, role_user, role_group, role_public,d_role from table(
sysproc.auth_list_authorities_for_authid ('public','g'))as t
order by authority"
Example:
db2 "select substr(authority,1,25) as authority, d_user, d_group,
d_public, role_user, role_group, role_public,d_role from table(
sysproc.auth_list_authorities_for_authid ('PUBLIC','G'))as t
order by authority"
Output:
AUTHORITY D_USER D_GROUP D_PUBLIC ROLE_USER ROLE_GROUP ROLE_PUBLIC D_ROLE
------------------------- ------ ------- -------- --------- ---------- ----------- ------
ACCESSCTRL * * N * * N *
BINDADD * * Y * * N *
CONNECT * * Y * * N *
CREATETAB * * Y * * N *
CREATE_EXTERNAL_ROUTINE * * N * * N *
CREATE_NOT_FENCED_ROUTINE * * N * * N *
CREATE_SECURE_OBJECT * * N * * N *
DATAACCESS * * N * * N *
DBADM * * N * * N *
EXPLAIN * * N * * N *
IMPLICIT_SCHEMA * * Y * * N *
LOAD * * N * * N *
QUIESCE_CONNECT * * N * * N *
SECADM * * N * * N *
SQLADM * * N * * N *
SYSADM * * * * * * *
SYSCTRL * * * * * * *
SYSMAINT * * * * * * *
SYSMON * * * * * * *
WLMADM * * N * * N *
20 record(s) selected.
Using the Drop command, you can remove our database from instance database directory. This command can delete all its objects, table, spaces, containers and associated files.
Syntax: [To drop any database from an instance]
db2 drop database <db_name>
Example: [To drop ‘six’ database from instance]
db2 drop database six
Output:
DB20000I The DROP DATABASE command completed successfully
This chapter introduces you to Bufferpools in the database.
The bufferpool is portion of a main memory space which is allocated by the database manager. The purpose of bufferpools is to cache table and index data from disk. All databases have their own bufferpools. A default bufferpool is created at the time of creation of new database. It called as “IBMDEFAULTBP”. Depending on the user requirements, it is possible to create a number of bufferpools. In the bufferpool, the database manager places the table row data as a page. This page stays in the bufferpool until the database is shutdown or until the space is written with new data. The pages in the bufferpool, which are updated with data but are not written onto the disk, are called “Dirty” pages. After the updated data pages in the bufferpool are written on the disk, the bufferpool is ready to take another data.
Each table space is associated with a specific buffer pool in a database. One tablespace is associated with one bufferpool. The size of bufferpool and tablespace must be same. Multiple bufferpools allow you to configure the memory used by the database to increase its overall performance.
The size of the bufferpool page is set when you use the “CREATE DATABASE” command. If you do not specify the page size, it will take default page size, which is 4KB. Once the bufferpool is created, it is not possible to modify the page size later
Syntax: [The syntax below shows all available bufferpools in database]
db2 select * from syscat.bufferpools
Example: [To see available bufferpools in current database]
db2 select * from syscat.bufferpools
Output:
BPNAME BUFFERPOOLID DBPGNAME NPAGES PAGESIZE ESTORE
NUMBLOCKPAGES BLOCKSIZE NGNAME
------------------------------------------------------------
IBMDEFAULTBP
1 -
-2 4096 N 0 0 -
1 record(s) selected.
To create a new bufferpool for database server, you need two parameters namely, “bufferpool name” and “size of page”. The following query is executed to create a new bufferpool.
Syntax: [In the syntax below,‘bp_name’ indicates bufferpool name and ‘size’ indicates size for page you need to declare for bufferpools (4K,8K,16K,32K)]
db2 create bufferpool <bp_name> pagesize <size>
Example: [To create a new bufferpool with name “bpnew” and size “8192”(8Kb).]
db2 create bufferpool bpnew pagesize 8192
Output
DB20000I The SQL command completed successfully.
Before dropping the bufferpool, it is required to check if any tablespace is assigned to it.
Syntax: [To drop the bufferpool]
drop bufferpool <bp_name>
Example: [To drop ‘bpnew’ named bufferpool]
db2 drop bufferpool bpnew
Output
DB20000I The SQL command completed successfully.
This chapter describes the tablespaces in detail
A table space is a storage structure, it contains tables, indexes, large objects, and long data. It can be used to organize data in a database into logical storage group which is related with where data stored on a system. This tablespaces are stored in database partition groups
The table spaces are beneficial in database in various ways given as follows:
Recoverability: Tablespaces make backup and restore operations more convenient. Using a single command, you can make backup or restore all the database objects in tablespaces.
Automatic storage Management: Database manager creates and extends containers depending on the needs.
Memory utilization: A single bufferpool can manage multiple tablespaces. You can assign temporary tablespaces to their own bufferpool to increase the performance of activities such as sorts or joins.
Tablespaces contains one or more containers. A container can be a directory name, a device name, or a filename. In a database, a single tablespace can have several containers on the same physical storage device. If the tablespace is created with automatic storage tablespace option, the creation and management of containers is handled automatically by the database manager. If it is not created with automatic storage tablespace option, you need to define and manage the containers yourself.
When you create a new database, the database manager creates some default tablespaces for database. These tablespace is used as a storage for user and temporary data. Each database must contain at least three tablespaces as given here:
Catalog tablespace
User tablespace
Temporary tablespace
Catalog tablespace
User tablespace
Temporary tablespace
Catalog tablespace: It contains system catalog tables for the database. It is named as SYSCATSPACE and it cannot be dropped.
User tablespace: This tablespace contains user-defined tables. In a database, we have one default user tablespace, named as USERSPACE1. If you do not specify user-defined tablespace for a table at the time you create it, then the database manager chooses default user tablespace for you.
Temporary tablespace: A temporary tablespace contains temporary table data. This tablespace contains system temporary tablespaces or user temporary tablespace.
System temporary tablespace holds temporary data required by the database manager while performing operation such as sorts or joins. A database must have at least one system temporary tablespace and it is named as TEMPSPACE1. It is created at the time of creating the database. User temporary tablespace holds temporary data from tables. It is created with DECLARE GLOBAL TEMPORARY TABLE or CREATE GLOBAL TEMPORARY TABLE statement. This temporary tablespace is not created by default at the time of database creation.
Tablespaces and storage management:
Tablespaces can be setup in different ways, depending on how you want to use them. You can setup the operating system to manage tablespace allocation, you can let the database manager allocate space or you can choose automatic allocation of tablespace for your data.
The following three types of managed spaces are available:
System Managed Space (SMS): The operating system’s file system manager allocates and manages the space where the table is stored. Storage space is allocated on demand. This model consists of files representing database objects. This tablespace type has been deprecated in Version 10.1 for user-defined tablespaces, and it is not deprecated for catalog and temporary tablespaces.
Database Managed Space (DMS): The Database Server controls the storage space. Storage space is pre- allocated on the file system based on container definition that you specify when you create the DMS table space. It is deprecated from version 10.1 fix pack 1 for user-defined tablespaces, but it is not deprecated for system tablespace and temporary tablespace.
Automatic Storage Tablespace: Database server can be managed automatically. Database server creates and extends containers depend on data on database. With automatic storage management, it is not required to provide container definitions. The database server looks after creating and extending containers to make use of the storage allocated to the database. If you add storage space to a storage group, new containers are automatically created when the existing container reach their maximum capacity. If you want to use the newly-added storage immediately, you can rebalance the tablespace.
Page, table and tablespace size:
Temporary DMS and automatic storage tablespaces, the page size you choose for your database determines the maximum limit for the tablespace size. For table SMS and temporary automatic storage tablespaces, the page size constrains the size of table itself. The page sizes can be 4kb, 8kb, 16kb or 32kb.
This chapter describes the Database Storagegroups.
A set of Storage paths to store database table or objects, is a storage group. You can assign the tablespaces to the storage group. When you create a database, all the tablespaces take default storagegorup. The default storage group for a database is ‘IBMSTOGROUP’. When you create a new database, the default storage group is active, if you pass the “AUTOMATIC STOGROUP NO” parameter at the end of “CREATE DATABASE” command. The database does not have any default storage groups.
You can list all the storagegroups in the database.
Syntax: [To see the list of available storagegroups in current database]
db2 select * from syscat.stogroups
Example: [To see the list of available storagegorups in current database]
db2 select * from syscat.stogroups
Here is a syntax to create a storagegroup in the database:
Syntax: [To create a new stogroup. The ‘stogropu_name’ indicates name of new storage group and ‘path’ indicates the location where data (tables) are stored]
db2 create stogroup on ‘path’
Example: [To create a new stogroup ‘stg1’ on the path ‘data1’ folder]
db2 create stogroup stg1 on ‘/data1’
Output:
DB20000I The SQL command completed succesfully
Here is how you can create a tablespace with storegroup:
Syntax: [To create a new tablespace using existed storage group]
db2 create tablespace <tablespace_name> using stogroup <stogroup_name>
Example: [To create a new tablespace named ‘ts1’ using existed storage group ‘stg1’]
db2 create tablespace ts1 using stogroup stg1
Output:
DB20000I The SQL command completed succesfully
You can alter the location of a storegroup by using following syntax:
Syntax: [To shift a storage group from old location to new location]
db2 alter stogroup add ‘location’, ‘location’
Example: [To modify location path from old location to new location for storage group named ‘sg1’]
db2 alter stogroup sg1 add ‘/path/data3’, ‘/path/data4’
Before dropping folder path of storagegroup, you can add new location for the storagegroup by using alter command.
Syntax: [To drop old path from storage group location]
db2 alter stogroup drop ‘/path’
Example: [To drop storage group location from ‘stg1’]
db2 alter stogroup stg1 drop ‘/path/data1’
Rebalancing the tablespace is required when we create a new folder for storagegroup or tablespaces while the transactions are conducted on the database and the tablespace becomes full. Rebalancing updates database configuration files with new storagegroup.
Syntax: [To rebalance the tablespace from old storage group path to new storage group]
db2 alter tablspace <ts_name> rebalance
Example: [To rebalance]
db2 alter tablespace ts1 rebalance
Syntax: [To modify the name of existing storage name]
db2 rename stogroup <old_stg_name> to <new_stg_name>
Example: [To modify the name of storage group from ‘sg1’ to new name ‘sgroup1’]
db2 rename stogroup sg1 to sgroup1
Step 1: Before dropping any storagegroup, you can assign some different storagegroup for tablespaces.
Syntax: [To assign another storagegroup for table space.]
db2 alter tablspace <ts_name> using stogroup <another sto_group_name>
Example: [To change from one old stogroup to new stogroup named ‘sg2’ for tablespace ‘ts1’]
db2 alter tablespace ts1 using stogroup sg2
Step 2:
Syntax: [To drop the existing stogroup]
db2 drop stogorup <stogroup_name>
Example: [To drop stogroup ‘stg1’ from database]
db2 drop stogroup stg1
This chapter introduces and describes the concept of Schema.
A schema is a collection of named objects classified logically in the database.
In a database, you cannot create multiple database objects with same name. To do so, the schema provides a group environment. You can create multiple schemas in a database and you can create multiple database objects with same name, with different schema groups.
A schema can contain tables, functions, indices, tablespaces, procedures, triggers etc. For example, you create two different schemas named as “Professional” and “Personal” for an “employee” database. It is possible to make two different tables with the same name “Employee”. In this environment, one table has professional information and the other has personal information of employee. In spite of having two tables with the same name, they have two different schemas “Personal” and “Professional”. Hence, the user can work with both without encountering any problem. This feature is useful when there are constraints on the naming of tables.
Let us see few commands related to Schema:
Syntax:
db2 get schema
Example: [To get current database schema]
db2 get schema
Syntax:
db2 set schema=<schema_name>
Example: [To arrange ‘schema1’ to current instance environment]
db2 set schema=schema1
Syntax: [To create a new schema with authorized user id]
db2 create schema <schema_name> authroization <inst_user>
Example: [To create “schema1” schema authorized with ‘db2inst2”]
db2 create schema schema1 authorization db2inst2
Let us create two different tables with same name but two different schemas. Here, you create employee table with two different schemas, one for personal and the other for professional information.
Step 1: Create two schemas.
Schema 1: [To create schema named professional]
db2 create schema professional authorization db2inst2
Schema 2: [To create schema named personal]
db2 create schema personal authorization db2inst2
Step 2: Create two tables with the same name for Employee details
Table1: professional.employee
[To create a new table ‘employee’ in the database using schema name ‘professional’]
db2 create table professional.employee(id number, name
varchar(20), profession varchar(20), join_date date,
salary number);
Table2: personal.employee
[To create a new table ‘employee’ in the same database, with schema name ‘personal’]
db2 create table personal.employee(id number, name
varchar(20), d_birth date, phone bigint, address
varchar(200));
After executing these steps, you get two tables with same name ’employee’, with two different schemas.
This chapter introduces various data types used in DB2.
In DB2 Database tables, each column has its own data type depending on developer’s requirements. The data type is said to be type and range of the values in columns of a table.
Datetime
TIME: It represents the time of the day in hours, minutes and seconds.
TIMESTAMP: It represents seven values of the date and time in the form of year, month, day, hours, minutes, seconds and microseconds.
DATE: It represents date of the day in three parts in the form of year, month and day.
TIME: It represents the time of the day in hours, minutes and seconds.
TIMESTAMP: It represents seven values of the date and time in the form of year, month, day, hours, minutes, seconds and microseconds.
DATE: It represents date of the day in three parts in the form of year, month and day.
String
Character
Character
CHAR (fixed length): Fixed length of Character strings.
Varying length
Varying length
VARCHAR: Varying length character strings.
CLOB: large object strings, you use this when a character string might exceed the limits of the VARCHAR data type.
Graphic
Graphic
GRAPHIC
Fixed length: Fixed length graphic strings that contains double-byte characters
Varying length
Fixed length: Fixed length graphic strings that contains double-byte characters
Varying length
VARGRAPHIC: Varying character graphic string that contains double bye characters.
DBCLOB: large object type
Binary
Binary
BLOB (varying length): binary string in large object
BOOLEAN: In the form of 0 and 1.
Signed numeric
Exact
Exact
Binary integer
SMALLINT [16BIT]: Using this you can insert small int values into columns
INTEGER [32BIT]: Using this you can insert large int values into columns
BIGINT [64BIT]: Using this you can insert larger int values into columns
SMALLINT [16BIT]: Using this you can insert small int values into columns
INTEGER [32BIT]: Using this you can insert large int values into columns
BIGINT [64BIT]: Using this you can insert larger int values into columns
Decimal
DECIMAL (packed)
DECFLOAT (decimal floating point): Using this, you can insert decimal floating point numbers
Approximate
DECIMAL (packed)
DECFLOAT (decimal floating point): Using this, you can insert decimal floating point numbers
Approximate
Floating points
REAL (single precision): Using this data type, you can insert single precision floating point numbers.
DOUBLE (double precision): Using this data type, you can insert double precision floating point numbers.
REAL (single precision): Using this data type, you can insert single precision floating point numbers.
DOUBLE (double precision): Using this data type, you can insert double precision floating point numbers.
eXtensible Mark-up Language
XML: You can store XML data into this data type column.
XML: You can store XML data into this data type column.
Tables are logical structure maintained by Database manager. In a table each vertical block called as column (Tuple) and each horizontal block called as row (Entity). The collection of data stored in the form of columns and rows is known as a table. In tables, each column has different data type. Tables are used to store persistent data.
Base Tables: They hold persistent data. There are different kinds of base tables, including:
Regular Tables: General purpose tables, Common tables with indexes are general purpose tables.
Multidimensional Clustering Table (MDC): This type of table physically clustered on more than one key, and it used to maintain large database environments. These type of tables are not supported in DB2 pureScale.
Insert time clustering Table (ITC): Similar to MDC tables, rows are clustered by the time they are inserted into the tables. They can be partitioned tables. They too, do not support pureScale environment.
Range-Clustered tables Table (RCT): These type of tables provide fast and direct access of data. These are implemented as sequential clusters. Each record in the table has a record ID. These type of tables are used where the data is clustered tightly with one or more columns in the table. This type of tables also do not support in DB2 pureScale.
Partitioned Tables: These type of tables are used in data organization schema, in which table data is divided into multiple storage objects. Data partitions can be added to, attached to and detached from a partitioned table. You can store multiple data partition from a table in one tablespace.
Temporal Tables: History of a table in a database is stored in temporal tables such as details of the modifications done previously.
Regular Tables: General purpose tables, Common tables with indexes are general purpose tables.
Multidimensional Clustering Table (MDC): This type of table physically clustered on more than one key, and it used to maintain large database environments. These type of tables are not supported in DB2 pureScale.
Insert time clustering Table (ITC): Similar to MDC tables, rows are clustered by the time they are inserted into the tables. They can be partitioned tables. They too, do not support pureScale environment.
Range-Clustered tables Table (RCT): These type of tables provide fast and direct access of data. These are implemented as sequential clusters. Each record in the table has a record ID. These type of tables are used where the data is clustered tightly with one or more columns in the table. This type of tables also do not support in DB2 pureScale.
Partitioned Tables: These type of tables are used in data organization schema, in which table data is divided into multiple storage objects. Data partitions can be added to, attached to and detached from a partitioned table. You can store multiple data partition from a table in one tablespace.
Temporal Tables: History of a table in a database is stored in temporal tables such as details of the modifications done previously.
Temporary Tables: For temporary work of different database operations, you need to use temporary tables. The temporary tables (DGTTs) do not appear in system catalog, XML columns cannot be used in created temporary tables.
Materialized Query Tables: MQT can be used to improve the performance of queries. These types of tables are defined by a query, which is used to determine the data in the tables.
The following syntax creates table:
Syntax: [To create a new table]
db2 create table <schema_name>.<table_name>
(column_name column_type....) in <tablespace_name>
Example: We create a table to store “employee” details in the schema of “professional”. This table has “id, name, jobrole, joindate, salary” fields and this table data would be stored in tablespace “ts1”.
db2 create table professional.employee(id int, name
varchar(50),jobrole varchar(30),joindate date,
salary double) in ts1
Output:
DB20000I The SQL command completed successfully.
The following syntax is used to list table details:
Syntax: [To see the list of tables created with schemas]
db2 select tabname, tabschema, tbspace from syscat.tables
Example: [To see the list of tables in the current database]
db2 select tabname, tabschema, tbspace from syscat.tables
Output:
TABNAME TABSCHEMA TBSPACE
------------ ------------- --------
EMPLOYEE PROFESSIONAL TS1
1 record(s) selected.
The following syntax lists columns in a table:
Syntax: [To see columns and data types of a table]
db2 describe table <table_name>
Example: [To see the columns and data types of table ‘employee’]
db2 describe table professional.employee
Output:
Data type Column
Column name schema Data type name Length Scale Nulls
------ ----- --------- ----------------- --------- ----- ------
ID SYSIBM INTEGER 4 0 Yes
NAME SYSIBM VARCHAR 50 0 Yes
JOBROLE SYSIBM VARCHAR 30 0 Yes
JOINDATE SYSIBM DATE 4 0 Yes
SALARY SYSIBM DOUBLE 8 0 Yes
5 record(s) selected.
You can hide an entire column of a table. If you call “select * from” query, the hidden columns are not returned in the resulting table. When you insert data into a table, an “INSERT” statement without a column list does not expect values for any implicitly hidden columns. These type of columns are highly referenced in materialized query tables. These type of columns do not support to create temporary tables.
The following syntax creates table with hidden columns:
Syntax: [To create a table with hidden columns]
db2 create table <tab_name> (col1 datatype,col2 datatype
implicitly hidden)
Example: [To create a ‘customer’ table with hidden columns ‘phone’]
db2 create table professional.customer(custid integer not
null, fullname varchar(100), phone char(10)
implicitly hidden)
The following syntax inserts values in the table:
Syntax: [To insert values into a table]
db2 insert into <tab_name>(col1,col2,...)
values(val1,val2,..)
Example: [To insert values in ‘customer’ table]
db2 insert into professional.customer(custid, fullname, phone)
values(100,'ravi','9898989')
db2 insert into professional.customer(custid, fullname, phone)
values(101,'krathi','87996659')
db2 insert into professional.customer(custid, fullname, phone)
values(102,'gopal','768678687')
Output:
DB20000I The SQL command completed successfully.
The following syntax retrieves values from the table:
Syntax: [To retrieve values form a table]
db2 select * from <tab_name>
Example: [To retrieve values from ‘customer’ table]
db2 select * from professional.customer
Output:
CUSTID FULLNAME
----------- ------------------------
100 ravi
101 krathi
102 gopal
3 record(s) selected.
The following syntax retrieves values from selected columns:
Syntax: [To retrieve selected hidden columns values from a table]
db2 select col1,col2,col3 from <tab_name>
Example: [To retrieve selected columns values result from a table]
db2 select custid,fullname,phone from professional.customer
Output:
CUSTID FULLNAME PHONE
------- --------- ------------
100 ravi 9898989
101 krathi 87996659
102 gopal 768678687
3 record(s) selected.
If you want to see the data in the hidden columns, you need to execute “DESCRIBE” command.
Syntax:
db2 describe table <table_name> show detail
Example:
db2 describe table professional.customer show detail
Output:
Column name Data type schema Data type name Column
column Partitionkey code
Length Scale Nulls
number sequence page Hidden Default
--------------- -------------------- --------------- -------- ----
---- -------- ---------- ------------- -------- ----------- ------
---
CUSTID SYSIBM INTEGER 4 0
No 0 0 0 No
FULLNAME SYSIBM VARCHAR 100 0
Yes 1 0 1208 No
PHONE SYSIBM CHARACTER 10 0
Yes 2 0 1208 Implicitly
3 record(s) selected.
You can modify our table structure using this “alter” command as follows:
Syntax:
db2 alter table <tab_name> alter column <col_name> set data type <data_type>
Example: [To modify the data type for column “id” from “int” to “bigint” for employee table]
db2 alter table professional.employee alter column id set data type bigint
Output::
DB20000I The SQL command completed successfully.
You can change column name as shown below:
Syntax: [To modify the column name from old name to new name of a table]
db2 alter table <tab_name> rename column <old_name> to <new_name>
Example: [To modify the column name from “fullname” to “custname” in “customers” table.]
db2 alter table professional.customer rename column fullname to custname
To delete any table, you need to use the “DROP” command as follows:
Syntax:
db2 drop table <tab_name>
Example: [To drop customer table form database]
db2 drop table professional.customers
To delete the entire hierarchy of the table (including triggers and relation), you need to use “DROP TABLE HIERARCHY” command.
Syntax:
db2 drop table hierarchy <tab_name>
Example: [To drop entire hierarchy of a table ‘customer’]
db2 drop table hierarchy professional.customers
This chapter describes the creation of alias and retrieving data using alias of database objects.
Alias is an alternative name for database objects. It can be used to reference the database object. You can say, it is a nick name for database objects. Alias are defined for the objects to make their name short, thereby reducing the query size and increasing readability of the query.
You can create database object alias as shown below:
Syntax:
db2 create alias <alias_name> for <table_name>
Example: Creating alias name for table “professional.customer” table
db2 create alias pro_cust for professional.customer
If you pass “SELECT * FROM PRO_CUST” or “SELECT * FROM PROFESSIONAL.CUSTOMER” the database server will show the same result.
Syntax: [To retrieve values from a table directly with schema name]
db2 select * from <schema_name>.<table_name>
Example: [To retrieve values from table customer]
db2 select * from professional.customer
Output:
CUSTID FULLNAME PHONE
------- --------- ------------
100 ravi 9898989
101 krathi 87996659
102 gopal 768678687
3 record(s) selected.
You can retrieve values from database using alias name as shown below:
Syntax: [To retrieve values from table by calling alias name of the table]
db2 select * from <alias_name>
Example: [To retrieve values from table customer using alias name]
db2 select * from pro_cust
Output:
CUSTID FULLNAME PHONE
------- --------- ------------
100 ravi 9898989
101 krathi 87996659
102 gopal 768678687
3 record(s) selected.
This chapter describes various constraints in the database.
To enforce database integrity, a set of rules is defined, called constraints. The constraints either permit or prohibit the values in the columns.
In a Real time database activities, the data should be added with certain restrictions. For example, in a sales database, sales-id or transaction-id should be unique. The constraints types are:
NOT NULL
Unique
Primary key
Foreign Key
Check
Informational
Constraints are only associated with tables. They are applied to only particular tables. They are defined and applied to the table at the time of table creation.
It is a rule to prohibit null values from one or more columns within the table.
Syntax:
db2 create table <table_name>(col_name col_type not null,..)
Example: [To create a sales table, with four columns (id, itemname, qty, price) in this adding “not null” constraints to all columns to avoid forming any null cell in the table.]
db2 create table shopper.sales(id bigint not null, itemname
varchar(40) not null, qty int not null,price double not null)
You can insert values in the table as shown below:
Example: [ERRORoneous Query]
db2 insert into shopper.sales(id,itemname,qty)
values(1,'raagi',12)
Output: [Correct query]
DB21034E The command was processed as an SQL statement because
it was not a
valid Command Line Processor command. During SQL processing
it returned:
SQL0407N Assignment of a NULL value to a NOT NULL column
"TBSPACEID=5,
TABLEID=4, COLNO=3" is not allowed. SQLSTATE=23502
Example: [Correct query]
db2 insert into shopper.sales(id,itemname,qty,price)
values(1,'raagi',12, 120.00)
db2 insert into shopper.sales(id,itemname,qty,price)
values(1,'raagi',12, 120.00)
Output:
DB20000I The SQL command completed successfully.
Using these constraints, you can set values of columns uniquely. For this, the unique constraints are declared with “not null” constraint at the time of creating table.
Syntax:
db2 create table <tab_name>(<col> <col_type> not null unique, ...)
Example:
db2 create table shopper.sales1(id bigint not null unique,
itemname varchar(40) not null, qty int not null,price
double not null)
Example: To insert four different rows with unique ids as 1, 2, 3 and 4.
db2 insert into shopper.sales1(id, itemname, qty, price)
values(1, 'sweet', 100, 89)
db2 insert into shopper.sales1(id, itemname, qty, price)
values(2, 'choco', 50, 60)
db2 insert into shopper.sales1(id, itemname, qty, price)
values(3, 'butter', 30, 40)
db2 insert into shopper.sales1(id, itemname, qty, price)
values(4, 'milk', 1000, 12)
Example: To insert a new row with “id” value 3
db2 insert into shopper.sales1(id, itemname, qty, price)
values(3, 'cheese', 60, 80)
Output: when you try to insert a new row with existed id value it will show this result:
DB21034E The command was processed as an SQL statement
because it was not a
valid Command Line Processor command. During
SQL processing it returned:
SQL0803N One or more values in the INSERT statement,
UPDATE statement, or foreign key update caused by a
DELETE statement are not valid because the primary key,
unique constraint or unique index identified by "1" constrains
table "SHOPPER.SALES1" from having duplicate values for the
index key. SQLSTATE=23505
Similar to the unique constraints, you can use a “primary key” and a “foreign key” constraint to declare relationships between multiple tables.
Syntax:
db2 create table <tab_name>( ,.., primary
key ())
Example: To create ‘salesboys’ table with “sid” as a primary key
db2 create table shopper.salesboys(sid int not null, name
varchar(40) not null, salary double not null, constraint
pk_boy_id primary key (sid))
A foreign key is a set of columns in a table which are required to match at least one primary key of a row in another table. It is a referential constraint or referential integrity constraint. It is a logical rule about values in multiple columns in one or more tables. It enables required relationship between the tables.
Earlier, you created a table named “shopper.salesboys” . For this table, the primary key is “sid”. Now you are creating a new table that has sales boy’s personal details with different schema named “employee” and table named “salesboys”. In this case, “sid” is the foreign key.
Syntax:
db2 create table <tab_name>(<col> <col_type>,constraint
<const_name> foreign key (<col_name>)
reference <ref_table> (<ref_col>)
Example: [To create a table named ‘salesboys’ with foreign key column ‘sid’]
db2 create table employee.salesboys(
sid int,
name varchar(30) not null,
phone int not null,
constraint fk_boy_id
foreign key (sid)
references shopper.salesboys (sid)
on delete restrict
)
Example: [Inserting values into primary key table “shopper.salesboys”]
db2 insert into shopper.salesboys values(100,'raju',20000.00),
(101,'kiran',15000.00),
(102,'radha',10000.00),
(103,'wali',20000.00),
(104,'rayan',15000.00)
Example: [Inserting values into foreign key table “employee.salesboys” [without error]]
db2 insert into employee.salesboys values(100,'raju',98998976),
(101,'kiran',98911176),
(102,'radha',943245176),
(103,'wali',89857330),
(104,'rayan',89851130)
If you entered an unknown number, which is not stored in “shopper.salesboys” table, it will show you SQL error.
Example: [error execution]
db2 insert into employee.salesboys values(105,'rayan',89851130)
Output:
DB21034E The command was processed as an SQL statement because it
was not a valid Command Line Processor command. During SQL
processing it returned: SQL0530N The insert or update value of
the FOREIGN KEY "EMPLOYEE.SALESBOYS.FK_BOY_ID" is not equal to any
value of the parent key of the parent table. SQLSTATE=23503
You need to use this constraint to add conditional restrictions for a specific column in a table.
Syntax:
db2 create table
(
primary key (),
constraint check (condition or condition)
)
Example: [To create emp1 table with constraints values]
db2 create table empl
(id smallint not null,
name varchar(9),
dept smallint check (dept between 10 and 100),
job char(5) check (job in ('sales', 'mgr', 'clerk')),
hiredate date,
salary decimal(7,2),
comm decimal(7,2),
primary key (id),
constraint yearsal check (year(hiredate) > 1986 or salary > 40500)
)
You can insert values into a table as shown below:
db2 insert into empl values (1,'lee', 15, 'mgr', '1985-01-01' ,
40000.00, 1000.00)
Let us see the syntaxes for dropping various constraints.
Syntax:
db2 alter table <tab_name> drop unique <const_name>
Syntax:
db2 alter table <tab_name> drop primary key
Syntax:
db2 alter table <tab_name> drop check <check_const_name>
Syntax:
db2 alter table <tab_name> drop foreigh key <foreign_key_name>
This chapter covers introduction to indexes, their types, creation and dropping.
Index is a set of pointers, which can refer to rows in a table, blocks in MDC or ITC tables, XML data in an XML storage object that are logically ordered by the values of one or more keys. It is created on DB2 table columns to speed up the data access for the queries, and to cluster and partition the data efficiently. It can also improve the performance of operation on the view. A table with a unique index can have rows with unique keys. Depending on the table requirements, you can take different types of indexes.
Unique and Non-Unique indexes
Clustered and non-clustered indexes
For creating unique indexes, you use following syntax:
Syntax:
db2 create unique index <index_name> on
<table_name>(<unique_column>) include (<column_names..>)
Example: To create index for “shopper.sales1” table.
db2 create unique index sales1_indx on
shopper.sales1(id) include (itemname)
For dropping the index, you use the following syntax:
Syntax:
db2 create unique index <index_name> on
<table_name>(<unique_column>) include (<column_names..>)
Example:
db2 drop index sales_index
This chapter describes triggers, their types, creation and dropping of the triggers.
A trigger is a set of actions, which are performed for responding to an INSERT, UPDATE or DELETE operation on a specified table in the database. Triggers are stored in the database at once. They handle governance of data. They can be accessed and shared among multiple applications. The advantage of using triggers is, if any change needs to be done in the application, it is done at the trigger; instead of changing each application that is accessing the trigger. Triggers are easy to maintain and they enforce faster application development. Triggers are defined using an SQL statement “CREATE TRIGGER”.
There are two types of triggers:
They are executed before any SQL operation.
They are executed after any SQL operation.
Let us see how to create a sequence of trigger:
Syntax:
db2 create sequence <seq_name>
Example: Creating a sequence of triggers for table shopper.sales1
db2 create sequence sales1_seq as int start with 1 increment by 1
Syntax:
db2 create trigger <trigger_name> no cascade before insert on
<table_name> referencing new as <table_object> for each row set
<table_object>.<col_name>=nextval for <sequence_name>
Example: Creating trigger for shopper.sales1 table to insert primary key numbers automatically
db2 create trigger sales1_trigger no cascade before insert on
shopper.sales1 referencing new as obj for each row set
obj.id=nextval for sales1_seq
Now try inserting any values:
db2 insert into shopper.sales1(itemname, qty, price)
values('bicks', 100, 24.00)
Let us see how to retrieve values from a table:
Syntax:
db2 select * from <tablename>
Example:
db2 select * from shopper.sales1
Output:
ID ITEMNAME QTY
------- ------------ ----------
3 bicks 100
2 bread 100
2 record(s) selected.
Let us see how to create an after trigger:
Syntax:
db2 create trigger <trigger_name> no cascade before insert on
<table_name> referencing new as <table_object> for each row set
<table_object>.<col_name>=nextval for <sequence_name>
Example: [To insert and retrieve the values]
db2 create trigger sales1_tri_after after insert on shopper.sales1
for each row mode db2sql begin atomic update shopper.sales1
set price=qty*price; end
Output:
//inseting values in shopper.sales1
db2 insert into shopper.sales1(itemname,qty,price)
values('chiken',100,124.00)
//output
ID ITEMNAME QTY PRICE
----- -------------- ----------- -----------
3 bicks 100 2400.00
4 chiken 100 12400.00
2 bread 100 2400.00
3 record(s) selected.
Here is how a database trigger is dropped:
Syntax:
db2 drop trigger <trigger_name>
Example:
db2 drop trigger slaes1_trigger
This chapter introduces you to the concept of sequence, creation of sequence, viewing the sequence, and dropping them.
A sequence is a software function that generates integer numbers in either ascending or descending order, within a definite range, to generate primary key and coordinate other keys among the table. You use sequence for availing integer numbers say, for employee_id or transaction_id. A sequence can support SMALLINT, BIGINT, INTEGER, and DECIMAL data types. A sequence can be shared among multiple applications. A sequence is incremented or decremented irrespective of transactions.
A sequence is created by CREATE SEQUENCE statement.
There are two type of sequences available:
NEXTVAL: It returns an incremented value for a sequence number.
NEXTVAL: It returns an incremented value for a sequence number.
PREVIOUS VALUE: It returns recently generated value.
PREVIOUS VALUE: It returns recently generated value.
The following parameters are used for sequences:
Data type: This is the data type of the returned incremented value. (SMALLINT, BIGINT, INTEGER, NUMBER, DOUBLE)
START WITH: The reference value, with which the sequence starts.
MINVALUE: A minimum value for a sequence to start with.
MAXVALUE: A maximum value for a sequence.
INCREMENT BY: step value by which a sequence is incremented.
Sequence cycling: the CYCLE clause causes generation of the sequence repeatedly. The sequence generation is conducted by referring the returned value, which is stored into the database by previous sequence generation.
You can create sequence using the following syntax:
Syntax:
db2 create sequence <seq_name>
Example: [To create a new sequence with the name ‘sales1_seq’ and increasing values from 1]
db2 create sequence sales1_seq as int start
with 1 increment by 1
You can view a sequence using the syntax given below:
Syntax:
db2 value <previous/next> value for <seq_name>
Example: [To see list of previous updated value in sequence ‘sales1_seq’]
db2 values previous value for sales1_seq
Output:
1
-----------
4
1 record(s) selected.
To remove the sequence, you need to use the “DROP SEQUENCE ” command. Here is how you do it:
Syntax:
db2 drop sequence <seq_name>>
Example: [To drop sequence ‘sales1_seq’ from database]
db2 drop sequence sales1_seq
Output:
DB20000I The SQL command completed successfully.
This chapter describes introduction of views, creating, modifying and dropping the views.
A view is an alternative way of representing the data stored in the tables. It is not an actual table and it does not have any permanent storage. View provides a way of looking at the data in one or more tables. It is a named specification of a result table.
You can create a view using the following syntax:
Syntax:
db2 create view <view_name> (<col_name>,
<col_name1...) as select <cols>..
from <table_name>
Example: Creating view for shopper.sales1 table
db2 create view view_sales1(id, itemname, qty, price)
as select id, itemname, qty, price from
shopper.sales1
You can modify a view using the following syntax:
Syntax:
db2 alter view <view_name> alter <col_name>
add scope <table_or_view_name>
Example: [To add new table column to existing view ‘view_sales1’]
db2 alter view view_sales1 alter id add
scope shopper.sales1
You can drop a view using the following syntax:
Syntax:
db2 drop view <view_name>
Example:
db2 drop view sales1_view
This chapter describes use of XML with DB2.
PureXML feature allows you to store well-formed XML documents in columns of database tables. Those columns have XML database. Data is kept in its native hierarchical form by storing XML data in XML column. The stored XML data can be accessed and managed by DB2 database server functionality. The storage of XML data in its native hierarchical form enables efficient search, retrieval, and update of XML. To update a value in XML data, you need to use XQuery, SQL or combination of both.
Create a database by issuing the following syntax:
Syntax:
db2 create database xmldb
By default, databases use UTF-8 (UNICODE) code set. Activate the database and connect to it:
Syntax:
db2 activate db <db_name>
db2 connect to <db_name>
Example:
db2 activate db xmldb
db2 connect to xmldb
Create a well-formed XML file and create a table with data type of the column as ‘XML’. It is mandatory to pass the SQL query containing XML syntax within double quotation marks.
Syntax:
db2 “create table <schema>.<table>(col <datatype>,
col <xml datatype>)”
Example:
db2 "create table shope.books(id bigint not null
primary key, book XML)"
Insert xml values into table, well-formed XML documents are inserted into XML type column using SQL statement ‘INSERT’.
Syntax:
db2 “insert into <table_name> values(value1, value2)”
Example:
db2 "insert into shope.books values(1000, '<catalog>
<book>
<author> Gambardella Matthew</author>
<title>XML Developers Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating application
with XML</description>
</book>
</catalog>')"
You can update XML data in a table by using the following syntax:
Syntax:
db2 “update <table_name> set <column>=<value> where
<column>=<value>”
Example:
db2 "update shope.books set book='<catalog>
<book>
<author> Gambardella, Matthew</author>
<title>XML Developers Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth XML</description>
</book>
</catalog>' where id=1000"
This chapter describes backup and restore methods of database.
Backup and recovery methods are designed to keep our information safe. In Command Line Interface (CLI) or Graphical User Interface (GUI) using backup and recovery utilities you can take backup or restore the data of databases in DB2 UDB.
Log files consist of error logs, which are used to recover from application errors. The logs keep the record of changes in the database. There are two types of logging as described below:
It is a method where the old transaction logs are overwritten when there is a need to allocate a new transaction log file, thus erasing the sequences of log files and reusing them. You are permitted to take only full back-up in offline mode. i.e., the database must be offline to take the full backup.
This mode supports for Online Backup and database recovery using log files called roll forward recovery. The mode of backup can be changed from circular to archive by setting logretain or userexit to ON. For archive logging, backup setting database require a directory that is writable for DB2 process.
Using Backup command you can take copy of entire database. This backup copy includes database system files, data files, log files, control information and so on.
You can take backup while working offline as well as online.
Syntax: [To list the active applications/databases]
db2 list application
Output:
Auth Id Application Appl. Application Id
DB # of
Name Handle
Name Agents
-------- -------------- ---------- ---------------------
----------------------------------------- -------- -----
DB2INST1 db2bp 39
*LOCAL.db2inst1.140722043938
ONE 1
Syntax: [To force application using app. Handled id]
db2 "force application (39)"
Output:
DB20000I The FORCE APPLICATION command completed
successfully.
DB21024I This command is asynchronous and may not
be effective immediately.
Syntax: [To terminate Database Connection]
db2 terminate
Syntax: [To deactivate Database]
db2 deactivate database one
Syntax: [To take the backup file]
db2 backup database <db_name> to <location>
Example:
db2 backup database one to /home/db2inst1/
Output:
Backup successful. The timestamp for this backup image is :
20140722105345
To start, you need to change the mode from Circular logging to Archive Logging.
Syntax: [To check if the database is using circular or archive logging]
db2 get db cfg for one | grep LOGARCH
Output:
First log archive method (LOGARCHMETH1) = OFF
Archive compression for logarchmeth1 (LOGARCHCOMPR1) = OFF
Options for logarchmeth1 (LOGARCHOPT1) =
Second log archive method (LOGARCHMETH2) = OFF
Archive compression for logarchmeth2 (LOGARCHCOMPR2) = OFF
Options for logarchmeth2 (LOGARCHOPT2) =
In the above output, the highlighted values are [logarchmeth1 and logarchmeth2] in off mode, which implies that the current database in “CIRCULLAR LOGGING” mode. If you need to work with ‘ARCHIVE LOGGING’ mode, you need to change or add path in the variables logarchmeth1 and logarchmeth2 present in the configuration file.
Syntax: [To make directories]
mkdir backup
mkdir backup/ArchiveDest
Syntax: [To provide user permissions for folder]
chown db2inst1:db2iadm1 backup/ArchiveDest
Syntax: [To update configuration LOGARCHMETH1]
db2 update database configuration for one using LOGARCHMETH1
'DISK:/home/db2inst1/backup/ArchiveDest'
You can take offline backup for safety, activate the database and connect to it.
Syntax: [To take online backup]
db2 backup database one online to
/home/db2inst1/onlinebackup/ compress include logs
Output:
db2 backup database one online to
/home/db2inst1/onlinebackup/ compress include logs
Verify Backup file using following command:
Syntax:
db2ckbkp <location/backup file>
Example:
db2ckbkp
/home/db2inst1/ONE.0.db2inst1.DBPART000.20140722112743.001
Listing the history of backup files
Syntax:
db2 list history backup all for one
Output:
List History File for one
Number of matching file entries = 4
Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log
Backup ID
-- --- ------------------ ---- --- ------------ ------------
--------------
B D 20140722105345001 F D S0000000.LOG S0000000.LOG
------------------------------------------------------------
----------------
Contains 4 tablespace(s):
00001 SYSCATSPACE
00002 USERSPACE1
00003 SYSTOOLSPACE
00004 TS1
------------------------------------------------------------
----------------
Comment: DB2 BACKUP ONE OFFLINE
Start Time: 20140722105345
End Time: 20140722105347
Status: A
------------------------------------------------------------
----------------
EID: 3 Location: /home/db2inst1
Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log
Backup ID
-- --- ------------------ ---- --- ------------ ------------
--------------
B D 20140722112239000 N S0000000.LOG S0000000.LOG
------------------------------------------------------------
-------------------------------------------------------------
-------------------------------
Comment: DB2 BACKUP ONE ONLINE
Start Time: 20140722112239
End Time: 20140722112240
Status: A
------------------------------------------------------------
----------------
EID: 4 Location:
SQLCA Information
sqlcaid : SQLCA sqlcabc: 136 sqlcode: -2413 sqlerrml: 0
sqlerrmc:
sqlerrp : sqlubIni
sqlerrd : (1) 0 (2) 0 (3) 0
(4) 0 (5) 0 (6) 0
sqlwarn : (1) (2) (3) (4) (5) (6)
(7) (8) (9) (10) (11)
sqlstate:
Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log
Backup ID
-- --- ------------------ ---- --- ------------ ------------
--------------
B D 20140722112743001 F D S0000000.LOG S0000000.LOG
------------------------------------------------------------
----------------
Contains 4 tablespace(s):
00001 SYSCATSPACE
00002 USERSPACE1
00003 SYSTOOLSPACE
00004 TS1
-------------------------------------------------------------
----------------
Comment: DB2 BACKUP ONE OFFLINE
Start Time: 20140722112743
End Time: 20140722112743
Status: A
-------------------------------------------------------------
----------------
EID: 5 Location: /home/db2inst1
Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log
Backup ID
-------------------------------------------------------------
----------------
R D 20140722114519001 F
20140722112743
------------------------------------------------------------
----------------
Contains 4 tablespace(s):
00001 SYSCATSPACE
00002 USERSPACE1
00003 SYSTOOLSPACE
00004 TS1
------------------------------------------------------------
----------------
Comment: RESTORE ONE WITH RF
Start Time: 20140722114519
End Time: 20140722115015
Status: A
------------------------------------------------------------
----------------
EID: 6 Location:
To restore the database from backup file, you need to follow the given syntax:
Syntax:
db2 restore database <db_name> from <location>
taken at <timestamp>
Example:
db2 restore database one from /home/db2inst1/ taken at
20140722112743
Output:
SQL2523W Warning! Restoring to an existing database that is
different from
the database on the backup image, but have matching names.
The target database
will be overwritten by the backup version. The Roll-forward
recovery logs
associated with the target database will be deleted.
Do you want to continue ? (y/n) y
DB20000I The RESTORE DATABASE command completed successfully.
Roll forward all the logs located in the log directory, including latest changes just before the disk drive failure.
Syntax:
db2 rollforward db <db_name> to end of logs and stop
Example:
db2 rollforward db one to end of logs and stop
Output:
Rollforward Status
Input database alias = one
Number of members have returned status = 1
Member ID = 0
Rollforward status = not pending
Next log file to be read =
Log files processed = S0000000.LOG -
S0000001.LOG
Last committed transaction = 2014-07-22-
06.00.33.000000 UTC
DB20000I The ROLLFORWARD command completed successfully.
This chapter describes database security.
DB2 database and functions can be managed by two different modes of security controls:
Authentication
Authorization
Authentication
Authorization
Authentication is the process of confirming that a user logs in only in accordance with the rights to perform the activities he is authorized to perform. User authentication can be performed at operating system level or database level itself. By using authentication tools for biometrics such as retina and figure prints are in use to keep the database from hackers or malicious users.
The database security can be managed from outside the db2 database system. Here are some type of security authentication process:
Based on Operating System authentications.
Lightweight Directory Access Protocol (LDAP)
For DB2, the security service is a part of operating system as a separate product. For Authentication, it requires two different credentials, those are userid or username, and password.
You can access the DB2 Database and its functionality within the DB2 database system, which is managed by the DB2 Database manager. Authorization is a process managed by the DB2 Database manager. The manager obtains information about the current authenticated user, that indicates which database operation the user can perform or access.
Here are different ways of permissions available for authorization:
Primary permission: Grants the authorization ID directly.
Secondary permission: Grants to the groups and roles if the user is a member
Public permission: Grants to all users publicly.
Context-sensitive permission: Grants to the trusted context role.
Authorization can be given to users based on the categories below:
System-level authorization
System administrator [SYSADM]
System Control [SYSCTRL]
System maintenance [SYSMAINT]
System monitor [SYSMON]
Authorities provide of control over instance-level functionality. Authority provide to group privileges, to control maintenance and authority operations. For instance, database and database objects.
Database-level authorization
Security Administrator [SECADM]
Database Administrator [DBADM]
Access Control [ACCESSCTRL]
Data access [DATAACCESS]
SQL administrator. [SQLADM]
Workload management administrator [WLMADM]
Explain [EXPLAIN]
Authorities provide controls within the database. Other authorities for database include with LDAD and CONNECT.
Object-Level Authorization: Object-Level authorization involves verifying privileges when an operation is performed on an object.
Content-based Authorization: User can have read and write access to individual rows and columns on a particular table using Label-based access Control [LBAC].
DB2 tables and configuration files are used to record the permissions associated with authorization names. When a user tries to access the data, the recorded permissions verify the following permissions:
Authorization name of the user
Which group belongs to the user
Which roles are granted directly to the user or indirectly to a group
Permissions acquired through a trusted context.
While working with the SQL statements, the DB2 authorization model considers the combination of the following permissions:
Permissions granted to the primary authorization ID associated with the SQL statements.
Secondary authorization IDs associated with the SQL statements.
Granted to PUBLIC
Granted to the trusted context role.
Let us discuss some instance related authorities.
It is highest level administrative authority at the instance-level. Users with SYSADM authority can execute some databases and database manager commands within the instance. Users with SYSADM authority can perform the following operations:
Upgrade a Database
Restore a Database
Update Database manager configuration file.
It is the highest level in System control authority. It provides to perform maintenance and utility operations against the database manager instance and its databases. These operations can affect system resources, but they do not allow direct access to data in the database.
Users with SYSCTRL authority can perform the following actions:
Updating the database, Node, or Distributed Connect Service (DCS) directory
Forcing users off the system-level
Creating or Dropping a database-level
Creating, altering, or dropping a table space
Using any table space
Restoring Database
It is a second level of system control authority. It provides to perform maintenance and utility operations against the database manager instance and its databases. These operations affect the system resources without allowing direct access to data in the database. This authority is designed for users to maintain databases within a database manager instance that contains sensitive data.
Only Users with SYSMAINT or higher level system authorities can perform the following tasks:
Taking backup
Restoring the backup
Roll forward recovery
Starting or stopping instance
Restoring tablespaces
Executing db2trc command
Taking system monitor snapshots in case of an Instance level user or a database level user.
A user with SYSMAINT can perform the following tasks:
Query the state of a tablespace
Updating log history files
Reorganizing of tables
Using RUNSTATS (Collection catalog statistics)
With this authority, the user can monitor or take snapshots of database manager instance or its database. SYSMON authority enables the user to run the following tasks:
GET DATABASE MANAGER MONITOR SWITCHES
GET MONITOR SWITCHES
GET SNAPSHOT
LIST
LIST ACTIVE DATABASES
LIST APPLICATIONS
LIST DATABASE PARTITION GROUPS
LIST DCS APPLICATIONS
LIST PACKAGES
LIST TABLES
LIST TABLESPACE CONTAINERS
LIST TABLESPACES
LIST UTITLITIES
LIST ACTIVE DATABASES
LIST APPLICATIONS
LIST DATABASE PARTITION GROUPS
LIST DCS APPLICATIONS
LIST PACKAGES
LIST TABLES
LIST TABLESPACE CONTAINERS
LIST TABLESPACES
LIST UTITLITIES
RESET MONITOR
UPDATE MONITOR SWITCHES
Each database authority holds the authorization ID to perform some action on the database. These database authorities are different from privileges. Here is the list of some database authorities:
ACCESSCTRL: allows to grant and revoke all object privileges and database authorities.
BINDADD: Allows to create a new package in the database.
CONNECT: Allows to connect to the database.
CREATETAB: Allows to create new tables in the database.
CREATE_EXTERNAL_ROUTINE: Allows to create a procedure to be used by applications and the users of the databases.
DATAACCESS: Allows to access data stored in the database tables.
DBADM: Act as a database administrator. It gives all other database authorities except ACCESSCTRL, DATAACCESS, and SECADM.
EXPLAIN: Allows to explain query plans without requiring them to hold the privileges to access the data in the tables.
IMPLICIT_SCHEMA: Allows a user to create a schema implicitly by creating an object using a CREATE statement.
LOAD: Allows to load data into table.
QUIESCE_CONNECT: Allows to access the database while it is quiesce (temporarily disabled).
SECADM: Allows to act as a security administrator for the database.
SQLADM: Allows to monitor and tune SQL statements.
WLMADM: Allows to act as a workload administrator
Authorization ID privileges involve actions on authorization IDs. There is only one privilege, called the SETSESSIONUSER privilege. It can be granted to user or a group and it allows to session user to switch identities to any of the authorization IDs on which the privileges are granted. This privilege is granted by user SECADM authority.
This privileges involve actions on schema in the database. The owner of the schema has all the permissions to manipulate the schema objects like tables, views, indexes, packages, data types, functions, triggers, procedures and aliases. A user, a group, a role, or PUBLIC can be granted any user of the following privileges:
CREATEIN: allows to create objects within the schema
ALTERIN: allows to modify objects within the schema.
This allows to delete the objects within the schema.
These privileges involve actions on the tablespaces in the database. User can be granted the USE privilege for the tablespaces. The privileges then allow them to create tables within tablespaces. The privilege owner can grant the USE privilege with the command WITH GRANT OPTION on the tablespace when tablespace is created. And SECADM or ACCESSCTRL authorities have the permissions to USE privileges on the tablespace.
The user must have CONNECT authority on the database to be able to use table and view privileges. The privileges for tables and views are as given below:
It provides all the privileges for a table or a view including drop and grant, revoke individual table privileges to the user.
It allows user to modify a table.
It allows the user to delete rows from the table or view.
It allows the user to insert a row into table or view. It can also run import utility.
It allows the users to create and drop a foreign key.
It allows the user to retrieve rows from a table or view.
It allows the user to change entries in a table, view.
User must have CONNECT authority to the database. Package is a database object that contains the information of database manager to access data in the most efficient way for a particular application.
It provides the user with privileges of rebinding, dropping or executing packages. A user with this privileges is granted to BIND and EXECUTE privileges.
It allows the user to bind or rebind that package.
Allows to execute a package.
This privilege automatically receives CONTROL privilege on the index.
Sequence automatically receives the USAGE and ALTER privileges on the sequence.
It involves the action of routines such as functions, procedures, and methods within a database.
A role is a database object that groups multiple privileges that can be assigned to users, groups, PUBLIC or other roles by using GRANT statement.
A role cannot own database objects.
Permissions and roles granted to groups are not considered when you create the following database objects.
Package Containing static SQL
Views
Materialized Query Tables (MQT)
Triggers
SQL Routines
Package Containing static SQL
Views
Materialized Query Tables (MQT)
Triggers
SQL Routines
Syntax: [To create a new role]
db2 create role <role_name>
Example: [To create a new role named ‘sales’ to add some table to be managed by some user or group]
db2 create role sales
Output:
DB20000I The SQL command completed successfully.
Syntax: [To grant permission of a role to a table]
db2 grant select on table <table_name> to role <role_name>
Example: [To add permission to manage a table ‘shope.books’ to role ‘sales’]
db2 grant select on table shope.books to role sales
Output:
DB20000I The SQL command completed successfully.
Security administrator grants role to the required users. (Before you use this command, you need to create the users.)
Syntax: [To add users to a role]
db2 grant role <role_name> to user <username>
Example: [To add a user ‘mastanvali’ to a role ‘sales’]
db2 grant sales to user mastanvali
Output:
DB20000I The SQL command completed successfully.
For creating a hierarchies for roles, each role is granted permissions/ membership with another role.
Syntax: [before this syntax create a new role with name of “production”]
db2 grant role <roll_name> to role <role_name>
Example: [To provide permission of a role ‘sales’ to another role ‘production’]
db2 grant sales to role production
LDAP is Lightweight Directory Access Protocol. LDAP is a global directory service, industry-standard protocol, which is based on client-server model and runs on a layer above the TCP/IP stack. The LDAP provides a facility to connect to, access, modify, and search the internet directory.
The LDAP servers contain information which is organized in the form of a directory tree. The clients ask server to provide information or to perform some operation on a particular information. The server answers the client by providing required information if it has one, or it refers the client to another server for action on required information. The client then acquires the desired information from another server.
The tree structure of directory is maintained same across all the participating servers. This is a prominent feature of LDAP directory service. Hence, irrespective of which server is referred to by the client, the client always gets required information in an error-free manner. Here, we use LDAP to authenticate IBM DB2 as a replacement of operating system authentication.
There are two types of LDAP:
Transparent
Plug-in
Transparent
Plug-in
Let us see how to configure a transparent LDAP.
To start with configuration of transparent LDAP, you need to configure the LDAP server.
Create a SLAPD.conf file, which contains all the information about users and group object in the LDAP. When you install LDAP server, by default it is configured with basic LDAP directory tree on your machine.
The table shown below indicates the file configuration after modification.
The text highlighted with yellow the code box means for the following:
DBA user-id = “db2my1”, group = “db1my1adm”, password= “db2my1” Admin user-id = “my1adm”, group = “dbmy1ctl”.
# base dn: example.com
dn: dc=example,dc=com
dc: example
o: example
objectClass: organization
objectClass: dcObject
# pc box db
dn: dc=db697,dc=example,dc=com
dc: db697
o: db697
objectClass: organization
objectClass: dcObject
#
# Group: dbadm
#
dn: cn=dbmy1adm,dc=db697,dc=example,dc=com
cn: dbmy1adm
objectClass: top
objectClass: posixGroup
gidNumber: 400
objectClass: groupOfNames
member: uid=db2my1,cn=dbmy1adm,dc=db697,dc=example,dc=com
memberUid: db2my1
#
# User: db2
#
dn: uid=db2my1,cn=dbmy1adm,dc=db697,dc=example,dc=com
cn: db2my1
sn: db2my1
uid: db2my1
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 400
gidNumber: 400
loginShell: /bin/csh
homeDirectory: /db2/db2my1
#
# Group: dbctl
#
dn: cn=dbmy1ctl,dc=db697,dc=example,dc=com
cn: dbmy1ctl
objectClass: top
objectClass: posixGroup
gidNumber: 404
objectClass: groupOfNames
member: uid=my1adm,cn=dbmy1adm,dc=db697,dc=example,dc=com
memberUid: my1adm
#
# User: adm
#
dn: uid=my1adm,cn=dbmy1ctl,dc=db697,dc=example,dc=com
cn: my1adm
sn: my1adm
uid: my1adm
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 404
gidNumber: 404
loginShell: /bin/csh
homeDirectory: /home/my1adm
Save the above file with name ‘/var/lib/slapd.conf’, then execute this file by following command to add these values into LDAP Server. This is a linux command; not a db2 command.
ldapadd r- -D ‘cn=Manager,dc=example,dc=com” –W –f
/var/lib/slapd.conf
After registering the DB2 users and the DB2 group at the LDAP Server, logon to the particular user where you have installed instance and database. You need to configure LDAP client to confirm to client where your server is located, be it remote or local.
The LDAP Client configuration is saved in the file ‘ldap.conf’. There are two files available for configuration parameters, one is common and the other is specific. You should find the first one at ‘/etc/ldap.conf’ and the latter is located at ‘/etc/openldap/ldap.conf’.
The following data is available in common LDAP client configuration file
# File: /etc/ldap.conf
# The file contains lots of more entries and many of them
# are comments. You show only the interesting values for now
host localhost
base dc=example,dc=com
ldap_version 3
pam_password crypt
pam_filter objectclass=posixAccount
nss_map_attribute uniqueMember member
nss_base_passwd dc=example,dc=com
nss_base_shadow dc=example,dc=com
nss_base_group dc=example,dc=com
You need to change the location of server and domain information according to the DB2 configuration. If we are using server in same system then mention it as ‘localhost’ at ‘host’ and at ‘base’ you can configure which is mentioned in ‘SLAPD.conf’ file for LDAP server.
Pluggable Authentication Model (PAM) is an API for authentication services. This is common interface for LDAP authentication with an encrypted password and special LDAP object of type posixAccount. All LDAP objects of this type represent an abstraction of an account with portable Operating System Interface (POSIX) attributes.
Network Security Services (NSS) is a set of libraries to support cross-platform development of security-enabled client and server applications. This includes libraries like SSL, TLS, PKCS S/MIME and other security standards.
You need to specify the base DN for this interface and two additional mapping attributes. OpenLDAP client configuration file contains the entries given below:
host localhost
base dc=example,dc=com
Till this you just define the host of LDAP serve and the base DN.
After you configured your LDAP Server and LDAP Client, verify both for communication.
Step1: Check your Local LDAP server is running. Using below command:
ps -ef | grep -i ldap
This command should list the LDAP deamon which represents your LDAP server:
/usr/lib/openldap/slapd -h ldap:/// -u ldap -g ldap -o slp=on
This indicates that you LDAP server is running and is waiting for request from clients. If there is no such process for previous commands you can start LDAP server with the ’rcldap’ command.
rcldap start
When the server starts, you can monitor this in the file ‘/var/log/messages/ by issuing the following command.
tail –f /var/log/messages
The ldapsearch command opens a connection to an LDAP server, binds to it and performs a search query which can be specified by using special parameters ‘-x’ connect to your LDAP server with a simple authentication mechanism by using the –x parameter instead of a more complex mechanism like Simple Authentication and Security Layer (SASL)
ldapsearch –x
LDAP server should reply with a response given below, containing all of your LDAP entries in a LDAP Data Interchange Format(LDIF).
# extended LDIF
#
# LDAPv3
# base <> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
# example.com
dn: dc=example,
dc=com dc: example
o: example
objectClass: organization
objectClass: dcObject
# search result
search: 2
result: 0 Success
# numResponses: 2
# numEntries: 1
After working with LDAP server and client, you need to configure our DB2 database for use with LDAP. Let us discuss, how you can install and configure your database to use our LDAP environment for the DB2 user authentication process.
IBM provides a free package with LDAP plug-ins for DB2. The DB2 package includes three DB2 security plug-ins for each of the following:
server side authentication
client side authentication
group lookup
Depending upon your requirements, you can use any of the three plug-ins or all of them. This plugin do not support environments where some users are defined in LDAP and others in the operating Systems. If you decide to use the LDAP plug-ins, you need to define all users associated with the database in the LDAP server. The same principle applies to the group plug-in.
You have to decide which plug-ins are mandatory for our system. The client authentication plug-ins used in scenarios where the user ID and the password validation supplied on a CONNECT or ATTACH statement occurs on the client system. So the database manager configuration parameters SRVCON_AUTH or AUTHENTICATION need to be set to the value CLIENT. The client authentication is difficult to secure and is not generally recommended. Server plug-in is generally recommended because it performs a server side validation of user IDs and passwords, if the client executes a CONNECT or ATTACH statement and this is secure way. The server plug-in also provides a way to map LDAP user IDs DB2 authorization IDs.
Now you can start installation and configuration of the DB2 security plug-ins, you need to think about the required directory information tree for DB2. DB2 uses indirect authorization which means that a user belongs to a group and this group was granted with fewer authorities. You need to define all DB2 users and DB2 groups in LDAP directory.
The LDIF file openldap.ldif should contain the code below:
#
# LDAP root object
# example.com
#
dn: dc=example,
dc=com
dc: example
o: example
objectClass: organization
objectClass: dcObject
#
# db2 groups
#
dn: cn=dasadm1,dc=example,dc=com
cn: dasadm1
objectClass: top
objectClass: posixGroup
gidNumber: 300
objectClass: groupOfNames
member: uid=dasusr1,cn=dasadm1,dc=example,dc=com
memberUid: dasusr1
dn: cn=db2grp1,dc=example,dc=com
cn: db2grp1
objectClass: top
objectClass: posixGroup
gidNumber: 301
objectClass: groupOfNames
member: uid=db2inst2,cn=db2grp1,dc=example,dc=com memberUid: db2inst2
dn: cn=db2fgrp1,dc=example,dc=com
cn: db2fgrp1
objectClass: top
objectClass: posixGroup
gidNumber: 302
objectClass: groupOfNames
member: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com
memberUid: db2fenc1
#
# db2 users
#
dn: uid=dasusr1,
cn=dasadm1,
dc=example,dc=com
cn: dasusr1
sn: dasusr1
uid: dasusr1
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 300
gidNumber: 300
loginShell: /bin/bash
homeDirectory: /home/dasusr1
dn: uid=db2inst2,cn=db2grp1,dc=example,dc=com
cn: db2inst2
sn: db2inst2
uid: db2inst2
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 301
gidNumber: 301
loginShell: /bin/bash
homeDirectory: /home/db2inst2
dn: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com
cn: db2fenc1
sn: db2fenc1
uid: db2fenc1
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 303
gidNumber: 303
loginShell: /bin/bash
homeDirectory: /home/db2fenc1
Create a file named ‘db2.ldif’ and paste the above example into it. Using this file, add the defined structures to your LDAP directory.
To add the DB2 users and DB2 groups to the LDAP directory, you need to bind the user as ‘rootdn’ to the LDAP server in order to get the exact privileges.
Execute the following syntaxes to fill the LDAP information directory with all our objects defined in the LDIF file ‘db2.ldif’
ldapadd –x –D “cn=Manager, dc=example,dc=com” –W –f <path>/db2.ldif
Perform the search result with more parameter
ldapsearch –x |more
Creating instance for our LDAP user db2inst2. This user requires home directory with two empty files inside the home directory. Before you create a new instance, you need to create a user who will be the owner of the instance.
After creating the instance user, you should have to create the file ‘.profile’ and ‘.login’ in user home directory, which will be modified by DB2. To create this file in the directory, execute the following command:
mkdir /home/db2inst2
mkdir /home/db2inst2/.login
mkdir /home/db2inst2/.profile
You have registered all users and groups related with DB2 in LDAP directory, now you can create an instance with the name ‘db2inst2’ with the instance owner id ‘db2inst2’ and use the fenced user id ‘db2fenc1’, which is needed for running user defined functions (UDFs)or stored procedures.
/opt/ibm/db2/V10.1/instance/db2icrt –u db2fenc1 db2inst2
DBI1070I Program db2icrt completed successfully.
Now check the instance home directory. You can see new sub-directory called ‘sqllib’ and the .profile and .login files customized for DB2 usage.
Copy the required LDAP plug-ins to the appropriate DB2 directory:
cp ///v10/IBMLDAPauthserver.so
/home/db2inst2/sqllib/security/plugin/server/.
cp ///v10/IBMLDAPgroups.so
/home/db2inst2/sqllib/security/plugin/group/.
Once the plug-ins are copied to the specified directory, you toned to login to DB2 instance owner and change the database manager configuration to use these plug-ins.
Su – db2inst2
db2inst2> db2 update dbm cfg using svrcon_pw_plugin
IBMLDAPauthserver
db2inst2> db2 update dbm cfg using group_plugin
IBMLDAPgroups
db2inst2> db2 update dbm cfg using authentication
SERVER_ENCRYPT
db2inst2> db2stop
db2inst2> db2start
This modification comes into effect after you start DB2 instance. After restarting the instance, you need to install and configure the main DB2 LDAP configuration file named “IBMLDAPSecurity.ini” to make DB2 plug-ins work with the current LDAP configuration.
IBMLDAPSecurity.ini file contains
;-----------------------------------------------------------
; SERVER RELATED VALUES
;-----------------------------------------------------------
; Name of your LDAP server(s).
; This is a space separated list of LDAP server addresses,
; with an optional port number for each one:
; host1[:port] [host2:[port2] ... ]
; The default port number is 389, or 636 if SSL is enabled.
LDAP_HOST = my.ldap.server
;-----------------------------------------------------------
; USER RELATED VALUES
;-----------------------------------------------------------
rs
; LDAP object class used for use USER_OBJECTCLASS = posixAccount
; LDAP user attribute that represents the "userid"
; This attribute is combined with the USER_OBJECTCLASS and
; USER_BASEDN (if specified) to construct an LDAP search
; filter when a user issues a DB2 CONNECT statement with an
; unqualified userid. For example, using the default values
; in this configuration file, (db2 connect to MYDB user bob
; using bobpass) results in the following search filter:
OrgPerson)(uid=bob)
; &(objectClass=inet USERID_ATTRIBUTE = uid
representing the DB2 authorization ID
; LDAP user attribute, AUTHID_ATTRIBUTE = uid
;-----------------------------------------------------------
; GROUP RELATED VALUES
;-----------------------------------------------------------
ps
; LDAP object class used for grou GROUP_OBJECTCLASS = groupOfNames
at represents the name of the group
; LDAP group attribute th GROUPNAME_ATTRIBUTE = cn
; Determines the method used to find the group memberships
; for a user. Possible values are:
; SEARCH_BY_DN - Search for groups that list the user as
; a member. Membership is indicated by the
; group attribute defined as
; GROUP_LOOKUP_ATTRIBUTE.
; USER_ATTRIBUTE - A user's groups are listed as attributes
; of the user object itself. Search for the
; user attribute defined as
TRIBUTE to get the groups.
; GROUP_LOOKUP_AT GROUP_LOOKUP_METHOD = SEARCH_BY_DN
; GROUP_LOOKUP_ATTRIBUTE
; Name of the attribute used to determine group membership,
; as described above.
llGroups
; GROUP_LOOKUP_ATTRIBUTE = ibm-a GROUP_LOOKUP_ATTRIBUTE = member
Now locate the file IBMLDAPSecurity.ini file in the current instance directory. Copy the above sample contents into the same.
Cp
//db2_ldap_pkg/IBMLDAPSecurity.ini
/home/db2inst2/sqllib/cfg/
Now you need to restart your DB2 instance, using two syntaxes given below:
db2inst2> db2stop
Db2inst2> db2start
At this point, if you try ‘db2start’ command, you will get security error message. Because, DB2 security configuration is not yet correctly configured for your LDAP environment.
Keep LDAP_HOST name handy, which is configured in slapd.conf file.
Now edit IMBLDAPSecurity.ini file and type the LDAP_HOST name. The LDAP_HOST name in both the said files must be identical.
The contents of file are as shown below:
;-----------------------------------------------------------
; SERVER RELATED VALUES
;-----------------------------------------------------------
LDAP_HOST = localhost
;-----------------------------------------------------------
; USER RELATED VALUES
----------------------------
;-------------------------------
USER_OBJECTCLASS = posixAccount
USER_BASEDN = dc=example,dc=com
USERID_ATTRIBUTE = uid
AUTHID_ATTRIBUTE = uid
;-----------------------------------------------------------
; GROUP RELATED VALUES
;-----------------------------------------------------------
GROUP_OBJECTCLASS = groupOfNames
GROUP_BASEDN = dc=example,dc=com
GROUPNAME_ATTRIBUTE = cn
GROUP_LOOKUP_METHOD = SEARCH_BY_DN
GROUP_LOOKUP_ATTRIBUTE = member
After changing these values, LDAP immediately takes effect and your DB2 environment with LDAP works perfectly.
You can logout and login again to ‘db2inst2’ user.
Now your instance is working with LDAP directory.
10 Lectures
1.5 hours
Nishant Malik
41 Lectures
8.5 hours
Parth Panjabi
53 Lectures
11.5 hours
Parth Panjabi
33 Lectures
7 hours
Parth Panjabi
44 Lectures
3 hours
Arnab Chakraborty
178 Lectures
14.5 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2021,
"s": 1928,
"text": "This chapter describes history of DB2, its versions, editions and their respective features."
},
{
"code": null,
"e": 2290,
"s": 2021,
"text": "DB2 is a database product from IBM. It is a Relational Database Management System (RDBMS). DB2 is designed to store, analyze and retrieve the data efficiently. DB2 product is extended with the support of Object-Oriented features and non-relational structures with XML."
},
{
"code": null,
"e": 2526,
"s": 2290,
"text": "Initially, IBM had developed DB2 product for their specific platform. Since year 1990, it decided to develop a Universal Database (UDB) DB2 Server, which can run on any authoritative operating systems such as Linux, UNIX, and Windows."
},
{
"code": null,
"e": 2694,
"s": 2526,
"text": "For IBM DB2, the UDB current version is 10.5 with the features of BLU Acceleration and its code name as 'Kepler'. All the versions of DB2 till today are listed below:"
},
{
"code": null,
"e": 2869,
"s": 2694,
"text": "Depending upon the requirement of needful features of DB2, the organizations select appropriate DB2 version. The following table shows DB2 server editions and their features:"
},
{
"code": null,
"e": 2926,
"s": 2869,
"text": "This chapter describes installation steps of DB2 server."
},
{
"code": null,
"e": 3343,
"s": 2926,
"text": "You can download the DB2 Server trial version or purchase the product license from www.ibm.com. There are two separate DB2 servers available for downloading, depending upon the size of operating system, on which it is intended to execute. For example, if you want to download a DB2 server for 32bit Linux or UNIX operating system, then you need to download a 32 bit DB2 server. The same applies for 64bit DB2 server."
},
{
"code": null,
"e": 3374,
"s": 3343,
"text": "Processor : Minimum Core 2Duo"
},
{
"code": null,
"e": 3393,
"s": 3374,
"text": "Ram : 1GB minimum"
},
{
"code": null,
"e": 3418,
"s": 3393,
"text": "Hard disk : 30GB minimum"
},
{
"code": null,
"e": 3564,
"s": 3418,
"text": "Before installing the DB2 server, your system needs to get ready with the required software on it. For Linux, you need to install “libstdc++6.0”."
},
{
"code": null,
"e": 3759,
"s": 3564,
"text": "Before installing DB2 Server, you need to verify if your system is compatible with the DB2 server. For confirming the compatibility, you need to call 'db2prereqcheck' command on command console."
},
{
"code": null,
"e": 3984,
"s": 3759,
"text": "Open the Terminal and set the db2 installation image folder path on console using “CD <DB2 installation folder>” command. Then type “./db2prereqcheck” command, which confirms the compatibility of your system with DB2 server."
},
{
"code": null,
"e": 4001,
"s": 3984,
"text": "./db2prereqcheck"
},
{
"code": null,
"e": 4094,
"s": 4001,
"text": "Figure-1 shows the compatibility requirements of Linux operating system and hardware system."
},
{
"code": null,
"e": 4158,
"s": 4094,
"text": "Follow the given steps for installing DB2 on your Linux system:"
},
{
"code": null,
"e": 4177,
"s": 4158,
"text": "Open the terminal."
},
{
"code": null,
"e": 4197,
"s": 4177,
"text": "Login as root user."
},
{
"code": null,
"e": 4227,
"s": 4197,
"text": "Open DB2 Installation folder."
},
{
"code": null,
"e": 4262,
"s": 4227,
"text": "Type “./db2setup” and press Enter."
},
{
"code": null,
"e": 4317,
"s": 4262,
"text": "This process will start execution of DB2 server setup."
},
{
"code": null,
"e": 4406,
"s": 4317,
"text": "Type “./db2setup” and press Enter on root terminal to start setup process of DB2 Server."
},
{
"code": null,
"e": 4470,
"s": 4406,
"text": "On doing so, the “Set up Launch Pad” screen appears. [Figure-2]"
},
{
"code": null,
"e": 4636,
"s": 4470,
"text": "On Setup Launch pad page, select “Install a Product” option from left side menu. Select option “DB2 Advanced Enterprise Server Edition”. Select “Install New” Button."
},
{
"code": null,
"e": 4711,
"s": 4636,
"text": "A new frame appears with name “DB2 setup wizard”. Click “Next”. [Figure-3]"
},
{
"code": null,
"e": 4819,
"s": 4711,
"text": "The next screen appears with DB2 license agreement. Select “I accept the terms...” Click “Next”. [Figure-4]"
},
{
"code": null,
"e": 4911,
"s": 4819,
"text": "Next screen comes up with offer of Installation type, which is set to “Typical” by default."
},
{
"code": null,
"e": 4961,
"s": 4911,
"text": "Keep the same selection. Click “Next”. [Figure-5]"
},
{
"code": null,
"e": 5011,
"s": 4961,
"text": "The next screen appears with installation action."
},
{
"code": null,
"e": 5070,
"s": 5011,
"text": "Select “Install DB2 Advanced Enterprise Server Edition...”"
},
{
"code": null,
"e": 5095,
"s": 5070,
"text": "Click “Next”. [Figure-6]"
},
{
"code": null,
"e": 5179,
"s": 5095,
"text": "On the next screen, the setup program asks for selection of installation directory."
},
{
"code": null,
"e": 5214,
"s": 5179,
"text": "Keep the default and click “Next”."
},
{
"code": null,
"e": 5309,
"s": 5214,
"text": "The next screen comes up with the user authentication. Enter your password for “dasusr1” user."
},
{
"code": null,
"e": 5392,
"s": 5309,
"text": "(Your password can be identical to username so that it is convenient to remember.)"
},
{
"code": null,
"e": 5473,
"s": 5392,
"text": "On the following screen, the setup asks you for creation of DB2 Server Instance."
},
{
"code": null,
"e": 5531,
"s": 5473,
"text": "Here, it is creating a DB2 instance with name “db2inst1”."
},
{
"code": null,
"e": 5620,
"s": 5531,
"text": "The next screen asks you the number of partitions you require for your default instance."
},
{
"code": null,
"e": 5674,
"s": 5620,
"text": "You have a choice of “single or Multiple” partitions."
},
{
"code": null,
"e": 5724,
"s": 5674,
"text": "Select “single partition instance”. Click “next”."
},
{
"code": null,
"e": 5814,
"s": 5724,
"text": "On the next screen, the setup asks you for authentication for DB2 instance being created."
},
{
"code": null,
"e": 5907,
"s": 5814,
"text": "Here, by default username is created as “db2inst1”. You can enter password same as username."
},
{
"code": null,
"e": 5921,
"s": 5907,
"text": "Click “Next”."
},
{
"code": null,
"e": 6012,
"s": 5921,
"text": "On the next screen, the setup asks to enter authentication information for “db2fenc” user."
},
{
"code": null,
"e": 6059,
"s": 6012,
"text": "Here, you can enter password same as username."
},
{
"code": null,
"e": 6073,
"s": 6059,
"text": "Click “Next”."
},
{
"code": null,
"e": 6182,
"s": 6073,
"text": "On the next screen, you can select “Do not setup your db2 server to send notifications at this time” option."
},
{
"code": null,
"e": 6196,
"s": 6182,
"text": "Click ”Next”."
},
{
"code": null,
"e": 6255,
"s": 6196,
"text": "The next screen shows you the information about db2 setup."
},
{
"code": null,
"e": 6271,
"s": 6255,
"text": "Click “Finish”."
},
{
"code": null,
"e": 6329,
"s": 6271,
"text": "The DB2 Installation procedure is complete at this stage."
},
{
"code": null,
"e": 6651,
"s": 6329,
"text": "You need to verify the installation of DB2 server for its usefulness. On completing the DB2 Server installation, logout from current user mode and login to “db2inst1” user. In “db2inst1” user environment, you can open terminal and execute the following commands to verify if your db2 product is installed properly or not."
},
{
"code": null,
"e": 6759,
"s": 6651,
"text": "This command shows the current version and service level of the installed DB2 product for current instance."
},
{
"code": null,
"e": 6767,
"s": 6759,
"text": "Syntax:"
},
{
"code": null,
"e": 6777,
"s": 6767,
"text": "db2level "
},
{
"code": null,
"e": 6786,
"s": 6777,
"text": "Example:"
},
{
"code": null,
"e": 6796,
"s": 6786,
"text": "db2level "
},
{
"code": null,
"e": 6804,
"s": 6796,
"text": "Output:"
},
{
"code": null,
"e": 7077,
"s": 6804,
"text": "DB21085I Instance \"db2inst2\" uses \"64\" bits \nAnd DB2 code release \"SQL10010\" with level \nidentifier \"0201010E\". Informational tokens \nare \"DB2 v10.1.0.0\", \"s120403\", \n\"LINUXAMD64101\", and Fix Pack \"0\". \nProduct is installed at \"/home/db2inst2/sqllib\". "
},
{
"code": null,
"e": 7152,
"s": 7077,
"text": "This command shows all the license related information of our DB2 Product."
},
{
"code": null,
"e": 7160,
"s": 7152,
"text": "Syntax:"
},
{
"code": null,
"e": 7181,
"s": 7160,
"text": "db2licm <parameter> "
},
{
"code": null,
"e": 7190,
"s": 7181,
"text": "Example:"
},
{
"code": null,
"e": 7202,
"s": 7190,
"text": "db2licm -l "
},
{
"code": null,
"e": 7210,
"s": 7202,
"text": "Output:"
},
{
"code": null,
"e": 7700,
"s": 7210,
"text": "Product name: \"DB2 Advanced Enterprise Server Edition\" \nLicense type: \"Trial\" \nExpiry date: \"10/02/2014\" \nProduct identifier: \"db2aese\" \nVersion information: \"10.1\" \nProduct name: \"DB2 Connect Server\" \nLicense type: \"Trial\" \nExpiry date: \"10/02/2014\" \nProduct identifier: \"db2consv\" \nVersion information: \"10.1\" "
},
{
"code": null,
"e": 7750,
"s": 7700,
"text": "The CLP can be started in one of the three modes:"
},
{
"code": null,
"e": 7887,
"s": 7750,
"text": "Command mode: In this mode, each command and SQL statement must be prefixed by “db2”. For example, query “db2 activate database sample”."
},
{
"code": null,
"e": 8024,
"s": 7887,
"text": "Command mode: In this mode, each command and SQL statement must be prefixed by “db2”. For example, query “db2 activate database sample”."
},
{
"code": null,
"e": 8192,
"s": 8024,
"text": "Interactive input mode: you can launch this mode by using the “db2” command. Here, you can pass SQL statements without prefix. For example, “activate database sample”."
},
{
"code": null,
"e": 8360,
"s": 8192,
"text": "Interactive input mode: you can launch this mode by using the “db2” command. Here, you can pass SQL statements without prefix. For example, “activate database sample”."
},
{
"code": null,
"e": 8573,
"s": 8360,
"text": "Batch mode: Here, you need to create a script file, which contains all SQL queries of requirements and save the file with “.db2” extension. You can call this in command line using syntax “db2 –tf <filename.db2>”."
},
{
"code": null,
"e": 8786,
"s": 8573,
"text": "Batch mode: Here, you need to create a script file, which contains all SQL queries of requirements and save the file with “.db2” extension. You can call this in command line using syntax “db2 –tf <filename.db2>”."
},
{
"code": null,
"e": 9022,
"s": 8786,
"text": "An Instance is a logical environment for DB2 Database Manager. Using instance, you can manage databases. Depending on our requirements, you can create multiple instances on one physical machine. The contents of Instance directory are:"
},
{
"code": null,
"e": 9058,
"s": 9022,
"text": "Database Manager Configuration file"
},
{
"code": null,
"e": 9084,
"s": 9058,
"text": "System Database Directory"
},
{
"code": null,
"e": 9099,
"s": 9084,
"text": "Node Directory"
},
{
"code": null,
"e": 9138,
"s": 9099,
"text": "Node Configuration File [db2nodes.cfg]"
},
{
"code": null,
"e": 9166,
"s": 9138,
"text": "Debugging files, dump files"
},
{
"code": null,
"e": 9480,
"s": 9166,
"text": "For DB2 Database Server, the default instance is “DB2”. It is not possible to change the location of Instance directory after its creation. An instance can manage multiple databases. In an instance, each database has a unique name, its own set of catalog tables, configurations files, authorities and privileges."
},
{
"code": null,
"e": 9628,
"s": 9480,
"text": "You can create multiple instances in one DB2Server on Linux, UNIX and Windows. It is possible to install multiple DB2Servers on a physical machine."
},
{
"code": null,
"e": 9862,
"s": 9628,
"text": "You can create multiple instances on Linux and UNIX if DB2 Server is installed as root user. An instance can run simultaneously on Linux and UNIX independently. You can work within a single instance of the database manager at a time."
},
{
"code": null,
"e": 10043,
"s": 9862,
"text": "An Instance folder contains database configuration files and folders. The Instance directory is stored at different locations on Windows depending on the operating system versions."
},
{
"code": null,
"e": 10092,
"s": 10043,
"text": "The following command is used to list instances:"
},
{
"code": null,
"e": 10161,
"s": 10092,
"text": "This command lists all the instances that are available on a system."
},
{
"code": null,
"e": 10169,
"s": 10161,
"text": "Syntax:"
},
{
"code": null,
"e": 10179,
"s": 10169,
"text": "db2ilist "
},
{
"code": null,
"e": 10239,
"s": 10179,
"text": "Example:[To see how many instances are created in DB2 copy]"
},
{
"code": null,
"e": 10249,
"s": 10239,
"text": "db2ilist "
},
{
"code": null,
"e": 10257,
"s": 10249,
"text": "Output:"
},
{
"code": null,
"e": 10288,
"s": 10257,
"text": "db2inst1 \ndb2inst2 \ndb2inst3 "
},
{
"code": null,
"e": 10367,
"s": 10288,
"text": "These commands are useful to work with arrangement of instance in the DB2 CLI."
},
{
"code": null,
"e": 10429,
"s": 10367,
"text": "This command shows details of the currently running instance."
},
{
"code": null,
"e": 10437,
"s": 10429,
"text": "Syntax:"
},
{
"code": null,
"e": 10455,
"s": 10437,
"text": "db2 get instance "
},
{
"code": null,
"e": 10526,
"s": 10455,
"text": "Example:[To see the current instance which activated the current user]"
},
{
"code": null,
"e": 10544,
"s": 10526,
"text": "db2 get instance "
},
{
"code": null,
"e": 10552,
"s": 10544,
"text": "Output:"
},
{
"code": null,
"e": 10605,
"s": 10552,
"text": "The current database manager instance is : db2inst1 "
},
{
"code": null,
"e": 10730,
"s": 10605,
"text": "To start or stop the database manager of an instance on DB2 UDB, the following command is executed for the current instance."
},
{
"code": null,
"e": 10740,
"s": 10732,
"text": "Syntax:"
},
{
"code": null,
"e": 10773,
"s": 10740,
"text": "set db2instance=<instance_name> "
},
{
"code": null,
"e": 10838,
"s": 10773,
"text": "Example:[ To arrange the “db2inst1” environment to current user]"
},
{
"code": null,
"e": 10863,
"s": 10838,
"text": "set db2instance=db2inst1"
},
{
"code": null,
"e": 10955,
"s": 10863,
"text": "Using this command, you can start an instance. Before this, you need to run “set instance”."
},
{
"code": null,
"e": 10963,
"s": 10955,
"text": "Syntax:"
},
{
"code": null,
"e": 10973,
"s": 10963,
"text": "db2start "
},
{
"code": null,
"e": 11004,
"s": 10973,
"text": "Example:[To start an instance]"
},
{
"code": null,
"e": 11013,
"s": 11004,
"text": "db2start"
},
{
"code": null,
"e": 11021,
"s": 11013,
"text": "Output:"
},
{
"code": null,
"e": 11065,
"s": 11021,
"text": "SQL1063N DB2START processing was successful"
},
{
"code": null,
"e": 11117,
"s": 11065,
"text": "Using this command you can stop a running instance."
},
{
"code": null,
"e": 11125,
"s": 11117,
"text": "Syntax:"
},
{
"code": null,
"e": 11134,
"s": 11125,
"text": "db2stop "
},
{
"code": null,
"e": 11142,
"s": 11134,
"text": "Output:"
},
{
"code": null,
"e": 11186,
"s": 11142,
"text": "SQL1064N DB2STOP processing was successful."
},
{
"code": null,
"e": 11227,
"s": 11186,
"text": "Let us see how to create a new instance."
},
{
"code": null,
"e": 11340,
"s": 11227,
"text": "If you want to create a new instance, you need to log in with root. Instance id is not a root id or a root name."
},
{
"code": null,
"e": 11385,
"s": 11340,
"text": "Here are the steps to create a new instance:"
},
{
"code": null,
"e": 11438,
"s": 11385,
"text": "Step1: Create an operating system user for instance."
},
{
"code": null,
"e": 11446,
"s": 11438,
"text": "Syntax:"
},
{
"code": null,
"e": 11529,
"s": 11446,
"text": "useradd -u <ID> -g <group name> -m -d <user location> <user name> \n-p <password> "
},
{
"code": null,
"e": 11635,
"s": 11529,
"text": "Example: [To create a user for instance with name ‘db2inst2’ in group ‘db2iadm1’ and password ‘db2inst2’]"
},
{
"code": null,
"e": 11707,
"s": 11635,
"text": "useradd -u 1000 -g db2iadm1 -m -d /home/db2inst2 db2inst2 -p db2inst2 "
},
{
"code": null,
"e": 11785,
"s": 11707,
"text": "Step2: Go to the DB2 instance directory in root user for create new instance."
},
{
"code": null,
"e": 11795,
"s": 11785,
"text": "Location:"
},
{
"code": null,
"e": 11828,
"s": 11795,
"text": "cd /opt/ibm/db2/v10.1/instance "
},
{
"code": null,
"e": 11875,
"s": 11828,
"text": "Step3: Create instance using the syntax below:"
},
{
"code": null,
"e": 11883,
"s": 11875,
"text": "Syntax:"
},
{
"code": null,
"e": 11929,
"s": 11883,
"text": "./db2icrt -s ese -u <inst id> <instance name>"
},
{
"code": null,
"e": 12050,
"s": 11929,
"text": "Example: [To create a new instance ‘db2inst2’ in user ‘db2inst2’ with the features of ‘ESE’ (Enterprise Server Edition)]"
},
{
"code": null,
"e": 12088,
"s": 12050,
"text": "./db2icrt -s ese -u db2inst2 db2inst2"
},
{
"code": null,
"e": 12096,
"s": 12088,
"text": "Output:"
},
{
"code": null,
"e": 12213,
"s": 12096,
"text": "DBI1446I The db2icrt command is running, please wait.\n ....\n ..... \nDBI1070I Program db2icrt completed successfully."
},
{
"code": null,
"e": 12384,
"s": 12213,
"text": "Edit the /etc/services file and add the port number. In the syntax given below, ‘inst_name’ indicates the Instance name and ‘inst_port’ indicates port number of instance."
},
{
"code": null,
"e": 12392,
"s": 12384,
"text": "Syntax:"
},
{
"code": null,
"e": 12425,
"s": 12392,
"text": "db2c_<inst name> <inst_port>/tcp"
},
{
"code": null,
"e": 12540,
"s": 12425,
"text": "Example: [Adding ‘50001/tcp’ port number for instance ‘db2inst2’ with variable ‘db2c_db2inst2’ in ‘services’ file]"
},
{
"code": null,
"e": 12564,
"s": 12540,
"text": "db2c_db2inst2 50001/tcp"
},
{
"code": null,
"e": 12745,
"s": 12564,
"text": "Syntax 1: [Update Database Manager Configuration with service name. The following syntax ‘svcename’ indicates the instance service name and ‘inst_name’ indicates the instance name]"
},
{
"code": null,
"e": 12820,
"s": 12745,
"text": "db2 update database manager configuration using svcename db2c_&<inst_name>"
},
{
"code": null,
"e": 12934,
"s": 12820,
"text": "Example 1: [Updating DBM Configuration with variable svcename with value ‘db2c_db2inst2’ for instance ‘db2inst2’ "
},
{
"code": null,
"e": 13006,
"s": 12934,
"text": "db2 update database manager configuration using svcename db2c_db2inst2 "
},
{
"code": null,
"e": 13013,
"s": 13006,
"text": "Output"
},
{
"code": null,
"e": 13096,
"s": 13013,
"text": "DB20000I The UPDATE DATABASE MANAGER CONFIGURATION command completed successfully."
},
{
"code": null,
"e": 13170,
"s": 13096,
"text": "Syntax 2: set the “tcpip” communication protocol for the current instance"
},
{
"code": null,
"e": 13192,
"s": 13170,
"text": "db2set DB2COMM=tcpip "
},
{
"code": null,
"e": 13301,
"s": 13192,
"text": "Syntax 3: [Stopping and starting current instance to get updated values from database manager configuration]"
},
{
"code": null,
"e": 13320,
"s": 13301,
"text": "db2stop \ndb2start "
},
{
"code": null,
"e": 13372,
"s": 13320,
"text": "You can update an instance using following command:"
},
{
"code": null,
"e": 13727,
"s": 13372,
"text": "This command is used to update the instance within the same version release. Before executing this command, you need to stop the instance database manager using “db2stop” command. The syntax below “inst_name” indicates the previous released or installed db2 server instance name, which you want to update to newer release or installed db2 server version."
},
{
"code": null,
"e": 13774,
"s": 13727,
"text": "Syntax 1: To update an instance in normal mode"
},
{
"code": null,
"e": 13796,
"s": 13774,
"text": "db2iupdt <inst_name> "
},
{
"code": null,
"e": 13806,
"s": 13796,
"text": "Example1:"
},
{
"code": null,
"e": 13827,
"s": 13806,
"text": "./db2iupdt db2inst2 "
},
{
"code": null,
"e": 13877,
"s": 13827,
"text": "Syntax 2: To update an instance in debugging mode"
},
{
"code": null,
"e": 13902,
"s": 13877,
"text": "db2iupdt -D <inst_name> "
},
{
"code": null,
"e": 13910,
"s": 13902,
"text": "Example"
},
{
"code": null,
"e": 13933,
"s": 13910,
"text": "db2iupdt -D db2inst2 "
},
{
"code": null,
"e": 14043,
"s": 13933,
"text": "You can upgrade an instance from previous version of DB2 copy to current newly installed version of DB2 copy."
},
{
"code": null,
"e": 14289,
"s": 14043,
"text": "On Linux or UNIX system, this command is located in DB2DIR/instance directory. In the following syntaxes, “inst_name” indicates the previous version DB2 instance and “inst_username” indicates the current installed version DB2 copy instance user."
},
{
"code": null,
"e": 14299,
"s": 14289,
"text": "Syntax 2:"
},
{
"code": null,
"e": 14350,
"s": 14299,
"text": "db2iupgrade -d -k -u <inst_username> <inst_name> "
},
{
"code": null,
"e": 14359,
"s": 14350,
"text": "Example:"
},
{
"code": null,
"e": 14399,
"s": 14359,
"text": "db2iupgrade -d -k -u db2inst2 db2inst2 "
},
{
"code": null,
"e": 14419,
"s": 14399,
"text": "Command Parameters:"
},
{
"code": null,
"e": 14449,
"s": 14419,
"text": "-d : Turns debugging mode on."
},
{
"code": null,
"e": 14567,
"s": 14449,
"text": "-k : Keeps the pre-upgrade instance type if it is supported in the DB2 copy, from where you are running this command."
},
{
"code": null,
"e": 14691,
"s": 14567,
"text": "If you are using the Super User (su) on Linux for db2iupgrade command, you must issue the “su” command with the “-” option."
},
{
"code": null,
"e": 14768,
"s": 14691,
"text": "You can drop or delete the instance, which was created by “db2icrt” command."
},
{
"code": null,
"e": 14879,
"s": 14768,
"text": "On Linux and UNIX operating system, this command is located in the DB2_installation_folder/instance directory."
},
{
"code": null,
"e": 15001,
"s": 14879,
"text": "Syntax: [in the following syntax, ‘inst_username’ indicates username of instance and ‘inst_name’ indicates instance name]"
},
{
"code": null,
"e": 15042,
"s": 15001,
"text": "db2idrop -u <inst_username> <inst_name> "
},
{
"code": null,
"e": 15070,
"s": 15042,
"text": "Example: [To drop db2inst2]"
},
{
"code": null,
"e": 15104,
"s": 15070,
"text": "./db2idrop -u db2inst2 db2inst2 "
},
{
"code": null,
"e": 15166,
"s": 15104,
"text": "Command to find out which DB2 instance we are working on now."
},
{
"code": null,
"e": 15239,
"s": 15166,
"text": "Syntax 1: [to check the current instance activated by database manager]"
},
{
"code": null,
"e": 15258,
"s": 15239,
"text": "db2 get instance "
},
{
"code": null,
"e": 15266,
"s": 15258,
"text": "Output:"
},
{
"code": null,
"e": 15320,
"s": 15266,
"text": "The current database manager instance is: db2inst1 "
},
{
"code": null,
"e": 15400,
"s": 15320,
"text": "Syntax 2: [To see the current instance with operating bits and release version]"
},
{
"code": null,
"e": 15424,
"s": 15400,
"text": "db2pd -inst | head -2 "
},
{
"code": null,
"e": 15433,
"s": 15424,
"text": "Example:"
},
{
"code": null,
"e": 15457,
"s": 15433,
"text": "db2pd -inst | head -2 "
},
{
"code": null,
"e": 15465,
"s": 15457,
"text": "Output:"
},
{
"code": null,
"e": 15529,
"s": 15465,
"text": "Instance db2inst1 uses 64 bits and DB2 code release SQL10010 "
},
{
"code": null,
"e": 15589,
"s": 15529,
"text": "Syntax 3: [To check the name of currently working instance]"
},
{
"code": null,
"e": 15643,
"s": 15589,
"text": "db2 select inst_name from sysibmadm.env_inst_info "
},
{
"code": null,
"e": 15652,
"s": 15643,
"text": "Example:"
},
{
"code": null,
"e": 15706,
"s": 15652,
"text": "db2 select inst_name from sysibmadm.env_inst_info "
},
{
"code": null,
"e": 15714,
"s": 15706,
"text": "Output:"
},
{
"code": null,
"e": 15813,
"s": 15714,
"text": "INST_NAME -------------------------------------- \ndb2inst1 \n1 record(s) selected. "
},
{
"code": null,
"e": 15856,
"s": 15813,
"text": "Syntax: [To set a new instance as default]"
},
{
"code": null,
"e": 15892,
"s": 15856,
"text": "db2set db2instdef=<inst_name> -g "
},
{
"code": null,
"e": 15957,
"s": 15892,
"text": "Example: [To array newly created instance as a default instance]"
},
{
"code": null,
"e": 15990,
"s": 15957,
"text": "db2set db2instdef=db2inst2 -g "
},
{
"code": null,
"e": 16093,
"s": 15990,
"text": "This chapter describes creating, activating and deactivating the databases with the associated syntax."
},
{
"code": null,
"e": 16250,
"s": 16093,
"text": "A database is a collection of Tables, Schemas, Bufferpools, Logs, Storage groups and Tablespaces working together to handle database operations efficiently."
},
{
"code": null,
"e": 16501,
"s": 16250,
"text": "Database directory is an organized repository of databases. When you create a database, all the details about database are stored in a database directory, such as details of default storage devices, configuration files, and temporary tables list etc."
},
{
"code": null,
"e": 16767,
"s": 16501,
"text": "Partition global directory is created in the instance folder. This directory contains all global information related to the database. This partition global directory is named as NODExxxx/SQLyyy, where xxxx is the data partition number and yyy is the database token."
},
{
"code": null,
"e": 17152,
"s": 16767,
"text": "In the partition-global directory, a member-specific directory is created. This directory contains local database information. The member-specific directory is named as MEMBERxxxx where xxxx is a member number. DB2 Enterprise Server Edition environment runs on a single member and has only one member specific directory. This member specific directory is uniquely named as MEMBER0000."
},
{
"code": null,
"e": 17199,
"s": 17152,
"text": "Directory Location : <instance>/NODExxx/SQLxxx"
},
{
"code": null,
"e": 17279,
"s": 17199,
"text": "The partition-global directory contains database related files as listed below."
},
{
"code": null,
"e": 17332,
"s": 17279,
"text": "Global deadlock write-to-file event monitoring files"
},
{
"code": null,
"e": 17385,
"s": 17332,
"text": "Table space information files [SQLSPCS.1, SQLSPCS.2]"
},
{
"code": null,
"e": 17434,
"s": 17385,
"text": "Storage group control files [SQLSGF.1, SQLSGF.2]"
},
{
"code": null,
"e": 17535,
"s": 17434,
"text": "Temporary table space container files. [/storage path//T0000011/C000000.TMP/SQL00002.MEMBER0001.TDA]"
},
{
"code": null,
"e": 17573,
"s": 17535,
"text": "Global Configuration file [SQLDBCONF]"
},
{
"code": null,
"e": 17644,
"s": 17573,
"text": "History files [DB2RHIST.ASC, DB2RHIST.BAK, DB2TSCHG.HIS, DB2TSCHG.HIS]"
},
{
"code": null,
"e": 17701,
"s": 17644,
"text": "Logging-related files [SQLOGCTL.GLFH.1, SQLOGCTL.GLFH.2]"
},
{
"code": null,
"e": 17736,
"s": 17701,
"text": "Locking files [SQLINSLK, SQLTMPLK]"
},
{
"code": null,
"e": 17765,
"s": 17736,
"text": "Automatic Storage containers"
},
{
"code": null,
"e": 17815,
"s": 17765,
"text": "Directory location : /NODExxxx/SQLxxxx/MEMBER0000"
},
{
"code": null,
"e": 17840,
"s": 17815,
"text": "This directory contains:"
},
{
"code": null,
"e": 17874,
"s": 17840,
"text": "Objects associated with databases"
},
{
"code": null,
"e": 17923,
"s": 17874,
"text": "Buffer pool information files [SQLBP.1, SQLBP.2]"
},
{
"code": null,
"e": 17952,
"s": 17923,
"text": "Local event monitoring files"
},
{
"code": null,
"e": 18022,
"s": 17952,
"text": "Logging-related files [SQLOGCTL.LFH.1, SQLOGCTL.LFH.2, SQLOGMIR.LFH]."
},
{
"code": null,
"e": 18048,
"s": 18022,
"text": "Local configuration files"
},
{
"code": null,
"e": 18231,
"s": 18048,
"text": "Deadlocks event monitor file. The detailed deadlock events monitor files are stored in the database directory of the catalog node in case of ESE and partitioned database environment."
},
{
"code": null,
"e": 18535,
"s": 18231,
"text": "You can create a database in instance using the “CREATE DATABASE” command. All databases are created with the default storage group “IBMSTOGROUP”, which is created at the time of creating an instance. In DB2, all the database tables are stored in “tablespace”, which use their respective storage groups."
},
{
"code": null,
"e": 18744,
"s": 18535,
"text": "The privileges for database are automatically set as PUBLIC [CREATETAB, BINDADD, CONNECT, IMPLICIT_SCHEMA, and SELECT], however, if the RESTRICTIVE option is present, the privileges are not granted as PUBLIC."
},
{
"code": null,
"e": 18803,
"s": 18744,
"text": "This command is used to create a non-restrictive database."
},
{
"code": null,
"e": 18912,
"s": 18803,
"text": "Syntax: [To create a new Database. ‘database_name’ indicates a new database name, which you want to create.]"
},
{
"code": null,
"e": 18948,
"s": 18912,
"text": "db2 create database <database name>"
},
{
"code": null,
"e": 19016,
"s": 18948,
"text": "Example: [To create a new non-restrictive database with name ‘one’]"
},
{
"code": null,
"e": 19040,
"s": 19016,
"text": "db2 create database one"
},
{
"code": null,
"e": 19048,
"s": 19040,
"text": "Output:"
},
{
"code": null,
"e": 19109,
"s": 19048,
"text": "DB20000I The CREATE DATABASE command completed successfully."
},
{
"code": null,
"e": 19167,
"s": 19109,
"text": "Restrictive database is created on invoking this command."
},
{
"code": null,
"e": 19237,
"s": 19167,
"text": "Syntax: [In the syntax below, “db_name” indicates the database name.]"
},
{
"code": null,
"e": 19280,
"s": 19237,
"text": "db2 create database <db_name> restrictive "
},
{
"code": null,
"e": 19348,
"s": 19280,
"text": "Example: [To create a new restrictive database with the name ‘two’]"
},
{
"code": null,
"e": 19385,
"s": 19348,
"text": "db2 create database two restrictive "
},
{
"code": null,
"e": 19702,
"s": 19385,
"text": "Create a database with default storage group “IBMSTOGROUP” on different path. Earlier, you invoked the command “create database” without any user-defined location to store or create database at a particular location. To create the database using user- defined database location, the following procedure is followed:"
},
{
"code": null,
"e": 19909,
"s": 19702,
"text": "Syntax: [In the syntax below, ‘db_name’ indicates the ‘database name’ and ‘data_location’ indicates where have to store data in folders and ‘db_path_location’ indicates driver location of ‘data_location’.]"
},
{
"code": null,
"e": 19995,
"s": 19909,
"text": "db2 create database '<db_name>' on '<data location>' dbpath on '<db_path_location>' "
},
{
"code": null,
"e": 20111,
"s": 19995,
"text": "Example: [To create database named ‘four’, where data is stored in ‘data1’ and this folder is stored in ‘dbpath1’]"
},
{
"code": null,
"e": 20169,
"s": 20111,
"text": "db2 create database four on '/data1' dbpath on '/dbpath1'"
},
{
"code": null,
"e": 20260,
"s": 20169,
"text": "You execute this command to see the list of directories available in the current instance."
},
{
"code": null,
"e": 20268,
"s": 20260,
"text": "Syntax:"
},
{
"code": null,
"e": 20297,
"s": 20268,
"text": "db2 list database directory "
},
{
"code": null,
"e": 20306,
"s": 20297,
"text": "Example:"
},
{
"code": null,
"e": 20335,
"s": 20306,
"text": "db2 list database directory "
},
{
"code": null,
"e": 20343,
"s": 20335,
"text": "Output:"
},
{
"code": null,
"e": 21297,
"s": 20343,
"text": " System Database Directory \n Number of entries in the directory = 6 \n Database 1 entry: \n Database alias = FOUR \n Database name = FOUR \n Local database directory = \n /home/db2inst4/Desktop/dbpath \n Database release level = f.00 \n Comment = \n Directory entry type = Indirect \n Catalog database partition number = 0 \n Alternate server hostname = \n Alternate server port number = \nDatabase 2 entry: \nDatabase alias = SIX \nDatabase name = SIX \nLocal database directory = /home/db2inst4 \nDatabase release level = f.00 \nComment = \nDirectory entry type = Indirect \nCatalog database partition number = 0 \nAlternate server hostname = \nAlternate server port number = "
},
{
"code": null,
"e": 21420,
"s": 21297,
"text": "This command starts up all necessary services for a particular database so that the database is available for application."
},
{
"code": null,
"e": 21463,
"s": 21420,
"text": "Syntax:[‘db_name’ indicates database name]"
},
{
"code": null,
"e": 21490,
"s": 21463,
"text": "db2 activate db <db_name> "
},
{
"code": null,
"e": 21531,
"s": 21490,
"text": "Example: [Activating the database ‘one’]"
},
{
"code": null,
"e": 21553,
"s": 21531,
"text": "db2 activate db one "
},
{
"code": null,
"e": 21609,
"s": 21553,
"text": "Using this command, you can stop the database services."
},
{
"code": null,
"e": 21617,
"s": 21609,
"text": "Syntax:"
},
{
"code": null,
"e": 21645,
"s": 21617,
"text": "db2 deactivate db <db_name>"
},
{
"code": null,
"e": 21685,
"s": 21645,
"text": "Example: [To Deactivate database ‘one’]"
},
{
"code": null,
"e": 21707,
"s": 21685,
"text": "db2 deactivate db one"
},
{
"code": null,
"e": 21793,
"s": 21707,
"text": "After creating a database, to put it into use, you need to connect or start database."
},
{
"code": null,
"e": 21801,
"s": 21793,
"text": "Syntax:"
},
{
"code": null,
"e": 21833,
"s": 21801,
"text": "db2 connect to <database name> "
},
{
"code": null,
"e": 21883,
"s": 21833,
"text": "Example: [To Connect Database one to current CLI]"
},
{
"code": null,
"e": 21903,
"s": 21883,
"text": "db2 connect to one "
},
{
"code": null,
"e": 21911,
"s": 21903,
"text": "Output:"
},
{
"code": null,
"e": 22065,
"s": 21911,
"text": " Database Connection Information \n Database server = DB2/LINUXX8664 10.1.0 \n SQL authorization ID = DB2INST4 \n Local database alias = ONE "
},
{
"code": null,
"e": 22134,
"s": 22065,
"text": "To check if this database is restrictive or not, here is the syntax:"
},
{
"code": null,
"e": 22259,
"s": 22134,
"text": "Syntax: [In the following syntax, ‘db’ indicates Database, ‘cfg’ indicates configuration, ‘db_name’ indicates database name]"
},
{
"code": null,
"e": 22308,
"s": 22259,
"text": "db2 get db cfg for <db_name> | grep -i restrict "
},
{
"code": null,
"e": 22367,
"s": 22308,
"text": "Example: [To check if ‘one’ database is restricted or not]"
},
{
"code": null,
"e": 22411,
"s": 22367,
"text": "db2 get db cfg for one | grep -i restrict "
},
{
"code": null,
"e": 22419,
"s": 22411,
"text": "Output:"
},
{
"code": null,
"e": 22465,
"s": 22419,
"text": "Restrict access = NO "
},
{
"code": null,
"e": 22792,
"s": 22465,
"text": "Instance configuration (Database manager configuration) is stored in a file named 'db2system' and the database related configuration is stored in a file named 'SQLDBCON'. These files cannot be edited directly. You can edit these files using tools which call API. Using the command line processor, you can use these commands."
},
{
"code": null,
"e": 22854,
"s": 22792,
"text": "Syntax: [To get the information of Instance Database manager]"
},
{
"code": null,
"e": 22896,
"s": 22854,
"text": "db2 get database manager configuration "
},
{
"code": null,
"e": 22915,
"s": 22896,
"text": "db2 get dbm cfg "
},
{
"code": null,
"e": 22961,
"s": 22915,
"text": "Syntax: [To update instance database manager]"
},
{
"code": null,
"e": 23006,
"s": 22961,
"text": "db2 update database manager configuration "
},
{
"code": null,
"e": 23027,
"s": 23006,
"text": "db2 update dbm cfg "
},
{
"code": null,
"e": 23070,
"s": 23027,
"text": "Syntax: [To reset previous configurations]"
},
{
"code": null,
"e": 23113,
"s": 23070,
"text": "db2 reset database manager configuration "
},
{
"code": null,
"e": 23133,
"s": 23113,
"text": "db2 reset dbm cfg "
},
{
"code": null,
"e": 23178,
"s": 23133,
"text": "Syntax: [To get the information of Database]"
},
{
"code": null,
"e": 23212,
"s": 23178,
"text": "db2 get database configuration "
},
{
"code": null,
"e": 23229,
"s": 23212,
"text": "db2 get db cfg "
},
{
"code": null,
"e": 23276,
"s": 23229,
"text": "Syntax: [To update the database configuration]"
},
{
"code": null,
"e": 23314,
"s": 23276,
"text": "db2 update database configuration "
},
{
"code": null,
"e": 23334,
"s": 23314,
"text": "db2 update db cfg "
},
{
"code": null,
"e": 23411,
"s": 23334,
"text": "Syntax: [To reset the previously configured values in database configuration"
},
{
"code": null,
"e": 23449,
"s": 23411,
"text": "db2 reset database configuration "
},
{
"code": null,
"e": 23469,
"s": 23449,
"text": "db2 reset db cfg "
},
{
"code": null,
"e": 23524,
"s": 23469,
"text": "Syntax: [To check the size of Current Active Database]"
},
{
"code": null,
"e": 23567,
"s": 23524,
"text": "db2 \"call get_dbsize_info(?,?,?,-1)\" "
},
{
"code": null,
"e": 23628,
"s": 23567,
"text": "Example: [To verify the size of Currently Activate Database]"
},
{
"code": null,
"e": 23671,
"s": 23628,
"text": "db2 \"call get_dbsize_info(?,?,?,-1)\" "
},
{
"code": null,
"e": 23679,
"s": 23671,
"text": "Output:"
},
{
"code": null,
"e": 23982,
"s": 23679,
"text": "Value of output parameters \n-------------------------- \nParameter Name : SNAPSHOTTIMESTAMP \nParameter Value : 2014-07-02-10.27.15.556775 \nParameter Name : DATABASESIZE \nParameter Value : 105795584 \nParameter Name : DATABASECAPACITY \nParameter Value : 396784705536 \nReturn Status = 0 "
},
{
"code": null,
"e": 24080,
"s": 23982,
"text": "To estimate the size of a database, the contribution of the following factors must be considered:"
},
{
"code": null,
"e": 24102,
"s": 24080,
"text": "System Catalog Tables"
},
{
"code": null,
"e": 24118,
"s": 24102,
"text": "User Table Data"
},
{
"code": null,
"e": 24134,
"s": 24118,
"text": "Long Field Data"
},
{
"code": null,
"e": 24158,
"s": 24134,
"text": "Large Object (LOB) Data"
},
{
"code": null,
"e": 24170,
"s": 24158,
"text": "Index Space"
},
{
"code": null,
"e": 24191,
"s": 24170,
"text": "Temporary Work Space"
},
{
"code": null,
"e": 24200,
"s": 24191,
"text": "XML data"
},
{
"code": null,
"e": 24215,
"s": 24200,
"text": "Log file space"
},
{
"code": null,
"e": 24240,
"s": 24215,
"text": "Local database directory"
},
{
"code": null,
"e": 24253,
"s": 24240,
"text": "System files"
},
{
"code": null,
"e": 24377,
"s": 24253,
"text": "You can use the following syntax to check which database authorities are granted to PUBLIC on the non-restrictive database."
},
{
"code": null,
"e": 24459,
"s": 24377,
"text": "Step 1: connect to database with authentication user-id and password of instance."
},
{
"code": null,
"e": 24519,
"s": 24459,
"text": "Syntax: [To connect to database with username and password]"
},
{
"code": null,
"e": 24581,
"s": 24519,
"text": "db2 connect to <db_name> user <userid> using <password> "
},
{
"code": null,
"e": 24670,
"s": 24581,
"text": "Example: [To Connect “one” Database with the user id ‘db2inst4’ and password ‘db2inst4’]"
},
{
"code": null,
"e": 24725,
"s": 24670,
"text": "db2 connect to one user db2inst4 using db2inst4 "
},
{
"code": null,
"e": 24733,
"s": 24725,
"text": "Output:"
},
{
"code": null,
"e": 24893,
"s": 24733,
"text": " Database Connection Information \n Database server = DB2/LINUXX8664 10.1.0 \n SQL authorization ID = DB2INST4 \n Local database alias = ONE "
},
{
"code": null,
"e": 24939,
"s": 24893,
"text": "Step2: To verify the authorities of database."
},
{
"code": null,
"e": 25026,
"s": 24939,
"text": "Syntax: [The syntax below shows the result of authority services for current database]"
},
{
"code": null,
"e": 25246,
"s": 25026,
"text": "db2 \"select substr(authority,1,25) as authority, d_user, d_group, \nd_public, role_user, role_group, role_public,d_role from table( \nsysproc.auth_list_authorities_for_authid ('public','g'))as t \norder by authority\" "
},
{
"code": null,
"e": 25255,
"s": 25246,
"text": "Example:"
},
{
"code": null,
"e": 25476,
"s": 25255,
"text": "db2 \"select substr(authority,1,25) as authority, d_user, d_group, \nd_public, role_user, role_group, role_public,d_role from table( \nsysproc.auth_list_authorities_for_authid ('PUBLIC','G'))as t \norder by authority\" "
},
{
"code": null,
"e": 25484,
"s": 25476,
"text": "Output:"
},
{
"code": null,
"e": 27534,
"s": 25484,
"text": "AUTHORITY D_USER D_GROUP D_PUBLIC ROLE_USER ROLE_GROUP ROLE_PUBLIC D_ROLE \n------------------------- ------ ------- -------- --------- ---------- ----------- ------ \nACCESSCTRL * * N * * N * \nBINDADD * * Y * * N * \nCONNECT * * Y * * N * \nCREATETAB * * Y * * N * \nCREATE_EXTERNAL_ROUTINE * * N * * N * \nCREATE_NOT_FENCED_ROUTINE * * N * * N * \nCREATE_SECURE_OBJECT * * N * * N * \nDATAACCESS * * N * * N * \nDBADM * * N * * N * \nEXPLAIN * * N * * N * \nIMPLICIT_SCHEMA * * Y * * N * \nLOAD * * N * * N * \nQUIESCE_CONNECT * * N * * N * \nSECADM * * N * * N * \nSQLADM * * N * * N * \nSYSADM * * * * * * * \nSYSCTRL * * * * * * * \nSYSMAINT * * * * * * * \nSYSMON * * * * * * * \nWLMADM * * N * * N * \n20 record(s) selected. "
},
{
"code": null,
"e": 27709,
"s": 27534,
"text": "Using the Drop command, you can remove our database from instance database directory. This command can delete all its objects, table, spaces, containers and associated files."
},
{
"code": null,
"e": 27757,
"s": 27709,
"text": "Syntax: [To drop any database from an instance]"
},
{
"code": null,
"e": 27785,
"s": 27757,
"text": "db2 drop database <db_name>"
},
{
"code": null,
"e": 27833,
"s": 27785,
"text": "Example: [To drop ‘six’ database from instance]"
},
{
"code": null,
"e": 27857,
"s": 27833,
"text": "db2 drop database six "
},
{
"code": null,
"e": 27865,
"s": 27857,
"text": "Output:"
},
{
"code": null,
"e": 27924,
"s": 27865,
"text": "DB20000I The DROP DATABASE command completed successfully "
},
{
"code": null,
"e": 27984,
"s": 27924,
"text": "This chapter introduces you to Bufferpools in the database."
},
{
"code": null,
"e": 28801,
"s": 27984,
"text": "The bufferpool is portion of a main memory space which is allocated by the database manager. The purpose of bufferpools is to cache table and index data from disk. All databases have their own bufferpools. A default bufferpool is created at the time of creation of new database. It called as “IBMDEFAULTBP”. Depending on the user requirements, it is possible to create a number of bufferpools. In the bufferpool, the database manager places the table row data as a page. This page stays in the bufferpool until the database is shutdown or until the space is written with new data. The pages in the bufferpool, which are updated with data but are not written onto the disk, are called “Dirty” pages. After the updated data pages in the bufferpool are written on the disk, the bufferpool is ready to take another data."
},
{
"code": null,
"e": 29090,
"s": 28801,
"text": "Each table space is associated with a specific buffer pool in a database. One tablespace is associated with one bufferpool. The size of bufferpool and tablespace must be same. Multiple bufferpools allow you to configure the memory used by the database to increase its overall performance."
},
{
"code": null,
"e": 29337,
"s": 29090,
"text": "The size of the bufferpool page is set when you use the “CREATE DATABASE” command. If you do not specify the page size, it will take default page size, which is 4KB. Once the bufferpool is created, it is not possible to modify the page size later"
},
{
"code": null,
"e": 29408,
"s": 29337,
"text": "Syntax: [The syntax below shows all available bufferpools in database]"
},
{
"code": null,
"e": 29448,
"s": 29408,
"text": "db2 select * from syscat.bufferpools "
},
{
"code": null,
"e": 29508,
"s": 29448,
"text": "Example: [To see available bufferpools in current database]"
},
{
"code": null,
"e": 29547,
"s": 29508,
"text": "db2 select * from syscat.bufferpools "
},
{
"code": null,
"e": 29555,
"s": 29547,
"text": "Output:"
},
{
"code": null,
"e": 30030,
"s": 29555,
"text": "BPNAME BUFFERPOOLID DBPGNAME NPAGES PAGESIZE ESTORE \nNUMBLOCKPAGES BLOCKSIZE NGNAME\n------------------------------------------------------------ \nIBMDEFAULTBP \n 1 - \n -2 4096 N 0 0 - \n \n 1 record(s) selected. "
},
{
"code": null,
"e": 30209,
"s": 30030,
"text": "To create a new bufferpool for database server, you need two parameters namely, “bufferpool name” and “size of page”. The following query is executed to create a new bufferpool."
},
{
"code": null,
"e": 30362,
"s": 30209,
"text": "Syntax: [In the syntax below,‘bp_name’ indicates bufferpool name and ‘size’ indicates size for page you need to declare for bufferpools (4K,8K,16K,32K)]"
},
{
"code": null,
"e": 30411,
"s": 30362,
"text": "db2 create bufferpool <bp_name> pagesize <size> "
},
{
"code": null,
"e": 30489,
"s": 30411,
"text": "Example: [To create a new bufferpool with name “bpnew” and size “8192”(8Kb).]"
},
{
"code": null,
"e": 30533,
"s": 30489,
"text": "db2 create bufferpool bpnew pagesize 8192 "
},
{
"code": null,
"e": 30540,
"s": 30533,
"text": "Output"
},
{
"code": null,
"e": 30591,
"s": 30540,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 30684,
"s": 30591,
"text": "Before dropping the bufferpool, it is required to check if any tablespace is assigned to it."
},
{
"code": null,
"e": 30717,
"s": 30684,
"text": "Syntax: [To drop the bufferpool]"
},
{
"code": null,
"e": 30745,
"s": 30717,
"text": "drop bufferpool <bp_name> "
},
{
"code": null,
"e": 30789,
"s": 30745,
"text": "Example: [To drop ‘bpnew’ named bufferpool]"
},
{
"code": null,
"e": 30817,
"s": 30789,
"text": "db2 drop bufferpool bpnew "
},
{
"code": null,
"e": 30824,
"s": 30817,
"text": "Output"
},
{
"code": null,
"e": 30875,
"s": 30824,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 30924,
"s": 30875,
"text": "This chapter describes the tablespaces in detail"
},
{
"code": null,
"e": 31204,
"s": 30924,
"text": "A table space is a storage structure, it contains tables, indexes, large objects, and long data. It can be used to organize data in a database into logical storage group which is related with where data stored on a system. This tablespaces are stored in database partition groups"
},
{
"code": null,
"e": 31282,
"s": 31204,
"text": "The table spaces are beneficial in database in various ways given as follows:"
},
{
"code": null,
"e": 31458,
"s": 31282,
"text": "Recoverability: Tablespaces make backup and restore operations more convenient. Using a single command, you can make backup or restore all the database objects in tablespaces."
},
{
"code": null,
"e": 31560,
"s": 31458,
"text": "Automatic storage Management: Database manager creates and extends containers depending on the needs."
},
{
"code": null,
"e": 31760,
"s": 31560,
"text": "Memory utilization: A single bufferpool can manage multiple tablespaces. You can assign temporary tablespaces to their own bufferpool to increase the performance of activities such as sorts or joins."
},
{
"code": null,
"e": 32253,
"s": 31760,
"text": "Tablespaces contains one or more containers. A container can be a directory name, a device name, or a filename. In a database, a single tablespace can have several containers on the same physical storage device. If the tablespace is created with automatic storage tablespace option, the creation and management of containers is handled automatically by the database manager. If it is not created with automatic storage tablespace option, you need to define and manage the containers yourself."
},
{
"code": null,
"e": 32489,
"s": 32253,
"text": "When you create a new database, the database manager creates some default tablespaces for database. These tablespace is used as a storage for user and temporary data. Each database must contain at least three tablespaces as given here:"
},
{
"code": null,
"e": 32547,
"s": 32489,
"text": "\nCatalog tablespace\nUser tablespace\nTemporary tablespace\n"
},
{
"code": null,
"e": 32566,
"s": 32547,
"text": "Catalog tablespace"
},
{
"code": null,
"e": 32582,
"s": 32566,
"text": "User tablespace"
},
{
"code": null,
"e": 32603,
"s": 32582,
"text": "Temporary tablespace"
},
{
"code": null,
"e": 32728,
"s": 32603,
"text": "Catalog tablespace: It contains system catalog tables for the database. It is named as SYSCATSPACE and it cannot be dropped."
},
{
"code": null,
"e": 33016,
"s": 32728,
"text": "User tablespace: This tablespace contains user-defined tables. In a database, we have one default user tablespace, named as USERSPACE1. If you do not specify user-defined tablespace for a table at the time you create it, then the database manager chooses default user tablespace for you."
},
{
"code": null,
"e": 33176,
"s": 33016,
"text": "Temporary tablespace: A temporary tablespace contains temporary table data. This tablespace contains system temporary tablespaces or user temporary tablespace."
},
{
"code": null,
"e": 33694,
"s": 33176,
"text": "System temporary tablespace holds temporary data required by the database manager while performing operation such as sorts or joins. A database must have at least one system temporary tablespace and it is named as TEMPSPACE1. It is created at the time of creating the database. User temporary tablespace holds temporary data from tables. It is created with DECLARE GLOBAL TEMPORARY TABLE or CREATE GLOBAL TEMPORARY TABLE statement. This temporary tablespace is not created by default at the time of database creation."
},
{
"code": null,
"e": 33730,
"s": 33694,
"text": "Tablespaces and storage management:"
},
{
"code": null,
"e": 33997,
"s": 33730,
"text": "Tablespaces can be setup in different ways, depending on how you want to use them. You can setup the operating system to manage tablespace allocation, you can let the database manager allocate space or you can choose automatic allocation of tablespace for your data."
},
{
"code": null,
"e": 34056,
"s": 33997,
"text": "The following three types of managed spaces are available:"
},
{
"code": null,
"e": 34435,
"s": 34056,
"text": "System Managed Space (SMS): The operating system’s file system manager allocates and manages the space where the table is stored. Storage space is allocated on demand. This model consists of files representing database objects. This tablespace type has been deprecated in Version 10.1 for user-defined tablespaces, and it is not deprecated for catalog and temporary tablespaces."
},
{
"code": null,
"e": 34797,
"s": 34435,
"text": "Database Managed Space (DMS): The Database Server controls the storage space. Storage space is pre- allocated on the file system based on container definition that you specify when you create the DMS table space. It is deprecated from version 10.1 fix pack 1 for user-defined tablespaces, but it is not deprecated for system tablespace and temporary tablespace."
},
{
"code": null,
"e": 35390,
"s": 34797,
"text": "Automatic Storage Tablespace: Database server can be managed automatically. Database server creates and extends containers depend on data on database. With automatic storage management, it is not required to provide container definitions. The database server looks after creating and extending containers to make use of the storage allocated to the database. If you add storage space to a storage group, new containers are automatically created when the existing container reach their maximum capacity. If you want to use the newly-added storage immediately, you can rebalance the tablespace."
},
{
"code": null,
"e": 35423,
"s": 35390,
"text": "Page, table and tablespace size:"
},
{
"code": null,
"e": 35725,
"s": 35423,
"text": "Temporary DMS and automatic storage tablespaces, the page size you choose for your database determines the maximum limit for the tablespace size. For table SMS and temporary automatic storage tablespaces, the page size constrains the size of table itself. The page sizes can be 4kb, 8kb, 16kb or 32kb."
},
{
"code": null,
"e": 35776,
"s": 35725,
"text": "This chapter describes the Database Storagegroups."
},
{
"code": null,
"e": 36258,
"s": 35776,
"text": "A set of Storage paths to store database table or objects, is a storage group. You can assign the tablespaces to the storage group. When you create a database, all the tablespaces take default storagegorup. The default storage group for a database is ‘IBMSTOGROUP’. When you create a new database, the default storage group is active, if you pass the “AUTOMATIC STOGROUP NO” parameter at the end of “CREATE DATABASE” command. The database does not have any default storage groups."
},
{
"code": null,
"e": 36310,
"s": 36258,
"text": "You can list all the storagegroups in the database."
},
{
"code": null,
"e": 36383,
"s": 36310,
"text": "Syntax: [To see the list of available storagegroups in current database]"
},
{
"code": null,
"e": 36418,
"s": 36383,
"text": "db2 select * from syscat.stogroups"
},
{
"code": null,
"e": 36492,
"s": 36418,
"text": "Example: [To see the list of available storagegorups in current database]"
},
{
"code": null,
"e": 36527,
"s": 36492,
"text": "db2 select * from syscat.stogroups"
},
{
"code": null,
"e": 36586,
"s": 36527,
"text": "Here is a syntax to create a storagegroup in the database:"
},
{
"code": null,
"e": 36743,
"s": 36586,
"text": "Syntax: [To create a new stogroup. The ‘stogropu_name’ indicates name of new storage group and ‘path’ indicates the location where data (tables) are stored]"
},
{
"code": null,
"e": 36774,
"s": 36743,
"text": "db2 create stogroup on ‘path’"
},
{
"code": null,
"e": 36844,
"s": 36774,
"text": "Example: [To create a new stogroup ‘stg1’ on the path ‘data1’ folder]"
},
{
"code": null,
"e": 36881,
"s": 36844,
"text": "db2 create stogroup stg1 on ‘/data1’"
},
{
"code": null,
"e": 36889,
"s": 36881,
"text": "Output:"
},
{
"code": null,
"e": 36937,
"s": 36889,
"text": "DB20000I The SQL command completed succesfully "
},
{
"code": null,
"e": 36994,
"s": 36937,
"text": "Here is how you can create a tablespace with storegroup:"
},
{
"code": null,
"e": 37059,
"s": 36994,
"text": "Syntax: [To create a new tablespace using existed storage group]"
},
{
"code": null,
"e": 37132,
"s": 37059,
"text": "db2 create tablespace <tablespace_name> using stogroup <stogroup_name> "
},
{
"code": null,
"e": 37217,
"s": 37132,
"text": "Example: [To create a new tablespace named ‘ts1’ using existed storage group ‘stg1’]"
},
{
"code": null,
"e": 37264,
"s": 37217,
"text": "db2 create tablespace ts1 using stogroup stg1 "
},
{
"code": null,
"e": 37272,
"s": 37264,
"text": "Output:"
},
{
"code": null,
"e": 37320,
"s": 37272,
"text": "DB20000I The SQL command completed succesfully "
},
{
"code": null,
"e": 37390,
"s": 37320,
"text": "You can alter the location of a storegroup by using following syntax:"
},
{
"code": null,
"e": 37459,
"s": 37390,
"text": "Syntax: [To shift a storage group from old location to new location]"
},
{
"code": null,
"e": 37507,
"s": 37459,
"text": "db2 alter stogroup add ‘location’, ‘location’ "
},
{
"code": null,
"e": 37606,
"s": 37507,
"text": "Example: [To modify location path from old location to new location for storage group named ‘sg1’]"
},
{
"code": null,
"e": 37663,
"s": 37606,
"text": "db2 alter stogroup sg1 add ‘/path/data3’, ‘/path/data4’ "
},
{
"code": null,
"e": 37778,
"s": 37663,
"text": "Before dropping folder path of storagegroup, you can add new location for the storagegroup by using alter command."
},
{
"code": null,
"e": 37833,
"s": 37778,
"text": "Syntax: [To drop old path from storage group location]"
},
{
"code": null,
"e": 37867,
"s": 37833,
"text": "db2 alter stogroup drop ‘/path’ "
},
{
"code": null,
"e": 37921,
"s": 37867,
"text": "Example: [To drop storage group location from ‘stg1’]"
},
{
"code": null,
"e": 37966,
"s": 37921,
"text": "db2 alter stogroup stg1 drop ‘/path/data1’ "
},
{
"code": null,
"e": 38223,
"s": 37966,
"text": "Rebalancing the tablespace is required when we create a new folder for storagegroup or tablespaces while the transactions are conducted on the database and the tablespace becomes full. Rebalancing updates database configuration files with new storagegroup."
},
{
"code": null,
"e": 38310,
"s": 38223,
"text": "Syntax: [To rebalance the tablespace from old storage group path to new storage group]"
},
{
"code": null,
"e": 38353,
"s": 38310,
"text": "db2 alter tablspace <ts_name> rebalance "
},
{
"code": null,
"e": 38377,
"s": 38353,
"text": "Example: [To rebalance]"
},
{
"code": null,
"e": 38415,
"s": 38377,
"text": "db2 alter tablespace ts1 rebalance "
},
{
"code": null,
"e": 38469,
"s": 38415,
"text": "Syntax: [To modify the name of existing storage name]"
},
{
"code": null,
"e": 38525,
"s": 38469,
"text": "db2 rename stogroup <old_stg_name> to <new_stg_name> "
},
{
"code": null,
"e": 38605,
"s": 38525,
"text": "Example: [To modify the name of storage group from ‘sg1’ to new name ‘sgroup1’]"
},
{
"code": null,
"e": 38643,
"s": 38605,
"text": "db2 rename stogroup sg1 to sgroup1 "
},
{
"code": null,
"e": 38745,
"s": 38643,
"text": "Step 1: Before dropping any storagegroup, you can assign some different storagegroup for tablespaces."
},
{
"code": null,
"e": 38803,
"s": 38745,
"text": "Syntax: [To assign another storagegroup for table space.]"
},
{
"code": null,
"e": 38877,
"s": 38803,
"text": "db2 alter tablspace <ts_name> using stogroup <another sto_group_name> "
},
{
"code": null,
"e": 38969,
"s": 38877,
"text": "Example: [To change from one old stogroup to new stogroup named ‘sg2’ for tablespace ‘ts1’]"
},
{
"code": null,
"e": 39016,
"s": 38969,
"text": "db2 alter tablespace ts1 using stogroup sg2 "
},
{
"code": null,
"e": 39024,
"s": 39016,
"text": "Step 2:"
},
{
"code": null,
"e": 39064,
"s": 39024,
"text": "Syntax: [To drop the existing stogroup]"
},
{
"code": null,
"e": 39101,
"s": 39064,
"text": "db2 drop stogorup <stogroup_name> "
},
{
"code": null,
"e": 39150,
"s": 39101,
"text": "Example: [To drop stogroup ‘stg1’ from database]"
},
{
"code": null,
"e": 39175,
"s": 39150,
"text": "db2 drop stogroup stg1 "
},
{
"code": null,
"e": 39236,
"s": 39175,
"text": "This chapter introduces and describes the concept of Schema."
},
{
"code": null,
"e": 39316,
"s": 39236,
"text": "A schema is a collection of named objects classified logically in the database."
},
{
"code": null,
"e": 39579,
"s": 39316,
"text": "In a database, you cannot create multiple database objects with same name. To do so, the schema provides a group environment. You can create multiple schemas in a database and you can create multiple database objects with same name, with different schema groups."
},
{
"code": null,
"e": 40225,
"s": 39579,
"text": "A schema can contain tables, functions, indices, tablespaces, procedures, triggers etc. For example, you create two different schemas named as “Professional” and “Personal” for an “employee” database. It is possible to make two different tables with the same name “Employee”. In this environment, one table has professional information and the other has personal information of employee. In spite of having two tables with the same name, they have two different schemas “Personal” and “Professional”. Hence, the user can work with both without encountering any problem. This feature is useful when there are constraints on the naming of tables."
},
{
"code": null,
"e": 40268,
"s": 40225,
"text": "Let us see few commands related to Schema:"
},
{
"code": null,
"e": 40276,
"s": 40268,
"text": "Syntax:"
},
{
"code": null,
"e": 40293,
"s": 40276,
"text": "db2 get schema "
},
{
"code": null,
"e": 40335,
"s": 40293,
"text": "Example: [To get current database schema]"
},
{
"code": null,
"e": 40353,
"s": 40335,
"text": "db2 get schema "
},
{
"code": null,
"e": 40361,
"s": 40353,
"text": "Syntax:"
},
{
"code": null,
"e": 40392,
"s": 40361,
"text": "db2 set schema=<schema_name> "
},
{
"code": null,
"e": 40456,
"s": 40392,
"text": "Example: [To arrange ‘schema1’ to current instance environment]"
},
{
"code": null,
"e": 40480,
"s": 40456,
"text": "db2 set schema=schema1 "
},
{
"code": null,
"e": 40537,
"s": 40480,
"text": "Syntax: [To create a new schema with authorized user id]"
},
{
"code": null,
"e": 40596,
"s": 40537,
"text": "db2 create schema <schema_name> authroization <inst_user> "
},
{
"code": null,
"e": 40661,
"s": 40596,
"text": "Example: [To create “schema1” schema authorized with ‘db2inst2”]"
},
{
"code": null,
"e": 40711,
"s": 40661,
"text": "db2 create schema schema1 authorization db2inst2 "
},
{
"code": null,
"e": 40909,
"s": 40711,
"text": "Let us create two different tables with same name but two different schemas. Here, you create employee table with two different schemas, one for personal and the other for professional information."
},
{
"code": null,
"e": 40937,
"s": 40909,
"text": "Step 1: Create two schemas."
},
{
"code": null,
"e": 40985,
"s": 40937,
"text": "Schema 1: [To create schema named professional]"
},
{
"code": null,
"e": 41040,
"s": 40985,
"text": "db2 create schema professional authorization db2inst2 "
},
{
"code": null,
"e": 41084,
"s": 41040,
"text": "Schema 2: [To create schema named personal]"
},
{
"code": null,
"e": 41134,
"s": 41084,
"text": "db2 create schema personal authorization db2inst2"
},
{
"code": null,
"e": 41200,
"s": 41134,
"text": "Step 2: Create two tables with the same name for Employee details"
},
{
"code": null,
"e": 41230,
"s": 41200,
"text": "Table1: professional.employee"
},
{
"code": null,
"e": 41314,
"s": 41230,
"text": "[To create a new table ‘employee’ in the database using schema name ‘professional’]"
},
{
"code": null,
"e": 41441,
"s": 41314,
"text": "db2 create table professional.employee(id number, name \nvarchar(20), profession varchar(20), join_date date, \nsalary number); "
},
{
"code": null,
"e": 41467,
"s": 41441,
"text": "Table2: personal.employee"
},
{
"code": null,
"e": 41552,
"s": 41467,
"text": "[To create a new table ‘employee’ in the same database, with schema name ‘personal’]"
},
{
"code": null,
"e": 41671,
"s": 41552,
"text": "db2 create table personal.employee(id number, name \nvarchar(20), d_birth date, phone bigint, address \nvarchar(200)); "
},
{
"code": null,
"e": 41774,
"s": 41671,
"text": "After executing these steps, you get two tables with same name ’employee’, with two different schemas."
},
{
"code": null,
"e": 41830,
"s": 41774,
"text": "This chapter introduces various data types used in DB2."
},
{
"code": null,
"e": 42007,
"s": 41830,
"text": "In DB2 Database tables, each column has its own data type depending on developer’s requirements. The data type is said to be type and range of the values in columns of a table."
},
{
"code": null,
"e": 42311,
"s": 42007,
"text": "Datetime\n\nTIME: It represents the time of the day in hours, minutes and seconds.\nTIMESTAMP: It represents seven values of the date and time in the form of year, month, day, hours, minutes, seconds and microseconds.\nDATE: It represents date of the day in three parts in the form of year, month and day.\n\n"
},
{
"code": null,
"e": 42382,
"s": 42311,
"text": "TIME: It represents the time of the day in hours, minutes and seconds."
},
{
"code": null,
"e": 42516,
"s": 42382,
"text": "TIMESTAMP: It represents seven values of the date and time in the form of year, month, day, hours, minutes, seconds and microseconds."
},
{
"code": null,
"e": 42603,
"s": 42516,
"text": "DATE: It represents date of the day in three parts in the form of year, month and day."
},
{
"code": null,
"e": 42623,
"s": 42603,
"text": "String\n\nCharacter\n\n"
},
{
"code": null,
"e": 42633,
"s": 42623,
"text": "Character"
},
{
"code": null,
"e": 42707,
"s": 42633,
"text": "CHAR (fixed length): Fixed length of Character strings.\n\nVarying length\n\n"
},
{
"code": null,
"e": 42722,
"s": 42707,
"text": "Varying length"
},
{
"code": null,
"e": 42765,
"s": 42722,
"text": "VARCHAR: Varying length character strings."
},
{
"code": null,
"e": 42891,
"s": 42765,
"text": "CLOB: large object strings, you use this when a character string might exceed the limits of the VARCHAR data type.\n\nGraphic\n\n"
},
{
"code": null,
"e": 42899,
"s": 42891,
"text": "Graphic"
},
{
"code": null,
"e": 43005,
"s": 42899,
"text": "GRAPHIC\n\nFixed length: Fixed length graphic strings that contains double-byte characters\nVarying length\n\n"
},
{
"code": null,
"e": 43085,
"s": 43005,
"text": "Fixed length: Fixed length graphic strings that contains double-byte characters"
},
{
"code": null,
"e": 43100,
"s": 43085,
"text": "Varying length"
},
{
"code": null,
"e": 43182,
"s": 43100,
"text": "VARGRAPHIC: Varying character graphic string that contains double bye characters."
},
{
"code": null,
"e": 43218,
"s": 43182,
"text": "DBCLOB: large object type\n\nBinary\n\n"
},
{
"code": null,
"e": 43225,
"s": 43218,
"text": "Binary"
},
{
"code": null,
"e": 43278,
"s": 43225,
"text": "BLOB (varying length): binary string in large object"
},
{
"code": null,
"e": 43311,
"s": 43278,
"text": "BOOLEAN: In the form of 0 and 1."
},
{
"code": null,
"e": 43335,
"s": 43311,
"text": "Signed numeric\n\nExact\n\n"
},
{
"code": null,
"e": 43341,
"s": 43335,
"text": "Exact"
},
{
"code": null,
"e": 43580,
"s": 43341,
"text": "Binary integer\n\nSMALLINT [16BIT]: Using this you can insert small int values into columns\nINTEGER [32BIT]: Using this you can insert large int values into columns\nBIGINT [64BIT]: Using this you can insert larger int values into columns \n\n"
},
{
"code": null,
"e": 43654,
"s": 43580,
"text": "SMALLINT [16BIT]: Using this you can insert small int values into columns"
},
{
"code": null,
"e": 43727,
"s": 43654,
"text": "INTEGER [32BIT]: Using this you can insert large int values into columns"
},
{
"code": null,
"e": 43801,
"s": 43727,
"text": "BIGINT [64BIT]: Using this you can insert larger int values into columns "
},
{
"code": null,
"e": 43934,
"s": 43801,
"text": "Decimal\n\nDECIMAL (packed)\nDECFLOAT (decimal floating point): Using this, you can insert decimal floating point numbers\nApproximate\n\n"
},
{
"code": null,
"e": 43951,
"s": 43934,
"text": "DECIMAL (packed)"
},
{
"code": null,
"e": 44044,
"s": 43951,
"text": "DECFLOAT (decimal floating point): Using this, you can insert decimal floating point numbers"
},
{
"code": null,
"e": 44056,
"s": 44044,
"text": "Approximate"
},
{
"code": null,
"e": 44283,
"s": 44056,
"text": "Floating points\n\nREAL (single precision): Using this data type, you can insert single precision floating point numbers.\nDOUBLE (double precision): Using this data type, you can insert double precision floating point numbers.\n\n"
},
{
"code": null,
"e": 44386,
"s": 44283,
"text": "REAL (single precision): Using this data type, you can insert single precision floating point numbers."
},
{
"code": null,
"e": 44491,
"s": 44386,
"text": "DOUBLE (double precision): Using this data type, you can insert double precision floating point numbers."
},
{
"code": null,
"e": 44578,
"s": 44491,
"text": "eXtensible Mark-up Language\n\nXML: You can store XML data into this data type column.\n\n"
},
{
"code": null,
"e": 44634,
"s": 44578,
"text": "XML: You can store XML data into this data type column."
},
{
"code": null,
"e": 44974,
"s": 44634,
"text": "Tables are logical structure maintained by Database manager. In a table each vertical block called as column (Tuple) and each horizontal block called as row (Entity). The collection of data stored in the form of columns and rows is known as a table. In tables, each column has different data type. Tables are used to store persistent data."
},
{
"code": null,
"e": 46360,
"s": 44974,
"text": "Base Tables: They hold persistent data. There are different kinds of base tables, including:\n\nRegular Tables: General purpose tables, Common tables with indexes are general purpose tables.\nMultidimensional Clustering Table (MDC): This type of table physically clustered on more than one key, and it used to maintain large database environments. These type of tables are not supported in DB2 pureScale.\nInsert time clustering Table (ITC): Similar to MDC tables, rows are clustered by the time they are inserted into the tables. They can be partitioned tables. They too, do not support pureScale environment.\nRange-Clustered tables Table (RCT): These type of tables provide fast and direct access of data. These are implemented as sequential clusters. Each record in the table has a record ID. These type of tables are used where the data is clustered tightly with one or more columns in the table. This type of tables also do not support in DB2 pureScale.\nPartitioned Tables: These type of tables are used in data organization schema, in which table data is divided into multiple storage objects. Data partitions can be added to, attached to and detached from a partitioned table. You can store multiple data partition from a table in one tablespace.\nTemporal Tables: History of a table in a database is stored in temporal tables such as details of the modifications done previously.\n\n"
},
{
"code": null,
"e": 46455,
"s": 46360,
"text": "Regular Tables: General purpose tables, Common tables with indexes are general purpose tables."
},
{
"code": null,
"e": 46668,
"s": 46455,
"text": "Multidimensional Clustering Table (MDC): This type of table physically clustered on more than one key, and it used to maintain large database environments. These type of tables are not supported in DB2 pureScale."
},
{
"code": null,
"e": 46873,
"s": 46668,
"text": "Insert time clustering Table (ITC): Similar to MDC tables, rows are clustered by the time they are inserted into the tables. They can be partitioned tables. They too, do not support pureScale environment."
},
{
"code": null,
"e": 47221,
"s": 46873,
"text": "Range-Clustered tables Table (RCT): These type of tables provide fast and direct access of data. These are implemented as sequential clusters. Each record in the table has a record ID. These type of tables are used where the data is clustered tightly with one or more columns in the table. This type of tables also do not support in DB2 pureScale."
},
{
"code": null,
"e": 47517,
"s": 47221,
"text": "Partitioned Tables: These type of tables are used in data organization schema, in which table data is divided into multiple storage objects. Data partitions can be added to, attached to and detached from a partitioned table. You can store multiple data partition from a table in one tablespace."
},
{
"code": null,
"e": 47650,
"s": 47517,
"text": "Temporal Tables: History of a table in a database is stored in temporal tables such as details of the modifications done previously."
},
{
"code": null,
"e": 47873,
"s": 47650,
"text": "Temporary Tables: For temporary work of different database operations, you need to use temporary tables. The temporary tables (DGTTs) do not appear in system catalog, XML columns cannot be used in created temporary tables."
},
{
"code": null,
"e": 48053,
"s": 47873,
"text": "Materialized Query Tables: MQT can be used to improve the performance of queries. These types of tables are defined by a query, which is used to determine the data in the tables."
},
{
"code": null,
"e": 48089,
"s": 48053,
"text": "The following syntax creates table:"
},
{
"code": null,
"e": 48121,
"s": 48089,
"text": "Syntax: [To create a new table]"
},
{
"code": null,
"e": 48219,
"s": 48121,
"text": "db2 create table <schema_name>.<table_name>\n(column_name column_type....) in <tablespace_name> "
},
{
"code": null,
"e": 48424,
"s": 48219,
"text": "Example: We create a table to store “employee” details in the schema of “professional”. This table has “id, name, jobrole, joindate, salary” fields and this table data would be stored in tablespace “ts1”."
},
{
"code": null,
"e": 48551,
"s": 48424,
"text": "db2 create table professional.employee(id int, name \nvarchar(50),jobrole varchar(30),joindate date, \nsalary double) in ts1 "
},
{
"code": null,
"e": 48559,
"s": 48551,
"text": "Output:"
},
{
"code": null,
"e": 48612,
"s": 48559,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 48664,
"s": 48612,
"text": "The following syntax is used to list table details:"
},
{
"code": null,
"e": 48721,
"s": 48664,
"text": "Syntax: [To see the list of tables created with schemas]"
},
{
"code": null,
"e": 48783,
"s": 48721,
"text": "db2 select tabname, tabschema, tbspace from syscat.tables "
},
{
"code": null,
"e": 48844,
"s": 48783,
"text": "Example: [To see the list of tables in the current database]"
},
{
"code": null,
"e": 48907,
"s": 48844,
"text": "db2 select tabname, tabschema, tbspace from syscat.tables "
},
{
"code": null,
"e": 48915,
"s": 48907,
"text": "Output:"
},
{
"code": null,
"e": 49053,
"s": 48915,
"text": "TABNAME TABSCHEMA TBSPACE \n------------ ------------- -------- \nEMPLOYEE PROFESSIONAL TS1 \n\n\n 1 record(s) selected. "
},
{
"code": null,
"e": 49100,
"s": 49053,
"text": "The following syntax lists columns in a table:"
},
{
"code": null,
"e": 49151,
"s": 49100,
"text": "Syntax: [To see columns and data types of a table]"
},
{
"code": null,
"e": 49187,
"s": 49151,
"text": "db2 describe table <table_name> "
},
{
"code": null,
"e": 49252,
"s": 49187,
"text": "Example: [To see the columns and data types of table ‘employee’]"
},
{
"code": null,
"e": 49298,
"s": 49252,
"text": "db2 describe table professional.employee "
},
{
"code": null,
"e": 49306,
"s": 49298,
"text": "Output:"
},
{
"code": null,
"e": 49833,
"s": 49306,
"text": " Data type Column \nColumn name schema Data type name Length Scale Nulls \n------ ----- --------- ----------------- --------- ----- ------ \nID SYSIBM INTEGER 4 0 Yes \nNAME SYSIBM VARCHAR 50 0 Yes \nJOBROLE SYSIBM VARCHAR 30 0 Yes \nJOINDATE SYSIBM DATE 4 0 Yes \nSALARY SYSIBM DOUBLE 8 0 Yes \n\n 5 record(s) selected. "
},
{
"code": null,
"e": 50247,
"s": 49833,
"text": "You can hide an entire column of a table. If you call “select * from” query, the hidden columns are not returned in the resulting table. When you insert data into a table, an “INSERT” statement without a column list does not expect values for any implicitly hidden columns. These type of columns are highly referenced in materialized query tables. These type of columns do not support to create temporary tables."
},
{
"code": null,
"e": 50303,
"s": 50247,
"text": "The following syntax creates table with hidden columns:"
},
{
"code": null,
"e": 50351,
"s": 50303,
"text": "Syntax: [To create a table with hidden columns]"
},
{
"code": null,
"e": 50432,
"s": 50351,
"text": "db2 create table <tab_name> (col1 datatype,col2 datatype \nimplicitly hidden) "
},
{
"code": null,
"e": 50500,
"s": 50432,
"text": "Example: [To create a ‘customer’ table with hidden columns ‘phone’]"
},
{
"code": null,
"e": 50628,
"s": 50500,
"text": "db2 create table professional.customer(custid integer not \nnull, fullname varchar(100), phone char(10) \nimplicitly hidden) "
},
{
"code": null,
"e": 50678,
"s": 50628,
"text": "The following syntax inserts values in the table:"
},
{
"code": null,
"e": 50718,
"s": 50678,
"text": "Syntax: [To insert values into a table]"
},
{
"code": null,
"e": 50786,
"s": 50718,
"text": "db2 insert into <tab_name>(col1,col2,...)\n values(val1,val2,..) "
},
{
"code": null,
"e": 50834,
"s": 50786,
"text": "Example: [To insert values in ‘customer’ table]"
},
{
"code": null,
"e": 51123,
"s": 50834,
"text": "db2 insert into professional.customer(custid, fullname, phone) \nvalues(100,'ravi','9898989')\n\n\ndb2 insert into professional.customer(custid, fullname, phone) \nvalues(101,'krathi','87996659')\n\n\ndb2 insert into professional.customer(custid, fullname, phone) \nvalues(102,'gopal','768678687')"
},
{
"code": null,
"e": 51131,
"s": 51123,
"text": "Output:"
},
{
"code": null,
"e": 51181,
"s": 51131,
"text": "DB20000I The SQL command completed successfully."
},
{
"code": null,
"e": 51235,
"s": 51181,
"text": "The following syntax retrieves values from the table:"
},
{
"code": null,
"e": 51277,
"s": 51235,
"text": "Syntax: [To retrieve values form a table]"
},
{
"code": null,
"e": 51310,
"s": 51277,
"text": "db2 select * from <tab_name> "
},
{
"code": null,
"e": 51362,
"s": 51310,
"text": "Example: [To retrieve values from ‘customer’ table]"
},
{
"code": null,
"e": 51403,
"s": 51362,
"text": "db2 select * from professional.customer "
},
{
"code": null,
"e": 51411,
"s": 51403,
"text": "Output:"
},
{
"code": null,
"e": 51561,
"s": 51411,
"text": "CUSTID FULLNAME \n----------- ------------------------ \n 100 ravi\n\t\t\n 101 krathi\n\t\t\n 102 gopal \n\t\t\n 3 record(s) selected. "
},
{
"code": null,
"e": 51622,
"s": 51561,
"text": "The following syntax retrieves values from selected columns:"
},
{
"code": null,
"e": 51688,
"s": 51622,
"text": "Syntax: [To retrieve selected hidden columns values from a table]"
},
{
"code": null,
"e": 51734,
"s": 51688,
"text": "db2 select col1,col2,col3 from <tab_name> "
},
{
"code": null,
"e": 51801,
"s": 51734,
"text": "Example: [To retrieve selected columns values result from a table]"
},
{
"code": null,
"e": 51863,
"s": 51801,
"text": "db2 select custid,fullname,phone from professional.customer "
},
{
"code": null,
"e": 51871,
"s": 51863,
"text": "Output:"
},
{
"code": null,
"e": 52050,
"s": 51871,
"text": "CUSTID FULLNAME PHONE \n------- --------- ------------ \n100 ravi 9898989\n \n101 krathi 87996659 \n\n102 gopal 768678687 \n\n 3 record(s) selected. "
},
{
"code": null,
"e": 52141,
"s": 52050,
"text": "If you want to see the data in the hidden columns, you need to execute “DESCRIBE” command."
},
{
"code": null,
"e": 52149,
"s": 52141,
"text": "Syntax:"
},
{
"code": null,
"e": 52198,
"s": 52149,
"text": "db2 describe table <table_name> show detail "
},
{
"code": null,
"e": 52207,
"s": 52198,
"text": "Example:"
},
{
"code": null,
"e": 52265,
"s": 52207,
"text": "db2 describe table professional.customer show detail "
},
{
"code": null,
"e": 52273,
"s": 52265,
"text": "Output:"
},
{
"code": null,
"e": 53009,
"s": 52273,
"text": "Column name Data type schema Data type name Column\n column Partitionkey code \n Length Scale Nulls \nnumber sequence page Hidden Default \n--------------- -------------------- --------------- -------- ----\n---- -------- ---------- ------------- -------- ----------- ------ \n--- \nCUSTID SYSIBM INTEGER 4 0 \nNo 0 0 0 No \nFULLNAME SYSIBM VARCHAR 100 0\nYes 1 0 1208 No \n\nPHONE SYSIBM CHARACTER 10 0 \nYes 2 0 1208 Implicitly \n \n3 record(s) selected. "
},
{
"code": null,
"e": 53083,
"s": 53009,
"text": "You can modify our table structure using this “alter” command as follows:"
},
{
"code": null,
"e": 53091,
"s": 53083,
"text": "Syntax:"
},
{
"code": null,
"e": 53173,
"s": 53091,
"text": "db2 alter table <tab_name> alter column <col_name> set data type <data_type> "
},
{
"code": null,
"e": 53266,
"s": 53173,
"text": "Example: [To modify the data type for column “id” from “int” to “bigint” for employee table]"
},
{
"code": null,
"e": 53347,
"s": 53266,
"text": "db2 alter table professional.employee alter column id set data type bigint "
},
{
"code": null,
"e": 53356,
"s": 53347,
"text": "Output::"
},
{
"code": null,
"e": 53409,
"s": 53356,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 53452,
"s": 53409,
"text": "You can change column name as shown below:"
},
{
"code": null,
"e": 53525,
"s": 53452,
"text": "Syntax: [To modify the column name from old name to new name of a table]"
},
{
"code": null,
"e": 53596,
"s": 53525,
"text": "db2 alter table <tab_name> rename column <old_name> to <new_name> "
},
{
"code": null,
"e": 53685,
"s": 53596,
"text": "Example: [To modify the column name from “fullname” to “custname” in “customers” table.]"
},
{
"code": null,
"e": 53765,
"s": 53685,
"text": "db2 alter table professional.customer rename column fullname to custname "
},
{
"code": null,
"e": 53833,
"s": 53765,
"text": "To delete any table, you need to use the “DROP” command as follows:"
},
{
"code": null,
"e": 53841,
"s": 53833,
"text": "Syntax:"
},
{
"code": null,
"e": 53872,
"s": 53841,
"text": "db2 drop table <tab_name> "
},
{
"code": null,
"e": 53920,
"s": 53872,
"text": "Example: [To drop customer table form database]"
},
{
"code": null,
"e": 53965,
"s": 53920,
"text": "db2 drop table professional.customers "
},
{
"code": null,
"e": 54092,
"s": 53965,
"text": "To delete the entire hierarchy of the table (including triggers and relation), you need to use “DROP TABLE HIERARCHY” command."
},
{
"code": null,
"e": 54100,
"s": 54092,
"text": "Syntax:"
},
{
"code": null,
"e": 54136,
"s": 54100,
"text": "db2 drop table hierarchy <tab_name>"
},
{
"code": null,
"e": 54194,
"s": 54136,
"text": "Example: [To drop entire hierarchy of a table ‘customer’]"
},
{
"code": null,
"e": 54249,
"s": 54194,
"text": "db2 drop table hierarchy professional.customers "
},
{
"code": null,
"e": 54347,
"s": 54249,
"text": "This chapter describes the creation of alias and retrieving data using alias of database objects."
},
{
"code": null,
"e": 54633,
"s": 54347,
"text": "Alias is an alternative name for database objects. It can be used to reference the database object. You can say, it is a nick name for database objects. Alias are defined for the objects to make their name short, thereby reducing the query size and increasing readability of the query."
},
{
"code": null,
"e": 54686,
"s": 54633,
"text": "You can create database object alias as shown below:"
},
{
"code": null,
"e": 54694,
"s": 54686,
"text": "Syntax:"
},
{
"code": null,
"e": 54745,
"s": 54694,
"text": "db2 create alias <alias_name> for <table_name> "
},
{
"code": null,
"e": 54814,
"s": 54745,
"text": "Example: Creating alias name for table “professional.customer” table"
},
{
"code": null,
"e": 54870,
"s": 54814,
"text": "db2 create alias pro_cust for professional.customer "
},
{
"code": null,
"e": 54995,
"s": 54870,
"text": "If you pass “SELECT * FROM PRO_CUST” or “SELECT * FROM PROFESSIONAL.CUSTOMER” the database server will show the same result."
},
{
"code": null,
"e": 55063,
"s": 54995,
"text": "Syntax: [To retrieve values from a table directly with schema name]"
},
{
"code": null,
"e": 55112,
"s": 55063,
"text": "db2 select * from <schema_name>.<table_name> "
},
{
"code": null,
"e": 55162,
"s": 55112,
"text": "Example: [To retrieve values from table customer]"
},
{
"code": null,
"e": 55206,
"s": 55162,
"text": "db2 select * from professional.customer "
},
{
"code": null,
"e": 55214,
"s": 55206,
"text": "Output:"
},
{
"code": null,
"e": 55395,
"s": 55214,
"text": "CUSTID FULLNAME PHONE\n------- --------- ------------ \n100 ravi 9898989 \n101 krathi 87996659 \n102 gopal 768678687 \n \n 3 record(s) selected. "
},
{
"code": null,
"e": 55466,
"s": 55395,
"text": "You can retrieve values from database using alias name as shown below:"
},
{
"code": null,
"e": 55541,
"s": 55466,
"text": "Syntax: [To retrieve values from table by calling alias name of the table]"
},
{
"code": null,
"e": 55576,
"s": 55541,
"text": "db2 select * from <alias_name> "
},
{
"code": null,
"e": 55643,
"s": 55576,
"text": "Example: [To retrieve values from table customer using alias name]"
},
{
"code": null,
"e": 55670,
"s": 55643,
"text": "db2 select * from pro_cust"
},
{
"code": null,
"e": 55678,
"s": 55670,
"text": "Output:"
},
{
"code": null,
"e": 55859,
"s": 55678,
"text": "CUSTID FULLNAME PHONE\n------- --------- ------------ \n100 ravi 9898989 \n101 krathi 87996659 \n102 gopal 768678687 \n \n 3 record(s) selected. "
},
{
"code": null,
"e": 55919,
"s": 55859,
"text": "This chapter describes various constraints in the database."
},
{
"code": null,
"e": 56066,
"s": 55919,
"text": "To enforce database integrity, a set of rules is defined, called constraints. The constraints either permit or prohibit the values in the columns."
},
{
"code": null,
"e": 56260,
"s": 56066,
"text": "In a Real time database activities, the data should be added with certain restrictions. For example, in a sales database, sales-id or transaction-id should be unique. The constraints types are:"
},
{
"code": null,
"e": 56269,
"s": 56260,
"text": "NOT NULL"
},
{
"code": null,
"e": 56276,
"s": 56269,
"text": "Unique"
},
{
"code": null,
"e": 56288,
"s": 56276,
"text": "Primary key"
},
{
"code": null,
"e": 56300,
"s": 56288,
"text": "Foreign Key"
},
{
"code": null,
"e": 56306,
"s": 56300,
"text": "Check"
},
{
"code": null,
"e": 56320,
"s": 56306,
"text": "Informational"
},
{
"code": null,
"e": 56483,
"s": 56320,
"text": "Constraints are only associated with tables. They are applied to only particular tables. They are defined and applied to the table at the time of table creation."
},
{
"code": null,
"e": 56563,
"s": 56483,
"text": "It is a rule to prohibit null values from one or more columns within the table."
},
{
"code": null,
"e": 56571,
"s": 56563,
"text": "Syntax:"
},
{
"code": null,
"e": 56634,
"s": 56571,
"text": "db2 create table <table_name>(col_name col_type not null,..) "
},
{
"code": null,
"e": 56813,
"s": 56634,
"text": "Example: [To create a sales table, with four columns (id, itemname, qty, price) in this adding “not null” constraints to all columns to avoid forming any null cell in the table.]"
},
{
"code": null,
"e": 56939,
"s": 56813,
"text": "db2 create table shopper.sales(id bigint not null, itemname \nvarchar(40) not null, qty int not null,price double not null) "
},
{
"code": null,
"e": 56990,
"s": 56939,
"text": "You can insert values in the table as shown below:"
},
{
"code": null,
"e": 57019,
"s": 56990,
"text": "Example: [ERRORoneous Query]"
},
{
"code": null,
"e": 57089,
"s": 57019,
"text": "db2 insert into shopper.sales(id,itemname,qty) \nvalues(1,'raagi',12) "
},
{
"code": null,
"e": 57113,
"s": 57089,
"text": "Output: [Correct query]"
},
{
"code": null,
"e": 57400,
"s": 57113,
"text": "DB21034E The command was processed as an SQL statement because \nit was not a \n\nvalid Command Line Processor command. During SQL processing \nit returned: \n\nSQL0407N Assignment of a NULL value to a NOT NULL column \n\"TBSPACEID=5, \n\nTABLEID=4, COLNO=3\" is not allowed. SQLSTATE=23502 \n "
},
{
"code": null,
"e": 57425,
"s": 57400,
"text": "Example: [Correct query]"
},
{
"code": null,
"e": 57595,
"s": 57425,
"text": "db2 insert into shopper.sales(id,itemname,qty,price) \nvalues(1,'raagi',12, 120.00) \n\ndb2 insert into shopper.sales(id,itemname,qty,price) \nvalues(1,'raagi',12, 120.00) "
},
{
"code": null,
"e": 57603,
"s": 57595,
"text": "Output:"
},
{
"code": null,
"e": 57652,
"s": 57603,
"text": "DB20000I The SQL command completed successfully."
},
{
"code": null,
"e": 57821,
"s": 57652,
"text": "Using these constraints, you can set values of columns uniquely. For this, the unique constraints are declared with “not null” constraint at the time of creating table."
},
{
"code": null,
"e": 57829,
"s": 57821,
"text": "Syntax:"
},
{
"code": null,
"e": 57897,
"s": 57829,
"text": "db2 create table <tab_name>(<col> <col_type> not null unique, ...) "
},
{
"code": null,
"e": 57906,
"s": 57897,
"text": "Example:"
},
{
"code": null,
"e": 58040,
"s": 57906,
"text": "db2 create table shopper.sales1(id bigint not null unique, \nitemname varchar(40) not null, qty int not null,price \ndouble not null) "
},
{
"code": null,
"e": 58113,
"s": 58040,
"text": "Example: To insert four different rows with unique ids as 1, 2, 3 and 4."
},
{
"code": null,
"e": 58467,
"s": 58113,
"text": "db2 insert into shopper.sales1(id, itemname, qty, price) \nvalues(1, 'sweet', 100, 89) \n\ndb2 insert into shopper.sales1(id, itemname, qty, price) \nvalues(2, 'choco', 50, 60) \n\ndb2 insert into shopper.sales1(id, itemname, qty, price) \nvalues(3, 'butter', 30, 40) \n\ndb2 insert into shopper.sales1(id, itemname, qty, price) \nvalues(4, 'milk', 1000, 12) "
},
{
"code": null,
"e": 58514,
"s": 58467,
"text": "Example: To insert a new row with “id” value 3"
},
{
"code": null,
"e": 58603,
"s": 58514,
"text": "db2 insert into shopper.sales1(id, itemname, qty, price) \nvalues(3, 'cheese', 60, 80) "
},
{
"code": null,
"e": 58692,
"s": 58603,
"text": "Output: when you try to insert a new row with existed id value it will show this result:"
},
{
"code": null,
"e": 59168,
"s": 58692,
"text": "DB21034E The command was processed as an SQL statement \nbecause it was not a \n\nvalid Command Line Processor command. During \nSQL processing it returned: \n\nSQL0803N One or more values in the INSERT statement, \nUPDATE statement, or foreign key update caused by a\nDELETE statement are not valid because the primary key, \nunique constraint or unique index identified by \"1\" constrains \ntable \"SHOPPER.SALES1\" from having duplicate values for the \nindex key. SQLSTATE=23505 "
},
{
"code": null,
"e": 59312,
"s": 59168,
"text": "Similar to the unique constraints, you can use a “primary key” and a “foreign key” constraint to declare relationships between multiple tables."
},
{
"code": null,
"e": 59320,
"s": 59312,
"text": "Syntax:"
},
{
"code": null,
"e": 59371,
"s": 59320,
"text": "db2 create table <tab_name>( ,.., primary\nkey ()) "
},
{
"code": null,
"e": 59436,
"s": 59371,
"text": "Example: To create ‘salesboys’ table with “sid” as a primary key"
},
{
"code": null,
"e": 59582,
"s": 59436,
"text": "db2 create table shopper.salesboys(sid int not null, name \nvarchar(40) not null, salary double not null, constraint \npk_boy_id primary key (sid))"
},
{
"code": null,
"e": 59905,
"s": 59582,
"text": "A foreign key is a set of columns in a table which are required to match at least one primary key of a row in another table. It is a referential constraint or referential integrity constraint. It is a logical rule about values in multiple columns in one or more tables. It enables required relationship between the tables."
},
{
"code": null,
"e": 60183,
"s": 59905,
"text": "Earlier, you created a table named “shopper.salesboys” . For this table, the primary key is “sid”. Now you are creating a new table that has sales boy’s personal details with different schema named “employee” and table named “salesboys”. In this case, “sid” is the foreign key."
},
{
"code": null,
"e": 60191,
"s": 60183,
"text": "Syntax:"
},
{
"code": null,
"e": 60342,
"s": 60191,
"text": "db2 create table <tab_name>(<col> <col_type>,constraint \n<const_name> foreign key (<col_name>) \n reference <ref_table> (<ref_col>) "
},
{
"code": null,
"e": 60419,
"s": 60342,
"text": "Example: [To create a table named ‘salesboys’ with foreign key column ‘sid’]"
},
{
"code": null,
"e": 60720,
"s": 60419,
"text": "db2 create table employee.salesboys( \n sid int, \n name varchar(30) not null, \n phone int not null, \n constraint fk_boy_id \n foreign key (sid) \n references shopper.salesboys (sid) \n\t\t\t on delete restrict \n ) "
},
{
"code": null,
"e": 60791,
"s": 60720,
"text": "Example: [Inserting values into primary key table “shopper.salesboys”]"
},
{
"code": null,
"e": 60952,
"s": 60791,
"text": "db2 insert into shopper.salesboys values(100,'raju',20000.00), \n(101,'kiran',15000.00), \n(102,'radha',10000.00), \n(103,'wali',20000.00), \n(104,'rayan',15000.00)"
},
{
"code": null,
"e": 61041,
"s": 60952,
"text": "Example: [Inserting values into foreign key table “employee.salesboys” [without error]]"
},
{
"code": null,
"e": 61206,
"s": 61041,
"text": "db2 insert into employee.salesboys values(100,'raju',98998976), \n(101,'kiran',98911176), \n(102,'radha',943245176), \n(103,'wali',89857330), \n(104,'rayan',89851130) "
},
{
"code": null,
"e": 61318,
"s": 61206,
"text": "If you entered an unknown number, which is not stored in “shopper.salesboys” table, it will show you SQL error."
},
{
"code": null,
"e": 61345,
"s": 61318,
"text": "Example: [error execution]"
},
{
"code": null,
"e": 61410,
"s": 61345,
"text": "db2 insert into employee.salesboys values(105,'rayan',89851130) "
},
{
"code": null,
"e": 61418,
"s": 61410,
"text": "Output:"
},
{
"code": null,
"e": 61743,
"s": 61418,
"text": "DB21034E The command was processed as an SQL statement because it \nwas not a valid Command Line Processor command. During SQL \nprocessing it returned: SQL0530N The insert or update value of \nthe FOREIGN KEY \"EMPLOYEE.SALESBOYS.FK_BOY_ID\" is not equal to any \nvalue of the parent key of the parent table. SQLSTATE=23503 "
},
{
"code": null,
"e": 61841,
"s": 61743,
"text": "You need to use this constraint to add conditional restrictions for a specific column in a table."
},
{
"code": null,
"e": 61849,
"s": 61841,
"text": "Syntax:"
},
{
"code": null,
"e": 62050,
"s": 61849,
"text": "db2 create table \n ( \n primary key (), \n constraint check (condition or condition) \n )\n "
},
{
"code": null,
"e": 62106,
"s": 62050,
"text": "Example: [To create emp1 table with constraints values]"
},
{
"code": null,
"e": 62832,
"s": 62106,
"text": "db2 create table empl \n (id smallint not null, \n name varchar(9), \n dept smallint check (dept between 10 and 100), \n job char(5) check (job in ('sales', 'mgr', 'clerk')), \n hiredate date, \n salary decimal(7,2), \n comm decimal(7,2), \n primary key (id), \n constraint yearsal check (year(hiredate) > 1986 or salary > 40500) \n )\n "
},
{
"code": null,
"e": 62883,
"s": 62832,
"text": "You can insert values into a table as shown below:"
},
{
"code": null,
"e": 62968,
"s": 62883,
"text": "db2 insert into empl values (1,'lee', 15, 'mgr', '1985-01-01' , \n40000.00, 1000.00) "
},
{
"code": null,
"e": 63026,
"s": 62968,
"text": "Let us see the syntaxes for dropping various constraints."
},
{
"code": null,
"e": 63034,
"s": 63026,
"text": "Syntax:"
},
{
"code": null,
"e": 63086,
"s": 63034,
"text": "db2 alter table <tab_name> drop unique <const_name>"
},
{
"code": null,
"e": 63094,
"s": 63086,
"text": "Syntax:"
},
{
"code": null,
"e": 63139,
"s": 63094,
"text": "db2 alter table <tab_name> drop primary key "
},
{
"code": null,
"e": 63147,
"s": 63139,
"text": "Syntax:"
},
{
"code": null,
"e": 63206,
"s": 63147,
"text": "db2 alter table <tab_name> drop check <check_const_name> "
},
{
"code": null,
"e": 63214,
"s": 63206,
"text": "Syntax:"
},
{
"code": null,
"e": 63279,
"s": 63214,
"text": "db2 alter table <tab_name> drop foreigh key <foreign_key_name> "
},
{
"code": null,
"e": 63360,
"s": 63279,
"text": "This chapter covers introduction to indexes, their types, creation and dropping."
},
{
"code": null,
"e": 63881,
"s": 63360,
"text": "Index is a set of pointers, which can refer to rows in a table, blocks in MDC or ITC tables, XML data in an XML storage object that are logically ordered by the values of one or more keys. It is created on DB2 table columns to speed up the data access for the queries, and to cluster and partition the data efficiently. It can also improve the performance of operation on the view. A table with a unique index can have rows with unique keys. Depending on the table requirements, you can take different types of indexes."
},
{
"code": null,
"e": 63911,
"s": 63881,
"text": "Unique and Non-Unique indexes"
},
{
"code": null,
"e": 63947,
"s": 63911,
"text": "Clustered and non-clustered indexes"
},
{
"code": null,
"e": 64002,
"s": 63947,
"text": "For creating unique indexes, you use following syntax:"
},
{
"code": null,
"e": 64010,
"s": 64002,
"text": "Syntax:"
},
{
"code": null,
"e": 64109,
"s": 64010,
"text": "db2 create unique index <index_name> on \n<table_name>(<unique_column>) include (<column_names..>) "
},
{
"code": null,
"e": 64162,
"s": 64109,
"text": "Example: To create index for “shopper.sales1” table."
},
{
"code": null,
"e": 64241,
"s": 64162,
"text": "db2 create unique index sales1_indx on \nshopper.sales1(id) include (itemname) "
},
{
"code": null,
"e": 64295,
"s": 64241,
"text": "For dropping the index, you use the following syntax:"
},
{
"code": null,
"e": 64303,
"s": 64295,
"text": "Syntax:"
},
{
"code": null,
"e": 64402,
"s": 64303,
"text": "db2 create unique index <index_name> on \n<table_name>(<unique_column>) include (<column_names..>) "
},
{
"code": null,
"e": 64411,
"s": 64402,
"text": "Example:"
},
{
"code": null,
"e": 64439,
"s": 64411,
"text": "db2 drop index sales_index "
},
{
"code": null,
"e": 64524,
"s": 64439,
"text": "This chapter describes triggers, their types, creation and dropping of the triggers."
},
{
"code": null,
"e": 65130,
"s": 64524,
"text": "A trigger is a set of actions, which are performed for responding to an INSERT, UPDATE or DELETE operation on a specified table in the database. Triggers are stored in the database at once. They handle governance of data. They can be accessed and shared among multiple applications. The advantage of using triggers is, if any change needs to be done in the application, it is done at the trigger; instead of changing each application that is accessing the trigger. Triggers are easy to maintain and they enforce faster application development. Triggers are defined using an SQL statement “CREATE TRIGGER”."
},
{
"code": null,
"e": 65163,
"s": 65130,
"text": "There are two types of triggers:"
},
{
"code": null,
"e": 65207,
"s": 65163,
"text": "They are executed before any SQL operation."
},
{
"code": null,
"e": 65250,
"s": 65207,
"text": "They are executed after any SQL operation."
},
{
"code": null,
"e": 65298,
"s": 65250,
"text": "Let us see how to create a sequence of trigger:"
},
{
"code": null,
"e": 65306,
"s": 65298,
"text": "Syntax:"
},
{
"code": null,
"e": 65338,
"s": 65306,
"text": "db2 create sequence <seq_name> "
},
{
"code": null,
"e": 65404,
"s": 65338,
"text": "Example: Creating a sequence of triggers for table shopper.sales1"
},
{
"code": null,
"e": 65471,
"s": 65404,
"text": "db2 create sequence sales1_seq as int start with 1 increment by 1 "
},
{
"code": null,
"e": 65479,
"s": 65471,
"text": "Syntax:"
},
{
"code": null,
"e": 65662,
"s": 65479,
"text": "db2 create trigger <trigger_name> no cascade before insert on \n<table_name> referencing new as <table_object> for each row set \n<table_object>.<col_name>=nextval for <sequence_name> "
},
{
"code": null,
"e": 65757,
"s": 65662,
"text": "Example: Creating trigger for shopper.sales1 table to insert primary key numbers automatically"
},
{
"code": null,
"e": 65906,
"s": 65757,
"text": "db2 create trigger sales1_trigger no cascade before insert on \nshopper.sales1 referencing new as obj for each row set \nobj.id=nextval for sales1_seq"
},
{
"code": null,
"e": 65936,
"s": 65906,
"text": "Now try inserting any values:"
},
{
"code": null,
"e": 66019,
"s": 65936,
"text": "db2 insert into shopper.sales1(itemname, qty, price) \nvalues('bicks', 100, 24.00) "
},
{
"code": null,
"e": 66067,
"s": 66019,
"text": "Let us see how to retrieve values from a table:"
},
{
"code": null,
"e": 66075,
"s": 66067,
"text": "Syntax:"
},
{
"code": null,
"e": 66105,
"s": 66075,
"text": "db2 select * from <tablename>"
},
{
"code": null,
"e": 66114,
"s": 66105,
"text": "Example:"
},
{
"code": null,
"e": 66147,
"s": 66114,
"text": "db2 select * from shopper.sales1"
},
{
"code": null,
"e": 66155,
"s": 66147,
"text": "Output:"
},
{
"code": null,
"e": 66316,
"s": 66155,
"text": " ID ITEMNAME QTY \n------- ------------ ---------- \n 3 bicks 100 \n 2 bread 100 \n \n 2 record(s) selected. "
},
{
"code": null,
"e": 66359,
"s": 66316,
"text": "Let us see how to create an after trigger:"
},
{
"code": null,
"e": 66367,
"s": 66359,
"text": "Syntax:"
},
{
"code": null,
"e": 66550,
"s": 66367,
"text": "db2 create trigger <trigger_name> no cascade before insert on \n<table_name> referencing new as <table_object> for each row set\n <table_object>.<col_name>=nextval for <sequence_name> "
},
{
"code": null,
"e": 66595,
"s": 66550,
"text": "Example: [To insert and retrieve the values]"
},
{
"code": null,
"e": 66751,
"s": 66595,
"text": "db2 create trigger sales1_tri_after after insert on shopper.sales1 \nfor each row mode db2sql begin atomic update shopper.sales1 \nset price=qty*price; end "
},
{
"code": null,
"e": 66759,
"s": 66751,
"text": "Output:"
},
{
"code": null,
"e": 67146,
"s": 66759,
"text": "//inseting values in shopper.sales1 \ndb2 insert into shopper.sales1(itemname,qty,price) \nvalues('chiken',100,124.00) \n//output \nID ITEMNAME QTY PRICE \n----- -------------- ----------- ----------- \n 3 bicks 100 2400.00 \n 4 chiken 100 12400.00 \n 2 bread 100 2400.00 \n\n\t3 record(s) selected. "
},
{
"code": null,
"e": 67189,
"s": 67146,
"text": "Here is how a database trigger is dropped:"
},
{
"code": null,
"e": 67197,
"s": 67189,
"text": "Syntax:"
},
{
"code": null,
"e": 67231,
"s": 67197,
"text": "db2 drop trigger <trigger_name> "
},
{
"code": null,
"e": 67240,
"s": 67231,
"text": "Example:"
},
{
"code": null,
"e": 67275,
"s": 67240,
"text": "db2 drop trigger slaes1_trigger "
},
{
"code": null,
"e": 67394,
"s": 67275,
"text": "This chapter introduces you to the concept of sequence, creation of sequence, viewing the sequence, and dropping them."
},
{
"code": null,
"e": 67877,
"s": 67394,
"text": "A sequence is a software function that generates integer numbers in either ascending or descending order, within a definite range, to generate primary key and coordinate other keys among the table. You use sequence for availing integer numbers say, for employee_id or transaction_id. A sequence can support SMALLINT, BIGINT, INTEGER, and DECIMAL data types. A sequence can be shared among multiple applications. A sequence is incremented or decremented irrespective of transactions."
},
{
"code": null,
"e": 67929,
"s": 67877,
"text": "A sequence is created by CREATE SEQUENCE statement."
},
{
"code": null,
"e": 67972,
"s": 67929,
"text": "There are two type of sequences available:"
},
{
"code": null,
"e": 68036,
"s": 67972,
"text": "NEXTVAL: It returns an incremented value for a sequence number."
},
{
"code": null,
"e": 68100,
"s": 68036,
"text": "NEXTVAL: It returns an incremented value for a sequence number."
},
{
"code": null,
"e": 68153,
"s": 68100,
"text": "PREVIOUS VALUE: It returns recently generated value."
},
{
"code": null,
"e": 68206,
"s": 68153,
"text": "PREVIOUS VALUE: It returns recently generated value."
},
{
"code": null,
"e": 68255,
"s": 68206,
"text": "The following parameters are used for sequences:"
},
{
"code": null,
"e": 68367,
"s": 68255,
"text": "Data type: This is the data type of the returned incremented value. (SMALLINT, BIGINT, INTEGER, NUMBER, DOUBLE)"
},
{
"code": null,
"e": 68432,
"s": 68367,
"text": "START WITH: The reference value, with which the sequence starts."
},
{
"code": null,
"e": 68488,
"s": 68432,
"text": "MINVALUE: A minimum value for a sequence to start with."
},
{
"code": null,
"e": 68530,
"s": 68488,
"text": "MAXVALUE: A maximum value for a sequence."
},
{
"code": null,
"e": 68591,
"s": 68530,
"text": "INCREMENT BY: step value by which a sequence is incremented."
},
{
"code": null,
"e": 68809,
"s": 68591,
"text": "Sequence cycling: the CYCLE clause causes generation of the sequence repeatedly. The sequence generation is conducted by referring the returned value, which is stored into the database by previous sequence generation."
},
{
"code": null,
"e": 68861,
"s": 68809,
"text": "You can create sequence using the following syntax:"
},
{
"code": null,
"e": 68869,
"s": 68861,
"text": "Syntax:"
},
{
"code": null,
"e": 68901,
"s": 68869,
"text": "db2 create sequence <seq_name> "
},
{
"code": null,
"e": 68993,
"s": 68901,
"text": "Example: [To create a new sequence with the name ‘sales1_seq’ and increasing values from 1]"
},
{
"code": null,
"e": 69062,
"s": 68993,
"text": "db2 create sequence sales1_seq as int start \nwith 1 increment by 1 "
},
{
"code": null,
"e": 69116,
"s": 69062,
"text": "You can view a sequence using the syntax given below:"
},
{
"code": null,
"e": 69124,
"s": 69116,
"text": "Syntax:"
},
{
"code": null,
"e": 69171,
"s": 69124,
"text": "db2 value <previous/next> value for <seq_name>"
},
{
"code": null,
"e": 69245,
"s": 69171,
"text": "Example: [To see list of previous updated value in sequence ‘sales1_seq’]"
},
{
"code": null,
"e": 69288,
"s": 69245,
"text": "db2 values previous value for sales1_seq "
},
{
"code": null,
"e": 69296,
"s": 69288,
"text": "Output:"
},
{
"code": null,
"e": 69343,
"s": 69296,
"text": " 1 \n----------- \n 4 \n 1 record(s) selected. "
},
{
"code": null,
"e": 69436,
"s": 69343,
"text": "To remove the sequence, you need to use the “DROP SEQUENCE ” command. Here is how you do it:"
},
{
"code": null,
"e": 69444,
"s": 69436,
"text": "Syntax:"
},
{
"code": null,
"e": 69474,
"s": 69444,
"text": "db2 drop sequence <seq_name>>"
},
{
"code": null,
"e": 69529,
"s": 69474,
"text": "Example: [To drop sequence ‘sales1_seq’ from database]"
},
{
"code": null,
"e": 69560,
"s": 69529,
"text": "db2 drop sequence sales1_seq "
},
{
"code": null,
"e": 69568,
"s": 69560,
"text": "Output:"
},
{
"code": null,
"e": 69619,
"s": 69568,
"text": " DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 69709,
"s": 69619,
"text": "This chapter describes introduction of views, creating, modifying and dropping the views."
},
{
"code": null,
"e": 69968,
"s": 69709,
"text": "A view is an alternative way of representing the data stored in the tables. It is not an actual table and it does not have any permanent storage. View provides a way of looking at the data in one or more tables. It is a named specification of a result table."
},
{
"code": null,
"e": 70018,
"s": 69968,
"text": "You can create a view using the following syntax:"
},
{
"code": null,
"e": 70026,
"s": 70018,
"text": "Syntax:"
},
{
"code": null,
"e": 70121,
"s": 70026,
"text": "db2 create view <view_name> (<col_name>,\n<col_name1...) as select <cols>.. \nfrom <table_name> "
},
{
"code": null,
"e": 70169,
"s": 70121,
"text": "Example: Creating view for shopper.sales1 table"
},
{
"code": null,
"e": 70282,
"s": 70169,
"text": "db2 create view view_sales1(id, itemname, qty, price) \nas select id, itemname, qty, price from \nshopper.sales1 "
},
{
"code": null,
"e": 70332,
"s": 70282,
"text": "You can modify a view using the following syntax:"
},
{
"code": null,
"e": 70340,
"s": 70332,
"text": "Syntax:"
},
{
"code": null,
"e": 70417,
"s": 70340,
"text": "db2 alter view <view_name> alter <col_name> \nadd scope <table_or_view_name> "
},
{
"code": null,
"e": 70483,
"s": 70417,
"text": "Example: [To add new table column to existing view ‘view_sales1’]"
},
{
"code": null,
"e": 70547,
"s": 70483,
"text": "db2 alter view view_sales1 alter id add \nscope shopper.sales1 "
},
{
"code": null,
"e": 70595,
"s": 70547,
"text": "You can drop a view using the following syntax:"
},
{
"code": null,
"e": 70603,
"s": 70595,
"text": "Syntax:"
},
{
"code": null,
"e": 70630,
"s": 70603,
"text": "db2 drop view <view_name> "
},
{
"code": null,
"e": 70639,
"s": 70630,
"text": "Example:"
},
{
"code": null,
"e": 70667,
"s": 70639,
"text": "db2 drop view sales1_view "
},
{
"code": null,
"e": 70711,
"s": 70667,
"text": "This chapter describes use of XML with DB2."
},
{
"code": null,
"e": 71199,
"s": 70711,
"text": "PureXML feature allows you to store well-formed XML documents in columns of database tables. Those columns have XML database. Data is kept in its native hierarchical form by storing XML data in XML column. The stored XML data can be accessed and managed by DB2 database server functionality. The storage of XML data in its native hierarchical form enables efficient search, retrieval, and update of XML. To update a value in XML data, you need to use XQuery, SQL or combination of both."
},
{
"code": null,
"e": 71250,
"s": 71199,
"text": "Create a database by issuing the following syntax:"
},
{
"code": null,
"e": 71258,
"s": 71250,
"text": "Syntax:"
},
{
"code": null,
"e": 71285,
"s": 71258,
"text": "db2 create database xmldb "
},
{
"code": null,
"e": 71378,
"s": 71285,
"text": "By default, databases use UTF-8 (UNICODE) code set. Activate the database and connect to it:"
},
{
"code": null,
"e": 71386,
"s": 71378,
"text": "Syntax:"
},
{
"code": null,
"e": 71438,
"s": 71386,
"text": "db2 activate db <db_name>\ndb2 connect to <db_name> "
},
{
"code": null,
"e": 71447,
"s": 71438,
"text": "Example:"
},
{
"code": null,
"e": 71493,
"s": 71447,
"text": "db2 activate db xmldb \ndb2 connect to xmldb "
},
{
"code": null,
"e": 71672,
"s": 71493,
"text": "Create a well-formed XML file and create a table with data type of the column as ‘XML’. It is mandatory to pass the SQL query containing XML syntax within double quotation marks."
},
{
"code": null,
"e": 71680,
"s": 71672,
"text": "Syntax:"
},
{
"code": null,
"e": 71754,
"s": 71680,
"text": "db2 “create table <schema>.<table>(col <datatype>, \ncol <xml datatype>)” "
},
{
"code": null,
"e": 71763,
"s": 71754,
"text": "Example:"
},
{
"code": null,
"e": 71840,
"s": 71763,
"text": "db2 \"create table shope.books(id bigint not null \nprimary key, book XML)\" "
},
{
"code": null,
"e": 71960,
"s": 71840,
"text": "Insert xml values into table, well-formed XML documents are inserted into XML type column using SQL statement ‘INSERT’."
},
{
"code": null,
"e": 71968,
"s": 71960,
"text": "Syntax:"
},
{
"code": null,
"e": 72023,
"s": 71968,
"text": "db2 “insert into <table_name> values(value1, value2)” "
},
{
"code": null,
"e": 72032,
"s": 72023,
"text": "Example:"
},
{
"code": null,
"e": 72366,
"s": 72032,
"text": "db2 \"insert into shope.books values(1000, '<catalog> \n<book> \n\n<author> Gambardella Matthew</author> \n<title>XML Developers Guide</title> \n<genre>Computer</genre> \n<price>44.95</price> \n<publish_date>2000-10-01</publish_date> \n<description>An in-depth look at creating application \nwith XML</description> \n</book> \n\n</catalog>')\" "
},
{
"code": null,
"e": 72432,
"s": 72366,
"text": "You can update XML data in a table by using the following syntax:"
},
{
"code": null,
"e": 72440,
"s": 72432,
"text": "Syntax:"
},
{
"code": null,
"e": 72513,
"s": 72440,
"text": "db2 “update <table_name> set <column>=<value> where \n<column>=<value>” "
},
{
"code": null,
"e": 72522,
"s": 72513,
"text": "Example:"
},
{
"code": null,
"e": 72833,
"s": 72522,
"text": "db2 \"update shope.books set book='<catalog> \n\n<book> \n<author> Gambardella, Matthew</author> \n<title>XML Developers Guide</title> \n<genre>Computer</genre> \n<price>44.95</price> \n<publish_date>2000-10-01</publish_date> \n<description>An in-depth XML</description>\n \n</book> \n \n</catalog>' where id=1000\" "
},
{
"code": null,
"e": 72896,
"s": 72833,
"text": "This chapter describes backup and restore methods of database."
},
{
"code": null,
"e": 73134,
"s": 72896,
"text": "Backup and recovery methods are designed to keep our information safe. In Command Line Interface (CLI) or Graphical User Interface (GUI) using backup and recovery utilities you can take backup or restore the data of databases in DB2 UDB."
},
{
"code": null,
"e": 73323,
"s": 73134,
"text": "Log files consist of error logs, which are used to recover from application errors. The logs keep the record of changes in the database. There are two types of logging as described below:"
},
{
"code": null,
"e": 73625,
"s": 73323,
"text": "It is a method where the old transaction logs are overwritten when there is a need to allocate a new transaction log file, thus erasing the sequences of log files and reusing them. You are permitted to take only full back-up in offline mode. i.e., the database must be offline to take the full backup."
},
{
"code": null,
"e": 73928,
"s": 73625,
"text": "This mode supports for Online Backup and database recovery using log files called roll forward recovery. The mode of backup can be changed from circular to archive by setting logretain or userexit to ON. For archive logging, backup setting database require a directory that is writable for DB2 process."
},
{
"code": null,
"e": 74090,
"s": 73928,
"text": "Using Backup command you can take copy of entire database. This backup copy includes database system files, data files, log files, control information and so on."
},
{
"code": null,
"e": 74151,
"s": 74090,
"text": "You can take backup while working offline as well as online."
},
{
"code": null,
"e": 74203,
"s": 74151,
"text": "Syntax: [To list the active applications/databases]"
},
{
"code": null,
"e": 74226,
"s": 74203,
"text": "db2 list application "
},
{
"code": null,
"e": 74234,
"s": 74226,
"text": "Output:"
},
{
"code": null,
"e": 74640,
"s": 74234,
"text": "Auth Id Application Appl. Application Id \nDB # of \n Name Handle \nName Agents \n-------- -------------- ---------- ---------------------\n----------------------------------------- -------- ----- \nDB2INST1 db2bp 39 \n*LOCAL.db2inst1.140722043938 \nONE 1 "
},
{
"code": null,
"e": 74693,
"s": 74640,
"text": "Syntax: [To force application using app. Handled id]"
},
{
"code": null,
"e": 74725,
"s": 74693,
"text": "db2 \"force application (39)\" "
},
{
"code": null,
"e": 74733,
"s": 74725,
"text": "Output:"
},
{
"code": null,
"e": 74880,
"s": 74733,
"text": "DB20000I The FORCE APPLICATION command completed \nsuccessfully. \n\nDB21024I This command is asynchronous and may not \nbe effective immediately. "
},
{
"code": null,
"e": 74923,
"s": 74880,
"text": "Syntax: [To terminate Database Connection]"
},
{
"code": null,
"e": 74939,
"s": 74923,
"text": "db2 terminate "
},
{
"code": null,
"e": 74972,
"s": 74939,
"text": "Syntax: [To deactivate Database]"
},
{
"code": null,
"e": 75003,
"s": 74972,
"text": "db2 deactivate database one "
},
{
"code": null,
"e": 75037,
"s": 75003,
"text": "Syntax: [To take the backup file]"
},
{
"code": null,
"e": 75084,
"s": 75037,
"text": "db2 backup database <db_name> to <location> "
},
{
"code": null,
"e": 75093,
"s": 75084,
"text": "Example:"
},
{
"code": null,
"e": 75137,
"s": 75093,
"text": "db2 backup database one to /home/db2inst1/ "
},
{
"code": null,
"e": 75145,
"s": 75137,
"text": "Output:"
},
{
"code": null,
"e": 75223,
"s": 75145,
"text": "Backup successful. The timestamp for this backup image is : \n20140722105345 "
},
{
"code": null,
"e": 75303,
"s": 75223,
"text": "To start, you need to change the mode from Circular logging to Archive Logging."
},
{
"code": null,
"e": 75375,
"s": 75303,
"text": "Syntax: [To check if the database is using circular or archive logging]"
},
{
"code": null,
"e": 75416,
"s": 75375,
"text": "db2 get db cfg for one | grep LOGARCH "
},
{
"code": null,
"e": 75424,
"s": 75416,
"text": "Output:"
},
{
"code": null,
"e": 75775,
"s": 75424,
"text": "First log archive method (LOGARCHMETH1) = OFF \n Archive compression for logarchmeth1 (LOGARCHCOMPR1) = OFF \n Options for logarchmeth1 (LOGARCHOPT1) = \n Second log archive method (LOGARCHMETH2) = OFF \n Archive compression for logarchmeth2 (LOGARCHCOMPR2) = OFF \n Options for logarchmeth2 (LOGARCHOPT2) = "
},
{
"code": null,
"e": 76099,
"s": 75775,
"text": "In the above output, the highlighted values are [logarchmeth1 and logarchmeth2] in off mode, which implies that the current database in “CIRCULLAR LOGGING” mode. If you need to work with ‘ARCHIVE LOGGING’ mode, you need to change or add path in the variables logarchmeth1 and logarchmeth2 present in the configuration file."
},
{
"code": null,
"e": 76129,
"s": 76099,
"text": "Syntax: [To make directories]"
},
{
"code": null,
"e": 76172,
"s": 76129,
"text": "mkdir backup \nmkdir backup/ArchiveDest "
},
{
"code": null,
"e": 76221,
"s": 76172,
"text": "Syntax: [To provide user permissions for folder]"
},
{
"code": null,
"e": 76265,
"s": 76221,
"text": "chown db2inst1:db2iadm1 backup/ArchiveDest "
},
{
"code": null,
"e": 76312,
"s": 76265,
"text": "Syntax: [To update configuration LOGARCHMETH1]"
},
{
"code": null,
"e": 76415,
"s": 76312,
"text": "db2 update database configuration for one using LOGARCHMETH1 \n'DISK:/home/db2inst1/backup/ArchiveDest'"
},
{
"code": null,
"e": 76496,
"s": 76415,
"text": "You can take offline backup for safety, activate the database and connect to it."
},
{
"code": null,
"e": 76528,
"s": 76496,
"text": "Syntax: [To take online backup]"
},
{
"code": null,
"e": 76617,
"s": 76528,
"text": "db2 backup database one online to \n/home/db2inst1/onlinebackup/ compress include logs "
},
{
"code": null,
"e": 76625,
"s": 76617,
"text": "Output:"
},
{
"code": null,
"e": 76715,
"s": 76625,
"text": "db2 backup database one online to \n/home/db2inst1/onlinebackup/ compress include logs "
},
{
"code": null,
"e": 76759,
"s": 76715,
"text": "Verify Backup file using following command:"
},
{
"code": null,
"e": 76767,
"s": 76759,
"text": "Syntax:"
},
{
"code": null,
"e": 76802,
"s": 76767,
"text": "db2ckbkp <location/backup file> "
},
{
"code": null,
"e": 76811,
"s": 76802,
"text": "Example:"
},
{
"code": null,
"e": 76881,
"s": 76811,
"text": "db2ckbkp \n/home/db2inst1/ONE.0.db2inst1.DBPART000.20140722112743.001 "
},
{
"code": null,
"e": 76917,
"s": 76881,
"text": "Listing the history of backup files"
},
{
"code": null,
"e": 76925,
"s": 76917,
"text": "Syntax:"
},
{
"code": null,
"e": 76965,
"s": 76925,
"text": "db2 list history backup all for one "
},
{
"code": null,
"e": 76973,
"s": 76965,
"text": "Output:"
},
{
"code": null,
"e": 80256,
"s": 76973,
"text": " List History File for one \n \nNumber of matching file entries = 4 \n \nOp Obj Timestamp+Sequence Type Dev Earliest Log Current Log \nBackup ID \n -- --- ------------------ ---- --- ------------ ------------ \n --------------\n B D 20140722105345001 F D S0000000.LOG S0000000.LOG \n\n ------------------------------------------------------------ \n ---------------- \n \n Contains 4 tablespace(s): \n 00001 SYSCATSPACE \n \n 00002 USERSPACE1\n \n 00003 SYSTOOLSPACE \n \n 00004 TS1 \n ------------------------------------------------------------ \n ---------------- \n Comment: DB2 BACKUP ONE OFFLINE \n \n Start Time: 20140722105345 \n \n End Time: 20140722105347\n \n Status: A\n ------------------------------------------------------------ \n ---------------- \n EID: 3 Location: /home/db2inst1 \n\n \n Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log \n Backup ID\n -- --- ------------------ ---- --- ------------ ------------ \n -------------- \n B D 20140722112239000 N S0000000.LOG S0000000.LOG \n ------------------------------------------------------------ \n ------------------------------------------------------------- \n ------------------------------- \n \n Comment: DB2 BACKUP ONE ONLINE \n \n Start Time: 20140722112239 \n \n End Time: 20140722112240 \n \n Status: A \n ------------------------------------------------------------ \n ---------------- \n EID: 4 Location: \nSQLCA Information \n \n sqlcaid : SQLCA sqlcabc: 136 sqlcode: -2413 sqlerrml: 0 \n \n sqlerrmc: \n sqlerrp : sqlubIni \n sqlerrd : (1) 0 (2) 0 (3) 0 \n \n (4) 0 (5) 0 (6) 0 \n\t\t \n sqlwarn : (1) (2) (3) (4) (5) (6) \n \n (7) (8) (9) (10) (11) \n sqlstate: \n \n Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log \n Backup ID\n -- --- ------------------ ---- --- ------------ ------------ \n -------------- \n B D 20140722112743001 F D S0000000.LOG S0000000.LOG \n \n ------------------------------------------------------------ \n ---------------- \n Contains 4 tablespace(s): \n \n 00001 SYSCATSPACE \n \n 00002 USERSPACE1 \n \n 00003 SYSTOOLSPACE \n \n 00004 TS1\n ------------------------------------------------------------- \n ---------------- \n Comment: DB2 BACKUP ONE OFFLINE \n \n Start Time: 20140722112743 \n \n End Time: 20140722112743 \n \n Status: A \n ------------------------------------------------------------- \n ---------------- \n EID: 5 Location: /home/db2inst1 \n \n Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log \n Backup ID \n ------------------------------------------------------------- \n ----------------\n \nR D 20140722114519001 F \n20140722112743 \n\n ------------------------------------------------------------ \n ---------------- \n Contains 4 tablespace(s): \n \n 00001 SYSCATSPACE \n \n 00002 USERSPACE1 \n \n 00003 SYSTOOLSPACE \n \n 00004 TS1\n ------------------------------------------------------------ \n ---------------- \nComment: RESTORE ONE WITH RF\n \n Start Time: 20140722114519 \n \n End Time: 20140722115015 \n Status: A \n\t \n ------------------------------------------------------------ \n ---------------- \n EID: 6 Location: "
},
{
"code": null,
"e": 80335,
"s": 80256,
"text": "To restore the database from backup file, you need to follow the given syntax:"
},
{
"code": null,
"e": 80343,
"s": 80335,
"text": "Syntax:"
},
{
"code": null,
"e": 80416,
"s": 80343,
"text": "db2 restore database <db_name> from <location> \ntaken at <timestamp> "
},
{
"code": null,
"e": 80425,
"s": 80416,
"text": "Example:"
},
{
"code": null,
"e": 80498,
"s": 80425,
"text": "db2 restore database one from /home/db2inst1/ taken at \n20140722112743 "
},
{
"code": null,
"e": 80506,
"s": 80498,
"text": "Output:"
},
{
"code": null,
"e": 80908,
"s": 80506,
"text": "SQL2523W Warning! Restoring to an existing database that is \ndifferent from \n \nthe database on the backup image, but have matching names. \nThe target database \n \nwill be overwritten by the backup version. The Roll-forward \nrecovery logs\n\nassociated with the target database will be deleted. \n\nDo you want to continue ? (y/n) y \n \nDB20000I The RESTORE DATABASE command completed successfully. "
},
{
"code": null,
"e": 81025,
"s": 80908,
"text": "Roll forward all the logs located in the log directory, including latest changes just before the disk drive failure."
},
{
"code": null,
"e": 81033,
"s": 81025,
"text": "Syntax:"
},
{
"code": null,
"e": 81089,
"s": 81033,
"text": "db2 rollforward db <db_name> to end of logs and stop "
},
{
"code": null,
"e": 81098,
"s": 81089,
"text": "Example:"
},
{
"code": null,
"e": 81147,
"s": 81098,
"text": "db2 rollforward db one to end of logs and stop "
},
{
"code": null,
"e": 81155,
"s": 81147,
"text": "Output:"
},
{
"code": null,
"e": 81659,
"s": 81155,
"text": " Rollforward Status \n Input database alias = one \n Number of members have returned status = 1 \n Member ID = 0 \n Rollforward status = not pending \n Next log file to be read = \n Log files processed = S0000000.LOG - \n S0000001.LOG \n Last committed transaction = 2014-07-22- \n 06.00.33.000000 UTC \nDB20000I The ROLLFORWARD command completed successfully. "
},
{
"code": null,
"e": 81701,
"s": 81659,
"text": "This chapter describes database security."
},
{
"code": null,
"e": 81788,
"s": 81701,
"text": "DB2 database and functions can be managed by two different modes of security controls:"
},
{
"code": null,
"e": 81819,
"s": 81788,
"text": "\nAuthentication\nAuthorization\n"
},
{
"code": null,
"e": 81834,
"s": 81819,
"text": "Authentication"
},
{
"code": null,
"e": 81848,
"s": 81834,
"text": "Authorization"
},
{
"code": null,
"e": 82234,
"s": 81848,
"text": "Authentication is the process of confirming that a user logs in only in accordance with the rights to perform the activities he is authorized to perform. User authentication can be performed at operating system level or database level itself. By using authentication tools for biometrics such as retina and figure prints are in use to keep the database from hackers or malicious users."
},
{
"code": null,
"e": 82364,
"s": 82234,
"text": "The database security can be managed from outside the db2 database system. Here are some type of security authentication process:"
},
{
"code": null,
"e": 82407,
"s": 82364,
"text": "Based on Operating System authentications."
},
{
"code": null,
"e": 82452,
"s": 82407,
"text": "Lightweight Directory Access Protocol (LDAP)"
},
{
"code": null,
"e": 82638,
"s": 82452,
"text": "For DB2, the security service is a part of operating system as a separate product. For Authentication, it requires two different credentials, those are userid or username, and password."
},
{
"code": null,
"e": 82976,
"s": 82638,
"text": "You can access the DB2 Database and its functionality within the DB2 database system, which is managed by the DB2 Database manager. Authorization is a process managed by the DB2 Database manager. The manager obtains information about the current authenticated user, that indicates which database operation the user can perform or access."
},
{
"code": null,
"e": 83044,
"s": 82976,
"text": "Here are different ways of permissions available for authorization:"
},
{
"code": null,
"e": 83102,
"s": 83044,
"text": "Primary permission: Grants the authorization ID directly."
},
{
"code": null,
"e": 83179,
"s": 83102,
"text": "Secondary permission: Grants to the groups and roles if the user is a member"
},
{
"code": null,
"e": 83228,
"s": 83179,
"text": "Public permission: Grants to all users publicly."
},
{
"code": null,
"e": 83294,
"s": 83228,
"text": "Context-sensitive permission: Grants to the trusted context role."
},
{
"code": null,
"e": 83361,
"s": 83294,
"text": "Authorization can be given to users based on the categories below:"
},
{
"code": null,
"e": 83388,
"s": 83361,
"text": "System-level authorization"
},
{
"code": null,
"e": 83418,
"s": 83388,
"text": "System administrator [SYSADM]"
},
{
"code": null,
"e": 83443,
"s": 83418,
"text": "System Control [SYSCTRL]"
},
{
"code": null,
"e": 83473,
"s": 83443,
"text": "System maintenance [SYSMAINT]"
},
{
"code": null,
"e": 83497,
"s": 83473,
"text": "System monitor [SYSMON]"
},
{
"code": null,
"e": 83696,
"s": 83497,
"text": "Authorities provide of control over instance-level functionality. Authority provide to group privileges, to control maintenance and authority operations. For instance, database and database objects."
},
{
"code": null,
"e": 83725,
"s": 83696,
"text": "Database-level authorization"
},
{
"code": null,
"e": 83757,
"s": 83725,
"text": "Security Administrator [SECADM]"
},
{
"code": null,
"e": 83788,
"s": 83757,
"text": "Database Administrator [DBADM]"
},
{
"code": null,
"e": 83816,
"s": 83788,
"text": "Access Control [ACCESSCTRL]"
},
{
"code": null,
"e": 83841,
"s": 83816,
"text": "Data access [DATAACCESS]"
},
{
"code": null,
"e": 83869,
"s": 83841,
"text": "SQL administrator. [SQLADM]"
},
{
"code": null,
"e": 83912,
"s": 83869,
"text": "Workload management administrator [WLMADM]"
},
{
"code": null,
"e": 83930,
"s": 83912,
"text": "Explain [EXPLAIN]"
},
{
"code": null,
"e": 84042,
"s": 83930,
"text": "Authorities provide controls within the database. Other authorities for database include with LDAD and CONNECT."
},
{
"code": null,
"e": 84172,
"s": 84042,
"text": "Object-Level Authorization: Object-Level authorization involves verifying privileges when an operation is performed on an object."
},
{
"code": null,
"e": 84331,
"s": 84172,
"text": "Content-based Authorization: User can have read and write access to individual rows and columns on a particular table using Label-based access Control [LBAC]."
},
{
"code": null,
"e": 84535,
"s": 84331,
"text": "DB2 tables and configuration files are used to record the permissions associated with authorization names. When a user tries to access the data, the recorded permissions verify the following permissions:"
},
{
"code": null,
"e": 84566,
"s": 84535,
"text": "Authorization name of the user"
},
{
"code": null,
"e": 84598,
"s": 84566,
"text": "Which group belongs to the user"
},
{
"code": null,
"e": 84668,
"s": 84598,
"text": "Which roles are granted directly to the user or indirectly to a group"
},
{
"code": null,
"e": 84716,
"s": 84668,
"text": "Permissions acquired through a trusted context."
},
{
"code": null,
"e": 84839,
"s": 84716,
"text": "While working with the SQL statements, the DB2 authorization model considers the combination of the following permissions:"
},
{
"code": null,
"e": 84927,
"s": 84839,
"text": "Permissions granted to the primary authorization ID associated with the SQL statements."
},
{
"code": null,
"e": 84991,
"s": 84927,
"text": "Secondary authorization IDs associated with the SQL statements."
},
{
"code": null,
"e": 85009,
"s": 84991,
"text": "Granted to PUBLIC"
},
{
"code": null,
"e": 85046,
"s": 85009,
"text": "Granted to the trusted context role."
},
{
"code": null,
"e": 85096,
"s": 85046,
"text": "Let us discuss some instance related authorities."
},
{
"code": null,
"e": 85337,
"s": 85096,
"text": "It is highest level administrative authority at the instance-level. Users with SYSADM authority can execute some databases and database manager commands within the instance. Users with SYSADM authority can perform the following operations:"
},
{
"code": null,
"e": 85356,
"s": 85337,
"text": "Upgrade a Database"
},
{
"code": null,
"e": 85375,
"s": 85356,
"text": "Restore a Database"
},
{
"code": null,
"e": 85419,
"s": 85375,
"text": "Update Database manager configuration file."
},
{
"code": null,
"e": 85694,
"s": 85419,
"text": "It is the highest level in System control authority. It provides to perform maintenance and utility operations against the database manager instance and its databases. These operations can affect system resources, but they do not allow direct access to data in the database."
},
{
"code": null,
"e": 85758,
"s": 85694,
"text": "Users with SYSCTRL authority can perform the following actions:"
},
{
"code": null,
"e": 85834,
"s": 85758,
"text": "Updating the database, Node, or Distributed Connect Service (DCS) directory"
},
{
"code": null,
"e": 85869,
"s": 85834,
"text": "Forcing users off the system-level"
},
{
"code": null,
"e": 85907,
"s": 85869,
"text": "Creating or Dropping a database-level"
},
{
"code": null,
"e": 85953,
"s": 85907,
"text": "Creating, altering, or dropping a table space"
},
{
"code": null,
"e": 85975,
"s": 85953,
"text": "Using any table space"
},
{
"code": null,
"e": 85994,
"s": 85975,
"text": "Restoring Database"
},
{
"code": null,
"e": 86385,
"s": 85994,
"text": "It is a second level of system control authority. It provides to perform maintenance and utility operations against the database manager instance and its databases. These operations affect the system resources without allowing direct access to data in the database. This authority is designed for users to maintain databases within a database manager instance that contains sensitive data."
},
{
"code": null,
"e": 86478,
"s": 86385,
"text": "Only Users with SYSMAINT or higher level system authorities can perform the following tasks:"
},
{
"code": null,
"e": 86492,
"s": 86478,
"text": "Taking backup"
},
{
"code": null,
"e": 86513,
"s": 86492,
"text": "Restoring the backup"
},
{
"code": null,
"e": 86535,
"s": 86513,
"text": "Roll forward recovery"
},
{
"code": null,
"e": 86565,
"s": 86535,
"text": "Starting or stopping instance"
},
{
"code": null,
"e": 86587,
"s": 86565,
"text": "Restoring tablespaces"
},
{
"code": null,
"e": 86612,
"s": 86587,
"text": "Executing db2trc command"
},
{
"code": null,
"e": 86704,
"s": 86612,
"text": "Taking system monitor snapshots in case of an Instance level user or a database level user."
},
{
"code": null,
"e": 86758,
"s": 86704,
"text": "A user with SYSMAINT can perform the following tasks:"
},
{
"code": null,
"e": 86790,
"s": 86758,
"text": "Query the state of a tablespace"
},
{
"code": null,
"e": 86817,
"s": 86790,
"text": "Updating log history files"
},
{
"code": null,
"e": 86840,
"s": 86817,
"text": "Reorganizing of tables"
},
{
"code": null,
"e": 86887,
"s": 86840,
"text": "Using RUNSTATS (Collection catalog statistics)"
},
{
"code": null,
"e": 87055,
"s": 86887,
"text": "With this authority, the user can monitor or take snapshots of database manager instance or its database. SYSMON authority enables the user to run the following tasks:"
},
{
"code": null,
"e": 87093,
"s": 87055,
"text": "GET DATABASE MANAGER MONITOR SWITCHES"
},
{
"code": null,
"e": 87114,
"s": 87093,
"text": "GET MONITOR SWITCHES"
},
{
"code": null,
"e": 87127,
"s": 87114,
"text": "GET SNAPSHOT"
},
{
"code": null,
"e": 87314,
"s": 87127,
"text": "LIST\n\nLIST ACTIVE DATABASES\nLIST APPLICATIONS\nLIST DATABASE PARTITION GROUPS\nLIST DCS APPLICATIONS\nLIST PACKAGES\nLIST TABLES\nLIST TABLESPACE CONTAINERS\nLIST TABLESPACES\nLIST UTITLITIES\n\n"
},
{
"code": null,
"e": 87336,
"s": 87314,
"text": "LIST ACTIVE DATABASES"
},
{
"code": null,
"e": 87354,
"s": 87336,
"text": "LIST APPLICATIONS"
},
{
"code": null,
"e": 87385,
"s": 87354,
"text": "LIST DATABASE PARTITION GROUPS"
},
{
"code": null,
"e": 87407,
"s": 87385,
"text": "LIST DCS APPLICATIONS"
},
{
"code": null,
"e": 87421,
"s": 87407,
"text": "LIST PACKAGES"
},
{
"code": null,
"e": 87433,
"s": 87421,
"text": "LIST TABLES"
},
{
"code": null,
"e": 87460,
"s": 87433,
"text": "LIST TABLESPACE CONTAINERS"
},
{
"code": null,
"e": 87477,
"s": 87460,
"text": "LIST TABLESPACES"
},
{
"code": null,
"e": 87493,
"s": 87477,
"text": "LIST UTITLITIES"
},
{
"code": null,
"e": 87507,
"s": 87493,
"text": "RESET MONITOR"
},
{
"code": null,
"e": 87531,
"s": 87507,
"text": "UPDATE MONITOR SWITCHES"
},
{
"code": null,
"e": 87727,
"s": 87531,
"text": "Each database authority holds the authorization ID to perform some action on the database. These database authorities are different from privileges. Here is the list of some database authorities:"
},
{
"code": null,
"e": 87814,
"s": 87727,
"text": "ACCESSCTRL: allows to grant and revoke all object privileges and database authorities."
},
{
"code": null,
"e": 87871,
"s": 87814,
"text": "BINDADD: Allows to create a new package in the database."
},
{
"code": null,
"e": 87915,
"s": 87871,
"text": "CONNECT: Allows to connect to the database."
},
{
"code": null,
"e": 87971,
"s": 87915,
"text": "CREATETAB: Allows to create new tables in the database."
},
{
"code": null,
"e": 88084,
"s": 87971,
"text": "CREATE_EXTERNAL_ROUTINE: Allows to create a procedure to be used by applications and the users of the databases."
},
{
"code": null,
"e": 88149,
"s": 88084,
"text": "DATAACCESS: Allows to access data stored in the database tables."
},
{
"code": null,
"e": 88272,
"s": 88149,
"text": "DBADM: Act as a database administrator. It gives all other database authorities except ACCESSCTRL, DATAACCESS, and SECADM."
},
{
"code": null,
"e": 88391,
"s": 88272,
"text": "EXPLAIN: Allows to explain query plans without requiring them to hold the privileges to access the data in the tables."
},
{
"code": null,
"e": 88500,
"s": 88391,
"text": "IMPLICIT_SCHEMA: Allows a user to create a schema implicitly by creating an object using a CREATE statement."
},
{
"code": null,
"e": 88538,
"s": 88500,
"text": "LOAD: Allows to load data into table."
},
{
"code": null,
"e": 88629,
"s": 88538,
"text": "QUIESCE_CONNECT: Allows to access the database while it is quiesce (temporarily disabled)."
},
{
"code": null,
"e": 88697,
"s": 88629,
"text": "SECADM: Allows to act as a security administrator for the database."
},
{
"code": null,
"e": 88748,
"s": 88697,
"text": "SQLADM: Allows to monitor and tune SQL statements."
},
{
"code": null,
"e": 88798,
"s": 88748,
"text": "WLMADM: Allows to act as a workload administrator"
},
{
"code": null,
"e": 89140,
"s": 88798,
"text": "Authorization ID privileges involve actions on authorization IDs. There is only one privilege, called the SETSESSIONUSER privilege. It can be granted to user or a group and it allows to session user to switch identities to any of the authorization IDs on which the privileges are granted. This privilege is granted by user SECADM authority."
},
{
"code": null,
"e": 89464,
"s": 89140,
"text": "This privileges involve actions on schema in the database. The owner of the schema has all the permissions to manipulate the schema objects like tables, views, indexes, packages, data types, functions, triggers, procedures and aliases. A user, a group, a role, or PUBLIC can be granted any user of the following privileges:"
},
{
"code": null,
"e": 89517,
"s": 89464,
"text": "CREATEIN: allows to create objects within the schema"
},
{
"code": null,
"e": 89570,
"s": 89517,
"text": "ALTERIN: allows to modify objects within the schema."
},
{
"code": null,
"e": 89623,
"s": 89570,
"text": "This allows to delete the objects within the schema."
},
{
"code": null,
"e": 90043,
"s": 89623,
"text": "These privileges involve actions on the tablespaces in the database. User can be granted the USE privilege for the tablespaces. The privileges then allow them to create tables within tablespaces. The privilege owner can grant the USE privilege with the command WITH GRANT OPTION on the tablespace when tablespace is created. And SECADM or ACCESSCTRL authorities have the permissions to USE privileges on the tablespace."
},
{
"code": null,
"e": 90198,
"s": 90043,
"text": "The user must have CONNECT authority on the database to be able to use table and view privileges. The privileges for tables and views are as given below:"
},
{
"code": null,
"e": 90325,
"s": 90198,
"text": "It provides all the privileges for a table or a view including drop and grant, revoke individual table privileges to the user."
},
{
"code": null,
"e": 90359,
"s": 90325,
"text": "It allows user to modify a table."
},
{
"code": null,
"e": 90417,
"s": 90359,
"text": "It allows the user to delete rows from the table or view."
},
{
"code": null,
"e": 90505,
"s": 90417,
"text": " It allows the user to insert a row into table or view. It can also run import utility."
},
{
"code": null,
"e": 90559,
"s": 90505,
"text": "It allows the users to create and drop a foreign key."
},
{
"code": null,
"e": 90617,
"s": 90559,
"text": "It allows the user to retrieve rows from a table or view."
},
{
"code": null,
"e": 90672,
"s": 90617,
"text": "It allows the user to change entries in a table, view."
},
{
"code": null,
"e": 90872,
"s": 90672,
"text": "User must have CONNECT authority to the database. Package is a database object that contains the information of database manager to access data in the most efficient way for a particular application."
},
{
"code": null,
"e": 91026,
"s": 90872,
"text": "It provides the user with privileges of rebinding, dropping or executing packages. A user with this privileges is granted to BIND and EXECUTE privileges."
},
{
"code": null,
"e": 91077,
"s": 91026,
"text": "It allows the user to bind or rebind that package."
},
{
"code": null,
"e": 91106,
"s": 91077,
"text": "Allows to execute a package."
},
{
"code": null,
"e": 91176,
"s": 91106,
"text": "This privilege automatically receives CONTROL privilege on the index."
},
{
"code": null,
"e": 91256,
"s": 91176,
"text": "Sequence automatically receives the USAGE and ALTER privileges on the sequence."
},
{
"code": null,
"e": 91353,
"s": 91256,
"text": "It involves the action of routines such as functions, procedures, and methods within a database."
},
{
"code": null,
"e": 91500,
"s": 91353,
"text": "A role is a database object that groups multiple privileges that can be assigned to users, groups, PUBLIC or other roles by using GRANT statement."
},
{
"code": null,
"e": 91536,
"s": 91500,
"text": "A role cannot own database objects."
},
{
"code": null,
"e": 91736,
"s": 91536,
"text": "Permissions and roles granted to groups are not considered when you create the following database objects.\n\nPackage Containing static SQL\nViews\nMaterialized Query Tables (MQT)\nTriggers\nSQL Routines\n\n"
},
{
"code": null,
"e": 91766,
"s": 91736,
"text": "Package Containing static SQL"
},
{
"code": null,
"e": 91772,
"s": 91766,
"text": "Views"
},
{
"code": null,
"e": 91804,
"s": 91772,
"text": "Materialized Query Tables (MQT)"
},
{
"code": null,
"e": 91813,
"s": 91804,
"text": "Triggers"
},
{
"code": null,
"e": 91826,
"s": 91813,
"text": "SQL Routines"
},
{
"code": null,
"e": 91857,
"s": 91826,
"text": "Syntax: [To create a new role]"
},
{
"code": null,
"e": 91886,
"s": 91857,
"text": "db2 create role <role_name> "
},
{
"code": null,
"e": 91986,
"s": 91886,
"text": "Example: [To create a new role named ‘sales’ to add some table to be managed by some user or group]"
},
{
"code": null,
"e": 92009,
"s": 91986,
"text": "db2 create role sales "
},
{
"code": null,
"e": 92017,
"s": 92009,
"text": "Output:"
},
{
"code": null,
"e": 92067,
"s": 92017,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 92118,
"s": 92067,
"text": "Syntax: [To grant permission of a role to a table]"
},
{
"code": null,
"e": 92178,
"s": 92118,
"text": "db2 grant select on table <table_name> to role <role_name> "
},
{
"code": null,
"e": 92255,
"s": 92178,
"text": "Example: [To add permission to manage a table ‘shope.books’ to role ‘sales’]"
},
{
"code": null,
"e": 92308,
"s": 92255,
"text": "db2 grant select on table shope.books to role sales "
},
{
"code": null,
"e": 92316,
"s": 92308,
"text": "Output:"
},
{
"code": null,
"e": 92367,
"s": 92316,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 92486,
"s": 92367,
"text": "Security administrator grants role to the required users. (Before you use this command, you need to create the users.)"
},
{
"code": null,
"e": 92519,
"s": 92486,
"text": "Syntax: [To add users to a role]"
},
{
"code": null,
"e": 92566,
"s": 92519,
"text": "db2 grant role <role_name> to user <username> "
},
{
"code": null,
"e": 92622,
"s": 92566,
"text": "Example: [To add a user ‘mastanvali’ to a role ‘sales’]"
},
{
"code": null,
"e": 92659,
"s": 92622,
"text": "db2 grant sales to user mastanvali "
},
{
"code": null,
"e": 92667,
"s": 92659,
"text": "Output:"
},
{
"code": null,
"e": 92718,
"s": 92667,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 92820,
"s": 92718,
"text": "For creating a hierarchies for roles, each role is granted permissions/ membership with another role."
},
{
"code": null,
"e": 92893,
"s": 92820,
"text": "Syntax: [before this syntax create a new role with name of “production”]"
},
{
"code": null,
"e": 92940,
"s": 92893,
"text": "db2 grant role <roll_name> to role <role_name>"
},
{
"code": null,
"e": 93020,
"s": 92940,
"text": "Example: [To provide permission of a role ‘sales’ to another role ‘production’]"
},
{
"code": null,
"e": 93056,
"s": 93020,
"text": "db2 grant sales to role production "
},
{
"code": null,
"e": 93344,
"s": 93056,
"text": "LDAP is Lightweight Directory Access Protocol. LDAP is a global directory service, industry-standard protocol, which is based on client-server model and runs on a layer above the TCP/IP stack. The LDAP provides a facility to connect to, access, modify, and search the internet directory."
},
{
"code": null,
"e": 93764,
"s": 93344,
"text": "The LDAP servers contain information which is organized in the form of a directory tree. The clients ask server to provide information or to perform some operation on a particular information. The server answers the client by providing required information if it has one, or it refers the client to another server for action on required information. The client then acquires the desired information from another server."
},
{
"code": null,
"e": 94138,
"s": 93764,
"text": "The tree structure of directory is maintained same across all the participating servers. This is a prominent feature of LDAP directory service. Hence, irrespective of which server is referred to by the client, the client always gets required information in an error-free manner. Here, we use LDAP to authenticate IBM DB2 as a replacement of operating system authentication."
},
{
"code": null,
"e": 94167,
"s": 94138,
"text": "There are two types of LDAP:"
},
{
"code": null,
"e": 94189,
"s": 94167,
"text": "\nTransparent\nPlug-in\n"
},
{
"code": null,
"e": 94201,
"s": 94189,
"text": "Transparent"
},
{
"code": null,
"e": 94209,
"s": 94201,
"text": "Plug-in"
},
{
"code": null,
"e": 94257,
"s": 94209,
"text": "Let us see how to configure a transparent LDAP."
},
{
"code": null,
"e": 94345,
"s": 94257,
"text": "To start with configuration of transparent LDAP, you need to configure the LDAP server."
},
{
"code": null,
"e": 94554,
"s": 94345,
"text": "Create a SLAPD.conf file, which contains all the information about users and group object in the LDAP. When you install LDAP server, by default it is configured with basic LDAP directory tree on your machine."
},
{
"code": null,
"e": 94629,
"s": 94554,
"text": "The table shown below indicates the file configuration after modification."
},
{
"code": null,
"e": 94700,
"s": 94629,
"text": "The text highlighted with yellow the code box means for the following:"
},
{
"code": null,
"e": 94810,
"s": 94700,
"text": "DBA user-id = “db2my1”, group = “db1my1adm”, password= “db2my1” Admin user-id = “my1adm”, group = “dbmy1ctl”."
},
{
"code": null,
"e": 96069,
"s": 94810,
"text": "# base dn: example.com \ndn: dc=example,dc=com \ndc: example \no: example \nobjectClass: organization \nobjectClass: dcObject \n# pc box db \ndn: dc=db697,dc=example,dc=com \ndc: db697 \no: db697 \nobjectClass: organization \nobjectClass: dcObject \n# \n# Group: dbadm \n# \ndn: cn=dbmy1adm,dc=db697,dc=example,dc=com \ncn: dbmy1adm \nobjectClass: top \nobjectClass: posixGroup \ngidNumber: 400 \nobjectClass: groupOfNames \nmember: uid=db2my1,cn=dbmy1adm,dc=db697,dc=example,dc=com \nmemberUid: db2my1 \n# \n# User: db2 \n# \ndn: uid=db2my1,cn=dbmy1adm,dc=db697,dc=example,dc=com \ncn: db2my1 \nsn: db2my1 \nuid: db2my1 \nobjectClass: top \nobjectClass: inetOrgPerson \nobjectClass: posixAccount \nuidNumber: 400 \ngidNumber: 400 \nloginShell: /bin/csh \nhomeDirectory: /db2/db2my1 \n# \n# Group: dbctl \n# \ndn: cn=dbmy1ctl,dc=db697,dc=example,dc=com \ncn: dbmy1ctl \nobjectClass: top \nobjectClass: posixGroup \ngidNumber: 404 \nobjectClass: groupOfNames \nmember: uid=my1adm,cn=dbmy1adm,dc=db697,dc=example,dc=com \nmemberUid: my1adm \n# \n# User: adm \n# \ndn: uid=my1adm,cn=dbmy1ctl,dc=db697,dc=example,dc=com \ncn: my1adm \nsn: my1adm \nuid: my1adm \nobjectClass: top \nobjectClass: inetOrgPerson \nobjectClass: posixAccount \nuidNumber: 404 \ngidNumber: 404 \nloginShell: /bin/csh \nhomeDirectory: /home/my1adm "
},
{
"code": null,
"e": 96248,
"s": 96069,
"text": "Save the above file with name ‘/var/lib/slapd.conf’, then execute this file by following command to add these values into LDAP Server. This is a linux command; not a db2 command."
},
{
"code": null,
"e": 96321,
"s": 96248,
"text": "ldapadd r- -D ‘cn=Manager,dc=example,dc=com” –W –f \n/var/lib/slapd.conf "
},
{
"code": null,
"e": 96576,
"s": 96321,
"text": "After registering the DB2 users and the DB2 group at the LDAP Server, logon to the particular user where you have installed instance and database. You need to configure LDAP client to confirm to client where your server is located, be it remote or local."
},
{
"code": null,
"e": 96850,
"s": 96576,
"text": "The LDAP Client configuration is saved in the file ‘ldap.conf’. There are two files available for configuration parameters, one is common and the other is specific. You should find the first one at ‘/etc/ldap.conf’ and the latter is located at ‘/etc/openldap/ldap.conf’."
},
{
"code": null,
"e": 96923,
"s": 96850,
"text": "The following data is available in common LDAP client configuration file"
},
{
"code": null,
"e": 97334,
"s": 96923,
"text": "# File: /etc/ldap.conf \n# The file contains lots of more entries and many of them \n# are comments. You show only the interesting values for now \nhost localhost \nbase dc=example,dc=com \nldap_version 3 \npam_password crypt \npam_filter objectclass=posixAccount \nnss_map_attribute uniqueMember member \nnss_base_passwd dc=example,dc=com \nnss_base_shadow dc=example,dc=com \nnss_base_group dc=example,dc=com "
},
{
"code": null,
"e": 97603,
"s": 97334,
"text": "You need to change the location of server and domain information according to the DB2 configuration. If we are using server in same system then mention it as ‘localhost’ at ‘host’ and at ‘base’ you can configure which is mentioned in ‘SLAPD.conf’ file for LDAP server."
},
{
"code": null,
"e": 97931,
"s": 97603,
"text": "Pluggable Authentication Model (PAM) is an API for authentication services. This is common interface for LDAP authentication with an encrypted password and special LDAP object of type posixAccount. All LDAP objects of this type represent an abstraction of an account with portable Operating System Interface (POSIX) attributes."
},
{
"code": null,
"e": 98156,
"s": 97931,
"text": "Network Security Services (NSS) is a set of libraries to support cross-platform development of security-enabled client and server applications. This includes libraries like SSL, TLS, PKCS S/MIME and other security standards."
},
{
"code": null,
"e": 98315,
"s": 98156,
"text": "You need to specify the base DN for this interface and two additional mapping attributes. OpenLDAP client configuration file contains the entries given below:"
},
{
"code": null,
"e": 98355,
"s": 98315,
"text": "host localhost \nbase dc=example,dc=com"
},
{
"code": null,
"e": 98421,
"s": 98355,
"text": "Till this you just define the host of LDAP serve and the base DN."
},
{
"code": null,
"e": 98507,
"s": 98421,
"text": "After you configured your LDAP Server and LDAP Client, verify both for communication."
},
{
"code": null,
"e": 98576,
"s": 98507,
"text": "Step1: Check your Local LDAP server is running. Using below command:"
},
{
"code": null,
"e": 98598,
"s": 98576,
"text": "ps -ef | grep -i ldap"
},
{
"code": null,
"e": 98674,
"s": 98598,
"text": "This command should list the LDAP deamon which represents your LDAP server:"
},
{
"code": null,
"e": 98736,
"s": 98674,
"text": "/usr/lib/openldap/slapd -h ldap:/// -u ldap -g ldap -o slp=on"
},
{
"code": null,
"e": 98927,
"s": 98736,
"text": "This indicates that you LDAP server is running and is waiting for request from clients. If there is no such process for previous commands you can start LDAP server with the ’rcldap’ command."
},
{
"code": null,
"e": 98941,
"s": 98927,
"text": "rcldap start "
},
{
"code": null,
"e": 99052,
"s": 98941,
"text": "When the server starts, you can monitor this in the file ‘/var/log/messages/ by issuing the following command."
},
{
"code": null,
"e": 99079,
"s": 99052,
"text": "tail –f /var/log/messages "
},
{
"code": null,
"e": 99418,
"s": 99079,
"text": "The ldapsearch command opens a connection to an LDAP server, binds to it and performs a search query which can be specified by using special parameters ‘-x’ connect to your LDAP server with a simple authentication mechanism by using the –x parameter instead of a more complex mechanism like Simple Authentication and Security Layer (SASL)"
},
{
"code": null,
"e": 99434,
"s": 99418,
"text": "ldapsearch –x "
},
{
"code": null,
"e": 99565,
"s": 99434,
"text": "LDAP server should reply with a response given below, containing all of your LDAP entries in a LDAP Data Interchange Format(LDIF)."
},
{
"code": null,
"e": 99883,
"s": 99565,
"text": "# extended LDIF \n# \n# LDAPv3 \n# base <> with scope subtree \n# filter: (objectclass=*) \n# requesting: ALL \n# example.com \ndn: dc=example,\ndc=com dc: example \no: example \nobjectClass: organization \nobjectClass: dcObject \n# search result \nsearch: 2 \nresult: 0 Success \n# numResponses: 2 \n# numEntries: 1 "
},
{
"code": null,
"e": 100118,
"s": 99883,
"text": "After working with LDAP server and client, you need to configure our DB2 database for use with LDAP. Let us discuss, how you can install and configure your database to use our LDAP environment for the DB2 user authentication process."
},
{
"code": null,
"e": 100254,
"s": 100118,
"text": "IBM provides a free package with LDAP plug-ins for DB2. The DB2 package includes three DB2 security plug-ins for each of the following:"
},
{
"code": null,
"e": 100281,
"s": 100254,
"text": "server side authentication"
},
{
"code": null,
"e": 100308,
"s": 100281,
"text": "client side authentication"
},
{
"code": null,
"e": 100321,
"s": 100308,
"text": "group lookup"
},
{
"code": null,
"e": 100690,
"s": 100321,
"text": "Depending upon your requirements, you can use any of the three plug-ins or all of them. This plugin do not support environments where some users are defined in LDAP and others in the operating Systems. If you decide to use the LDAP plug-ins, you need to define all users associated with the database in the LDAP server. The same principle applies to the group plug-in."
},
{
"code": null,
"e": 101394,
"s": 100690,
"text": "You have to decide which plug-ins are mandatory for our system. The client authentication plug-ins used in scenarios where the user ID and the password validation supplied on a CONNECT or ATTACH statement occurs on the client system. So the database manager configuration parameters SRVCON_AUTH or AUTHENTICATION need to be set to the value CLIENT. The client authentication is difficult to secure and is not generally recommended. Server plug-in is generally recommended because it performs a server side validation of user IDs and passwords, if the client executes a CONNECT or ATTACH statement and this is secure way. The server plug-in also provides a way to map LDAP user IDs DB2 authorization IDs."
},
{
"code": null,
"e": 101739,
"s": 101394,
"text": "Now you can start installation and configuration of the DB2 security plug-ins, you need to think about the required directory information tree for DB2. DB2 uses indirect authorization which means that a user belongs to a group and this group was granted with fewer authorities. You need to define all DB2 users and DB2 groups in LDAP directory."
},
{
"code": null,
"e": 101798,
"s": 101739,
"text": "The LDIF file openldap.ldif should contain the code below:"
},
{
"code": null,
"e": 103467,
"s": 101798,
"text": "# \n# LDAP root object \n# example.com \n# \ndn: dc=example,\ndc=com \ndc: example \no: example \nobjectClass: organization \nobjectClass: dcObject \n # \n # db2 groups \n # \n dn: cn=dasadm1,dc=example,dc=com \n cn: dasadm1 \n objectClass: top \n objectClass: posixGroup \n gidNumber: 300 \n objectClass: groupOfNames \n member: uid=dasusr1,cn=dasadm1,dc=example,dc=com \n memberUid: dasusr1 \n dn: cn=db2grp1,dc=example,dc=com \n cn: db2grp1 \n objectClass: top \n objectClass: posixGroup \n gidNumber: 301 \n objectClass: groupOfNames \n member: uid=db2inst2,cn=db2grp1,dc=example,dc=com memberUid: db2inst2 \n dn: cn=db2fgrp1,dc=example,dc=com \n cn: db2fgrp1 \n objectClass: top \n objectClass: posixGroup \n gidNumber: 302 \n objectClass: groupOfNames \n member: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com \n memberUid: db2fenc1 \n # \n # db2 users \n # \n dn: uid=dasusr1,\n cn=dasadm1,\n dc=example,dc=com \n cn: dasusr1 \n sn: dasusr1 \n uid: dasusr1 \n objectClass: top \n objectClass: inetOrgPerson \n objectClass: posixAccount \n uidNumber: 300 \n gidNumber: 300 \n loginShell: /bin/bash \n homeDirectory: /home/dasusr1 \n dn: uid=db2inst2,cn=db2grp1,dc=example,dc=com \n cn: db2inst2 \n sn: db2inst2 \n uid: db2inst2 \n objectClass: top \n objectClass: inetOrgPerson \n objectClass: posixAccount \n uidNumber: 301 \n gidNumber: 301 \n loginShell: /bin/bash \n homeDirectory: /home/db2inst2 \n dn: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com \n cn: db2fenc1 \n sn: db2fenc1 \n uid: db2fenc1 \n objectClass: top \n objectClass: inetOrgPerson \n objectClass: posixAccount \n uidNumber: 303 \n gidNumber: 303 \n loginShell: /bin/bash \n homeDirectory: /home/db2fenc1 \n "
},
{
"code": null,
"e": 103603,
"s": 103467,
"text": "Create a file named ‘db2.ldif’ and paste the above example into it. Using this file, add the defined structures to your LDAP directory."
},
{
"code": null,
"e": 103757,
"s": 103603,
"text": "To add the DB2 users and DB2 groups to the LDAP directory, you need to bind the user as ‘rootdn’ to the LDAP server in order to get the exact privileges."
},
{
"code": null,
"e": 103884,
"s": 103757,
"text": "Execute the following syntaxes to fill the LDAP information directory with all our objects defined in the LDIF file ‘db2.ldif’"
},
{
"code": null,
"e": 103953,
"s": 103884,
"text": "ldapadd –x –D “cn=Manager, dc=example,dc=com” –W –f <path>/db2.ldif "
},
{
"code": null,
"e": 103999,
"s": 103953,
"text": "Perform the search result with more parameter"
},
{
"code": null,
"e": 104020,
"s": 103999,
"text": "ldapsearch –x |more "
},
{
"code": null,
"e": 104247,
"s": 104020,
"text": "Creating instance for our LDAP user db2inst2. This user requires home directory with two empty files inside the home directory. Before you create a new instance, you need to create a user who will be the owner of the instance."
},
{
"code": null,
"e": 104465,
"s": 104247,
"text": "After creating the instance user, you should have to create the file ‘.profile’ and ‘.login’ in user home directory, which will be modified by DB2. To create this file in the directory, execute the following command:"
},
{
"code": null,
"e": 104549,
"s": 104465,
"text": "mkdir /home/db2inst2 \nmkdir /home/db2inst2/.login \nmkdir /home/db2inst2/.profile "
},
{
"code": null,
"e": 104838,
"s": 104549,
"text": "You have registered all users and groups related with DB2 in LDAP directory, now you can create an instance with the name ‘db2inst2’ with the instance owner id ‘db2inst2’ and use the fenced user id ‘db2fenc1’, which is needed for running user defined functions (UDFs)or stored procedures."
},
{
"code": null,
"e": 104948,
"s": 104838,
"text": "/opt/ibm/db2/V10.1/instance/db2icrt –u db2fenc1 db2inst2 \nDBI1070I Program db2icrt completed successfully. "
},
{
"code": null,
"e": 105093,
"s": 104948,
"text": "Now check the instance home directory. You can see new sub-directory called ‘sqllib’ and the .profile and .login files customized for DB2 usage."
},
{
"code": null,
"e": 105159,
"s": 105093,
"text": "Copy the required LDAP plug-ins to the appropriate DB2 directory:"
},
{
"code": null,
"e": 105338,
"s": 105159,
"text": "cp ///v10/IBMLDAPauthserver.so \n/home/db2inst2/sqllib/security/plugin/server/. \n \ncp ///v10/IBMLDAPgroups.so \n/home/db2inst2/sqllib/security/plugin/group/."
},
{
"code": null,
"e": 105505,
"s": 105338,
"text": "Once the plug-ins are copied to the specified directory, you toned to login to DB2 instance owner and change the database manager configuration to use these plug-ins."
},
{
"code": null,
"e": 105764,
"s": 105505,
"text": "Su – db2inst2 \ndb2inst2> db2 update dbm cfg using svrcon_pw_plugin \nIBMLDAPauthserver \ndb2inst2> db2 update dbm cfg using group_plugin \nIBMLDAPgroups \ndb2inst2> db2 update dbm cfg using authentication \nSERVER_ENCRYPT \ndb2inst2> db2stop \ndb2inst2> db2start "
},
{
"code": null,
"e": 106023,
"s": 105764,
"text": "This modification comes into effect after you start DB2 instance. After restarting the instance, you need to install and configure the main DB2 LDAP configuration file named “IBMLDAPSecurity.ini” to make DB2 plug-ins work with the current LDAP configuration."
},
{
"code": null,
"e": 106057,
"s": 106023,
"text": "IBMLDAPSecurity.ini file contains"
},
{
"code": null,
"e": 108262,
"s": 106057,
"text": ";----------------------------------------------------------- \n; SERVER RELATED VALUES \n;----------------------------------------------------------- \n; Name of your LDAP server(s). \n; This is a space separated list of LDAP server addresses, \n; with an optional port number for each one: \n; host1[:port] [host2:[port2] ... ] \n; The default port number is 389, or 636 if SSL is enabled. \nLDAP_HOST = my.ldap.server \n;----------------------------------------------------------- \n; USER RELATED VALUES \n;----------------------------------------------------------- \nrs \n; LDAP object class used for use USER_OBJECTCLASS = posixAccount \n; LDAP user attribute that represents the \"userid\" \n; This attribute is combined with the USER_OBJECTCLASS and \n; USER_BASEDN (if specified) to construct an LDAP search \n; filter when a user issues a DB2 CONNECT statement with an \n; unqualified userid. For example, using the default values \n; in this configuration file, (db2 connect to MYDB user bob \n; using bobpass) results in the following search filter: \nOrgPerson)(uid=bob) \n; &(objectClass=inet USERID_ATTRIBUTE = uid \nrepresenting the DB2 authorization ID \n; LDAP user attribute, AUTHID_ATTRIBUTE = uid \n;----------------------------------------------------------- \n; GROUP RELATED VALUES \n;----------------------------------------------------------- \nps \n; LDAP object class used for grou GROUP_OBJECTCLASS = groupOfNames \nat represents the name of the group \n; LDAP group attribute th GROUPNAME_ATTRIBUTE = cn \n; Determines the method used to find the group memberships \n; for a user. Possible values are: \n; SEARCH_BY_DN - Search for groups that list the user as \n; a member. Membership is indicated by the \n; group attribute defined as \n; GROUP_LOOKUP_ATTRIBUTE. \n; USER_ATTRIBUTE - A user's groups are listed as attributes \n; of the user object itself. Search for the \n; user attribute defined as \nTRIBUTE to get the groups. \n; GROUP_LOOKUP_AT GROUP_LOOKUP_METHOD = SEARCH_BY_DN \n; GROUP_LOOKUP_ATTRIBUTE \n; Name of the attribute used to determine group membership, \n; as described above. \nllGroups \n; GROUP_LOOKUP_ATTRIBUTE = ibm-a GROUP_LOOKUP_ATTRIBUTE = member "
},
{
"code": null,
"e": 108388,
"s": 108262,
"text": "Now locate the file IBMLDAPSecurity.ini file in the current instance directory. Copy the above sample contents into the same."
},
{
"code": null,
"e": 108457,
"s": 108388,
"text": "Cp \n//db2_ldap_pkg/IBMLDAPSecurity.ini \n/home/db2inst2/sqllib/cfg/ "
},
{
"code": null,
"e": 108532,
"s": 108457,
"text": "Now you need to restart your DB2 instance, using two syntaxes given below:"
},
{
"code": null,
"e": 108572,
"s": 108532,
"text": "db2inst2> db2stop \n\nDb2inst2> db2start "
},
{
"code": null,
"e": 108750,
"s": 108572,
"text": "At this point, if you try ‘db2start’ command, you will get security error message. Because, DB2 security configuration is not yet correctly configured for your LDAP environment."
},
{
"code": null,
"e": 108817,
"s": 108750,
"text": "Keep LDAP_HOST name handy, which is configured in slapd.conf file."
},
{
"code": null,
"e": 108941,
"s": 108817,
"text": "Now edit IMBLDAPSecurity.ini file and type the LDAP_HOST name. The LDAP_HOST name in both the said files must be identical."
},
{
"code": null,
"e": 108982,
"s": 108941,
"text": "The contents of file are as shown below:"
},
{
"code": null,
"e": 109863,
"s": 108982,
"text": " ;----------------------------------------------------------- \n ; SERVER RELATED VALUES \n ;----------------------------------------------------------- \n LDAP_HOST = localhost \n ;----------------------------------------------------------- \n ; USER RELATED VALUES \n ---------------------------- \n ;------------------------------- \n USER_OBJECTCLASS = posixAccount \n USER_BASEDN = dc=example,dc=com \n USERID_ATTRIBUTE = uid \n AUTHID_ATTRIBUTE = uid \n ;----------------------------------------------------------- \n ; GROUP RELATED VALUES \n ;----------------------------------------------------------- \n GROUP_OBJECTCLASS = groupOfNames \n\t GROUP_BASEDN = dc=example,dc=com \n GROUPNAME_ATTRIBUTE = cn \n GROUP_LOOKUP_METHOD = SEARCH_BY_DN \n GROUP_LOOKUP_ATTRIBUTE = member "
},
{
"code": null,
"e": 109974,
"s": 109863,
"text": "After changing these values, LDAP immediately takes effect and your DB2 environment with LDAP works perfectly."
},
{
"code": null,
"e": 110025,
"s": 109974,
"text": "You can logout and login again to ‘db2inst2’ user."
},
{
"code": null,
"e": 110075,
"s": 110025,
"text": "Now your instance is working with LDAP directory."
},
{
"code": null,
"e": 110110,
"s": 110075,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 110125,
"s": 110110,
"text": " Nishant Malik"
},
{
"code": null,
"e": 110160,
"s": 110125,
"text": "\n 41 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 110175,
"s": 110160,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 110211,
"s": 110175,
"text": "\n 53 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 110226,
"s": 110211,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 110259,
"s": 110226,
"text": "\n 33 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 110274,
"s": 110259,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 110307,
"s": 110274,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 110326,
"s": 110307,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 110363,
"s": 110326,
"text": "\n 178 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 110382,
"s": 110363,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 110389,
"s": 110382,
"text": " Print"
},
{
"code": null,
"e": 110400,
"s": 110389,
"text": " Add Notes"
}
] |
Reading images using Python? | OpenCV(Open source computer vision) is an open source programming library basically developed for machine learning and computer vision. It provides common infrastructure to work on computer vision applications and to fasten the use of machine learning in commercial products.
With more than 2.5 thousand optimized algorithms for both computer vision and machine learning are both classic and state-of-the-art algorithms. With so many algorithms, makes it to use the library for multiple purposes including face detection & recognization, identify objects, classify human actions in videos, track camera movements, join images together to produce a high resolution image of an entire scene and much more.
In this I'll try to explain how we can use OpenCV library and python to read and display image. This is implemented using cv2 and Numpy modules.
You can download numpy module from the Python Package Index(PyPI).
$ pip install numpy
We use cv2.imread() function to read an image. The image should be placed in the current working directory or else we need to provide the absoluate path.
import numpy as np
import cv2
# Load an color image in grayscale
img = cv2.imread('Top-bike-wallpaper.jpg',0)
To display an image in a window, use cv2.imshow() function.
#Display the image
cv2.imshow('image',img)
#key binding function
cv2.waitKey(0)
#Destroyed all window we created earlier.
cv2.destroyAllWindows()
On running above code, a screenshot of the window will look like this,
Use the function cv2.imwrite() to save an image.
First argument is the file name, second argument is the image you want to save.
cv2.imwrite('messigray.png',img)
Sum it up −
import numpy as np
import cv2
#Read the Image
# Load an color image in grayscale
img = cv2.imread('Top-bike-wallpaper.jpg',0)
#Display the image
cv2.imshow('image',img)
#key binding function
k = cv2.waitKey(0)
# wait for ESC key to exit
if k == 27:
cv2.destroyAllWindows()
# wait for 's' key to save and exit
elif k == ord('s'):
cv2.imwrite('myBike.jpg',img)
cv2.destroyAllWindows()
Save the image by pressing 's' or press 'ESC' key to simply exit without saving.
The Python Imaging Library (PIL) is image manipulation library in python. Use pip to install PIL library,
$ pip install Pillow
from PIL import Image, ImageFilter
#Read image
im = Image.open( 'myBike.png' )
#Display image
im.show()
#Applying a filter to the image
im_sharp = im.filter( ImageFilter.SHARPEN )
#Saving the filtered image to a new file
im_sharp.save( 'another_Bike.jpg', 'JPEG' )
Image is saved in my default location .i.e. currently working directory and a screenshot of the window will display our images. | [
{
"code": null,
"e": 1338,
"s": 1062,
"text": "OpenCV(Open source computer vision) is an open source programming library basically developed for machine learning and computer vision. It provides common infrastructure to work on computer vision applications and to fasten the use of machine learning in commercial products."
},
{
"code": null,
"e": 1766,
"s": 1338,
"text": "With more than 2.5 thousand optimized algorithms for both computer vision and machine learning are both classic and state-of-the-art algorithms. With so many algorithms, makes it to use the library for multiple purposes including face detection & recognization, identify objects, classify human actions in videos, track camera movements, join images together to produce a high resolution image of an entire scene and much more."
},
{
"code": null,
"e": 1911,
"s": 1766,
"text": "In this I'll try to explain how we can use OpenCV library and python to read and display image. This is implemented using cv2 and Numpy modules."
},
{
"code": null,
"e": 1978,
"s": 1911,
"text": "You can download numpy module from the Python Package Index(PyPI)."
},
{
"code": null,
"e": 1998,
"s": 1978,
"text": "$ pip install numpy"
},
{
"code": null,
"e": 2152,
"s": 1998,
"text": "We use cv2.imread() function to read an image. The image should be placed in the current working directory or else we need to provide the absoluate path."
},
{
"code": null,
"e": 2262,
"s": 2152,
"text": "import numpy as np\nimport cv2\n# Load an color image in grayscale\nimg = cv2.imread('Top-bike-wallpaper.jpg',0)"
},
{
"code": null,
"e": 2322,
"s": 2262,
"text": "To display an image in a window, use cv2.imshow() function."
},
{
"code": null,
"e": 2468,
"s": 2322,
"text": "#Display the image\ncv2.imshow('image',img)\n#key binding function\ncv2.waitKey(0)\n#Destroyed all window we created earlier.\ncv2.destroyAllWindows()"
},
{
"code": null,
"e": 2539,
"s": 2468,
"text": "On running above code, a screenshot of the window will look like this,"
},
{
"code": null,
"e": 2588,
"s": 2539,
"text": "Use the function cv2.imwrite() to save an image."
},
{
"code": null,
"e": 2668,
"s": 2588,
"text": "First argument is the file name, second argument is the image you want to save."
},
{
"code": null,
"e": 2701,
"s": 2668,
"text": "cv2.imwrite('messigray.png',img)"
},
{
"code": null,
"e": 2713,
"s": 2701,
"text": "Sum it up −"
},
{
"code": null,
"e": 3109,
"s": 2713,
"text": "import numpy as np\nimport cv2\n\n#Read the Image\n# Load an color image in grayscale\nimg = cv2.imread('Top-bike-wallpaper.jpg',0)\n\n#Display the image\ncv2.imshow('image',img)\n\n#key binding function\nk = cv2.waitKey(0)\n\n# wait for ESC key to exit\nif k == 27:\n cv2.destroyAllWindows()\n# wait for 's' key to save and exit\nelif k == ord('s'):\n cv2.imwrite('myBike.jpg',img)\n cv2.destroyAllWindows()"
},
{
"code": null,
"e": 3190,
"s": 3109,
"text": "Save the image by pressing 's' or press 'ESC' key to simply exit without saving."
},
{
"code": null,
"e": 3296,
"s": 3190,
"text": "The Python Imaging Library (PIL) is image manipulation library in python. Use pip to install PIL library,"
},
{
"code": null,
"e": 3317,
"s": 3296,
"text": "$ pip install Pillow"
},
{
"code": null,
"e": 3352,
"s": 3317,
"text": "from PIL import Image, ImageFilter"
},
{
"code": null,
"e": 3585,
"s": 3352,
"text": "#Read image\nim = Image.open( 'myBike.png' )\n\n#Display image\nim.show()\n\n#Applying a filter to the image\nim_sharp = im.filter( ImageFilter.SHARPEN )\n\n#Saving the filtered image to a new file\nim_sharp.save( 'another_Bike.jpg', 'JPEG' )"
},
{
"code": null,
"e": 3713,
"s": 3585,
"text": "Image is saved in my default location .i.e. currently working directory and a screenshot of the window will display our images."
}
] |
Head Pose Estimation using Python | Towards Data Science | Head pose estimation is one of the computer vision tasks that exist. In this task, we want to know the object’s pose from its translation and rotation.
This task has lots of applications. For example, we can detect whether the driver is paying attention to the road or not. The second example is that we can check whether the student is getting distracted from study or not. And there are lots of applications that we can do with it.
As you know, we have only a two-dimensional image. How can we estimate the pose of an object by relying on the image itself? We can use a solution called the Perspective-n-Point (PnP).
The PnP problem equation looks like this:
From this equation, we can retrieve the rotational and the translational matrix. But before we get those matrices, this equation needs to take three inputs, such as:
The 2D coordinates in the image space
The 3D coordinates in the world space
The camera parameters, such as the focal points, the center coordinate, and the skew parameter
From that equation, we got two main problems:
How can we get those inputs?
How can we estimate the pose from an object based on those inputs?
This article will show you how. In this article, we will use Python as the programming language. Also, we use the mediapipe library for detecting face keypoints and the OpenCV library for estimating the pose of a head.
Here is the preview of what we will create:
Without further, let’s get started!
Before we get into the implementation, the first step is to install the libraries. In this case, we will install the OpenCV and the Mediapipe library by using pip. On your terminal, please write this command:
pip install opencv-pythonpip install mediapipe
After we install the libraries, the next step is to load the libraries into our code. We will import the NumPy, OpenCV, and Mediapipe libraries. Please add this line of code:
After we load the libraries, the next step is to initialize several objects. There are two objects that we initialize. They are:
The FaceMesh object from the Mediapipe library. This object will detect faces and also detect keypoints from one or more faces.
The VideoCapture object from the OpenCV library. This object will be used for retrieving images from the webcam. We set a parameter on the object with 0 for retrieving images from the webcam.
Please add these lines of code:
Now we have initialized the objects. The next step is to capture the image from the webcam. Please add this line of code for doing that:
After we capture the image, the next step is to process the image. For your information, the OpenCV and the Mediapipe library read their image differently.
On the OpenCV library, the image is in BGR color space. Meanwhile, the mediapipe library needs an image with RGB color space.
Therefore, we need to convert the color space to RGB first, apply face landmark detection, then convert it back to BGR color space.
Please add these lines of code (Be careful with the indentation):
After we process the image, the next step is to retrieve the keypoint coordinates. For your information, the mediapipe’s face landmark detection algorithm catches around 468 keypoints from a face. Each keypoint is on 3D coordinates.
For head pose estimation, we don’t have to use all the keypoints. Instead, we choose 6 points that at least can represent a face. Those points are on the edge of the eyes, the nose, the chin, and the edge of the mouth.
For accessing those points, we refer to the index that has been used on the BlazeFace model. I’ve already marked the index. Here is the picture of it:
Now let’s extract those keypoints. For 2D coordinates, we will take only the x and y-axis coordinates. And for 3D coordinates, we retrieve all of the axes.
But before we extract those keypoints, we have to multiply the x-axis with the image’s width. Also, we multiply the y-axis with the image’s height.
Also, we will take the nose coordinates. We do that to display the projection of our nose on the image space.
Now let’s add these lines of code, and be careful with the indentation:
Now we have the 2D and 3D coordinates of our face keypoints. The next step is to get the camera matrix. Let’s recall the camera matrix once again.
As you can see from above, we need to have several parameters. The first one is the focal point. We can get the focal point (fx and fy) by taking the width of the image.
The second parameter that we will take is the skew parameter. The parameter has the symbol of gamma. For this parameter, we set the value to 0.
The third parameter is the center coordinate of our image. We will set the u0 with the image’s width set the v0 with the image’s height.
Now let’s create the matrix by generating a NumPy array. Now let’s add these lines of code:
Before we apply the PnP problem, we need to add another matrix. It’s a distance matrix. This matrix only contains zero, and it has a shape of 4x1. Now let’s create the matrix by adding this line of code:
We have all the inputs, ranging from the 2D coordinates, the 3D coordinates, the camera parameters matrix, and the empty distance matrix. Let’s apply the PnP to our problem by adding this line of code:
From this process, now we have the translational vector and the rotational vector. Wait, the rotational section is not in a matrix format. We cannot retrieve the rotation angle with it.
Don’t worry. We can convert the vector into the matrix by using the cv2.Rodrigues function.
Now let’s add this line of code:
Now we have the rotational matrix. Now let’s retrieve the rotational angle on each axis. For doing that, we can use the cv2.RQDecomp3x3 function for extracting the angles.
Now let’s add this line of code:
The last step that we have to do now is to determine where our head is heading. We display the direction and create a line to see the projection of our nose on the image space.
Now let’s add these lines of code:
By combining all of those lines of code, the result will look like this:
Well done! We have implemented the head pose estimation using Python. I hope it helps you in building your computer vision solution, especially the head pose estimation problem.
If you are interested in my articles, you can follow me on Medium. If you have any questions, you can connect with me on LinkedIn.
In case that you have confusion on writing the code, you can check the complete code here to help you:
Thank you for reading my article!
[1] https://medium.com/analytics-vidhya/real-time-head-pose-estimation-with-opencv-and-dlib-e8dc10d62078[2] https://learnopencv.com/head-pose-estimation-using-opencv-and-dlib/ | [
{
"code": null,
"e": 324,
"s": 172,
"text": "Head pose estimation is one of the computer vision tasks that exist. In this task, we want to know the object’s pose from its translation and rotation."
},
{
"code": null,
"e": 606,
"s": 324,
"text": "This task has lots of applications. For example, we can detect whether the driver is paying attention to the road or not. The second example is that we can check whether the student is getting distracted from study or not. And there are lots of applications that we can do with it."
},
{
"code": null,
"e": 791,
"s": 606,
"text": "As you know, we have only a two-dimensional image. How can we estimate the pose of an object by relying on the image itself? We can use a solution called the Perspective-n-Point (PnP)."
},
{
"code": null,
"e": 833,
"s": 791,
"text": "The PnP problem equation looks like this:"
},
{
"code": null,
"e": 999,
"s": 833,
"text": "From this equation, we can retrieve the rotational and the translational matrix. But before we get those matrices, this equation needs to take three inputs, such as:"
},
{
"code": null,
"e": 1037,
"s": 999,
"text": "The 2D coordinates in the image space"
},
{
"code": null,
"e": 1075,
"s": 1037,
"text": "The 3D coordinates in the world space"
},
{
"code": null,
"e": 1170,
"s": 1075,
"text": "The camera parameters, such as the focal points, the center coordinate, and the skew parameter"
},
{
"code": null,
"e": 1216,
"s": 1170,
"text": "From that equation, we got two main problems:"
},
{
"code": null,
"e": 1245,
"s": 1216,
"text": "How can we get those inputs?"
},
{
"code": null,
"e": 1312,
"s": 1245,
"text": "How can we estimate the pose from an object based on those inputs?"
},
{
"code": null,
"e": 1531,
"s": 1312,
"text": "This article will show you how. In this article, we will use Python as the programming language. Also, we use the mediapipe library for detecting face keypoints and the OpenCV library for estimating the pose of a head."
},
{
"code": null,
"e": 1575,
"s": 1531,
"text": "Here is the preview of what we will create:"
},
{
"code": null,
"e": 1611,
"s": 1575,
"text": "Without further, let’s get started!"
},
{
"code": null,
"e": 1820,
"s": 1611,
"text": "Before we get into the implementation, the first step is to install the libraries. In this case, we will install the OpenCV and the Mediapipe library by using pip. On your terminal, please write this command:"
},
{
"code": null,
"e": 1867,
"s": 1820,
"text": "pip install opencv-pythonpip install mediapipe"
},
{
"code": null,
"e": 2042,
"s": 1867,
"text": "After we install the libraries, the next step is to load the libraries into our code. We will import the NumPy, OpenCV, and Mediapipe libraries. Please add this line of code:"
},
{
"code": null,
"e": 2171,
"s": 2042,
"text": "After we load the libraries, the next step is to initialize several objects. There are two objects that we initialize. They are:"
},
{
"code": null,
"e": 2299,
"s": 2171,
"text": "The FaceMesh object from the Mediapipe library. This object will detect faces and also detect keypoints from one or more faces."
},
{
"code": null,
"e": 2491,
"s": 2299,
"text": "The VideoCapture object from the OpenCV library. This object will be used for retrieving images from the webcam. We set a parameter on the object with 0 for retrieving images from the webcam."
},
{
"code": null,
"e": 2523,
"s": 2491,
"text": "Please add these lines of code:"
},
{
"code": null,
"e": 2660,
"s": 2523,
"text": "Now we have initialized the objects. The next step is to capture the image from the webcam. Please add this line of code for doing that:"
},
{
"code": null,
"e": 2816,
"s": 2660,
"text": "After we capture the image, the next step is to process the image. For your information, the OpenCV and the Mediapipe library read their image differently."
},
{
"code": null,
"e": 2942,
"s": 2816,
"text": "On the OpenCV library, the image is in BGR color space. Meanwhile, the mediapipe library needs an image with RGB color space."
},
{
"code": null,
"e": 3074,
"s": 2942,
"text": "Therefore, we need to convert the color space to RGB first, apply face landmark detection, then convert it back to BGR color space."
},
{
"code": null,
"e": 3140,
"s": 3074,
"text": "Please add these lines of code (Be careful with the indentation):"
},
{
"code": null,
"e": 3373,
"s": 3140,
"text": "After we process the image, the next step is to retrieve the keypoint coordinates. For your information, the mediapipe’s face landmark detection algorithm catches around 468 keypoints from a face. Each keypoint is on 3D coordinates."
},
{
"code": null,
"e": 3592,
"s": 3373,
"text": "For head pose estimation, we don’t have to use all the keypoints. Instead, we choose 6 points that at least can represent a face. Those points are on the edge of the eyes, the nose, the chin, and the edge of the mouth."
},
{
"code": null,
"e": 3743,
"s": 3592,
"text": "For accessing those points, we refer to the index that has been used on the BlazeFace model. I’ve already marked the index. Here is the picture of it:"
},
{
"code": null,
"e": 3899,
"s": 3743,
"text": "Now let’s extract those keypoints. For 2D coordinates, we will take only the x and y-axis coordinates. And for 3D coordinates, we retrieve all of the axes."
},
{
"code": null,
"e": 4047,
"s": 3899,
"text": "But before we extract those keypoints, we have to multiply the x-axis with the image’s width. Also, we multiply the y-axis with the image’s height."
},
{
"code": null,
"e": 4157,
"s": 4047,
"text": "Also, we will take the nose coordinates. We do that to display the projection of our nose on the image space."
},
{
"code": null,
"e": 4229,
"s": 4157,
"text": "Now let’s add these lines of code, and be careful with the indentation:"
},
{
"code": null,
"e": 4376,
"s": 4229,
"text": "Now we have the 2D and 3D coordinates of our face keypoints. The next step is to get the camera matrix. Let’s recall the camera matrix once again."
},
{
"code": null,
"e": 4546,
"s": 4376,
"text": "As you can see from above, we need to have several parameters. The first one is the focal point. We can get the focal point (fx and fy) by taking the width of the image."
},
{
"code": null,
"e": 4690,
"s": 4546,
"text": "The second parameter that we will take is the skew parameter. The parameter has the symbol of gamma. For this parameter, we set the value to 0."
},
{
"code": null,
"e": 4827,
"s": 4690,
"text": "The third parameter is the center coordinate of our image. We will set the u0 with the image’s width set the v0 with the image’s height."
},
{
"code": null,
"e": 4919,
"s": 4827,
"text": "Now let’s create the matrix by generating a NumPy array. Now let’s add these lines of code:"
},
{
"code": null,
"e": 5123,
"s": 4919,
"text": "Before we apply the PnP problem, we need to add another matrix. It’s a distance matrix. This matrix only contains zero, and it has a shape of 4x1. Now let’s create the matrix by adding this line of code:"
},
{
"code": null,
"e": 5325,
"s": 5123,
"text": "We have all the inputs, ranging from the 2D coordinates, the 3D coordinates, the camera parameters matrix, and the empty distance matrix. Let’s apply the PnP to our problem by adding this line of code:"
},
{
"code": null,
"e": 5511,
"s": 5325,
"text": "From this process, now we have the translational vector and the rotational vector. Wait, the rotational section is not in a matrix format. We cannot retrieve the rotation angle with it."
},
{
"code": null,
"e": 5603,
"s": 5511,
"text": "Don’t worry. We can convert the vector into the matrix by using the cv2.Rodrigues function."
},
{
"code": null,
"e": 5636,
"s": 5603,
"text": "Now let’s add this line of code:"
},
{
"code": null,
"e": 5808,
"s": 5636,
"text": "Now we have the rotational matrix. Now let’s retrieve the rotational angle on each axis. For doing that, we can use the cv2.RQDecomp3x3 function for extracting the angles."
},
{
"code": null,
"e": 5841,
"s": 5808,
"text": "Now let’s add this line of code:"
},
{
"code": null,
"e": 6018,
"s": 5841,
"text": "The last step that we have to do now is to determine where our head is heading. We display the direction and create a line to see the projection of our nose on the image space."
},
{
"code": null,
"e": 6053,
"s": 6018,
"text": "Now let’s add these lines of code:"
},
{
"code": null,
"e": 6126,
"s": 6053,
"text": "By combining all of those lines of code, the result will look like this:"
},
{
"code": null,
"e": 6304,
"s": 6126,
"text": "Well done! We have implemented the head pose estimation using Python. I hope it helps you in building your computer vision solution, especially the head pose estimation problem."
},
{
"code": null,
"e": 6435,
"s": 6304,
"text": "If you are interested in my articles, you can follow me on Medium. If you have any questions, you can connect with me on LinkedIn."
},
{
"code": null,
"e": 6538,
"s": 6435,
"text": "In case that you have confusion on writing the code, you can check the complete code here to help you:"
},
{
"code": null,
"e": 6572,
"s": 6538,
"text": "Thank you for reading my article!"
}
] |
Machine Learning - Confusion Matrix | It is the easiest way to measure the performance of a classification problem where the output can be of two or more type of classes. A confusion matrix is nothing but a table with two dimensions viz. “Actual” and “Predicted” and furthermore, both the dimensions have “True Positives (TP)”, “True Negatives (TN)”, “False Positives (FP)”, “False Negatives (FN)” as shown below −
The explanation of the terms associated with confusion matrix are as follows −
True Positives (TP) − It is the case when both actual class & predicted class of data point is 1.
True Positives (TP) − It is the case when both actual class & predicted class of data point is 1.
True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0.
True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0.
False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1.
False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1.
False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0.
False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0.
We can find the confusion matrix with the help of confusion_matrix() function of sklearn. With the help of the following script, we can find the confusion matrix of above built binary classifier −
from sklearn.metrics import confusion_matrix
Output
[[ 73 7]
[ 4 144]]
It may be defined as the number of correct predictions made by our ML model. We can easily calculate it by confusion matrix with the help of following formula −
Accuracy=TP+TNTP+FP+FN+TN
For above built binary classifier, TP + TN = 73+144 = 217 and TP+FP+FN+TN = 73+7+4+144=228.
Hence, Accuracy = 217/228 = 0.951754385965 which is same as we have calculated after creating our binary classifier.
Precision, used in document retrievals, may be defined as the number of correct documents returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −
Precision=TPTP+FP
For the above built binary classifier, TP = 73 and TP+FP = 73+7 = 80.
Hence, Precision = 73/80 = 0.915
Recall may be defined as the number of positives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −
Recall=TPTP+FN
For above built binary classifier, TP = 73 and TP+FN = 73+4 = 77.
Hence, Precision = 73/77 = 0.94805
Specificity, in contrast to recall, may be defined as the number of negatives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −
Specificity=TNTN+FP
For the above built binary classifier, TN = 144 and TN+FP = 144+7 = 151.
Hence, Precision = 144/151 = 0.95364
168 Lectures
13.5 hours
Er. Himanshu Vasishta
64 Lectures
10.5 hours
Eduonix Learning Solutions
91 Lectures
10 hours
Abhilash Nelson
54 Lectures
6 hours
Abhishek And Pukhraj
49 Lectures
5 hours
Abhishek And Pukhraj
35 Lectures
4 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2681,
"s": 2304,
"text": "It is the easiest way to measure the performance of a classification problem where the output can be of two or more type of classes. A confusion matrix is nothing but a table with two dimensions viz. “Actual” and “Predicted” and furthermore, both the dimensions have “True Positives (TP)”, “True Negatives (TN)”, “False Positives (FP)”, “False Negatives (FN)” as shown below −"
},
{
"code": null,
"e": 2760,
"s": 2681,
"text": "The explanation of the terms associated with confusion matrix are as follows −"
},
{
"code": null,
"e": 2858,
"s": 2760,
"text": "True Positives (TP) − It is the case when both actual class & predicted class of data point is 1."
},
{
"code": null,
"e": 2956,
"s": 2858,
"text": "True Positives (TP) − It is the case when both actual class & predicted class of data point is 1."
},
{
"code": null,
"e": 3054,
"s": 2956,
"text": "True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0."
},
{
"code": null,
"e": 3152,
"s": 3054,
"text": "True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0."
},
{
"code": null,
"e": 3265,
"s": 3152,
"text": "False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1."
},
{
"code": null,
"e": 3378,
"s": 3265,
"text": "False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1."
},
{
"code": null,
"e": 3491,
"s": 3378,
"text": "False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0."
},
{
"code": null,
"e": 3604,
"s": 3491,
"text": "False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0."
},
{
"code": null,
"e": 3801,
"s": 3604,
"text": "We can find the confusion matrix with the help of confusion_matrix() function of sklearn. With the help of the following script, we can find the confusion matrix of above built binary classifier −"
},
{
"code": null,
"e": 3847,
"s": 3801,
"text": "from sklearn.metrics import confusion_matrix\n"
},
{
"code": null,
"e": 3854,
"s": 3847,
"text": "Output"
},
{
"code": null,
"e": 3874,
"s": 3854,
"text": "[[ 73 7]\n[ 4 144]]\n"
},
{
"code": null,
"e": 4035,
"s": 3874,
"text": "It may be defined as the number of correct predictions made by our ML model. We can easily calculate it by confusion matrix with the help of following formula −"
},
{
"code": null,
"e": 4061,
"s": 4035,
"text": "Accuracy=TP+TNTP+FP+FN+TN"
},
{
"code": null,
"e": 4153,
"s": 4061,
"text": "For above built binary classifier, TP + TN = 73+144 = 217 and TP+FP+FN+TN = 73+7+4+144=228."
},
{
"code": null,
"e": 4270,
"s": 4153,
"text": "Hence, Accuracy = 217/228 = 0.951754385965 which is same as we have calculated after creating our binary classifier."
},
{
"code": null,
"e": 4470,
"s": 4270,
"text": "Precision, used in document retrievals, may be defined as the number of correct documents returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −"
},
{
"code": null,
"e": 4488,
"s": 4470,
"text": "Precision=TPTP+FP"
},
{
"code": null,
"e": 4558,
"s": 4488,
"text": "For the above built binary classifier, TP = 73 and TP+FP = 73+7 = 80."
},
{
"code": null,
"e": 4591,
"s": 4558,
"text": "Hence, Precision = 73/80 = 0.915"
},
{
"code": null,
"e": 4750,
"s": 4591,
"text": "Recall may be defined as the number of positives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −"
},
{
"code": null,
"e": 4765,
"s": 4750,
"text": "Recall=TPTP+FN"
},
{
"code": null,
"e": 4831,
"s": 4765,
"text": "For above built binary classifier, TP = 73 and TP+FN = 73+4 = 77."
},
{
"code": null,
"e": 4866,
"s": 4831,
"text": "Hence, Precision = 73/77 = 0.94805"
},
{
"code": null,
"e": 5054,
"s": 4866,
"text": "Specificity, in contrast to recall, may be defined as the number of negatives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −"
},
{
"code": null,
"e": 5074,
"s": 5054,
"text": "Specificity=TNTN+FP"
},
{
"code": null,
"e": 5147,
"s": 5074,
"text": "For the above built binary classifier, TN = 144 and TN+FP = 144+7 = 151."
},
{
"code": null,
"e": 5184,
"s": 5147,
"text": "Hence, Precision = 144/151 = 0.95364"
},
{
"code": null,
"e": 5221,
"s": 5184,
"text": "\n 168 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 5244,
"s": 5221,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 5280,
"s": 5244,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5308,
"s": 5280,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5342,
"s": 5308,
"text": "\n 91 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5359,
"s": 5342,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5392,
"s": 5359,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5414,
"s": 5392,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5447,
"s": 5414,
"text": "\n 49 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5469,
"s": 5447,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5502,
"s": 5469,
"text": "\n 35 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5524,
"s": 5502,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5531,
"s": 5524,
"text": " Print"
},
{
"code": null,
"e": 5542,
"s": 5531,
"text": " Add Notes"
}
] |
Convert Row Names into Column of DataFrame in R - GeeksforGeeks | 17 Nov, 2021
In this article, we will discuss how to Convert Row Names into Columns of Dataframe in R Programming Language.
row.name() function is used to set and get the name of the DataFrame. Apply the row.name() function to the copy of the DataFrame and a name to the column which contains the name of the column with the help of the $ sign.
Syntax:
row.names(dataframe)
Example:
R
# DataFrame is created with the# help of data.frame functiondata <- data.frame(x1 = (10:15), x2 = (15:10)) # print the DataFramedata # make copy of DataFramecopydata <- data # apply row.name function to get# the name of the rowcopydata$rn <- row.names(data) # print the resultcopydata
Output:
In the R language there’s a package named dplyr which performs several DataFrame tasks. So, we are going to add a row name into a column of a DataFrame with the help of this package. At first, we are going to install and load the dplyr package. After loading the package we follow the same steps we followed in the first method but this time with the help of the function of dplyr library. The function used in this method is rownames_to_columns().
Syntax:
tibble::rownames_to_column(data_frame, column_name)
Example:
R
# DataFrame is created with the# help of data.frame functiondata <- data.frame(x1 = (10:15), x2 = (15:10)) # load the packagelibrary("dplyr") # make the copy of the data framecopydata <- data # Apply rownames_to_column on the copy of# DataFrame and put name of function rncopydata <- tibble::rownames_to_column(copydata, "rn") # print the copied DataFramecopydata
Output:
In the R language there’s a package named data.table which performs several DataFrame tasks. So, we are going to add a row name into a column of a DataFrame with the help of this package. At first, we are going to install and load the data.table package. After loading the package we follow the same steps we followed in the first method but this time with the help of the function of data.table library. The function used in this method is setDT().
Syntax:
setDT(x, keep.rownames=TRUE/FALSE, key=NULL, check.names=TRUE/FALSE)
While using this syntax we keep the row name true to get the name of the row.
Example:
R
# DataFrame is created with the help# of data.frame functiondata <- data.frame(x1 = (10:15), x2 = (15:10)) # print the DataFramedata # load the librarylibrary("data.table") # make copy of dataframecopydata <- data # Apply setDT function with rowname true# to get the rownamecopydata <- setDT(data, keep.rownames = TRUE)[] # print the datacopydata
Output:
prachisoda1234
sweetyty
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 25354,
"s": 25242,
"text": "In this article, we will discuss how to Convert Row Names into Columns of Dataframe in R Programming Language. "
},
{
"code": null,
"e": 25575,
"s": 25354,
"text": "row.name() function is used to set and get the name of the DataFrame. Apply the row.name() function to the copy of the DataFrame and a name to the column which contains the name of the column with the help of the $ sign."
},
{
"code": null,
"e": 25583,
"s": 25575,
"text": "Syntax:"
},
{
"code": null,
"e": 25604,
"s": 25583,
"text": "row.names(dataframe)"
},
{
"code": null,
"e": 25613,
"s": 25604,
"text": "Example:"
},
{
"code": null,
"e": 25615,
"s": 25613,
"text": "R"
},
{
"code": "# DataFrame is created with the# help of data.frame functiondata <- data.frame(x1 = (10:15), x2 = (15:10)) # print the DataFramedata # make copy of DataFramecopydata <- data # apply row.name function to get# the name of the rowcopydata$rn <- row.names(data) # print the resultcopydata",
"e": 25928,
"s": 25615,
"text": null
},
{
"code": null,
"e": 25936,
"s": 25928,
"text": "Output:"
},
{
"code": null,
"e": 26386,
"s": 25936,
"text": "In the R language there’s a package named dplyr which performs several DataFrame tasks. So, we are going to add a row name into a column of a DataFrame with the help of this package. At first, we are going to install and load the dplyr package. After loading the package we follow the same steps we followed in the first method but this time with the help of the function of dplyr library. The function used in this method is rownames_to_columns(). "
},
{
"code": null,
"e": 26394,
"s": 26386,
"text": "Syntax:"
},
{
"code": null,
"e": 26446,
"s": 26394,
"text": "tibble::rownames_to_column(data_frame, column_name)"
},
{
"code": null,
"e": 26455,
"s": 26446,
"text": "Example:"
},
{
"code": null,
"e": 26457,
"s": 26455,
"text": "R"
},
{
"code": "# DataFrame is created with the# help of data.frame functiondata <- data.frame(x1 = (10:15), x2 = (15:10)) # load the packagelibrary(\"dplyr\") # make the copy of the data framecopydata <- data # Apply rownames_to_column on the copy of# DataFrame and put name of function rncopydata <- tibble::rownames_to_column(copydata, \"rn\") # print the copied DataFramecopydata",
"e": 26843,
"s": 26457,
"text": null
},
{
"code": null,
"e": 26851,
"s": 26843,
"text": "Output:"
},
{
"code": null,
"e": 27302,
"s": 26851,
"text": "In the R language there’s a package named data.table which performs several DataFrame tasks. So, we are going to add a row name into a column of a DataFrame with the help of this package. At first, we are going to install and load the data.table package. After loading the package we follow the same steps we followed in the first method but this time with the help of the function of data.table library. The function used in this method is setDT(). "
},
{
"code": null,
"e": 27310,
"s": 27302,
"text": "Syntax:"
},
{
"code": null,
"e": 27379,
"s": 27310,
"text": "setDT(x, keep.rownames=TRUE/FALSE, key=NULL, check.names=TRUE/FALSE)"
},
{
"code": null,
"e": 27457,
"s": 27379,
"text": "While using this syntax we keep the row name true to get the name of the row."
},
{
"code": null,
"e": 27466,
"s": 27457,
"text": "Example:"
},
{
"code": null,
"e": 27468,
"s": 27466,
"text": "R"
},
{
"code": "# DataFrame is created with the help# of data.frame functiondata <- data.frame(x1 = (10:15), x2 = (15:10)) # print the DataFramedata # load the librarylibrary(\"data.table\") # make copy of dataframecopydata <- data # Apply setDT function with rowname true# to get the rownamecopydata <- setDT(data, keep.rownames = TRUE)[] # print the datacopydata ",
"e": 27854,
"s": 27468,
"text": null
},
{
"code": null,
"e": 27862,
"s": 27854,
"text": "Output:"
},
{
"code": null,
"e": 27877,
"s": 27862,
"text": "prachisoda1234"
},
{
"code": null,
"e": 27886,
"s": 27877,
"text": "sweetyty"
},
{
"code": null,
"e": 27893,
"s": 27886,
"text": "Picked"
},
{
"code": null,
"e": 27914,
"s": 27893,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 27926,
"s": 27914,
"text": "R-DataFrame"
},
{
"code": null,
"e": 27937,
"s": 27926,
"text": "R Language"
},
{
"code": null,
"e": 27948,
"s": 27937,
"text": "R Programs"
},
{
"code": null,
"e": 28046,
"s": 27948,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28098,
"s": 28046,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28136,
"s": 28098,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28171,
"s": 28136,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28229,
"s": 28171,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28278,
"s": 28229,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28336,
"s": 28278,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28385,
"s": 28336,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28435,
"s": 28385,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 28478,
"s": 28435,
"text": "Replace Specific Characters in String in R"
}
] |
Android ListView in Kotlin - GeeksforGeeks | 16 Mar, 2022
Android ListView is a ViewGroup which is used to display the list of items in multiple rows and contains an adapter which automatically inserts the items into the list.
The main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result. So, it is main source to pull data from strings.xml file which contains all the required strings in Kotlin or xml files.
Adapter holds the data fetched from an array and iterates through each item in data set and generates the respective views for each item of the list. So, we can say it act as an intermediate between the data sources and adapter views such as ListView, Gridview.
Different Types of Adapter –
ArrayAdapter: It always accepts an Array or List as input. We can store the list items in the strings.xml file also.
CursorAdapter: It always accepts an instance of cursor as an input means
SimpleAdapter: It mainly accepts a static data defined in the resources like array or database.
BaseAdapter: It is a generic implementation for all three adapter types and it can be used in the views according to our requirements.
Now, we going to create an android application named as ListViewInKotlin using an arrayadapter. Open an activity_main.xml file from \res\layout path and write the code like as shown below.
In this file, we declare the LisitView within LinearLayout and set its attributes. Later, we will access the ListView in Kotlin file using the id.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:id="@+id/userlist" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView></LinearLayout>
When we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById.
Kotlin
import android.widget.ArrayAdapterimport android.widget.ListViewclass MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // use arrayadapter and define an array val arrayAdapter: ArrayAdapter<*> val users = arrayOf( "Virat Kohli", "Rohit Sharma", "Steve Smith", "Kane Williamson", "Ross Taylor" ) // access the listView from xml file var mListView = findViewById<ListView>(R.id.userlist) arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, users) mListView.adapter = arrayAdapter }}
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:dist="http://schemas.android.com/apk/distribution" package="com.geeksforgeeks.myfirstkotlinapp"> <dist:module dist:instant="true" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
We need to run using Android Virtual Device(AVD) to see the output.
ayushpandey3july
android
Android-View
Kotlin Android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
CardView in Android With Example
Content Providers in Android with Example
Broadcast Receiver in Android With Example
Android UI Layouts
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android | [
{
"code": null,
"e": 23827,
"s": 23799,
"text": "\n16 Mar, 2022"
},
{
"code": null,
"e": 23996,
"s": 23827,
"text": "Android ListView is a ViewGroup which is used to display the list of items in multiple rows and contains an adapter which automatically inserts the items into the list."
},
{
"code": null,
"e": 24263,
"s": 23996,
"text": "The main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result. So, it is main source to pull data from strings.xml file which contains all the required strings in Kotlin or xml files."
},
{
"code": null,
"e": 24525,
"s": 24263,
"text": "Adapter holds the data fetched from an array and iterates through each item in data set and generates the respective views for each item of the list. So, we can say it act as an intermediate between the data sources and adapter views such as ListView, Gridview."
},
{
"code": null,
"e": 24554,
"s": 24525,
"text": "Different Types of Adapter –"
},
{
"code": null,
"e": 24671,
"s": 24554,
"text": "ArrayAdapter: It always accepts an Array or List as input. We can store the list items in the strings.xml file also."
},
{
"code": null,
"e": 24744,
"s": 24671,
"text": "CursorAdapter: It always accepts an instance of cursor as an input means"
},
{
"code": null,
"e": 24840,
"s": 24744,
"text": "SimpleAdapter: It mainly accepts a static data defined in the resources like array or database."
},
{
"code": null,
"e": 24975,
"s": 24840,
"text": "BaseAdapter: It is a generic implementation for all three adapter types and it can be used in the views according to our requirements."
},
{
"code": null,
"e": 25164,
"s": 24975,
"text": "Now, we going to create an android application named as ListViewInKotlin using an arrayadapter. Open an activity_main.xml file from \\res\\layout path and write the code like as shown below."
},
{
"code": null,
"e": 25311,
"s": 25164,
"text": "In this file, we declare the LisitView within LinearLayout and set its attributes. Later, we will access the ListView in Kotlin file using the id."
},
{
"code": null,
"e": 25315,
"s": 25311,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <ListView android:id=\"@+id/userlist\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" > </ListView></LinearLayout>",
"e": 25756,
"s": 25315,
"text": null
},
{
"code": null,
"e": 25929,
"s": 25756,
"text": "When we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById."
},
{
"code": null,
"e": 25936,
"s": 25929,
"text": "Kotlin"
},
{
"code": "import android.widget.ArrayAdapterimport android.widget.ListViewclass MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // use arrayadapter and define an array val arrayAdapter: ArrayAdapter<*> val users = arrayOf( \"Virat Kohli\", \"Rohit Sharma\", \"Steve Smith\", \"Kane Williamson\", \"Ross Taylor\" ) // access the listView from xml file var mListView = findViewById<ListView>(R.id.userlist) arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, users) mListView.adapter = arrayAdapter }}",
"e": 26674,
"s": 25936,
"text": null
},
{
"code": null,
"e": 26678,
"s": 26674,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:dist=\"http://schemas.android.com/apk/distribution\" package=\"com.geeksforgeeks.myfirstkotlinapp\"> <dist:module dist:instant=\"true\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 27494,
"s": 26678,
"text": null
},
{
"code": null,
"e": 27562,
"s": 27494,
"text": "We need to run using Android Virtual Device(AVD) to see the output."
},
{
"code": null,
"e": 27579,
"s": 27562,
"text": "ayushpandey3july"
},
{
"code": null,
"e": 27587,
"s": 27579,
"text": "android"
},
{
"code": null,
"e": 27600,
"s": 27587,
"text": "Android-View"
},
{
"code": null,
"e": 27615,
"s": 27600,
"text": "Kotlin Android"
},
{
"code": null,
"e": 27623,
"s": 27615,
"text": "Android"
},
{
"code": null,
"e": 27630,
"s": 27623,
"text": "Kotlin"
},
{
"code": null,
"e": 27638,
"s": 27630,
"text": "Android"
},
{
"code": null,
"e": 27736,
"s": 27638,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27745,
"s": 27736,
"text": "Comments"
},
{
"code": null,
"e": 27758,
"s": 27745,
"text": "Old Comments"
},
{
"code": null,
"e": 27816,
"s": 27758,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 27859,
"s": 27816,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 27890,
"s": 27859,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 27923,
"s": 27890,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 27965,
"s": 27923,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 28008,
"s": 27965,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 28027,
"s": 28008,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 28058,
"s": 28027,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 28100,
"s": 28058,
"text": "Content Providers in Android with Example"
}
] |
Classification Algorithms - Naà ̄ve Bayes | Naïve Bayes algorithms is a classification technique based on applying Bayes’ theorem with a strong assumption that all the predictors are independent to each other. In simple words, the assumption is that the presence of a feature in a class is independent to the presence of any other feature in the same class. For example, a phone may be considered as smart if it is having touch screen, internet facility, good camera etc. Though all these features are dependent on each other, they contribute independently to the probability of that the phone is a smart phone.
In Bayesian classification, the main interest is to find the posterior probabilities i.e. the probability of a label given some observed features, P(L | features). With the help of Bayes theorem, we can express this in quantitative form as follows −
P(L|features)=P(L)P(features|L)P(features)
Here, (L | features) is the posterior probability of class.
P(L) is the prior probability of class.
P(features|L) is the likelihood which is the probability of predictor given class.
P(features) is the prior probability of predictor.
Python library, Scikit learn is the most useful library that helps us to build a Naïve Bayes model in Python. We have the following three types of Naïve Bayes model under Scikit learn Python library −
It is the simplest Naïve Bayes classifier having the assumption that the data from each label is drawn from a simple Gaussian distribution.
Another useful Naïve Bayes classifier is Multinomial Naïve Bayes in which the features are assumed to be drawn from a simple Multinomial distribution. Such kind of Naïve Bayes are most appropriate for the features that represents discrete counts.
Another important model is Bernoulli Naïve Bayes in which features are assumed to be binary (0s and 1s). Text classification with ‘bag of words’ model can be an application of Bernoulli Naïve Bayes.
Depending on our data set, we can choose any of the Naïve Bayes model explained above. Here, we are implementing Gaussian Naïve Bayes model in Python −
We will start with required imports as follows −
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
Now, by using make_blobs() function of Scikit learn, we can generate blobs of points with Gaussian distribution as follows −
from sklearn.datasets import make_blobs
X, y = make_blobs(300, 2, centers = 2, random_state = 2, cluster_std = 1.5)
plt.scatter(X[:, 0], X[:, 1], c = y, s = 50, cmap = 'summer');
Next, for using GaussianNB model, we need to import and make its object as follows −
from sklearn.naive_bayes import GaussianNB
model_GBN = GaussianNB()
model_GNB.fit(X, y);
Now, we have to do prediction. It can be done after generating some new data as follows −
rng = np.random.RandomState(0)
Xnew = [-6, -14] + [14, 18] * rng.rand(2000, 2)
ynew = model_GNB.predict(Xnew)
Next, we are plotting new data to find its boundaries −
plt.scatter(X[:, 0], X[:, 1], c = y, s = 50, cmap = 'summer')
lim = plt.axis()
plt.scatter(Xnew[:, 0], Xnew[:, 1], c = ynew, s = 20, cmap = 'summer', alpha = 0.1)
plt.axis(lim);
Now, with the help of following line of codes, we can find the posterior probabilities of first and second label −
yprob = model_GNB.predict_proba(Xnew)
yprob[-10:].round(3)
array([[0.998, 0.002],
[1. , 0. ],
[0.987, 0.013],
[1. , 0. ],
[1. , 0. ],
[1. , 0. ],
[1. , 0. ],
[1. , 0. ],
[0. , 1. ],
[0.986, 0.014]])
The followings are some pros of using Naïve Bayes classifiers −
Naïve Bayes classification is easy to implement and fast.
Naïve Bayes classification is easy to implement and fast.
It will converge faster than discriminative models like logistic regression.
It will converge faster than discriminative models like logistic regression.
It requires less training data.
It requires less training data.
It is highly scalable in nature, or they scale linearly with the number of predictors and data points.
It is highly scalable in nature, or they scale linearly with the number of predictors and data points.
It can make probabilistic predictions and can handle continuous as well as discrete data.
It can make probabilistic predictions and can handle continuous as well as discrete data.
Naïve Bayes classification algorithm can be used for binary as well as multi-class classification problems both.
Naïve Bayes classification algorithm can be used for binary as well as multi-class classification problems both.
The followings are some cons of using Naïve Bayes classifiers −
One of the most important cons of Naïve Bayes classification is its strong feature independence because in real life it is almost impossible to have a set of features which are completely independent of each other.
One of the most important cons of Naïve Bayes classification is its strong feature independence because in real life it is almost impossible to have a set of features which are completely independent of each other.
Another issue with Naïve Bayes classification is its ‘zero frequency’ which means that if a categorial variable has a category but not being observed in training data set, then Naïve Bayes model will assign a zero probability to it and it will be unable to make a prediction.
Another issue with Naïve Bayes classification is its ‘zero frequency’ which means that if a categorial variable has a category but not being observed in training data set, then Naïve Bayes model will assign a zero probability to it and it will be unable to make a prediction.
The following are some common applications of Naïve Bayes classification −
Real-time prediction − Due to its ease of implementation and fast computation, it can be used to do prediction in real-time.
Real-time prediction − Due to its ease of implementation and fast computation, it can be used to do prediction in real-time.
Multi-class prediction − Naïve Bayes classification algorithm can be used to predict posterior probability of multiple classes of target variable.
Multi-class prediction − Naïve Bayes classification algorithm can be used to predict posterior probability of multiple classes of target variable.
Text classification − Due to the feature of multi-class prediction, Naïve Bayes classification algorithms are well suited for text classification. That is why it is also used to solve problems like spam-filtering and sentiment analysis.
Text classification − Due to the feature of multi-class prediction, Naïve Bayes classification algorithms are well suited for text classification. That is why it is also used to solve problems like spam-filtering and sentiment analysis.
Recommendation system − Along with the algorithms like collaborative filtering, Naïve Bayes makes a Recommendation system which can be used to filter unseen information and to predict weather a user would like the given resource or not.
Recommendation system − Along with the algorithms like collaborative filtering, Naïve Bayes makes a Recommendation system which can be used to filter unseen information and to predict weather a user would like the given resource or not.
168 Lectures
13.5 hours
Er. Himanshu Vasishta
64 Lectures
10.5 hours
Eduonix Learning Solutions
91 Lectures
10 hours
Abhilash Nelson
54 Lectures
6 hours
Abhishek And Pukhraj
49 Lectures
5 hours
Abhishek And Pukhraj
35 Lectures
4 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2873,
"s": 2304,
"text": "Naïve Bayes algorithms is a classification technique based on applying Bayes’ theorem with a strong assumption that all the predictors are independent to each other. In simple words, the assumption is that the presence of a feature in a class is independent to the presence of any other feature in the same class. For example, a phone may be considered as smart if it is having touch screen, internet facility, good camera etc. Though all these features are dependent on each other, they contribute independently to the probability of that the phone is a smart phone."
},
{
"code": null,
"e": 3123,
"s": 2873,
"text": "In Bayesian classification, the main interest is to find the posterior probabilities i.e. the probability of a label given some observed features, P(L | features). With the help of Bayes theorem, we can express this in quantitative form as follows −"
},
{
"code": null,
"e": 3166,
"s": 3123,
"text": "P(L|features)=P(L)P(features|L)P(features)"
},
{
"code": null,
"e": 3226,
"s": 3166,
"text": "Here, (L | features) is the posterior probability of class."
},
{
"code": null,
"e": 3266,
"s": 3226,
"text": "P(L) is the prior probability of class."
},
{
"code": null,
"e": 3349,
"s": 3266,
"text": "P(features|L) is the likelihood which is the probability of predictor given class."
},
{
"code": null,
"e": 3400,
"s": 3349,
"text": "P(features) is the prior probability of predictor."
},
{
"code": null,
"e": 3603,
"s": 3400,
"text": "Python library, Scikit learn is the most useful library that helps us to build a Naïve Bayes model in Python. We have the following three types of Naïve Bayes model under Scikit learn Python library −"
},
{
"code": null,
"e": 3744,
"s": 3603,
"text": "It is the simplest Naïve Bayes classifier having the assumption that the data from each label is drawn from a simple Gaussian distribution."
},
{
"code": null,
"e": 3994,
"s": 3744,
"text": "Another useful Naïve Bayes classifier is Multinomial Naïve Bayes in which the features are assumed to be drawn from a simple Multinomial distribution. Such kind of Naïve Bayes are most appropriate for the features that represents discrete counts."
},
{
"code": null,
"e": 4195,
"s": 3994,
"text": "Another important model is Bernoulli Naïve Bayes in which features are assumed to be binary (0s and 1s). Text classification with ‘bag of words’ model can be an application of Bernoulli Naïve Bayes."
},
{
"code": null,
"e": 4349,
"s": 4195,
"text": "Depending on our data set, we can choose any of the Naïve Bayes model explained above. Here, we are implementing Gaussian Naïve Bayes model in Python −"
},
{
"code": null,
"e": 4398,
"s": 4349,
"text": "We will start with required imports as follows −"
},
{
"code": null,
"e": 4483,
"s": 4398,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\n"
},
{
"code": null,
"e": 4608,
"s": 4483,
"text": "Now, by using make_blobs() function of Scikit learn, we can generate blobs of points with Gaussian distribution as follows −"
},
{
"code": null,
"e": 4788,
"s": 4608,
"text": "from sklearn.datasets import make_blobs\nX, y = make_blobs(300, 2, centers = 2, random_state = 2, cluster_std = 1.5)\nplt.scatter(X[:, 0], X[:, 1], c = y, s = 50, cmap = 'summer');\n"
},
{
"code": null,
"e": 4873,
"s": 4788,
"text": "Next, for using GaussianNB model, we need to import and make its object as follows −"
},
{
"code": null,
"e": 4963,
"s": 4873,
"text": "from sklearn.naive_bayes import GaussianNB\nmodel_GBN = GaussianNB()\nmodel_GNB.fit(X, y);\n"
},
{
"code": null,
"e": 5053,
"s": 4963,
"text": "Now, we have to do prediction. It can be done after generating some new data as follows −"
},
{
"code": null,
"e": 5164,
"s": 5053,
"text": "rng = np.random.RandomState(0)\nXnew = [-6, -14] + [14, 18] * rng.rand(2000, 2)\nynew = model_GNB.predict(Xnew)\n"
},
{
"code": null,
"e": 5220,
"s": 5164,
"text": "Next, we are plotting new data to find its boundaries −"
},
{
"code": null,
"e": 5399,
"s": 5220,
"text": "plt.scatter(X[:, 0], X[:, 1], c = y, s = 50, cmap = 'summer')\nlim = plt.axis()\nplt.scatter(Xnew[:, 0], Xnew[:, 1], c = ynew, s = 20, cmap = 'summer', alpha = 0.1)\nplt.axis(lim);\n"
},
{
"code": null,
"e": 5514,
"s": 5399,
"text": "Now, with the help of following line of codes, we can find the posterior probabilities of first and second label −"
},
{
"code": null,
"e": 5574,
"s": 5514,
"text": "yprob = model_GNB.predict_proba(Xnew)\nyprob[-10:].round(3)\n"
},
{
"code": null,
"e": 5742,
"s": 5574,
"text": "array([[0.998, 0.002],\n [1. , 0. ],\n [0.987, 0.013],\n [1. , 0. ],\n [1. , 0. ],\n [1. , 0. ],\n [1. , 0. ],\n [1. , 0. ],\n [0. , 1. ],\n [0.986, 0.014]])\n"
},
{
"code": null,
"e": 5807,
"s": 5742,
"text": "The followings are some pros of using Naïve Bayes classifiers −"
},
{
"code": null,
"e": 5866,
"s": 5807,
"text": "Naïve Bayes classification is easy to implement and fast."
},
{
"code": null,
"e": 5925,
"s": 5866,
"text": "Naïve Bayes classification is easy to implement and fast."
},
{
"code": null,
"e": 6002,
"s": 5925,
"text": "It will converge faster than discriminative models like logistic regression."
},
{
"code": null,
"e": 6079,
"s": 6002,
"text": "It will converge faster than discriminative models like logistic regression."
},
{
"code": null,
"e": 6111,
"s": 6079,
"text": "It requires less training data."
},
{
"code": null,
"e": 6143,
"s": 6111,
"text": "It requires less training data."
},
{
"code": null,
"e": 6246,
"s": 6143,
"text": "It is highly scalable in nature, or they scale linearly with the number of predictors and data points."
},
{
"code": null,
"e": 6349,
"s": 6246,
"text": "It is highly scalable in nature, or they scale linearly with the number of predictors and data points."
},
{
"code": null,
"e": 6439,
"s": 6349,
"text": "It can make probabilistic predictions and can handle continuous as well as discrete data."
},
{
"code": null,
"e": 6529,
"s": 6439,
"text": "It can make probabilistic predictions and can handle continuous as well as discrete data."
},
{
"code": null,
"e": 6643,
"s": 6529,
"text": "Naïve Bayes classification algorithm can be used for binary as well as multi-class classification problems both."
},
{
"code": null,
"e": 6757,
"s": 6643,
"text": "Naïve Bayes classification algorithm can be used for binary as well as multi-class classification problems both."
},
{
"code": null,
"e": 6822,
"s": 6757,
"text": "The followings are some cons of using Naïve Bayes classifiers −"
},
{
"code": null,
"e": 7038,
"s": 6822,
"text": "One of the most important cons of Naïve Bayes classification is its strong feature independence because in real life it is almost impossible to have a set of features which are completely independent of each other."
},
{
"code": null,
"e": 7254,
"s": 7038,
"text": "One of the most important cons of Naïve Bayes classification is its strong feature independence because in real life it is almost impossible to have a set of features which are completely independent of each other."
},
{
"code": null,
"e": 7532,
"s": 7254,
"text": "Another issue with Naïve Bayes classification is its ‘zero frequency’ which means that if a categorial variable has a category but not being observed in training data set, then Naïve Bayes model will assign a zero probability to it and it will be unable to make a prediction."
},
{
"code": null,
"e": 7810,
"s": 7532,
"text": "Another issue with Naïve Bayes classification is its ‘zero frequency’ which means that if a categorial variable has a category but not being observed in training data set, then Naïve Bayes model will assign a zero probability to it and it will be unable to make a prediction."
},
{
"code": null,
"e": 7886,
"s": 7810,
"text": "The following are some common applications of Naïve Bayes classification −"
},
{
"code": null,
"e": 8011,
"s": 7886,
"text": "Real-time prediction − Due to its ease of implementation and fast computation, it can be used to do prediction in real-time."
},
{
"code": null,
"e": 8136,
"s": 8011,
"text": "Real-time prediction − Due to its ease of implementation and fast computation, it can be used to do prediction in real-time."
},
{
"code": null,
"e": 8284,
"s": 8136,
"text": "Multi-class prediction − Naïve Bayes classification algorithm can be used to predict posterior probability of multiple classes of target variable."
},
{
"code": null,
"e": 8432,
"s": 8284,
"text": "Multi-class prediction − Naïve Bayes classification algorithm can be used to predict posterior probability of multiple classes of target variable."
},
{
"code": null,
"e": 8670,
"s": 8432,
"text": "Text classification − Due to the feature of multi-class prediction, Naïve Bayes classification algorithms are well suited for text classification. That is why it is also used to solve problems like spam-filtering and sentiment analysis."
},
{
"code": null,
"e": 8908,
"s": 8670,
"text": "Text classification − Due to the feature of multi-class prediction, Naïve Bayes classification algorithms are well suited for text classification. That is why it is also used to solve problems like spam-filtering and sentiment analysis."
},
{
"code": null,
"e": 9146,
"s": 8908,
"text": "Recommendation system − Along with the algorithms like collaborative filtering, Naïve Bayes makes a Recommendation system which can be used to filter unseen information and to predict weather a user would like the given resource or not."
},
{
"code": null,
"e": 9384,
"s": 9146,
"text": "Recommendation system − Along with the algorithms like collaborative filtering, Naïve Bayes makes a Recommendation system which can be used to filter unseen information and to predict weather a user would like the given resource or not."
},
{
"code": null,
"e": 9421,
"s": 9384,
"text": "\n 168 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 9444,
"s": 9421,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 9480,
"s": 9444,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 9508,
"s": 9480,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9542,
"s": 9508,
"text": "\n 91 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 9559,
"s": 9542,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9592,
"s": 9559,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9614,
"s": 9592,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 9647,
"s": 9614,
"text": "\n 49 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9669,
"s": 9647,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 9702,
"s": 9669,
"text": "\n 35 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9724,
"s": 9702,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 9731,
"s": 9724,
"text": " Print"
},
{
"code": null,
"e": 9742,
"s": 9731,
"text": " Add Notes"
}
] |
Find depth of the deepest odd level leaf node - GeeksforGeeks | 20 Jan, 2022
Write a code to get the depth of the deepest odd level leaf node in a binary tree. Consider that level starts with 1. Depth of a leaf node is number of nodes on the path from root to leaf (including both leaf and root).For example, consider the following tree. The deepest odd level node is the node with value 9 and depth of this node is 5.
1
/ \
2 3
/ / \
4 5 6
\ \
7 8
/ \
9 10
/
11
The idea is to recursively traverse the given binary tree and while traversing, maintain a variable “level” which will store the current node’s level in the tree. If current node is leaf then check “level” is odd or not. If level is odd then return it. If current node is not leaf, then recursively find maximum depth in left and right subtrees, and return maximum of the two depths.
C++
C
Java
Python3
C#
Javascript
// C++ program to find depth of the// deepest odd level leaf node#include <bits/stdc++.h>using namespace std; // A utility function to find// maximum of two integersint max(int x, int y){ return (x > y)? x : y;} // A Binary Tree nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to allocate a// new tree nodestruct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // A recursive function to find depth of// the deepest odd level leafint depthOfOddLeafUtil(struct Node *root, int level){ // Base Case if (root == NULL) return 0; // If this node is a leaf and its level // is odd, return its level if (root->left == NULL && root->right == NULL && level & 1) return level; // If not leaf, return the maximum value // from left and right subtrees return max(depthOfOddLeafUtil(root->left, level + 1), depthOfOddLeafUtil(root->right, level + 1));} /* Main function which calculates the depth of deepest odd level leaf. This function mainly uses depthOfOddLeafUtil() */int depthOfOddLeaf(struct Node *root){ int level = 1, depth = 0; return depthOfOddLeafUtil(root, level);} // Driver Codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); root->right->right->right->right->left = newNode(11); cout << depthOfOddLeaf(root) << " is the required depth"; getchar(); return 0;} // This code is contributed// by Akanksha Rai
// C program to find depth of the deepest odd level leaf node#include <stdio.h>#include <stdlib.h> // A utility function to find maximum of two integersint max(int x, int y) { return (x > y)? x : y; } // A Binary Tree nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to allocate a new tree nodestruct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // A recursive function to find depth of the deepest odd level leafint depthOfOddLeafUtil(struct Node *root,int level){ // Base Case if (root == NULL) return 0; // If this node is a leaf and its level is odd, return its level if (root->left==NULL && root->right==NULL && level&1) return level; // If not leaf, return the maximum value from left and right subtrees return max(depthOfOddLeafUtil(root->left, level+1), depthOfOddLeafUtil(root->right, level+1));} /* Main function which calculates the depth of deepest odd level leaf.This function mainly uses depthOfOddLeafUtil() */int depthOfOddLeaf(struct Node *root){ int level = 1, depth = 0; return depthOfOddLeafUtil(root, level);} // Driver program to test above functionsint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); root->right->right->right->right->left = newNode(11); printf("%d is the required depth\n", depthOfOddLeaf(root)); getchar(); return 0;}
// Java program to find depth of deepest odd level node // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; // A recursive function to find depth of the deepest odd level leaf int depthOfOddLeafUtil(Node node, int level) { // Base Case if (node == null) return 0; // If this node is a leaf and its level is odd, return its level if (node.left == null && node.right == null && (level & 1) != 0) return level; // If not leaf, return the maximum value from left and right subtrees return Math.max(depthOfOddLeafUtil(node.left, level + 1), depthOfOddLeafUtil(node.right, level + 1)); } /* Main function which calculates the depth of deepest odd level leaf. This function mainly uses depthOfOddLeafUtil() */ int depthOfOddLeaf(Node node) { int level = 1, depth = 0; return depthOfOddLeafUtil(node, level); } public static void main(String args[]) { int k = 45; BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.right.left = new Node(5); tree.root.right.right = new Node(6); tree.root.right.left.right = new Node(7); tree.root.right.right.right = new Node(8); tree.root.right.left.right.left = new Node(9); tree.root.right.right.right.right = new Node(10); tree.root.right.right.right.right.left = new Node(11); System.out.println(tree.depthOfOddLeaf(tree.root) + " is the required depth"); }} // This code has been contributed by Mayank Jaiswal
# Python program to find depth of the deepest odd level# leaf node # A Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # A recursive function to find depth of the deepest# odd level leaf nodedef depthOfOddLeafUtil(root, level): # Base Case if root is None: return 0 # If this node is leaf and its level is odd, return # its level if root.left is None and root.right is None and level&1: return level # If not leaf, return the maximum value from left # and right subtrees return (max(depthOfOddLeafUtil(root.left, level+1), depthOfOddLeafUtil(root.right, level+1))) # Main function which calculates the depth of deepest odd# level leaf .# This function mainly uses depthOfOddLeafUtil()def depthOfOddLeaf(root): level = 1 depth = 0 return depthOfOddLeafUtil(root, level) # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.right.left = Node(5)root.right.right = Node(6)root.right.left.right = Node(7)root.right.right.right = Node(8)root.right.left.right.left = Node(9)root.right.right.right.right = Node(10)root.right.right.right.right.left= Node(11) print ("%d is the required depth" %(depthOfOddLeaf(root))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
using System; // C# program to find depth of deepest odd level node // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; // A recursive function to find depth of the deepest odd level leaf public virtual int depthOfOddLeafUtil(Node node, int level) { // Base Case if (node == null) { return 0; } // If this node is a leaf and its level is odd, return its level if (node.left == null && node.right == null && (level & 1) != 0) { return level; } // If not leaf, return the maximum value from left and right subtrees return Math.Max(depthOfOddLeafUtil(node.left, level + 1), depthOfOddLeafUtil(node.right, level + 1)); } /* Main function which calculates the depth of deepest odd level leaf. This function mainly uses depthOfOddLeafUtil() */ public virtual int depthOfOddLeaf(Node node) { int level = 1, depth = 0; return depthOfOddLeafUtil(node, level); } public static void Main(string[] args) { int k = 45; BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.right.left = new Node(5); tree.root.right.right = new Node(6); tree.root.right.left.right = new Node(7); tree.root.right.right.right = new Node(8); tree.root.right.left.right.left = new Node(9); tree.root.right.right.right.right = new Node(10); tree.root.right.right.right.right.left = new Node(11); Console.WriteLine(tree.depthOfOddLeaf(tree.root) + " is the required depth"); }} // This code is contributed by Shrikant13
<script> // JavaScript program to find depth of// deepest odd level node // A binary tree nodeclass Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} var root; // A recursive function to find depth of the // deepest odd level leaf function depthOfOddLeafUtil(node , level) { // Base Case if (node == null) return 0; // If this node is a leaf and its level is odd, // return its level if (node.left == null && node.right == null && (level & 1) != 0) return level; // If not leaf, return the maximum value // from left and right subtrees return Math.max(depthOfOddLeafUtil(node.left, level + 1), depthOfOddLeafUtil(node.right, level + 1)); } /* * Main function which calculates the depth of deepest odd level leaf. This * function mainly uses depthOfOddLeafUtil() */ function depthOfOddLeaf(node) { var level = 1, depth = 0; return depthOfOddLeafUtil(node, level); } var k = 45; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.left.right = new Node(7); root.right.right.right = new Node(8); root.right.left.right.left = new Node(9); root.right.right.right.right = new Node(10); root.right.right.right.right.left = new Node(11); document.write( depthOfOddLeaf(root) + " is the required depth" ); // This code contributed by Rajput-Ji </script>
Output:
5 is the required depth
Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n).Iterative Approach This approach is contributed by Mandeep Singh. Traverse the tree in iterative fashion for each level, and whenever you encounter the leaf node, check if level is odd, if level is odd, then update the result.
C++
Java
Python3
C#
Javascript
// CPP program to find// depth of the deepest// odd level leaf node// of binary tree#include <bits/stdc++.h>using namespace std; // tree nodestruct Node{ int data; Node *left, *right;}; // returns a new// tree NodeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // return max odd number// depth of leaf nodeint maxOddLevelDepth(Node* root){ if (!root) return 0; // create a queue // for level order // traversal queue<Node*> q; q.push(root); int result = INT_MAX; int level = 0; // traverse until the // queue is empty while (!q.empty()) { int size = q.size(); level += 1; // traverse for // complete level while(size > 0) { Node* temp = q.front(); q.pop(); // check if the node is // leaf node and level // is odd if level is // odd, then update result if(!temp->left && !temp->right && (level % 2 != 0)) { result = level; } // check for left child if (temp->left) { q.push(temp->left); } // check for right child if (temp->right) { q.push(temp->right); } size -= 1; } } return result;} // driver programint main(){ // construct a tree Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); root->right->right->right->right->left = newNode(11); int result = maxOddLevelDepth(root); if (result == INT_MAX) cout << "No leaf node at odd level\n"; else cout << result; cout << " is the required depth " << endl; return 0;}
// Java program to find depth of the deepest// odd level leaf node of binary treeimport java.util.*; class GFG{ // tree nodestatic class Node{ int data; Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // return max odd number depth of leaf nodestatic int maxOddLevelDepth(Node root){ if (root == null) return 0; // create a queue for level order // traversal Queue<Node> q = new LinkedList<>(); q.add(root); int result = Integer.MAX_VALUE; int level = 0; // traverse until the queue is empty while (!q.isEmpty()) { int size = q.size(); level += 1; // traverse for complete level while(size > 0) { Node temp = q.peek(); q.remove(); // check if the node is leaf node and // level is odd if level is odd, // then update result if(temp.left == null && temp.right == null && (level % 2 != 0)) { result = level; } // check for left child if (temp.left != null) { q.add(temp.left); } // check for right child if (temp.right != null) { q.add(temp.right); } size -= 1; } } return result;} // Driver Codepublic static void main(String[] args){ // construct a tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); root.right.right.right.right.left = newNode(11); int result = maxOddLevelDepth(root); if (result == Integer.MAX_VALUE) System.out.println("No leaf node at odd level"); else { System.out.print(result); System.out.println(" is the required depth "); }}} // This code is contributed by Rajput-Ji
# Python3 program to find depth of the deepest# odd level leaf node of binary tree INT_MAX = 2**31 # tree node returns a new tree Nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # return max odd number depth# of leaf nodedef maxOddLevelDepth(root) : if (not root): return 0 # create a queue for level order # traversal q = [] q.append(root) result = INT_MAX level = 0 # traverse until the queue is empty while (len(q)) : size = len(q) level += 1 # traverse for complete level while(size > 0) : temp = q[0] q.pop(0) # check if the node is leaf node # and level is odd if level is # odd, then update result if(not temp.left and not temp.right and (level % 2 != 0)) : result = level # check for left child if (temp.left) : q.append(temp.left) # check for right child if (temp.right) : q.append(temp.right) size -= 1 return result # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.right.left = newNode(5) root.right.right = newNode(6) root.right.left.right = newNode(7) root.right.right.right = newNode(8) root.right.left.right.left = newNode(9) root.right.right.right.right = newNode(10) root.right.right.right.right.left = newNode(11) result = maxOddLevelDepth(root) if (result == INT_MAX) : print("No leaf node at odd level") else: print(result, end = "") print(" is the required depth ") # This code is contributed# by SHUBHAMSINGH10
// C# program to find depth of the deepest// odd level leaf node of binary treeusing System;using System.Collections.Generic; class GFG{ // tree nodepublic class Node{ public int data; public Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // return max odd number depth of leaf nodestatic int maxOddLevelDepth(Node root){ if (root == null) return 0; // create a queue for level order // traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); int result = int.MaxValue; int level = 0; // traverse until the queue is empty while (q.Count != 0) { int size = q.Count; level += 1; // traverse for complete level while(size > 0) { Node temp = q.Peek(); q.Dequeue(); // check if the node is leaf node and // level is odd if level is odd, // then update result if(temp.left == null && temp.right == null && (level % 2 != 0)) { result = level; } // check for left child if (temp.left != null) { q.Enqueue(temp.left); } // check for right child if (temp.right != null) { q.Enqueue(temp.right); } size -= 1; } } return result;} // Driver Codepublic static void Main(String[] args){ // construct a tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); root.right.right.right.right.left = newNode(11); int result = maxOddLevelDepth(root); if (result == int.MaxValue) Console.WriteLine("No leaf node at odd level"); else { Console.Write(result); Console.WriteLine(" is the required depth "); }}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to find depth of the deepest // odd level leaf node of binary tree // tree node class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } // returns a new tree Node function newNode(data) { var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp; } // return max odd number depth of leaf node function maxOddLevelDepth(root) { if (root == null) return 0; // create a queue for level order // traversal var q = []; q.push(root); var result = 2147483647; var level = 0; // traverse until the queue is empty while (q.length != 0) { var size = q.length; level += 1; // traverse for complete level while (size > 0) { var temp = q[0]; q.shift(); // check if the node is leaf node and // level is odd if level is odd, // then update result if (temp.left == null && temp.right == null && level % 2 != 0) { result = level; } // check for left child if (temp.left != null) { q.push(temp.left); } // check for right child if (temp.right != null) { q.push(temp.right); } size -= 1; } } return result; } // Driver Code // construct a tree var root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); root.right.right.right.right.left = newNode(11); var result = maxOddLevelDepth(root); if (result == 2147483647) document.write("No leaf node at odd level"); else { document.write(result); document.write(" is the required depth"); } </script>
Output:
5 is the required depth
Time Complexity: Time Complexity is O(n).
YouTubeGeeksforGeeks502K subscribersFind depth of the deepest odd level leaf node | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bPp5bjjXhhQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
SHUBHAMSINGH10
Akanksha_Rai
Rajput-Ji
princiraj1992
rdtank
amartyaghoshgfg
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
BFS vs DFS for Binary Tree
Expression Tree
Sorted Array to Balanced BST | [
{
"code": null,
"e": 25366,
"s": 25338,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 25710,
"s": 25366,
"text": "Write a code to get the depth of the deepest odd level leaf node in a binary tree. Consider that level starts with 1. Depth of a leaf node is number of nodes on the path from root to leaf (including both leaf and root).For example, consider the following tree. The deepest odd level node is the node with value 9 and depth of this node is 5. "
},
{
"code": null,
"e": 25882,
"s": 25710,
"text": " 1\n / \\\n 2 3\n / / \\ \n 4 5 6\n \\ \\\n 7 8\n / \\\n 9 10\n /\n 11"
},
{
"code": null,
"e": 26269,
"s": 25884,
"text": "The idea is to recursively traverse the given binary tree and while traversing, maintain a variable “level” which will store the current node’s level in the tree. If current node is leaf then check “level” is odd or not. If level is odd then return it. If current node is not leaf, then recursively find maximum depth in left and right subtrees, and return maximum of the two depths. "
},
{
"code": null,
"e": 26273,
"s": 26269,
"text": "C++"
},
{
"code": null,
"e": 26275,
"s": 26273,
"text": "C"
},
{
"code": null,
"e": 26280,
"s": 26275,
"text": "Java"
},
{
"code": null,
"e": 26288,
"s": 26280,
"text": "Python3"
},
{
"code": null,
"e": 26291,
"s": 26288,
"text": "C#"
},
{
"code": null,
"e": 26302,
"s": 26291,
"text": "Javascript"
},
{
"code": "// C++ program to find depth of the// deepest odd level leaf node#include <bits/stdc++.h>using namespace std; // A utility function to find// maximum of two integersint max(int x, int y){ return (x > y)? x : y;} // A Binary Tree nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to allocate a// new tree nodestruct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // A recursive function to find depth of// the deepest odd level leafint depthOfOddLeafUtil(struct Node *root, int level){ // Base Case if (root == NULL) return 0; // If this node is a leaf and its level // is odd, return its level if (root->left == NULL && root->right == NULL && level & 1) return level; // If not leaf, return the maximum value // from left and right subtrees return max(depthOfOddLeafUtil(root->left, level + 1), depthOfOddLeafUtil(root->right, level + 1));} /* Main function which calculates the depth of deepest odd level leaf. This function mainly uses depthOfOddLeafUtil() */int depthOfOddLeaf(struct Node *root){ int level = 1, depth = 0; return depthOfOddLeafUtil(root, level);} // Driver Codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); root->right->right->right->right->left = newNode(11); cout << depthOfOddLeaf(root) << \" is the required depth\"; getchar(); return 0;} // This code is contributed// by Akanksha Rai",
"e": 28235,
"s": 26302,
"text": null
},
{
"code": "// C program to find depth of the deepest odd level leaf node#include <stdio.h>#include <stdlib.h> // A utility function to find maximum of two integersint max(int x, int y) { return (x > y)? x : y; } // A Binary Tree nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to allocate a new tree nodestruct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // A recursive function to find depth of the deepest odd level leafint depthOfOddLeafUtil(struct Node *root,int level){ // Base Case if (root == NULL) return 0; // If this node is a leaf and its level is odd, return its level if (root->left==NULL && root->right==NULL && level&1) return level; // If not leaf, return the maximum value from left and right subtrees return max(depthOfOddLeafUtil(root->left, level+1), depthOfOddLeafUtil(root->right, level+1));} /* Main function which calculates the depth of deepest odd level leaf.This function mainly uses depthOfOddLeafUtil() */int depthOfOddLeaf(struct Node *root){ int level = 1, depth = 0; return depthOfOddLeafUtil(root, level);} // Driver program to test above functionsint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); root->right->right->right->right->left = newNode(11); printf(\"%d is the required depth\\n\", depthOfOddLeaf(root)); getchar(); return 0;}",
"e": 30057,
"s": 28235,
"text": null
},
{
"code": "// Java program to find depth of deepest odd level node // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; // A recursive function to find depth of the deepest odd level leaf int depthOfOddLeafUtil(Node node, int level) { // Base Case if (node == null) return 0; // If this node is a leaf and its level is odd, return its level if (node.left == null && node.right == null && (level & 1) != 0) return level; // If not leaf, return the maximum value from left and right subtrees return Math.max(depthOfOddLeafUtil(node.left, level + 1), depthOfOddLeafUtil(node.right, level + 1)); } /* Main function which calculates the depth of deepest odd level leaf. This function mainly uses depthOfOddLeafUtil() */ int depthOfOddLeaf(Node node) { int level = 1, depth = 0; return depthOfOddLeafUtil(node, level); } public static void main(String args[]) { int k = 45; BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.right.left = new Node(5); tree.root.right.right = new Node(6); tree.root.right.left.right = new Node(7); tree.root.right.right.right = new Node(8); tree.root.right.left.right.left = new Node(9); tree.root.right.right.right.right = new Node(10); tree.root.right.right.right.right.left = new Node(11); System.out.println(tree.depthOfOddLeaf(tree.root) + \" is the required depth\"); }} // This code has been contributed by Mayank Jaiswal",
"e": 31932,
"s": 30057,
"text": null
},
{
"code": "# Python program to find depth of the deepest odd level# leaf node # A Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # A recursive function to find depth of the deepest# odd level leaf nodedef depthOfOddLeafUtil(root, level): # Base Case if root is None: return 0 # If this node is leaf and its level is odd, return # its level if root.left is None and root.right is None and level&1: return level # If not leaf, return the maximum value from left # and right subtrees return (max(depthOfOddLeafUtil(root.left, level+1), depthOfOddLeafUtil(root.right, level+1))) # Main function which calculates the depth of deepest odd# level leaf .# This function mainly uses depthOfOddLeafUtil()def depthOfOddLeaf(root): level = 1 depth = 0 return depthOfOddLeafUtil(root, level) # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.right.left = Node(5)root.right.right = Node(6)root.right.left.right = Node(7)root.right.right.right = Node(8)root.right.left.right.left = Node(9)root.right.right.right.right = Node(10)root.right.right.right.right.left= Node(11) print (\"%d is the required depth\" %(depthOfOddLeaf(root))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 33370,
"s": 31932,
"text": null
},
{
"code": "using System; // C# program to find depth of deepest odd level node // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; // A recursive function to find depth of the deepest odd level leaf public virtual int depthOfOddLeafUtil(Node node, int level) { // Base Case if (node == null) { return 0; } // If this node is a leaf and its level is odd, return its level if (node.left == null && node.right == null && (level & 1) != 0) { return level; } // If not leaf, return the maximum value from left and right subtrees return Math.Max(depthOfOddLeafUtil(node.left, level + 1), depthOfOddLeafUtil(node.right, level + 1)); } /* Main function which calculates the depth of deepest odd level leaf. This function mainly uses depthOfOddLeafUtil() */ public virtual int depthOfOddLeaf(Node node) { int level = 1, depth = 0; return depthOfOddLeafUtil(node, level); } public static void Main(string[] args) { int k = 45; BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.right.left = new Node(5); tree.root.right.right = new Node(6); tree.root.right.left.right = new Node(7); tree.root.right.right.right = new Node(8); tree.root.right.left.right.left = new Node(9); tree.root.right.right.right.right = new Node(10); tree.root.right.right.right.right.left = new Node(11); Console.WriteLine(tree.depthOfOddLeaf(tree.root) + \" is the required depth\"); }} // This code is contributed by Shrikant13",
"e": 35301,
"s": 33370,
"text": null
},
{
"code": "<script> // JavaScript program to find depth of// deepest odd level node // A binary tree nodeclass Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} var root; // A recursive function to find depth of the // deepest odd level leaf function depthOfOddLeafUtil(node , level) { // Base Case if (node == null) return 0; // If this node is a leaf and its level is odd, // return its level if (node.left == null && node.right == null && (level & 1) != 0) return level; // If not leaf, return the maximum value // from left and right subtrees return Math.max(depthOfOddLeafUtil(node.left, level + 1), depthOfOddLeafUtil(node.right, level + 1)); } /* * Main function which calculates the depth of deepest odd level leaf. This * function mainly uses depthOfOddLeafUtil() */ function depthOfOddLeaf(node) { var level = 1, depth = 0; return depthOfOddLeafUtil(node, level); } var k = 45; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.left.right = new Node(7); root.right.right.right = new Node(8); root.right.left.right.left = new Node(9); root.right.right.right.right = new Node(10); root.right.right.right.right.left = new Node(11); document.write( depthOfOddLeaf(root) + \" is the required depth\" ); // This code contributed by Rajput-Ji </script>",
"e": 37009,
"s": 35301,
"text": null
},
{
"code": null,
"e": 37018,
"s": 37009,
"text": "Output: "
},
{
"code": null,
"e": 37042,
"s": 37018,
"text": "5 is the required depth"
},
{
"code": null,
"e": 37364,
"s": 37042,
"text": "Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n).Iterative Approach This approach is contributed by Mandeep Singh. Traverse the tree in iterative fashion for each level, and whenever you encounter the leaf node, check if level is odd, if level is odd, then update the result. "
},
{
"code": null,
"e": 37368,
"s": 37364,
"text": "C++"
},
{
"code": null,
"e": 37373,
"s": 37368,
"text": "Java"
},
{
"code": null,
"e": 37381,
"s": 37373,
"text": "Python3"
},
{
"code": null,
"e": 37384,
"s": 37381,
"text": "C#"
},
{
"code": null,
"e": 37395,
"s": 37384,
"text": "Javascript"
},
{
"code": "// CPP program to find// depth of the deepest// odd level leaf node// of binary tree#include <bits/stdc++.h>using namespace std; // tree nodestruct Node{ int data; Node *left, *right;}; // returns a new// tree NodeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // return max odd number// depth of leaf nodeint maxOddLevelDepth(Node* root){ if (!root) return 0; // create a queue // for level order // traversal queue<Node*> q; q.push(root); int result = INT_MAX; int level = 0; // traverse until the // queue is empty while (!q.empty()) { int size = q.size(); level += 1; // traverse for // complete level while(size > 0) { Node* temp = q.front(); q.pop(); // check if the node is // leaf node and level // is odd if level is // odd, then update result if(!temp->left && !temp->right && (level % 2 != 0)) { result = level; } // check for left child if (temp->left) { q.push(temp->left); } // check for right child if (temp->right) { q.push(temp->right); } size -= 1; } } return result;} // driver programint main(){ // construct a tree Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); root->right->right->right->right->left = newNode(11); int result = maxOddLevelDepth(root); if (result == INT_MAX) cout << \"No leaf node at odd level\\n\"; else cout << result; cout << \" is the required depth \" << endl; return 0;}",
"e": 39559,
"s": 37395,
"text": null
},
{
"code": "// Java program to find depth of the deepest// odd level leaf node of binary treeimport java.util.*; class GFG{ // tree nodestatic class Node{ int data; Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // return max odd number depth of leaf nodestatic int maxOddLevelDepth(Node root){ if (root == null) return 0; // create a queue for level order // traversal Queue<Node> q = new LinkedList<>(); q.add(root); int result = Integer.MAX_VALUE; int level = 0; // traverse until the queue is empty while (!q.isEmpty()) { int size = q.size(); level += 1; // traverse for complete level while(size > 0) { Node temp = q.peek(); q.remove(); // check if the node is leaf node and // level is odd if level is odd, // then update result if(temp.left == null && temp.right == null && (level % 2 != 0)) { result = level; } // check for left child if (temp.left != null) { q.add(temp.left); } // check for right child if (temp.right != null) { q.add(temp.right); } size -= 1; } } return result;} // Driver Codepublic static void main(String[] args){ // construct a tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); root.right.right.right.right.left = newNode(11); int result = maxOddLevelDepth(root); if (result == Integer.MAX_VALUE) System.out.println(\"No leaf node at odd level\"); else { System.out.print(result); System.out.println(\" is the required depth \"); }}} // This code is contributed by Rajput-Ji",
"e": 41797,
"s": 39559,
"text": null
},
{
"code": "# Python3 program to find depth of the deepest# odd level leaf node of binary tree INT_MAX = 2**31 # tree node returns a new tree Nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # return max odd number depth# of leaf nodedef maxOddLevelDepth(root) : if (not root): return 0 # create a queue for level order # traversal q = [] q.append(root) result = INT_MAX level = 0 # traverse until the queue is empty while (len(q)) : size = len(q) level += 1 # traverse for complete level while(size > 0) : temp = q[0] q.pop(0) # check if the node is leaf node # and level is odd if level is # odd, then update result if(not temp.left and not temp.right and (level % 2 != 0)) : result = level # check for left child if (temp.left) : q.append(temp.left) # check for right child if (temp.right) : q.append(temp.right) size -= 1 return result # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.right.left = newNode(5) root.right.right = newNode(6) root.right.left.right = newNode(7) root.right.right.right = newNode(8) root.right.left.right.left = newNode(9) root.right.right.right.right = newNode(10) root.right.right.right.right.left = newNode(11) result = maxOddLevelDepth(root) if (result == INT_MAX) : print(\"No leaf node at odd level\") else: print(result, end = \"\") print(\" is the required depth \") # This code is contributed# by SHUBHAMSINGH10",
"e": 43713,
"s": 41797,
"text": null
},
{
"code": "// C# program to find depth of the deepest// odd level leaf node of binary treeusing System;using System.Collections.Generic; class GFG{ // tree nodepublic class Node{ public int data; public Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // return max odd number depth of leaf nodestatic int maxOddLevelDepth(Node root){ if (root == null) return 0; // create a queue for level order // traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); int result = int.MaxValue; int level = 0; // traverse until the queue is empty while (q.Count != 0) { int size = q.Count; level += 1; // traverse for complete level while(size > 0) { Node temp = q.Peek(); q.Dequeue(); // check if the node is leaf node and // level is odd if level is odd, // then update result if(temp.left == null && temp.right == null && (level % 2 != 0)) { result = level; } // check for left child if (temp.left != null) { q.Enqueue(temp.left); } // check for right child if (temp.right != null) { q.Enqueue(temp.right); } size -= 1; } } return result;} // Driver Codepublic static void Main(String[] args){ // construct a tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); root.right.right.right.right.left = newNode(11); int result = maxOddLevelDepth(root); if (result == int.MaxValue) Console.WriteLine(\"No leaf node at odd level\"); else { Console.Write(result); Console.WriteLine(\" is the required depth \"); }}} // This code is contributed by PrinciRaj1992",
"e": 46007,
"s": 43713,
"text": null
},
{
"code": "<script> // JavaScript program to find depth of the deepest // odd level leaf node of binary tree // tree node class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } // returns a new tree Node function newNode(data) { var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp; } // return max odd number depth of leaf node function maxOddLevelDepth(root) { if (root == null) return 0; // create a queue for level order // traversal var q = []; q.push(root); var result = 2147483647; var level = 0; // traverse until the queue is empty while (q.length != 0) { var size = q.length; level += 1; // traverse for complete level while (size > 0) { var temp = q[0]; q.shift(); // check if the node is leaf node and // level is odd if level is odd, // then update result if (temp.left == null && temp.right == null && level % 2 != 0) { result = level; } // check for left child if (temp.left != null) { q.push(temp.left); } // check for right child if (temp.right != null) { q.push(temp.right); } size -= 1; } } return result; } // Driver Code // construct a tree var root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); root.right.right.right.right.left = newNode(11); var result = maxOddLevelDepth(root); if (result == 2147483647) document.write(\"No leaf node at odd level\"); else { document.write(result); document.write(\" is the required depth\"); } </script>",
"e": 48254,
"s": 46007,
"text": null
},
{
"code": null,
"e": 48263,
"s": 48254,
"text": "Output: "
},
{
"code": null,
"e": 48287,
"s": 48263,
"text": "5 is the required depth"
},
{
"code": null,
"e": 48330,
"s": 48287,
"text": "Time Complexity: Time Complexity is O(n). "
},
{
"code": null,
"e": 49174,
"s": 48330,
"text": "YouTubeGeeksforGeeks502K subscribersFind depth of the deepest odd level leaf node | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:35•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=bPp5bjjXhhQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 49348,
"s": 49174,
"text": "This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 49360,
"s": 49348,
"text": "shrikanth13"
},
{
"code": null,
"e": 49375,
"s": 49360,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 49388,
"s": 49375,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 49398,
"s": 49388,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 49412,
"s": 49398,
"text": "princiraj1992"
},
{
"code": null,
"e": 49419,
"s": 49412,
"text": "rdtank"
},
{
"code": null,
"e": 49435,
"s": 49419,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 49440,
"s": 49435,
"text": "Tree"
},
{
"code": null,
"e": 49445,
"s": 49440,
"text": "Tree"
},
{
"code": null,
"e": 49543,
"s": 49445,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49586,
"s": 49543,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 49619,
"s": 49586,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 49633,
"s": 49619,
"text": "Decision Tree"
},
{
"code": null,
"e": 49716,
"s": 49633,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 49774,
"s": 49716,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 49810,
"s": 49774,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 49858,
"s": 49810,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 49885,
"s": 49858,
"text": "BFS vs DFS for Binary Tree"
},
{
"code": null,
"e": 49901,
"s": 49885,
"text": "Expression Tree"
}
] |
Designing Deterministic Finite Automata (Set 3) - GeeksforGeeks | 15 Jun, 2021
Prerequisite: Designing finite automata, Designing Deterministic Finite Automata (Set 2) In this article, we will see some designing of Deterministic Finite Automata (DFA).
Problem-1: Construction of a minimal DFA accepting set of string over {a, b} where each string containing ‘a’ as the substring.
Explanation: The desired language will be like:
L1 = {a, aa, ab, ba, ..............}
Here as we can see that each string of the language containing ‘a’ as the substring but the below language is not accepted by this DFA because some of the string of the below language does not contain ‘a’ as the substring.
L2 = {b, bb, bbb, ..............}
The state transition diagram of the language containing ‘a’ as the substring will be like:
In the above DFA, states ‘X’ and ‘Y’ are the initial and final state respectively, it accepts all the strings containing ‘a’ as the substring. Here as we see that on getting input as ‘b’ it remains in the state of ‘X’ itself but on getting ‘a’ as the input it transit to final state ‘Y’ and hence such string is accepted by above DFA.
Problem-2: Construction of a minimal DFA accepting set of string over {a, b} where each string containing ‘ab’ as the substring.
Explanation: The desired language will be like:
L1 = {ab, aab, abb, bab, ..............}
Here as we can see that each string of the language containing ‘ab’ as the substring but the below language is not accepted by this DFA because some of the string of the below language does not contain ‘ab’ as the substring-
L2 = {aba, bba, bbbaaa, ..............}
The state transition diagram of the language containing ‘ab’ as the substring will be like:
In the above DFA, states ‘X’ and ‘Z’ are the initial and final state respectively, it accepts all the strings containing ‘ab’ as the substring. Here as we see that on getting ‘b’ as the input it remains in the state of initial state itself, on getting ‘a’ as the input it transit to state ‘Y’ and then on getting ‘b’ it finally transit to the final state ‘Z’ and hence this DFA is accepting all the language containing ‘ab’ as the substring.
avipanwar6565
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Semaphores in Process Synchronization
Types of Network Topology
Difference between DFA and NFA
Turing Machine in TOC
Difference between Mealy machine and Moore machine
Conversion from NFA to DFA
Introduction of Pushdown Automata | [
{
"code": null,
"e": 24454,
"s": 24426,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 24628,
"s": 24454,
"text": "Prerequisite: Designing finite automata, Designing Deterministic Finite Automata (Set 2) In this article, we will see some designing of Deterministic Finite Automata (DFA). "
},
{
"code": null,
"e": 24757,
"s": 24628,
"text": "Problem-1: Construction of a minimal DFA accepting set of string over {a, b} where each string containing ‘a’ as the substring. "
},
{
"code": null,
"e": 24807,
"s": 24757,
"text": "Explanation: The desired language will be like: "
},
{
"code": null,
"e": 24844,
"s": 24807,
"text": "L1 = {a, aa, ab, ba, ..............}"
},
{
"code": null,
"e": 25069,
"s": 24844,
"text": "Here as we can see that each string of the language containing ‘a’ as the substring but the below language is not accepted by this DFA because some of the string of the below language does not contain ‘a’ as the substring. "
},
{
"code": null,
"e": 25103,
"s": 25069,
"text": "L2 = {b, bb, bbb, ..............}"
},
{
"code": null,
"e": 25196,
"s": 25103,
"text": "The state transition diagram of the language containing ‘a’ as the substring will be like: "
},
{
"code": null,
"e": 25532,
"s": 25196,
"text": "In the above DFA, states ‘X’ and ‘Y’ are the initial and final state respectively, it accepts all the strings containing ‘a’ as the substring. Here as we see that on getting input as ‘b’ it remains in the state of ‘X’ itself but on getting ‘a’ as the input it transit to final state ‘Y’ and hence such string is accepted by above DFA. "
},
{
"code": null,
"e": 25662,
"s": 25532,
"text": "Problem-2: Construction of a minimal DFA accepting set of string over {a, b} where each string containing ‘ab’ as the substring. "
},
{
"code": null,
"e": 25712,
"s": 25662,
"text": "Explanation: The desired language will be like: "
},
{
"code": null,
"e": 25753,
"s": 25712,
"text": "L1 = {ab, aab, abb, bab, ..............}"
},
{
"code": null,
"e": 25980,
"s": 25753,
"text": "Here as we can see that each string of the language containing ‘ab’ as the substring but the below language is not accepted by this DFA because some of the string of the below language does not contain ‘ab’ as the substring- "
},
{
"code": null,
"e": 26020,
"s": 25980,
"text": "L2 = {aba, bba, bbbaaa, ..............}"
},
{
"code": null,
"e": 26114,
"s": 26020,
"text": "The state transition diagram of the language containing ‘ab’ as the substring will be like: "
},
{
"code": null,
"e": 26557,
"s": 26114,
"text": "In the above DFA, states ‘X’ and ‘Z’ are the initial and final state respectively, it accepts all the strings containing ‘ab’ as the substring. Here as we see that on getting ‘b’ as the input it remains in the state of initial state itself, on getting ‘a’ as the input it transit to state ‘Y’ and then on getting ‘b’ it finally transit to the final state ‘Z’ and hence this DFA is accepting all the language containing ‘ab’ as the substring. "
},
{
"code": null,
"e": 26571,
"s": 26557,
"text": "avipanwar6565"
},
{
"code": null,
"e": 26579,
"s": 26571,
"text": "GATE CS"
},
{
"code": null,
"e": 26612,
"s": 26579,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 26710,
"s": 26612,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26719,
"s": 26710,
"text": "Comments"
},
{
"code": null,
"e": 26732,
"s": 26719,
"text": "Old Comments"
},
{
"code": null,
"e": 26781,
"s": 26732,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 26813,
"s": 26781,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 26852,
"s": 26813,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 26890,
"s": 26852,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 26916,
"s": 26890,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 26947,
"s": 26916,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 26969,
"s": 26947,
"text": "Turing Machine in TOC"
},
{
"code": null,
"e": 27020,
"s": 26969,
"text": "Difference between Mealy machine and Moore machine"
},
{
"code": null,
"e": 27047,
"s": 27020,
"text": "Conversion from NFA to DFA"
}
] |
Matplotlib.axis.Axis.axis_date() function in Python - GeeksforGeeks | 05 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.axis_date() function in axis module of matplotlib library is used to set up axis ticks and labels treating data along this axis as dates.
Syntax: Axis.axis_date(self, tz=None)
Parameters: This method accepts the following parameters.
tz : This parameter is the timezone used to create date labels.
Return value: This method does not return any value.
Below examples illustrate the matplotlib.axis.Axis.axis_date() function in matplotlib.axis:
Example 1:
Python3
# Implementation of matplotlib function from matplotlib.axis import Axisimport datetime as dtimport matplotlib.pyplot as pltfrom matplotlib.dates import DateFormatter, MinuteLocator x = [16.7,16.8,17.1,17.4]y = [15,17,14,16]plt.plot(x, y) plt.gca().yaxis.axis_date() plt.title("Matplotlib.axis.Axis.axis_date()\Function Example", fontsize = 12, fontweight ='bold') plt.show()
Output:
Example 2:
Python3
# Implementation of matplotlib function from matplotlib.axis import Axis from datetime import datetime import matplotlib.pyplot as plt from matplotlib.dates import ( DateFormatter, AutoDateLocator, AutoDateFormatter, datestr2num ) days = [ '30/01/2019', '31/01/2019', '01/02/2019', '02/02/2019', '03/02/2019', '04/02/2019'] data1 = [2, 5, 13, 6, 11, 7] data2 = [6, 3, 10, 3, 6, 5] z = datestr2num([ datetime.strptime(day, '%d/%m/%Y').strftime('%m/%d/%Y') for day in days ]) r = 0.25 figure = plt.figure(figsize =(8, 4)) axes = figure.add_subplot(111) axes.bar(z - r, data1, width = 2 * r, color ='g', align ='center', tick_label = days) axes.bar(z + r, data2, width = 2 * r, color ='y', align ='center', tick_label = days) axes.xaxis.axis_date() plt.title("Matplotlib.axis.Axis.axis_date()\Function Example", fontsize = 12, fontweight ='bold') plt.show()
Output:
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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": "\n05 Jun, 2020"
},
{
"code": null,
"e": 24513,
"s": 24292,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack."
},
{
"code": null,
"e": 24662,
"s": 24513,
"text": "The Axis.axis_date() function in axis module of matplotlib library is used to set up axis ticks and labels treating data along this axis as dates. "
},
{
"code": null,
"e": 24701,
"s": 24662,
"text": "Syntax: Axis.axis_date(self, tz=None) "
},
{
"code": null,
"e": 24760,
"s": 24701,
"text": "Parameters: This method accepts the following parameters. "
},
{
"code": null,
"e": 24824,
"s": 24760,
"text": "tz : This parameter is the timezone used to create date labels."
},
{
"code": null,
"e": 24878,
"s": 24824,
"text": "Return value: This method does not return any value. "
},
{
"code": null,
"e": 24970,
"s": 24878,
"text": "Below examples illustrate the matplotlib.axis.Axis.axis_date() function in matplotlib.axis:"
},
{
"code": null,
"e": 24981,
"s": 24970,
"text": "Example 1:"
},
{
"code": null,
"e": 24989,
"s": 24981,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib function from matplotlib.axis import Axisimport datetime as dtimport matplotlib.pyplot as pltfrom matplotlib.dates import DateFormatter, MinuteLocator x = [16.7,16.8,17.1,17.4]y = [15,17,14,16]plt.plot(x, y) plt.gca().yaxis.axis_date() plt.title(\"Matplotlib.axis.Axis.axis_date()\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()",
"e": 25369,
"s": 24989,
"text": null
},
{
"code": null,
"e": 25378,
"s": 25369,
"text": "Output: "
},
{
"code": null,
"e": 25390,
"s": 25378,
"text": "Example 2: "
},
{
"code": null,
"e": 25398,
"s": 25390,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib function from matplotlib.axis import Axis from datetime import datetime import matplotlib.pyplot as plt from matplotlib.dates import ( DateFormatter, AutoDateLocator, AutoDateFormatter, datestr2num ) days = [ '30/01/2019', '31/01/2019', '01/02/2019', '02/02/2019', '03/02/2019', '04/02/2019'] data1 = [2, 5, 13, 6, 11, 7] data2 = [6, 3, 10, 3, 6, 5] z = datestr2num([ datetime.strptime(day, '%d/%m/%Y').strftime('%m/%d/%Y') for day in days ]) r = 0.25 figure = plt.figure(figsize =(8, 4)) axes = figure.add_subplot(111) axes.bar(z - r, data1, width = 2 * r, color ='g', align ='center', tick_label = days) axes.bar(z + r, data2, width = 2 * r, color ='y', align ='center', tick_label = days) axes.xaxis.axis_date() plt.title(\"Matplotlib.axis.Axis.axis_date()\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()",
"e": 26361,
"s": 25398,
"text": null
},
{
"code": null,
"e": 26370,
"s": 26361,
"text": "Output: "
},
{
"code": null,
"e": 26394,
"s": 26372,
"text": "Matplotlib-Axis Class"
},
{
"code": null,
"e": 26412,
"s": 26394,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26419,
"s": 26412,
"text": "Python"
},
{
"code": null,
"e": 26517,
"s": 26419,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26549,
"s": 26517,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26605,
"s": 26549,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26647,
"s": 26605,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26689,
"s": 26647,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26711,
"s": 26689,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26742,
"s": 26711,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26781,
"s": 26742,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26836,
"s": 26781,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26865,
"s": 26836,
"text": "Create a directory in Python"
}
] |
Python Pillow - Image Sequences | The Python Imaging Library (PIL) contains some basic support for Image sequences (animation formats). FLI/FLC, GIF and a few experimental formats are the supported sequence formats. TIFF files can contain more than one frame as well.
Opening a sequence file, PIL automatically loads the first frame in the sequence. To move between different frames, you can use the seek and tell methods.
from PIL import Image
img = Image.open('bird.jpg')
#Skip to the second frame
img.seek(1)
try:
while 1:
img.seek(img.tell() + 1)
#do_something to img
except EOFError:
#End of sequence
pass
raise EOFError
EOFError
As we can see above, you’ll get an EOFError exception when the sequence ends.
Most drivers in the latest version of library only allow you to seek to the next frame (as in above example), to rewind the file, you may have to reopen it.
class ImageSequence:
def __init__(self, img):
self.img = img
def __getitem__(self, ix):
try:
if ix:
self.img.seek(ix)
return self.img
except EOFError:
raise IndexError # end of sequence
for frame in ImageSequence(img):
# ...do something to frame...
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2434,
"s": 2200,
"text": "The Python Imaging Library (PIL) contains some basic support for Image sequences (animation formats). FLI/FLC, GIF and a few experimental formats are the supported sequence formats. TIFF files can contain more than one frame as well."
},
{
"code": null,
"e": 2589,
"s": 2434,
"text": "Opening a sequence file, PIL automatically loads the first frame in the sequence. To move between different frames, you can use the seek and tell methods."
},
{
"code": null,
"e": 2798,
"s": 2589,
"text": "from PIL import Image\nimg = Image.open('bird.jpg')\n#Skip to the second frame\nimg.seek(1)\ntry:\n while 1:\n img.seek(img.tell() + 1)\n #do_something to img\nexcept EOFError:\n #End of sequence\n pass"
},
{
"code": null,
"e": 2823,
"s": 2798,
"text": "raise EOFError\nEOFError\n"
},
{
"code": null,
"e": 2901,
"s": 2823,
"text": "As we can see above, you’ll get an EOFError exception when the sequence ends."
},
{
"code": null,
"e": 3058,
"s": 2901,
"text": "Most drivers in the latest version of library only allow you to seek to the next frame (as in above example), to rewind the file, you may have to reopen it."
},
{
"code": null,
"e": 3373,
"s": 3058,
"text": "class ImageSequence:\n def __init__(self, img):\n self.img = img\n def __getitem__(self, ix):\n try:\n if ix:\n self.img.seek(ix)\n return self.img\n except EOFError:\n raise IndexError # end of sequence\nfor frame in ImageSequence(img):\n # ...do something to frame..."
},
{
"code": null,
"e": 3410,
"s": 3373,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3426,
"s": 3410,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3459,
"s": 3426,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3478,
"s": 3459,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3513,
"s": 3478,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3535,
"s": 3513,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3569,
"s": 3535,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3597,
"s": 3569,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3632,
"s": 3597,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3646,
"s": 3632,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3679,
"s": 3646,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3696,
"s": 3679,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3703,
"s": 3696,
"text": " Print"
},
{
"code": null,
"e": 3714,
"s": 3703,
"text": " Add Notes"
}
] |
XAML - ComboBox | A ComboBox represents a selection control that combines a non-editable textbox and a drop-down list box that allows users to select an item from a list. It either displays the current selection or is empty if there is no selected item. The hierarchical inheritance of ComboBox class is as follows −
Background
Gets or sets a brush that provides the background of the control. (Inherited from Control)
BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control)
FontFamily
Gets or sets the font used to display text in the control. (Inherited from Control)
FontSize
Gets or sets the size of the text in this control. (Inherited from Control)
FontStyle
Gets or sets the style in which the text is rendered. (Inherited from Control)
FontWeight
Gets or sets the thickness of the specified font. (Inherited from Control)
Foreground
Gets or sets a brush that describes the foreground color. (Inherited from Control)
GroupStyle
Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl)
Header
Gets or sets the content for the control's header.
Height
Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement)
HorizontalAlignment
Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement)
IsDropDownOpen
Gets or sets a value that indicates whether the drop-down portion of the ComboBox is currently open.
IsEditable
Gets a value that indicates whether the user can edit text in the text box portion of the ComboBox. This property always returns false.
IsEnabled
Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control)
Margin
Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement)
Name
Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAMLdeclared object by this name. (Inherited from FrameworkElement)
Opacity
Gets or sets the degree of the object's opacity. (Inherited from UIElement)
SelectedIndex
Gets or sets the index of the selected item. (Inherited from Selector)
SelectedItem
Gets or sets the selected item. (Inherited from Selector)
SelectedValue
Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector)
Style
Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement
VerticalAlignment
Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement)
Width
Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement)
ItemsSource
Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl)
Arrange
Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement)
FindName
Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement)
Focus
Attempts to set the focus on the control. (Inherited from Control)
GetValue
Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject)
IndexFromContainer
Returns the index to the item that has the specified, generated container. (Inherited from ItemsControl)
OnDragEnter
Called before the DragEnter event occurs. (Inherited from Control)
OnDragLeave
Called before the DragLeave event occurs. (Inherited from Control)
OnDragOver
Called before the DragOver event occurs. (Inherited from Control)
OnDrop
Called before the Drop event occurs. (Inherited from Control)
OnKeyDown
Called before the KeyDown event occurs. (Inherited from Control)
OnKeyUp
Called before the KeyUp event occurs. (Inherited from Control)
OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)
ReadLocalValue
Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject)
SetBinding
Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement)
SetValue
Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject)
DragEnter
Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)
DragLeave
Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)
DragOver
Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)
DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)
Drop
Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement)
DropCompleted
Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)
DropDownClosed
Occurs when the drop-down portion of the ComboBox closes.
DropDownOpened
Occurs when the drop-down portion of the ComboBox opens.
GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
IsEnabledChanged
Occurs when the IsEnabled property changes. (Inherited from Control)
KeyDown
Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)
KeyUp
Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)
LostFocus
Occurs when a UIElement loses focus. (Inherited from UIElement)
SelectionChanged
Occurs when the currently selected item changes. (Inherited from Selector)
SizeChanged
Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)
The following example contains two comboboxes. The first combobox is a simple one and the second one is editable.
Here is the XAML code in which two comboboxes have been created with some properties.
<Window x:Class = "XAMLComboBox.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<ComboBox Height = "20" Width = "100" HorizontalAlignment = "Left" Margin = "116,77,0,212">
<ComboBoxItem Content = "Item #1"/>
<ComboBoxItem Content = "Item #2"/>
<ComboBoxItem Content = "Item #3"/>
</ComboBox>
<ComboBox IsEditable = "True" Height = "20" Width = "100"
HorizontalAlignment = "Right" Margin = "0,77,180,212">
<ComboBoxItem Content = "Item #1"/>
<ComboBoxItem Content = "Item #2"/>
<ComboBoxItem Content = "Item #3"/>
</ComboBox>
</Grid>
</Window>
When you compile and execute the above code, it will produce the following output −
We recommend you to execute the above example code and experiment with some other properties and events.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2222,
"s": 1923,
"text": "A ComboBox represents a selection control that combines a non-editable textbox and a drop-down list box that allows users to select an item from a list. It either displays the current selection or is empty if there is no selected item. The hierarchical inheritance of ComboBox class is as follows −"
},
{
"code": null,
"e": 2233,
"s": 2222,
"text": "Background"
},
{
"code": null,
"e": 2324,
"s": 2233,
"text": "Gets or sets a brush that provides the background of the control. (Inherited from Control)"
},
{
"code": null,
"e": 2340,
"s": 2324,
"text": "BorderThickness"
},
{
"code": null,
"e": 2413,
"s": 2340,
"text": "Gets or sets the border thickness of a control. (Inherited from Control)"
},
{
"code": null,
"e": 2424,
"s": 2413,
"text": "FontFamily"
},
{
"code": null,
"e": 2508,
"s": 2424,
"text": "Gets or sets the font used to display text in the control. (Inherited from Control)"
},
{
"code": null,
"e": 2517,
"s": 2508,
"text": "FontSize"
},
{
"code": null,
"e": 2593,
"s": 2517,
"text": "Gets or sets the size of the text in this control. (Inherited from Control)"
},
{
"code": null,
"e": 2603,
"s": 2593,
"text": "FontStyle"
},
{
"code": null,
"e": 2682,
"s": 2603,
"text": "Gets or sets the style in which the text is rendered. (Inherited from Control)"
},
{
"code": null,
"e": 2693,
"s": 2682,
"text": "FontWeight"
},
{
"code": null,
"e": 2768,
"s": 2693,
"text": "Gets or sets the thickness of the specified font. (Inherited from Control)"
},
{
"code": null,
"e": 2779,
"s": 2768,
"text": "Foreground"
},
{
"code": null,
"e": 2862,
"s": 2779,
"text": "Gets or sets a brush that describes the foreground color. (Inherited from Control)"
},
{
"code": null,
"e": 2873,
"s": 2862,
"text": "GroupStyle"
},
{
"code": null,
"e": 2995,
"s": 2873,
"text": "Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl)"
},
{
"code": null,
"e": 3002,
"s": 2995,
"text": "Header"
},
{
"code": null,
"e": 3053,
"s": 3002,
"text": "Gets or sets the content for the control's header."
},
{
"code": null,
"e": 3060,
"s": 3053,
"text": "Height"
},
{
"code": null,
"e": 3151,
"s": 3060,
"text": "Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 3171,
"s": 3151,
"text": "HorizontalAlignment"
},
{
"code": null,
"e": 3372,
"s": 3171,
"text": "Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 3387,
"s": 3372,
"text": "IsDropDownOpen"
},
{
"code": null,
"e": 3488,
"s": 3387,
"text": "Gets or sets a value that indicates whether the drop-down portion of the ComboBox is currently open."
},
{
"code": null,
"e": 3499,
"s": 3488,
"text": "IsEditable"
},
{
"code": null,
"e": 3635,
"s": 3499,
"text": "Gets a value that indicates whether the user can edit text in the text box portion of the ComboBox. This property always returns false."
},
{
"code": null,
"e": 3645,
"s": 3635,
"text": "IsEnabled"
},
{
"code": null,
"e": 3750,
"s": 3645,
"text": "Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control)"
},
{
"code": null,
"e": 3757,
"s": 3750,
"text": "Margin"
},
{
"code": null,
"e": 3844,
"s": 3757,
"text": "Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 3849,
"s": 3844,
"text": "Name"
},
{
"code": null,
"e": 4061,
"s": 3849,
"text": "Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAMLdeclared object by this name. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 4069,
"s": 4061,
"text": "Opacity"
},
{
"code": null,
"e": 4145,
"s": 4069,
"text": "Gets or sets the degree of the object's opacity. (Inherited from UIElement)"
},
{
"code": null,
"e": 4159,
"s": 4145,
"text": "SelectedIndex"
},
{
"code": null,
"e": 4230,
"s": 4159,
"text": "Gets or sets the index of the selected item. (Inherited from Selector)"
},
{
"code": null,
"e": 4243,
"s": 4230,
"text": "SelectedItem"
},
{
"code": null,
"e": 4301,
"s": 4243,
"text": "Gets or sets the selected item. (Inherited from Selector)"
},
{
"code": null,
"e": 4315,
"s": 4301,
"text": "SelectedValue"
},
{
"code": null,
"e": 4427,
"s": 4315,
"text": "Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector)"
},
{
"code": null,
"e": 4433,
"s": 4427,
"text": "Style"
},
{
"code": null,
"e": 4558,
"s": 4433,
"text": "Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement"
},
{
"code": null,
"e": 4576,
"s": 4558,
"text": "VerticalAlignment"
},
{
"code": null,
"e": 4774,
"s": 4576,
"text": "Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 4780,
"s": 4774,
"text": "Width"
},
{
"code": null,
"e": 4860,
"s": 4780,
"text": "Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 4872,
"s": 4860,
"text": "ItemsSource"
},
{
"code": null,
"e": 4982,
"s": 4872,
"text": "Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl)"
},
{
"code": null,
"e": 4990,
"s": 4982,
"text": "Arrange"
},
{
"code": null,
"e": 5252,
"s": 4990,
"text": "Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement)"
},
{
"code": null,
"e": 5262,
"s": 5252,
"text": "FindName "
},
{
"code": null,
"e": 5356,
"s": 5262,
"text": "Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 5362,
"s": 5356,
"text": "Focus"
},
{
"code": null,
"e": 5429,
"s": 5362,
"text": "Attempts to set the focus on the control. (Inherited from Control)"
},
{
"code": null,
"e": 5438,
"s": 5429,
"text": "GetValue"
},
{
"code": null,
"e": 5558,
"s": 5438,
"text": "Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject)"
},
{
"code": null,
"e": 5577,
"s": 5558,
"text": "IndexFromContainer"
},
{
"code": null,
"e": 5682,
"s": 5577,
"text": "Returns the index to the item that has the specified, generated container. (Inherited from ItemsControl)"
},
{
"code": null,
"e": 5694,
"s": 5682,
"text": "OnDragEnter"
},
{
"code": null,
"e": 5761,
"s": 5694,
"text": "Called before the DragEnter event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 5773,
"s": 5761,
"text": "OnDragLeave"
},
{
"code": null,
"e": 5840,
"s": 5773,
"text": "Called before the DragLeave event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 5851,
"s": 5840,
"text": "OnDragOver"
},
{
"code": null,
"e": 5917,
"s": 5851,
"text": "Called before the DragOver event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 5924,
"s": 5917,
"text": "OnDrop"
},
{
"code": null,
"e": 5986,
"s": 5924,
"text": "Called before the Drop event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 5996,
"s": 5986,
"text": "OnKeyDown"
},
{
"code": null,
"e": 6061,
"s": 5996,
"text": "Called before the KeyDown event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6069,
"s": 6061,
"text": "OnKeyUp"
},
{
"code": null,
"e": 6132,
"s": 6069,
"text": "Called before the KeyUp event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6144,
"s": 6132,
"text": "OnLostFocus"
},
{
"code": null,
"e": 6211,
"s": 6144,
"text": "Called before the LostFocus event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6226,
"s": 6211,
"text": "ReadLocalValue"
},
{
"code": null,
"e": 6335,
"s": 6226,
"text": "Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject)"
},
{
"code": null,
"e": 6346,
"s": 6335,
"text": "SetBinding"
},
{
"code": null,
"e": 6457,
"s": 6346,
"text": "Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 6466,
"s": 6457,
"text": "SetValue"
},
{
"code": null,
"e": 6569,
"s": 6466,
"text": "Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject)"
},
{
"code": null,
"e": 6579,
"s": 6569,
"text": "DragEnter"
},
{
"code": null,
"e": 6701,
"s": 6579,
"text": "Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)"
},
{
"code": null,
"e": 6711,
"s": 6701,
"text": "DragLeave"
},
{
"code": null,
"e": 6833,
"s": 6711,
"text": "Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)"
},
{
"code": null,
"e": 6842,
"s": 6833,
"text": "DragOver"
},
{
"code": null,
"e": 6979,
"s": 6842,
"text": "Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)"
},
{
"code": null,
"e": 6992,
"s": 6979,
"text": "DragStarting"
},
{
"code": null,
"e": 7062,
"s": 6992,
"text": "Occurs when a drag operation is initiated. (Inherited from UIElement)"
},
{
"code": null,
"e": 7067,
"s": 7062,
"text": "Drop"
},
{
"code": null,
"e": 7194,
"s": 7067,
"text": "Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement)"
},
{
"code": null,
"e": 7208,
"s": 7194,
"text": "DropCompleted"
},
{
"code": null,
"e": 7283,
"s": 7208,
"text": "Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)"
},
{
"code": null,
"e": 7298,
"s": 7283,
"text": "DropDownClosed"
},
{
"code": null,
"e": 7356,
"s": 7298,
"text": "Occurs when the drop-down portion of the ComboBox closes."
},
{
"code": null,
"e": 7371,
"s": 7356,
"text": "DropDownOpened"
},
{
"code": null,
"e": 7428,
"s": 7371,
"text": "Occurs when the drop-down portion of the ComboBox opens."
},
{
"code": null,
"e": 7437,
"s": 7428,
"text": "GotFocus"
},
{
"code": null,
"e": 7504,
"s": 7437,
"text": "Occurs when a UIElement receives focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 7521,
"s": 7504,
"text": "IsEnabledChanged"
},
{
"code": null,
"e": 7590,
"s": 7521,
"text": "Occurs when the IsEnabled property changes. (Inherited from Control)"
},
{
"code": null,
"e": 7598,
"s": 7590,
"text": "KeyDown"
},
{
"code": null,
"e": 7694,
"s": 7598,
"text": "Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 7700,
"s": 7694,
"text": "KeyUp"
},
{
"code": null,
"e": 7797,
"s": 7700,
"text": "Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 7807,
"s": 7797,
"text": "LostFocus"
},
{
"code": null,
"e": 7871,
"s": 7807,
"text": "Occurs when a UIElement loses focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 7888,
"s": 7871,
"text": "SelectionChanged"
},
{
"code": null,
"e": 7963,
"s": 7888,
"text": "Occurs when the currently selected item changes. (Inherited from Selector)"
},
{
"code": null,
"e": 7975,
"s": 7963,
"text": "SizeChanged"
},
{
"code": null,
"e": 8110,
"s": 7975,
"text": "Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 8224,
"s": 8110,
"text": "The following example contains two comboboxes. The first combobox is a simple one and the second one is editable."
},
{
"code": null,
"e": 8310,
"s": 8224,
"text": "Here is the XAML code in which two comboboxes have been created with some properties."
},
{
"code": null,
"e": 9126,
"s": 8310,
"text": "<Window x:Class = \"XAMLComboBox.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid>\n <ComboBox Height = \"20\" Width = \"100\" HorizontalAlignment = \"Left\" Margin = \"116,77,0,212\"> \n <ComboBoxItem Content = \"Item #1\"/> \n <ComboBoxItem Content = \"Item #2\"/> \n <ComboBoxItem Content = \"Item #3\"/> \n </ComboBox> \n\t\t\n <ComboBox IsEditable = \"True\" Height = \"20\" Width = \"100\" \n HorizontalAlignment = \"Right\" Margin = \"0,77,180,212\"> \n <ComboBoxItem Content = \"Item #1\"/> \n <ComboBoxItem Content = \"Item #2\"/> \n <ComboBoxItem Content = \"Item #3\"/> \n </ComboBox>\n </Grid>\n \n</Window> "
},
{
"code": null,
"e": 9210,
"s": 9126,
"text": "When you compile and execute the above code, it will produce the following output −"
},
{
"code": null,
"e": 9315,
"s": 9210,
"text": "We recommend you to execute the above example code and experiment with some other properties and events."
},
{
"code": null,
"e": 9322,
"s": 9315,
"text": " Print"
},
{
"code": null,
"e": 9333,
"s": 9322,
"text": " Add Notes"
}
] |
Data Structures | Misc | Question 4 - GeeksforGeeks | 28 Jun, 2021
The best data structure to check whether an arithmetic expression has balanced parentheses is a (GATE CS 2004)
(A) queue(B) stack(C) tree(D) listAnswer: (B)Explanation: There are three types of parentheses [ ] { } (). Below is an arbit c code segment which has parentheses of all three types.
void func(int c, int a[]){ return ((c +2) + arr[(c-2)]) ; }
Stack is a straightforward choice for checking if left and right parentheses are balanced. Here is a algorithm to do the same.
/*Return 1 if expression has balanced parentheses */bool areParenthesesBalanced(expression ){ for each character in expression { if(character == ’(’ || character == ’{’ || character == ’[’) push(stack, character); if(character == ’)’ || character == ’}’ || character == ’]’) { if(isEmpty(stack)) return 0; /*We are seeing a right parenthesis without a left pair*/ /* Pop the top element from stack, if it is not a pair bracket of character then there is a mismatch. This will happen for expressions like {(}) */ else if (! isMatchingPair(pop(stack), character) ) return 0; } } if(isEmpty(stack)) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* End of function to check parentheses */ /* Returns 1 if character1 and character2 are matching left and right parentheses */bool isMatchingPair(character1, character2){ if(character1 == ‘(‘ && character2 == ‘)’) return 1; else If(character1 == ‘{‘ && character2 == ‘}’) return 1; else If(character1 == ‘[‘ && character2 == ‘]’) return 1; else return 0;}
Quiz of this Question
Data Structures
Data Structures-Misc
Misc
Data Structures
Misc
Data Structures
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C program to implement Adjacency Matrix of a given Graph
Advantages and Disadvantages of Linked List
Difference between Singly linked list and Doubly linked list
FIFO vs LIFO approach in Programming
Multilevel Linked List
Advantages of vector over array in C++
Difference between data type and data structure
Data Structures | Array | Question 2
Bit manipulation | Swap Endianness of a number
Data Structures | Queue | Question 1 | [
{
"code": null,
"e": 25020,
"s": 24992,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25131,
"s": 25020,
"text": "The best data structure to check whether an arithmetic expression has balanced parentheses is a (GATE CS 2004)"
},
{
"code": null,
"e": 25313,
"s": 25131,
"text": "(A) queue(B) stack(C) tree(D) listAnswer: (B)Explanation: There are three types of parentheses [ ] { } (). Below is an arbit c code segment which has parentheses of all three types."
},
{
"code": "void func(int c, int a[]){ return ((c +2) + arr[(c-2)]) ; }",
"e": 25377,
"s": 25313,
"text": null
},
{
"code": null,
"e": 25504,
"s": 25377,
"text": "Stack is a straightforward choice for checking if left and right parentheses are balanced. Here is a algorithm to do the same."
},
{
"code": "/*Return 1 if expression has balanced parentheses */bool areParenthesesBalanced(expression ){ for each character in expression { if(character == ’(’ || character == ’{’ || character == ’[’) push(stack, character); if(character == ’)’ || character == ’}’ || character == ’]’) { if(isEmpty(stack)) return 0; /*We are seeing a right parenthesis without a left pair*/ /* Pop the top element from stack, if it is not a pair bracket of character then there is a mismatch. This will happen for expressions like {(}) */ else if (! isMatchingPair(pop(stack), character) ) return 0; } } if(isEmpty(stack)) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* End of function to check parentheses */ /* Returns 1 if character1 and character2 are matching left and right parentheses */bool isMatchingPair(character1, character2){ if(character1 == ‘(‘ && character2 == ‘)’) return 1; else If(character1 == ‘{‘ && character2 == ‘}’) return 1; else If(character1 == ‘[‘ && character2 == ‘]’) return 1; else return 0;}",
"e": 26700,
"s": 25504,
"text": null
},
{
"code": null,
"e": 26722,
"s": 26700,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26738,
"s": 26722,
"text": "Data Structures"
},
{
"code": null,
"e": 26759,
"s": 26738,
"text": "Data Structures-Misc"
},
{
"code": null,
"e": 26764,
"s": 26759,
"text": "Misc"
},
{
"code": null,
"e": 26780,
"s": 26764,
"text": "Data Structures"
},
{
"code": null,
"e": 26785,
"s": 26780,
"text": "Misc"
},
{
"code": null,
"e": 26801,
"s": 26785,
"text": "Data Structures"
},
{
"code": null,
"e": 26806,
"s": 26801,
"text": "Misc"
},
{
"code": null,
"e": 26904,
"s": 26806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26913,
"s": 26904,
"text": "Comments"
},
{
"code": null,
"e": 26926,
"s": 26913,
"text": "Old Comments"
},
{
"code": null,
"e": 26983,
"s": 26926,
"text": "C program to implement Adjacency Matrix of a given Graph"
},
{
"code": null,
"e": 27027,
"s": 26983,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 27088,
"s": 27027,
"text": "Difference between Singly linked list and Doubly linked list"
},
{
"code": null,
"e": 27125,
"s": 27088,
"text": "FIFO vs LIFO approach in Programming"
},
{
"code": null,
"e": 27148,
"s": 27125,
"text": "Multilevel Linked List"
},
{
"code": null,
"e": 27187,
"s": 27148,
"text": "Advantages of vector over array in C++"
},
{
"code": null,
"e": 27235,
"s": 27187,
"text": "Difference between data type and data structure"
},
{
"code": null,
"e": 27272,
"s": 27235,
"text": "Data Structures | Array | Question 2"
},
{
"code": null,
"e": 27319,
"s": 27272,
"text": "Bit manipulation | Swap Endianness of a number"
}
] |
How to change MySQL column definition? | To change MySQL column definition, we can use modify or change clause with ALTER command. Let us first create a table with a column as ID, with int data type. We will modify the same column name with varchar data type.
Creating a table.
mysql> create table ModifyColumnDemo
-> (
-> id int
-> );
Query OK, 0 rows affected (0.52 sec)
Now, let us write the syntax to change the column definition. The syntax is as follows −
alter table yourTableName modify column columnName data type;
Apply the above syntax to change the MySQL definition.
mysql> alter table ModifyColumnDemo modify column id varchar(10) not null;
Query OK, 0 rows affected (1.52 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us now check whether the column has been change with the new data type or not. For that, we will be using the DESC command.
mysql> desc ModifyColumnDemo;
The following is the output.
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | varchar(10) | NO | | NULL | |
+-------+-------------+------+-----+---------+-------+
1 row in set (0.15 sec)
You can see in the above output, we have changed the column definition with new datatype varchar. | [
{
"code": null,
"e": 1281,
"s": 1062,
"text": "To change MySQL column definition, we can use modify or change clause with ALTER command. Let us first create a table with a column as ID, with int data type. We will modify the same column name with varchar data type."
},
{
"code": null,
"e": 1299,
"s": 1281,
"text": "Creating a table."
},
{
"code": null,
"e": 1403,
"s": 1299,
"text": "mysql> create table ModifyColumnDemo\n -> (\n -> id int\n -> );\nQuery OK, 0 rows affected (0.52 sec)"
},
{
"code": null,
"e": 1492,
"s": 1403,
"text": "Now, let us write the syntax to change the column definition. The syntax is as follows −"
},
{
"code": null,
"e": 1554,
"s": 1492,
"text": "alter table yourTableName modify column columnName data type;"
},
{
"code": null,
"e": 1609,
"s": 1554,
"text": "Apply the above syntax to change the MySQL definition."
},
{
"code": null,
"e": 1760,
"s": 1609,
"text": "mysql> alter table ModifyColumnDemo modify column id varchar(10) not null;\nQuery OK, 0 rows affected (1.52 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 1888,
"s": 1760,
"text": "Let us now check whether the column has been change with the new data type or not. For that, we will be using the DESC command."
},
{
"code": null,
"e": 1918,
"s": 1888,
"text": "mysql> desc ModifyColumnDemo;"
},
{
"code": null,
"e": 1947,
"s": 1918,
"text": "The following is the output."
},
{
"code": null,
"e": 2247,
"s": 1947,
"text": "+-------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+-------------+------+-----+---------+-------+\n| id | varchar(10) | NO | | NULL | |\n+-------+-------------+------+-----+---------+-------+\n1 row in set (0.15 sec)\n"
},
{
"code": null,
"e": 2345,
"s": 2247,
"text": "You can see in the above output, we have changed the column definition with new datatype varchar."
}
] |
How to use AutoCompleteTextView in Android App? | This example demonstrate about How to use AutoCompleteTextView in Android App.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.java
<? xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :layout_margin= "16dp"
android :orientation= "vertical"
tools :context= ".MainActivity" >
<android.support.v7.widget.AppCompatAutoCompleteTextView
android :id= "@+id/autoTextView"
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :hint= "Enter fruit name"
android :textColor= "#000000"
android :textColorHint= "#000000" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
import android.support.v7.widget.AppCompatAutoCompleteTextView ;
import android.widget.ArrayAdapter ;
public class MainActivity extends AppCompatActivity {
private String[] fruits = { "Apple" , "Banana" , "Cherry" , "Date" , "Grape" , "Kiwi" , "Mango" , "Pear" } ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
AppCompatAutoCompleteTextView autoTextView = findViewById(R.id. autoTextView ) ;
ArrayAdapter<String> adapter = new ArrayAdapter<>( this,
android.R.layout. select_dialog_item , fruits ) ;
autoTextView.setThreshold( 1 ) ; //will start working from first character
autoTextView.setAdapter(adapter) ;
}
}
Step 4 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package= "app.tutorialspoint.com.sample" >
<uses-permission android :name= "android.permission.VIBRATE" />
<application
android :allowBackup= "true"
android :icon= "@mipmap/ic_launcher"
android:label= "@string/app_name"
android:roundIcon= "@mipmap/ic_launcher_round"
android:supportsRtl= "true"
android:theme= "@style/AppTheme" >
<activity android:name= ".MainActivity" >
<intent-filter>
<action android:name= "android.intent.action.MAIN" />
<category android:name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "This example demonstrate about How to use AutoCompleteTextView in Android App."
},
{
"code": null,
"e": 1270,
"s": 1141,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1335,
"s": 1270,
"text": "Step 2 − Add the following code to res/layout/activity_main.java"
},
{
"code": null,
"e": 2020,
"s": 1335,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<LinearLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n android :orientation= \"vertical\"\n tools :context= \".MainActivity\" >\n <android.support.v7.widget.AppCompatAutoCompleteTextView\n android :id= \"@+id/autoTextView\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :hint= \"Enter fruit name\"\n android :textColor= \"#000000\"\n android :textColorHint= \"#000000\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2077,
"s": 2020,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2960,
"s": 2077,
"text": "package app.tutorialspoint.com.sample ;\nimport android.os.Bundle ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.support.v7.widget.AppCompatAutoCompleteTextView ;\nimport android.widget.ArrayAdapter ;\npublic class MainActivity extends AppCompatActivity {\n private String[] fruits = { \"Apple\" , \"Banana\" , \"Cherry\" , \"Date\" , \"Grape\" , \"Kiwi\" , \"Mango\" , \"Pear\" } ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n AppCompatAutoCompleteTextView autoTextView = findViewById(R.id. autoTextView ) ;\n ArrayAdapter<String> adapter = new ArrayAdapter<>( this,\n android.R.layout. select_dialog_item , fruits ) ;\n autoTextView.setThreshold( 1 ) ; //will start working from first character\n autoTextView.setAdapter(adapter) ;\n }\n}"
},
{
"code": null,
"e": 3015,
"s": 2960,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3792,
"s": 3015,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.VIBRATE\" />\n <application\n android :allowBackup= \"true\"\n android :icon= \"@mipmap/ic_launcher\"\n android:label= \"@string/app_name\"\n android:roundIcon= \"@mipmap/ic_launcher_round\"\n android:supportsRtl= \"true\"\n android:theme= \"@style/AppTheme\" >\n <activity android:name= \".MainActivity\" >\n <intent-filter>\n <action android:name= \"android.intent.action.MAIN\" />\n <category android:name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4139,
"s": 3792,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
] |
How to check whether a form or a control is invalid or not in Angular 10 ? - GeeksforGeeks | 24 May, 2021
In this article, we are going to check whether a form is invalid or not in Angular 10. invalid property is used to report that the control or the form is invalid or not.
Syntax:
form.invalid
Return Value:
boolean: the boolean value to check whether a form is invalid or not.
NgModule: Module used by the invalid property is:
FormsModule
Approach:
Create the Angular app to be used.
In app.component.html make a form using ngForm directive.
In app.component.ts get the information using the invalid property.
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { form = new FormGroup({ name: new FormControl( ), rollno: new FormControl() }); get name(): any { return this.form.get('name');} onSubmit(): void { console.log("Form is invalid : ",this.form.invalid);}}
app.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit()"> <input formControlName="name" placeholder="Name"><br><button type='submit'>Submit</button><br><br></form>
Output:
Reference: https://angular.io/api/forms/AbstractControlDirective#invalid
Angular10
AngularJS-Basics
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 25279,
"s": 25109,
"text": "In this article, we are going to check whether a form is invalid or not in Angular 10. invalid property is used to report that the control or the form is invalid or not."
},
{
"code": null,
"e": 25287,
"s": 25279,
"text": "Syntax:"
},
{
"code": null,
"e": 25301,
"s": 25287,
"text": "form.invalid "
},
{
"code": null,
"e": 25315,
"s": 25301,
"text": "Return Value:"
},
{
"code": null,
"e": 25385,
"s": 25315,
"text": "boolean: the boolean value to check whether a form is invalid or not."
},
{
"code": null,
"e": 25435,
"s": 25385,
"text": "NgModule: Module used by the invalid property is:"
},
{
"code": null,
"e": 25447,
"s": 25435,
"text": "FormsModule"
},
{
"code": null,
"e": 25458,
"s": 25447,
"text": "Approach: "
},
{
"code": null,
"e": 25493,
"s": 25458,
"text": "Create the Angular app to be used."
},
{
"code": null,
"e": 25551,
"s": 25493,
"text": "In app.component.html make a form using ngForm directive."
},
{
"code": null,
"e": 25619,
"s": 25551,
"text": "In app.component.ts get the information using the invalid property."
},
{
"code": null,
"e": 25675,
"s": 25619,
"text": "Serve the angular app using ng serve to see the output."
},
{
"code": null,
"e": 25686,
"s": 25675,
"text": "Example 1:"
},
{
"code": null,
"e": 25703,
"s": 25686,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { form = new FormGroup({ name: new FormControl( ), rollno: new FormControl() }); get name(): any { return this.form.get('name');} onSubmit(): void { console.log(\"Form is invalid : \",this.form.invalid);}}",
"e": 26188,
"s": 25703,
"text": null
},
{
"code": null,
"e": 26207,
"s": 26188,
"text": "app.component.html"
},
{
"code": "<form [formGroup]=\"form\" (ngSubmit)=\"onSubmit()\"> <input formControlName=\"name\" placeholder=\"Name\"><br><button type='submit'>Submit</button><br><br></form>",
"e": 26364,
"s": 26207,
"text": null
},
{
"code": null,
"e": 26372,
"s": 26364,
"text": "Output:"
},
{
"code": null,
"e": 26445,
"s": 26372,
"text": "Reference: https://angular.io/api/forms/AbstractControlDirective#invalid"
},
{
"code": null,
"e": 26455,
"s": 26445,
"text": "Angular10"
},
{
"code": null,
"e": 26472,
"s": 26455,
"text": "AngularJS-Basics"
},
{
"code": null,
"e": 26482,
"s": 26472,
"text": "AngularJS"
},
{
"code": null,
"e": 26499,
"s": 26482,
"text": "Web Technologies"
},
{
"code": null,
"e": 26597,
"s": 26499,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26606,
"s": 26597,
"text": "Comments"
},
{
"code": null,
"e": 26619,
"s": 26606,
"text": "Old Comments"
},
{
"code": null,
"e": 26663,
"s": 26619,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 26727,
"s": 26663,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 26780,
"s": 26727,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 26804,
"s": 26780,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 26839,
"s": 26804,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 26881,
"s": 26839,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26914,
"s": 26881,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26957,
"s": 26914,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27019,
"s": 26957,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
PyQt5 - QAction - GeeksforGeeks | 29 Aug, 2020
QAction : In PyQt5 applications many common commands can be invoked via menus, toolbar buttons, and keyboard shortcuts, since the user expects each command to be performed in the same way, regardless of the user interface used, QAction is useful to represent each command as an action. Actions can be added to menus and toolbars, and will automatically keep them in sync. For example, in a word processor, if the user presses a Bold toolbar button, the Bold menu item will automatically be checked.
Below is how an action will look inside the tool bar
Syntax:
action = QAction(name)
This action can be added to toolbars or QMenus with the help of addAction and addActions method. Below are the some frequently used commands with the QAction
setCheckable : To make QAction Chekable
setIcon : To add icon to the QAction
setText : To set the display name of the QAction
text : To get the display name of the QAction
setPriority : To set the priority of the action
triggered.connect : To connect an method with it when triggered signal is emitted
Example :In this example we will create a main window having a tool bar, label and tool bar is consisting of QAction each having separate method connected to it, below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a tool bar toolbar = QToolBar(self) # setting geometry to the tool bar toolbar.setGeometry(50, 100, 300, 35) # creating QAction Instances action1 = QAction("First Action", self) action2 = QAction("Second Action", self) action3 = QAction("Third Action", self) # adding these actions to the tool bar toolbar.addAction(action1) toolbar.addAction(action2) toolbar.addAction(action3) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(100, 150, 200, 50) # adding triggered action to the first action action1.triggered.connect(lambda: label.setText("First Action Triggered")) # adding triggered action to the second action action2.triggered.connect(lambda: label.setText("Second Action Triggered")) # adding triggered action to the third action action3.triggered.connect(lambda: label.setText("Third Action Triggered")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Another exampleIn this example we will create a commandlink button and add menu to it which is having QAction, below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a command link button cl_button = QCommandLinkButton("Press", self) # setting geometry cl_button.setGeometry(150, 100, 150, 60) # QActions action1 = QAction("Geeks", self) action2 = QAction("GfG", self) # making action2 checkable action2.setCheckable(True) # QMenu menu = QMenu() # adding actions to menu menu.addActions([action1, action2]) # setting menu to the button cl_button.setMenu(menu) # creating label label = QLabel("GeeksforGeeks", self) # setting label geometry label.setGeometry(100, 200, 300, 80) # making label multiline label.setWordWrap(True) # adding method to the action action1.triggered.connect(lambda: label.setText("Action1 is triggered")) # adding method to the action2 when it get checked action2.toggled.connect(lambda: label.setText("Action2 is toggled")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Window window = Window() # start the app sys.exit(App.exec())
Output :
Python PyQt-QAction
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Print lists in Python (4 Different Ways)
Convert integer to string in Python
Check if element exists in list in Python | [
{
"code": null,
"e": 24826,
"s": 24798,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 25325,
"s": 24826,
"text": "QAction : In PyQt5 applications many common commands can be invoked via menus, toolbar buttons, and keyboard shortcuts, since the user expects each command to be performed in the same way, regardless of the user interface used, QAction is useful to represent each command as an action. Actions can be added to menus and toolbars, and will automatically keep them in sync. For example, in a word processor, if the user presses a Bold toolbar button, the Bold menu item will automatically be checked."
},
{
"code": null,
"e": 25378,
"s": 25325,
"text": "Below is how an action will look inside the tool bar"
},
{
"code": null,
"e": 25386,
"s": 25378,
"text": "Syntax:"
},
{
"code": null,
"e": 25410,
"s": 25386,
"text": "action = QAction(name)\n"
},
{
"code": null,
"e": 25568,
"s": 25410,
"text": "This action can be added to toolbars or QMenus with the help of addAction and addActions method. Below are the some frequently used commands with the QAction"
},
{
"code": null,
"e": 25876,
"s": 25568,
"text": "setCheckable : To make QAction Chekable\n\nsetIcon : To add icon to the QAction\n\nsetText : To set the display name of the QAction\n\ntext : To get the display name of the QAction\n\nsetPriority : To set the priority of the action\n\ntriggered.connect : To connect an method with it when triggered signal is emitted\n"
},
{
"code": null,
"e": 26066,
"s": 25876,
"text": "Example :In this example we will create a main window having a tool bar, label and tool bar is consisting of QAction each having separate method connected to it, below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a tool bar toolbar = QToolBar(self) # setting geometry to the tool bar toolbar.setGeometry(50, 100, 300, 35) # creating QAction Instances action1 = QAction(\"First Action\", self) action2 = QAction(\"Second Action\", self) action3 = QAction(\"Third Action\", self) # adding these actions to the tool bar toolbar.addAction(action1) toolbar.addAction(action2) toolbar.addAction(action3) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(100, 150, 200, 50) # adding triggered action to the first action action1.triggered.connect(lambda: label.setText(\"First Action Triggered\")) # adding triggered action to the second action action2.triggered.connect(lambda: label.setText(\"Second Action Triggered\")) # adding triggered action to the third action action3.triggered.connect(lambda: label.setText(\"Third Action Triggered\")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27797,
"s": 26066,
"text": null
},
{
"code": null,
"e": 27806,
"s": 27797,
"text": "Output :"
},
{
"code": null,
"e": 27945,
"s": 27806,
"text": "Another exampleIn this example we will create a commandlink button and add menu to it which is having QAction, below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a command link button cl_button = QCommandLinkButton(\"Press\", self) # setting geometry cl_button.setGeometry(150, 100, 150, 60) # QActions action1 = QAction(\"Geeks\", self) action2 = QAction(\"GfG\", self) # making action2 checkable action2.setCheckable(True) # QMenu menu = QMenu() # adding actions to menu menu.addActions([action1, action2]) # setting menu to the button cl_button.setMenu(menu) # creating label label = QLabel(\"GeeksforGeeks\", self) # setting label geometry label.setGeometry(100, 200, 300, 80) # making label multiline label.setWordWrap(True) # adding method to the action action1.triggered.connect(lambda: label.setText(\"Action1 is triggered\")) # adding method to the action2 when it get checked action2.toggled.connect(lambda: label.setText(\"Action2 is toggled\")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Window window = Window() # start the app sys.exit(App.exec()) ",
"e": 29631,
"s": 27945,
"text": null
},
{
"code": null,
"e": 29640,
"s": 29631,
"text": "Output :"
},
{
"code": null,
"e": 29660,
"s": 29640,
"text": "Python PyQt-QAction"
},
{
"code": null,
"e": 29671,
"s": 29660,
"text": "Python-gui"
},
{
"code": null,
"e": 29683,
"s": 29671,
"text": "Python-PyQt"
},
{
"code": null,
"e": 29690,
"s": 29683,
"text": "Python"
},
{
"code": null,
"e": 29788,
"s": 29690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29820,
"s": 29788,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29862,
"s": 29820,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29899,
"s": 29862,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29928,
"s": 29899,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29953,
"s": 29928,
"text": "sum() function in Python"
},
{
"code": null,
"e": 30009,
"s": 29953,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30051,
"s": 30009,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30092,
"s": 30051,
"text": "Print lists in Python (4 Different Ways)"
},
{
"code": null,
"e": 30128,
"s": 30092,
"text": "Convert integer to string in Python"
}
] |
Big Data Analytics - Data Collection | Data collection plays the most important role in the Big Data cycle. The Internet provides almost unlimited sources of data for a variety of topics. The importance of this area depends on the type of business, but traditional industries can acquire a diverse source of external data and combine those with their transactional data.
For example, let’s assume we would like to build a system that recommends restaurants. The first step would be to gather data, in this case, reviews of restaurants from different websites and store them in a database. As we are interested in raw text, and would use that for analytics, it is not that relevant where the data for developing the model would be stored. This may sound contradictory with the big data main technologies, but in order to implement a big data application, we simply need to make it work in real time.
Once the problem is defined, the following stage is to collect the data. The following miniproject idea is to work on collecting data from the web and structuring it to be used in a machine learning model. We will collect some tweets from the twitter rest API using the R programming language.
First of all create a twitter account, and then follow the instructions in the twitteR package vignette to create a twitter developer account. This is a summary of those instructions −
Go to https://twitter.com/apps/new and log in.
Go to https://twitter.com/apps/new and log in.
After filling in the basic info, go to the "Settings" tab and select "Read, Write and Access direct messages".
After filling in the basic info, go to the "Settings" tab and select "Read, Write and Access direct messages".
Make sure to click on the save button after doing this
Make sure to click on the save button after doing this
In the "Details" tab, take note of your consumer key and consumer secret
In the "Details" tab, take note of your consumer key and consumer secret
In your R session, you’ll be using the API key and API secret values
In your R session, you’ll be using the API key and API secret values
Finally run the following script. This will install the twitteR package from its repository on github.
Finally run the following script. This will install the twitteR package from its repository on github.
install.packages(c("devtools", "rjson", "bit64", "httr"))
# Make sure to restart your R session at this point
library(devtools)
install_github("geoffjentry/twitteR")
We are interested in getting data where the string "big mac" is included and finding out which topics stand out about this. In order to do this, the first step is collecting the data from twitter. Below is our R script to collect required data from twitter. This code is also available in bda/part1/collect_data/collect_data_twitter.R file.
rm(list = ls(all = TRUE)); gc() # Clears the global environment
library(twitteR)
Sys.setlocale(category = "LC_ALL", locale = "C")
### Replace the xxx’s with the values you got from the previous instructions
# consumer_key = "xxxxxxxxxxxxxxxxxxxx"
# consumer_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# access_token = "xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# access_token_secret= "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# Connect to twitter rest API
setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_token_secret)
# Get tweets related to big mac
tweets <- searchTwitter(’big mac’, n = 200, lang = ’en’)
df <- twListToDF(tweets)
# Take a look at the data
head(df)
# Check which device is most used
sources <- sapply(tweets, function(x) x$getStatusSource())
sources <- gsub("</a>", "", sources)
sources <- strsplit(sources, ">")
sources <- sapply(sources, function(x) ifelse(length(x) > 1, x[2], x[1]))
source_table = table(sources)
source_table = source_table[source_table > 1]
freq = source_table[order(source_table, decreasing = T)]
as.data.frame(freq)
# Frequency
# Twitter for iPhone 71
# Twitter for Android 29
# Twitter Web Client 25
# recognia 20
65 Lectures
6 hours
Arnab Chakraborty
18 Lectures
1.5 hours
Pranjal Srivastava, Harshit Srivastava
23 Lectures
2 hours
John Shea
18 Lectures
1.5 hours
Pranjal Srivastava
46 Lectures
3.5 hours
Pranjal Srivastava
37 Lectures
3.5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2886,
"s": 2554,
"text": "Data collection plays the most important role in the Big Data cycle. The Internet provides almost unlimited sources of data for a variety of topics. The importance of this area depends on the type of business, but traditional industries can acquire a diverse source of external data and combine those with their transactional data."
},
{
"code": null,
"e": 3414,
"s": 2886,
"text": "For example, let’s assume we would like to build a system that recommends restaurants. The first step would be to gather data, in this case, reviews of restaurants from different websites and store them in a database. As we are interested in raw text, and would use that for analytics, it is not that relevant where the data for developing the model would be stored. This may sound contradictory with the big data main technologies, but in order to implement a big data application, we simply need to make it work in real time."
},
{
"code": null,
"e": 3708,
"s": 3414,
"text": "Once the problem is defined, the following stage is to collect the data. The following miniproject idea is to work on collecting data from the web and structuring it to be used in a machine learning model. We will collect some tweets from the twitter rest API using the R programming language."
},
{
"code": null,
"e": 3893,
"s": 3708,
"text": "First of all create a twitter account, and then follow the instructions in the twitteR package vignette to create a twitter developer account. This is a summary of those instructions −"
},
{
"code": null,
"e": 3940,
"s": 3893,
"text": "Go to https://twitter.com/apps/new and log in."
},
{
"code": null,
"e": 3987,
"s": 3940,
"text": "Go to https://twitter.com/apps/new and log in."
},
{
"code": null,
"e": 4098,
"s": 3987,
"text": "After filling in the basic info, go to the \"Settings\" tab and select \"Read, Write and Access direct messages\"."
},
{
"code": null,
"e": 4209,
"s": 4098,
"text": "After filling in the basic info, go to the \"Settings\" tab and select \"Read, Write and Access direct messages\"."
},
{
"code": null,
"e": 4264,
"s": 4209,
"text": "Make sure to click on the save button after doing this"
},
{
"code": null,
"e": 4319,
"s": 4264,
"text": "Make sure to click on the save button after doing this"
},
{
"code": null,
"e": 4392,
"s": 4319,
"text": "In the \"Details\" tab, take note of your consumer key and consumer secret"
},
{
"code": null,
"e": 4465,
"s": 4392,
"text": "In the \"Details\" tab, take note of your consumer key and consumer secret"
},
{
"code": null,
"e": 4534,
"s": 4465,
"text": "In your R session, you’ll be using the API key and API secret values"
},
{
"code": null,
"e": 4603,
"s": 4534,
"text": "In your R session, you’ll be using the API key and API secret values"
},
{
"code": null,
"e": 4706,
"s": 4603,
"text": "Finally run the following script. This will install the twitteR package from its repository on github."
},
{
"code": null,
"e": 4809,
"s": 4706,
"text": "Finally run the following script. This will install the twitteR package from its repository on github."
},
{
"code": null,
"e": 4982,
"s": 4809,
"text": "install.packages(c(\"devtools\", \"rjson\", \"bit64\", \"httr\")) \n\n# Make sure to restart your R session at this point \nlibrary(devtools) \ninstall_github(\"geoffjentry/twitteR\") \n"
},
{
"code": null,
"e": 5323,
"s": 4982,
"text": "We are interested in getting data where the string \"big mac\" is included and finding out which topics stand out about this. In order to do this, the first step is collecting the data from twitter. Below is our R script to collect required data from twitter. This code is also available in bda/part1/collect_data/collect_data_twitter.R file."
},
{
"code": null,
"e": 6607,
"s": 5323,
"text": "rm(list = ls(all = TRUE)); gc() # Clears the global environment\nlibrary(twitteR)\nSys.setlocale(category = \"LC_ALL\", locale = \"C\")\n\n### Replace the xxx’s with the values you got from the previous instructions\n\n# consumer_key = \"xxxxxxxxxxxxxxxxxxxx\"\n# consumer_secret = \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n\n# access_token = \"xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n\n# access_token_secret= \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n\n# Connect to twitter rest API\nsetup_twitter_oauth(consumer_key, consumer_secret, access_token, access_token_secret)\n\n# Get tweets related to big mac\ntweets <- searchTwitter(’big mac’, n = 200, lang = ’en’)\ndf <- twListToDF(tweets)\n\n# Take a look at the data\nhead(df)\n\n# Check which device is most used\nsources <- sapply(tweets, function(x) x$getStatusSource())\nsources <- gsub(\"</a>\", \"\", sources)\nsources <- strsplit(sources, \">\")\nsources <- sapply(sources, function(x) ifelse(length(x) > 1, x[2], x[1]))\nsource_table = table(sources)\nsource_table = source_table[source_table > 1]\nfreq = source_table[order(source_table, decreasing = T)]\nas.data.frame(freq)\n\n# Frequency\n# Twitter for iPhone 71\n# Twitter for Android 29\n# Twitter Web Client 25\n# recognia 20"
},
{
"code": null,
"e": 6640,
"s": 6607,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6659,
"s": 6640,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6694,
"s": 6659,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6734,
"s": 6694,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 6767,
"s": 6734,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6778,
"s": 6767,
"text": " John Shea"
},
{
"code": null,
"e": 6813,
"s": 6778,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6833,
"s": 6813,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6868,
"s": 6833,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6888,
"s": 6868,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6923,
"s": 6888,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6963,
"s": 6923,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 6970,
"s": 6963,
"text": " Print"
},
{
"code": null,
"e": 6981,
"s": 6970,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.